问:
Unable to write text field after adding onChange (that have setState) ReactJS
I want to create poll/exercise form that update the value by useState. So, I created handleChange() to handle update from input form and that work perfeclt fine for the most of my input field except the one that is store state as object (I have state field that called answers to keep multiple answer choices from my poll/excercise as answer1 ... answer4) like this

```<code>const [pollValues, setpollValues] = useState({
    name: "",
    question: "",
    type: "",
    answers: {
      answer1: "",
      answer2: "",
      answer3: "",
      answer4: "",
    },
  });
</code>```

and handleChange() use by passing event form input form:

```<code> function handleChange(e) {
    const { name, value } = e.target;
    console.log(name, value);

    setpollValues((prev) => ({
      ...prev,
      [name]: value,
    }));
  }
</code>```

and use it for handle input with name (that locate in main return() ), question, type work perfectly fine. but the poll answers choice, I make a sub-component in the same file and passing name as props to identify the choice

```<code>     <ChoiceAnswer type="required" name="answer1" choiceNumber="1" />
     <ChoiceAnswer type="required" name="answer2" choiceNumber="2" />
     <ChoiceAnswer type="optional" name="answer3" choiceNumber="3" />
     <ChoiceAnswer type="optional" name="answer4" choiceNumber="4" />

 const ChoiceAnswer = (props) => {
    const { type, choiceNumber, name } = props;
    if (type == "required") {
      return (
        <div
          className="d-flex flex-column "
          style={{
            rowGap: "0.5rem",
            margin: "0px",
            padding: "0px",
            width: "100%",
          }}
        >
          <div
            className="d-flex align-items-center"
            style={{
              padding: "1rem",
              border: "1.5px #ccc solid",
              borderRadius: "1rem",
              columnGap: "1rem",
            }}
          >
            <div style={{ width: "7rem" }}>
              <h5>ตัวเลือกที่ {choiceNumber}</h5>
              <p style={{ color: "red" }}>* จำเป็น</p>
            </div>

            <input
              type="text"
              style={{ width: "100%" }}

              id={name}
              name={name}
              placeholder="ใส่คำตอบ"
              onChange={handleChange}
              required
            ></input>
          </div>
        </div>
      ); else if (type == "optional") {...}
</code>```

the problem that occurs with the answers only, cannot typing text in text field (try to console log and found that it can only update only 1 character at once cannot type in string) but If I delete the setState It will normally typable. So, I don't know what happend that make my answers field cannot typing and using handleChang() to update their values.

答:
There is a mistake in your handleChange function. answers are nested one more level.

Try like below.

```<code>function handleChange(e) {
    const { name, value } = e.target;
    console.log(name, value);

    setpollValues(prev => ({
        ...prev,
        answers: {
            ...prev.answers,
            [name]: value
        }
    }));
}
</code>```

Body:
I want to create poll/exercise form that update the value by useState. So, I created handleChange() to handle update from input form and that work perfeclt fine for the most of my input field except the one that is store state as object (I have state field that called answers to keep multiple answer choices from my poll/excercise as answer1 ... answer4) like this

const [pollValues, setpollValues] = useState({
    name: "",
    question: "",
    type: "",
    answers: {
      answer1: "",
      answer2: "",
      answer3: "",
      answer4: "",
    },
  });

and handleChange() use by passing event form input form:

 function handleChange(e) {
    const { name, value } = e.target;
    console.log(name, value);

    setpollValues((prev) => ({
      ...prev,
      [name]: value,
    }));
  }

and use it for handle input with name (that locate in main return() ), question, type work perfectly fine. but the poll answers choice, I make a sub-component in the same file and passing name as props to identify the choice

     <ChoiceAnswer type="required" name="answer1" choiceNumber="1" />
     <ChoiceAnswer type="required" name="answer2" choiceNumber="2" />
     <ChoiceAnswer type="optional" name="answer3" choiceNumber="3" />
     <ChoiceAnswer type="optional" name="answer4" choiceNumber="4" />

 const ChoiceAnswer = (props) => {
    const { type, choiceNumber, name } = props;
    if (type == "required") {
      return (

ตัวเลือกที่ {choiceNumber}

* จำเป็น

            <input
              type="text"
              style={{ width: "100%" }}

              id={name}
              name={name}
              placeholder="ใส่คำตอบ"
              onChange={handleChange}
              required
            ></input>

      ); else if (type == "optional") {...}

the problem that occurs with the answers only, cannot typing text in text field (try to console log and found that it can only update only 1 character at once cannot type in string) but If I delete the setState It will normally typable. So, I don't know what happend that make my answers field cannot typing and using handleChang() to update their values.

Body:
There is a mistake in your handleChange function. answers are nested one more level.

Try like below.

function handleChange(e) {
    const { name, value } = e.target;
    console.log(name, value);

    setpollValues(prev => ({
        ...prev,
        answers: {
            ...prev.answers,
            [name]: value
        }
    }));
}


来源: stackexchange

问:
Oracle sql cannot insert string with length more than 200 characters "Error: ORA-06502: PL/SQL: numeric or value error"
I am trying to INSERT to a column with datatype VARCHAR2(4000 bytes) in Oracle sql.
I wrote an API using node js as lambda function, but when I insert a string with more than 200 characters, I am getting error "Error: ORA-06502: PL/SQL: numeric or value error: DML Returning: Error writing to host variable".
But when I tried to insert directly through Oracle sql developer windows, I am able to insert string of length upto 4000 character.

Here's my query:

```<code>const sql = `BEGIN INSERT INTO job_log(
        job_log_entry_id,
          job_id,
          entry_text,
          entry_date)VALUES (
          job_log_entry_seq.nextval,
          :jobID,
          :entryText,
          TO_DATE('${params.entryDate}', 'DD/MM/YY')
          )
        RETURNING job_log_entry_id, entry_text
        INTO :logEntryId, :note;
        COMMIT; END;`

const opt = {
                jobId:{val:params.jobId,dir: oracledb.BIND_IN,type: oracledb.STRING},
                entryText:{val: params.entryText,dir: oracledb.BIND_IN,type: oracledb.STRING},
                entryDate:{dir: oracledb.BIND_OUT,type: oracledb.DATE}
            };
            try {
                result = await conn.execute(sql, opt);
            } catch (error) {
                sqlError = true
            }
</code>```

答:
You are passing the parameter as a DATE data type. However, the PL/SQL block is passing it to the TO_DATE function and that expects string arguments so there will be an implicit cast from the DATE being passed to a string so that it can then be converted back to a DATE; this implicit cast will cause issues when the NLS_DATE_FORMAT does not match the DD/MM/YY format in the explicit cast. Remove the TO_DATE function and just pass a DATE:

const sql = `BEGIN
  INSERT INTO job_log(
    job_log_entry_id,
    job_id,
    entry_text,
    entry_date
  )VALUES (
    job_log_entry_seq.nextval,
    :jobID,
    :entryText,
    :entryDate
  )
  RETURNING job_log_entry_id, entry_text INTO :logEntryId, :note;
  COMMIT;
  END;`
```
<p>You also pass the <code>entryDate</code> as an <code>OUT</code> parameter when it should be an <code>IN</code> parameter and you do not have <code>OUT</code> parameters for <code>logEntryId</code> or <code>note</code> (although I am unsure why you need <code>note</code> as it should be the value you put in).</p>
<p>Something like:</p>
<pre class="lang-js prettyprint-override"><code>const opt = {
  jobId:     {val: params.jobId,     dir: oracledb.BIND_IN, type: oracledb.STRING},
  entryText: {val: params.entryText, dir: oracledb.BIND_IN, type: oracledb.STRING},
  entryDate: {val: params.entryDate, dir: oracledb.BIND_IN, type: oracledb.DATE},
  logEntryId:{dir: oracledb.BIND_OUT, type: oracledb.NUMBER},
  note:      {dir: oracledb.BIND_OUT, type: oracledb.STRING, maxSize: 4000}
};
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to INSERT to a column with datatype VARCHAR2(4000 bytes) in Oracle sql.
I wrote an API using node js as lambda function, but when I insert a string with more than 200 characters, I am getting error "Error: ORA-06502: PL/SQL: numeric or value error: DML Returning: Error writing to host variable".
But when I tried to insert directly through Oracle sql developer windows, I am able to insert string of length upto 4000 character.

Here's my query:

const sql = `BEGIN INSERT INTO job_log(
        job_log_entry_id,
          job_id,
          entry_text,
          entry_date)VALUES (
          job_log_entry_seq.nextval,
          :jobID,
          :entryText,
          TO_DATE('${params.entryDate}', 'DD/MM/YY')
          )
        RETURNING job_log_entry_id, entry_text
        INTO :logEntryId, :note;
        COMMIT; END;`

const opt = {
                jobId:{val:params.jobId,dir: oracledb.BIND_IN,type: oracledb.STRING},
                entryText:{val: params.entryText,dir: oracledb.BIND_IN,type: oracledb.STRING},
                entryDate:{dir: oracledb.BIND_OUT,type: oracledb.DATE}
            };
            try {
                result = await conn.execute(sql, opt);
            } catch (error) {
                sqlError = true
            }

Body:
You are passing the parameter as a DATE data type. However, the PL/SQL block is passing it to the TO_DATE function and that expects string arguments so there will be an implicit cast from the DATE being passed to a string so that it can then be converted back to a DATE; this implicit cast will cause issues when the NLS_DATE_FORMAT does not match the DD/MM/YY format in the explicit cast. Remove the TO_DATE function and just pass a DATE:

const sql = `BEGIN
  INSERT INTO job_log(
    job_log_entry_id,
    job_id,
    entry_text,
    entry_date
  )VALUES (
    job_log_entry_seq.nextval,
    :jobID,
    :entryText,
    :entryDate
  )
  RETURNING job_log_entry_id, entry_text INTO :logEntryId, :note;
  COMMIT;
  END;`

You also pass the entryDate as an OUT parameter when it should be an IN parameter and you do not have OUT parameters for logEntryId or note (although I am unsure why you need note as it should be the value you put in).

Something like:

const opt = {
  jobId:     {val: params.jobId,     dir: oracledb.BIND_IN, type: oracledb.STRING},
  entryText: {val: params.entryText, dir: oracledb.BIND_IN, type: oracledb.STRING},
  entryDate: {val: params.entryDate, dir: oracledb.BIND_IN, type: oracledb.DATE},
  logEntryId:{dir: oracledb.BIND_OUT, type: oracledb.NUMBER},
  note:      {dir: oracledb.BIND_OUT, type: oracledb.STRING, maxSize: 4000}
};


问:
Fabric Js - change position of control corners
I have a fabric js rectangle and I would like to move the control squares inside the rectangle.

I don't know if this is possible in the version I'm using, I didn't found how to do this.

Note I am using fabric.js version: 2.4.6

Here is what I've tried:

```<code>      this._cropRect = new window.fabric.Rect({
        top: 0,
        left: 0,
        width: this.options.canvasWidth,
        height: this.options.canvasHeight,
        fill: 'red',
        strokeWidth: 0,
        lockRotation: true,
        lockScalingFlip: true,
        lockUniScaling: true,
        hasBorders: false,
        hasRotatingPoint: false,
        padding: -12,
        cornerColor: 'red',
        borderColor: 'red',
        cornerStroke: 10,
        borderScaleFactor: 2,
        cornerSize: CROP_CORNER_SIZE,
        borderOpacityWhenMoving: 1,
      })

      this._cropRect.set('globalCompositeOperation', 'destination-out')

      this._fabricCanvas.add(this._cropRect)
      this._fabricCanvas.setActiveObject(this._cropRect)
      this._fabricCanvas.requestRenderAll()
</code>```

Here is the image of what I have now and what I want to achieve:

UPDATE:

I have created a jsfiddle: https://jsfiddle.net/t94ksgeq/

答:
You could extend the draw function of the cropping rectangles.

cropRect.drawControls = function(t, e) {
    e = e || {};
    var i = this._calculateCurrentDimensions(),
        // Modified variable r and n
        r = i.x - this.cornerSize,
        n = i.y - this.cornerSize,
        s = e.cornerSize || this.cornerSize,
        o = -(r + s) / 2,
        a = -(n + s) / 2,
        h = void 0 !== e.transparentCorners ? e.transparentCorners : this.transparentCorners,
        c = void 0 !== e.hasRotatingPoint ? e.hasRotatingPoint : this.hasRotatingPoint,
        l = h ? "stroke" : "fill";
    return t.save(), t.strokeStyle = t.fillStyle = e.cornerColor || this.cornerColor, this.transparentCorners || (t.strokeStyle = e.cornerStrokeColor || this.cornerStrokeColor), this._setLineDash(t, e.cornerDashArray || this.cornerDashArray, null), this._drawControl("tl", t, l, o, a, e), this._drawControl("tr", t, l, o + r, a, e), this._drawControl("bl", t, l, o, a + n, e), this._drawControl("br", t, l, o + r, a + n, e), this.get("lockUniScaling") || (this._drawControl("mt", t, l, o + r / 2, a, e), this._drawControl("mb", t, l, o + r / 2, a + n, e), this._drawControl("mr", t, l, o + r, a + n / 2, e), this._drawControl("ml", t, l, o, a + n / 2, e)), c && this._drawControl("mtr", t, l, o + r / 2, a - this.rotatingPointOffset, e), t.restore(), this
}
```
<p>in this code <code>r</code> and <code>n</code> represent the x and y values and I found that if you subtract the cornersize. The recetangles get drawn inside the image. Now the rectangles are exactly inside the the rectangle on the edge, but ofcourse you can modify it to your needs.</p>
<p>EDIT:</p>
<p>After further inspection I found that you can adjust the position of the resize controls in the <code>_setCornerCoords</code> function.</p>
<pre class="lang-js prettyprint-override"><code>function degrees_to_radians(degrees) {
  var pi = Math.PI;
  return degrees * (pi/180);
}

cropRect._setCornerCoords = function () {
    var t,
    e,
    i = this.oCoords,
    r = degrees_to_radians(45 - this.angle),
    n = .707106 * this.cornerSize,
    s = n * fabric.util.cos(r),
    o = n * fabric.util.sin(r);

    // Again this is setup to be the cornerSize, but this can be any number
    var p = this.cornerSize;
    var q = p / 2;

    for (var a in i) {
      t = i[a].x;
      e = i[a].y;

      // Check which kind of corner it is and translate it accordingly
      switch(a) {
        case "tl":
            t += q;
          e += q;
          break;
        case "tr":
          t -= q;
          e += q;
          break;
        case "br":
          t -= q;
          e -= q;
          break;
        case "bl":
          t += q;
          e -= q;
          break;
      }

      i[a].corner = {
        tl: { x: t - o,  y: e - s },
        tr: { x: t + s, y: e - o },
        bl: { x: t - s,  y: e + o },
        br: { x: t + o, y: e + s }
      }
    }
}
</code>```

This enables the user to resize within the previously drawn corners. The resize may seem not aligned with the mouse position (hardly noticable in usage).

This is because you begin resizing not from the corner. And the resize function follows the difference in mouse position. And uses some different coordinates, but I was unable to find those.

Body:
I have a fabric js rectangle and I would like to move the control squares inside the rectangle.

I don't know if this is possible in the version I'm using, I didn't found how to do this.

Note I am using fabric.js version: 2.4.6

Here is what I've tried:

      this._cropRect = new window.fabric.Rect({
        top: 0,
        left: 0,
        width: this.options.canvasWidth,
        height: this.options.canvasHeight,
        fill: 'red',
        strokeWidth: 0,
        lockRotation: true,
        lockScalingFlip: true,
        lockUniScaling: true,
        hasBorders: false,
        hasRotatingPoint: false,
        padding: -12,
        cornerColor: 'red',
        borderColor: 'red',
        cornerStroke: 10,
        borderScaleFactor: 2,
        cornerSize: CROP_CORNER_SIZE,
        borderOpacityWhenMoving: 1,
      })

      this._cropRect.set('globalCompositeOperation', 'destination-out')

      this._fabricCanvas.add(this._cropRect)
      this._fabricCanvas.setActiveObject(this._cropRect)
      this._fabricCanvas.requestRenderAll()

Here is the image of what I have now and what I want to achieve:

UPDATE:

I have created a jsfiddle: https://jsfiddle.net/t94ksgeq/

Body:
You could extend the draw function of the cropping rectangles.

cropRect.drawControls = function(t, e) {
    e = e || {};
    var i = this._calculateCurrentDimensions(),
        // Modified variable r and n
        r = i.x - this.cornerSize,
        n = i.y - this.cornerSize,
        s = e.cornerSize || this.cornerSize,
        o = -(r + s) / 2,
        a = -(n + s) / 2,
        h = void 0 !== e.transparentCorners ? e.transparentCorners : this.transparentCorners,
        c = void 0 !== e.hasRotatingPoint ? e.hasRotatingPoint : this.hasRotatingPoint,
        l = h ? "stroke" : "fill";
    return t.save(), t.strokeStyle = t.fillStyle = e.cornerColor || this.cornerColor, this.transparentCorners || (t.strokeStyle = e.cornerStrokeColor || this.cornerStrokeColor), this._setLineDash(t, e.cornerDashArray || this.cornerDashArray, null), this._drawControl("tl", t, l, o, a, e), this._drawControl("tr", t, l, o + r, a, e), this._drawControl("bl", t, l, o, a + n, e), this._drawControl("br", t, l, o + r, a + n, e), this.get("lockUniScaling") || (this._drawControl("mt", t, l, o + r / 2, a, e), this._drawControl("mb", t, l, o + r / 2, a + n, e), this._drawControl("mr", t, l, o + r, a + n / 2, e), this._drawControl("ml", t, l, o, a + n / 2, e)), c && this._drawControl("mtr", t, l, o + r / 2, a - this.rotatingPointOffset, e), t.restore(), this
}

in this code r and n represent the x and y values and I found that if you subtract the cornersize. The recetangles get drawn inside the image. Now the rectangles are exactly inside the the rectangle on the edge, but ofcourse you can modify it to your needs.

EDIT:

After further inspection I found that you can adjust the position of the resize controls in the _setCornerCoords function.

function degrees_to_radians(degrees) {
  var pi = Math.PI;
  return degrees * (pi/180);
}

cropRect._setCornerCoords = function () {
    var t,
    e,
    i = this.oCoords,
    r = degrees_to_radians(45 - this.angle),
    n = .707106 * this.cornerSize,
    s = n * fabric.util.cos(r),
    o = n * fabric.util.sin(r);

    // Again this is setup to be the cornerSize, but this can be any number
    var p = this.cornerSize;
    var q = p / 2;

    for (var a in i) {
      t = i[a].x;
      e = i[a].y;

      // Check which kind of corner it is and translate it accordingly
      switch(a) {
        case "tl":
            t += q;
          e += q;
          break;
        case "tr":
          t -= q;
          e += q;
          break;
        case "br":
          t -= q;
          e -= q;
          break;
        case "bl":
          t += q;
          e -= q;
          break;
      }

      i[a].corner = {
        tl: { x: t - o,  y: e - s },
        tr: { x: t + s, y: e - o },
        bl: { x: t - s,  y: e + o },
        br: { x: t + o, y: e + s }
      }
    }
}

This enables the user to resize within the previously drawn corners. The resize may seem not aligned with the mouse position (hardly noticable in usage).

This is because you begin resizing not from the corner. And the resize function follows the difference in mouse position. And uses some different coordinates, but I was unable to find those.


问:
Convert object to array of prorperties
I need to convert object:

```<code>{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }
</code>```

to array:

```<code>[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];
</code>```

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

```<code>let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });
</code>```

Thanks

答:
This is the most bulletproof I could do :D, without needing a global variable, you just take it, and us it wherever you want!

const test = {
  middleName: null,
  name: "Test Name",
  university: {
    country: {
      code: "PL"
    },
    isGraduated: true,
    speciality: "Computer Science"
  }
};

function toPropertiesByPath(inputObj) {
  let arr = [];
  let initialObj = {};

  const getKeys = (obj, parentK='') => {
    initialObj = arr.length === 0 ? obj: initialObj;
    const entries = Object.entries(obj);
    for(let i=0; i<entries.length; i++) {
      const key = entries[i][0];
      const val = entries[i][1];
      const isRootElement = initialObj.hasOwnProperty(key);
      parentK = isRootElement ? key: parentK+'.'+key;

      if(typeof val === 'object' && val!==null && !Array.isArray(val)){
        getKeys(val, parentK);
      } else {
       arr.push({ key: parentK, property: val });
      }
    }
  };

  getKeys(inputObj);
  return arr;
}

console.log(toPropertiesByPath(test));```

Title: Convert object to array of prorperties

Body:
I need to convert object:

{
        middleName: null,
        name: "Test Name",
        university: {
            country: {
                code: "PL"
            },
            isGraduated: true,
            speciality: "Computer Science"
        }
    }

to array:

[{
        key: "name",
        propertyValue: "Test Name",
    },
    {
        key: "middleName",
        propertyValue: null,
    },
    {
        key: "university.isGraduated",
        propertyValue: true,
    },
    {
        key: "university.speciality",
        propertyValue: "Computer Science",
    },
    {
        key: "university.country.code",
        propertyValue: "PL"
    }];

I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")

let arr = [];
    Object.keys(parsedObj).map((key) => {
        if (parsedObj[key] instanceof Object) {
            Object.keys(parsedObj[key]).map((keyNested) => {
                if (parsedObj[key][keyNested] instanceof Object) {
                    Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
                        arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
                    })
                } else {
                    arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
                }
            })
        } else {
            arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
        }
    });

Thanks


问:
Does the datetime.datetime.ctime() function return a fixed width string?
If I were to run the following code:

```<code>import datetime
dt = datetime.datetime.now()
date_str = dt.ctime()
</code>```

Will the result of len(date_str) always be the same, regardless of when I happen to run the code?  I think it will be, but I'm not certain. I looked at the datetime module reference but the relevant section says:

Return a string representing the date:

```<code>>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'
</code>```

d.ctime() is equivalent to:

```<code>time.ctime(time.mktime(d.timetuple()))
</code>```

on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

But looking at the article on cppreference.com, the answer is less than clear to me. I did find a reference here which suggests that it will be a 24-character wide string, but I was hoping for a more official source or reference if possible. It's possible that I didn't delve far enough into the C-standard to divine the answer.

Also, based on that quote, does that mean the behavior might be platform-dependent?  Or is it likely to be generally uniform outside of niche operating systems?

(yes I know that I can manually format to fixed-width, but I want to know whether the built-in one already is that way)

答:
It's fixed-width. You can see in the cppreference article you linked that the output of C ctime follows the format

```<code>Www Mmm dd hh:mm:ss yyyy\n
</code>```

which is fixed-width. (Python doesn't include the trailing \n, but it's still fixed-width.)

You can also check the C standard directly and find that the standard-mandated output is fixed-width.

You can also check the implementation of datetime.ctime if you want to be extra sure.

Also, based on that quote, does that mean the behavior might be platform-dependent?

No. The behavior is platform-independent. The quote is saying that datetime.ctime behaves like the C standard mandated behavior of the C ctime function, even if the platform implementation of the C function does not conform to the C standard.

Body:
If I were to run the following code:

import datetime
dt = datetime.datetime.now()
date_str = dt.ctime()

Will the result of len(date_str) always be the same, regardless of when I happen to run the code?  I think it will be, but I'm not certain. I looked at the datetime module reference but the relevant section says:

Return a string representing the date:

>>> from datetime import date
>>> date(2002, 12, 4).ctime()
'Wed Dec  4 00:00:00 2002'

d.ctime() is equivalent to:

time.ctime(time.mktime(d.timetuple()))

on platforms where the native C ctime() function (which time.ctime() invokes, but which date.ctime() does not invoke) conforms to the C standard.

But looking at the article on cppreference.com, the answer is less than clear to me. I did find a reference here which suggests that it will be a 24-character wide string, but I was hoping for a more official source or reference if possible. It's possible that I didn't delve far enough into the C-standard to divine the answer.

Also, based on that quote, does that mean the behavior might be platform-dependent?  Or is it likely to be generally uniform outside of niche operating systems?

(yes I know that I can manually format to fixed-width, but I want to know whether the built-in one already is that way)

Body:
It's fixed-width. You can see in the cppreference article you linked that the output of C ctime follows the format

Www Mmm dd hh:mm:ss yyyy\n

which is fixed-width. (Python doesn't include the trailing \n, but it's still fixed-width.)

You can also check the C standard directly and find that the standard-mandated output is fixed-width.

You can also check the implementation of datetime.ctime if you want to be extra sure.

Also, based on that quote, does that mean the behavior might be platform-dependent?

No. The behavior is platform-independent. The quote is saying that datetime.ctime behaves like the C standard mandated behavior of the C ctime function, even if the platform implementation of the C function does not conform to the C standard.


问:
Visual FoxPro - Memo field operations lead to "String is too long to fit" error
Fox: Visual FoxPro 6 / SP5 & Visual FoxPro 9 / SP2
OS: Windows 7 Professional & Windows 10 Professional

I have a legacy application that imports data from a text file of wage information. Each data line is SSN, Name, Wage. As you can expect, these wage files can get quite large, a few hundred MB sometimes.

The data from the wage file is imported into a memo field of a FoxPro table.

append memo xmemo.xmemo from (m.drive_file)

This works as it should, even with files nearing 400MB.

Then there's some code that verifies and checks the new data in the memo field for things that may need to be stripped out. (linefeeds and carriage returns).  The code that does this uses the OCCURS() function.

m.nchr10 = occurs(chr(10), xmemo.xmemo)   && count for line feeds

m.nchr13 = occurs(chr(13), xmemo.xmemo)   && count for carriage returns

Within the last week, the above two lines have failed with the error "String is too long to fit". Smaller wage files (about 60MB or so), will work fine. But anything larger than that will throw the error. I can even reproduce the error from the command line with

?occurs("x", xmemo.xmemo)  && show a count of 'x' characters.

Background:

This application has been in production for over 20 years and has taken large files without issue all of that time.

I can reproduce the error in Fox 6 and Fox 9.

At this point, I'm stumped. Anyone have any idea what the issue is? Thanks in advance to anyone that can offer some help.

答:
For each memo, I would copy it to a file (COPY MEMO MemoFieldName TO FileName),
Fopen() it and use fgets() to process the file line by line</p>


问:
Turning off Strict Mode in Angular?
I'm running into this issue and I'd like to turn off strict mode to get around it.

I've modified tsconfig.json with:

```<code>"compilerOptions": {
  "strict": false,
</code>```

And also tried:

```<code> "compilerOptions": {
   "noImplicitUseStrict": true,
</code>```

But no love.  Thoughts?

答: Removed the "strict": true from tsconfig.json

Title: Turning off Strict Mode in Angular?

Body:
I'm running into this issue and I'd like to turn off strict mode to get around it.

I've modified tsconfig.json with:

"compilerOptions": {
  "strict": false,

And also tried:

 "compilerOptions": {
   "noImplicitUseStrict": true,

But no love.  Thoughts?


问:
Can't understand the use of window.onscroll = null in React
What's the use of window.onscroll = null here?
It shows no difference even when i comment that last line out.</p>
```<code>const [isScrolled, setIsScrolled] = useState(false);

window.onscroll = () => {
    setIsScrolled(window.pageYOffset === 0? false : true)
    console.log(isScrolled);

    return () => (window.onscroll = null);
};
</code>```

答: Removes the event handler added to onScroll event. But better to move it inside useEffect hook.</p>

Body:
What's the use of window.onscroll = null here?
It shows no difference even when i comment that last line out.

const [isScrolled, setIsScrolled] = useState(false);

window.onscroll = () => {
    setIsScrolled(window.pageYOffset === 0? false : true)
    console.log(isScrolled);

    return () => (window.onscroll = null);
};


问:
Angular. TS2339: Property 'subscribe' does not exist on type 'void'
I am getting this error: TS2339: Property 'subscribe' does not exist on type 'void'.

答: Change the return type of httpService.gameDetails to the object that you created called Game instead of void, also return the response. I think it's implicitly marking as void becase you won't be returning anything in your gameDetails method.


问:
AWS Terraform IAM user with assume role for S3 back end
To store the Terraform state file in S3 bucket, I have used admin account credentials and configured. Now I have created IAM user and trying to use assume role. Assume role has the administrator policy attached.

I have tested this AIM user setup with aws sts assume-role --role-arn commands. I was able to get the token and using the token able access the S3 bucket using aws s3 ls command.

Now trying to use the IAM user access/secret key with assume role for terraform. when I run terraform refresh command its giving below errors.

provider code:

```<code>provider "aws" {
  region  = "us-west-2"
  max_retries = 1
  assume_role {
    role_arn = var.assume_role_arn
  }

}
</code>```

Error

```<code> Error: Error acquiring the state lock
│
│ Error message: 2 errors occurred:
│       * AccessDeniedException: User: arn:aws:iam::xxxxxxxx:user/deploy is not authorized to perform: dynamodb:PutItem on resource:
│ arn:aws:dynamodb:us-west-2:xxxxxxxx:table/terraform-state-lock
│       status code: 400, request id: CV4J3JN1LD0KPDGHAOA9UL13ONVV4KQNSO5AEMVJF66Q9ASUAAJG
│       * AccessDeniedException: User: arn:aws:iam::xxxxxxxx:user/deploy is not authorized to perform: dynamodb:GetItem on resource:
│ arn:aws:dynamodb:us-west-2:xxxxxxxx:table/terraform-state-lock
│       status code: 400, request id: BISQQDU4659LLI3CEDP26T8RJ7VV4KQNSO5AEMVJF66Q9ASUAAJG
│
│
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.
</code>```

Why this is not working in Terraform How to fix this error?

Thanks
SR

答:
It does not seem like it's even assuming the role, otherwise the error would show up as an assumed-role/deploy identity.

I'd suggest you try exporting the AWS_SECRET_ACCESS_KEY and AWS_ACCESS_KEY_ID variables in the command line and then run Terraform again.

I tried this few days back using Terraform Cloud with the terraform user credentials there, which is not exactly your case, but it should behave in the same way.

Body:
To store the Terraform state file in S3 bucket, I have used admin account credentials and configured. Now I have created IAM user and trying to use assume role. Assume role has the administrator policy attached.

I have tested this AIM user setup with aws sts assume-role --role-arn commands. I was able to get the token and using the token able access the S3 bucket using aws s3 ls command.

Now trying to use the IAM user access/secret key with assume role for terraform. when I run terraform refresh command its giving below errors.

provider code:

provider "aws" {
  region  = "us-west-2"
  max_retries = 1
  assume_role {
    role_arn = var.assume_role_arn
  }

}

Error

 Error: Error acquiring the state lock
│
│ Error message: 2 errors occurred:
│       * AccessDeniedException: User: arn:aws:iam::xxxxxxxx:user/deploy is not authorized to perform: dynamodb:PutItem on resource:
│ arn:aws:dynamodb:us-west-2:xxxxxxxx:table/terraform-state-lock
│       status code: 400, request id: CV4J3JN1LD0KPDGHAOA9UL13ONVV4KQNSO5AEMVJF66Q9ASUAAJG
│       * AccessDeniedException: User: arn:aws:iam::xxxxxxxx:user/deploy is not authorized to perform: dynamodb:GetItem on resource:
│ arn:aws:dynamodb:us-west-2:xxxxxxxx:table/terraform-state-lock
│       status code: 400, request id: BISQQDU4659LLI3CEDP26T8RJ7VV4KQNSO5AEMVJF66Q9ASUAAJG
│
│
│
│ Terraform acquires a state lock to protect the state from being written
│ by multiple users at the same time. Please resolve the issue above and try
│ again. For most commands, you can disable locking with the "-lock=false"
│ flag, but this is not recommended.

Why this is not working in Terraform How to fix this error?

Thanks
SR


问:
pulling out data from a colums in Excel
I have the following Data in Excel.

```<code>CHM0123456  SRM0123:01
CHM0123456  SRM0123:02
CHM0123456  SRM0256:12
CHM0123456  SRM0123:03
CHM0123457  SRM0789:01
CHM0123457  SRM0789:02
CHM0123457  SRM0789:03
CHM0123457  SRM0789:04
</code>```

What I need to do is pull out all the relevent SRM numbers that relate to a single CHM ref. now I have a formular that will do some thing like this

```<code>=INDEX($C$2:$C$6, SMALL(IF($B$8=$B$2:$B$6, ROW($B$2:$B$6)-MIN(ROW($B$2:$B$6))+1, ""), ROW(A1)))
</code>```

however this is a bit untidy and I really want to produce this same using short vb script, do i jsut have to right a loop that will run though and check each row in turn.

```<code>For x = 1 to 6555
if Ax = Chm123456
string = string + Bx
else
next
</code>```

which should give me a final string of

SRM0123:01,SRM123:02,SRM0256:12,SRM0123:03

to use with how i want.

Or is ther a neater way to do this ?

Cheers

Aaron

my current code

```<code>    For x = 2 To 6555
If Cells(x, 1).Value = "CHM0123456" Then
outstring = outstring + vbCr + Cells(x, 2).Value

End If

Next
MsgBox (outstring)

End Function
</code>```

答:
I'm not sure what your definition of 'neat' is, but here is a VBA function that I consider very neat and also flexible and it's lightning fast (10k+ entires with no lag). You pass it the CHM you want to look for, then the range to look in. You can pass a third optional paramater to set how each entry is seperated. So in your case you could write (assuming your list is :

=ListUnique(B2, B2:B6555)

You can also use Char(10) as the third parameter to seperat by line breaks, etc.

```<code>Function ListUnique(ByVal search_text As String, _
                    ByVal cell_range As range, _
                    Optional seperator As String = ", ") As String

Application.ScreenUpdating = False
Dim result As String
Dim i as Long
Dim cell As range
Dim keys As Variant
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

On Error Resume Next
For Each cell In cell_range
    If cell.Value = search_text Then
        dict.Add cell.Offset(, 1).Value, 1
    End If
Next

keys = dict.keys
For i = 0 To UBound(keys)
    result = result & (seperator & keys(i))
Next

If Len(result) <> 0 Then
    result = Right$(result, (Len(result) - Len(seperator)))
End If

ListUnique = result
Application.ScreenUpdating = True

End Function
</code>```

How it works: It simple loops through your range looking for the search_string you give it. If it finds it, it adds it to a dictionary object (which will eliminate all dupes). You dump the results in an array then create a string out of them. Technically you can just pass it "B:B" as the search array if you aren't sure where the end of the column is and this function will still work just fine (1/5th of a second for scanning every cell in column B with 1000 unique hits returned).

ContentLicense: CC BY-SA 3.0

Title: pulling out data from a colums in Excel

Body:
I have the following Data in Excel.

CHM0123456  SRM0123:01
CHM0123456  SRM0123:02
CHM0123456  SRM0256:12
CHM0123456  SRM0123:03
CHM0123457  SRM0789:01
CHM0123457  SRM0789:02
CHM0123457  SRM0789:03
CHM0123457  SRM0789:04

What I need to do is pull out all the relevent SRM numbers that relate to a single CHM ref. now I have a formular that will do some thing like this

=INDEX($C$2:$C$6, SMALL(IF($B$8=$B$2:$B$6, ROW($B$2:$B$6)-MIN(ROW($B$2:$B$6))+1, ""), ROW(A1)))

however this is a bit untidy and I really want to produce this same using short vb script, do i jsut have to right a loop that will run though and check each row in turn.

For x = 1 to 6555
if Ax = Chm123456
string = string + Bx
else
next

which should give me a final string of

SRM0123:01,SRM123:02,SRM0256:12,SRM0123:03

to use with how i want.

Or is ther a neater way to do this ?

Cheers

Aaron

my current code

    For x = 2 To 6555
If Cells(x, 1).Value = "CHM0123456" Then
outstring = outstring + vbCr + Cells(x, 2).Value

End If

Next
MsgBox (outstring)

End Function

Body:
I'm not sure what your definition of 'neat' is, but here is a VBA function that I consider very neat and also flexible and it's lightning fast (10k+ entires with no lag). You pass it the CHM you want to look for, then the range to look in. You can pass a third optional paramater to set how each entry is seperated. So in your case you could write (assuming your list is :

=ListUnique(B2, B2:B6555)

You can also use Char(10) as the third parameter to seperat by line breaks, etc.

Function ListUnique(ByVal search_text As String, _
                    ByVal cell_range As range, _
                    Optional seperator As String = ", ") As String

Application.ScreenUpdating = False
Dim result As String
Dim i as Long
Dim cell As range
Dim keys As Variant
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")

On Error Resume Next
For Each cell In cell_range
    If cell.Value = search_text Then
        dict.Add cell.Offset(, 1).Value, 1
    End If
Next

keys = dict.keys
For i = 0 To UBound(keys)
    result = result & (seperator & keys(i))
Next

If Len(result) <> 0 Then
    result = Right$(result, (Len(result) - Len(seperator)))
End If

ListUnique = result
Application.ScreenUpdating = True

End Function

How it works: It simple loops through your range looking for the search_string you give it. If it finds it, it adds it to a dictionary object (which will eliminate all dupes). You dump the results in an array then create a string out of them. Technically you can just pass it "B:B" as the search array if you aren't sure where the end of the column is and this function will still work just fine (1/5th of a second for scanning every cell in column B with 1000 unique hits returned).


问:
Flutter Firebase Messaging Crashing Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE
Recently we released android application targets to 31 which has reported more crashes (only Android OS 12 users) in Firebase Messaging (PendingIntent). When Application is in Pause/Background state on Notification Receive its crashing.
I've tried possible solutions but no luck still crashing. As i understood is we have to add PendingIntent.FLAG_IMMUTABLE on PendingIntent start activity but not getting any idea how to add or fix this.

If anyone faced same issue and fixed. Share solution for this.

Thanks in advance...

```<code>dependencies{
    implementation platform('com.google.firebase:firebase-bom')
    implementation 'com.google.firebase:firebase-messaging'
    implementation 'com.google.firebase:firebase-iid'
    implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
}
</code>```
```<code>E/AndroidRuntime( 7058): java.lang.IllegalArgumentException: com.package: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
E/AndroidRuntime( 7058): Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
E/AndroidRuntime( 7058):    at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:458)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:444)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:408)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createContentIntent(com.google.firebase:firebase-messaging@@20.3.0:125)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:9)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.DisplayNotification.handleNotification(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(com.google.firebase:firebase-messaging@@20.3.0:65)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(com.google.firebase:firebase-messaging@@20.3.0:44)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(com.google.firebase:firebase-messaging@@20.3.0:17)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(com.google.firebase:firebase-messaging@@20.3.0:43)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(Unknown Source:6)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime( 7058):    at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement@@17.6.0:2)
E/AndroidRuntime( 7058):    at java.lang.Thread.run(Thread.java:920)
W/CrashlyticsCore( 7058): Cannot send reports. Settings are unavailable.
D/TransportRuntime.SQLiteEventStore( 7058): Storing event with priority=HIGHEST, name=FIREBASE_CRASHLYTICS_REPORT for destination cct
</code>```

答:
As per the official doc "If your app targets Android 12, you must specify the mutability of each PendingIntent object that your app creates. This additional requirement improves your app's security."

```<code>Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

PendingIntent contentIntent = PendingIntent.getActivity(context,NOTIFICATION_REQUEST_CODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
</code>```

we’re constructing a standard type of Intent that will open our app, and then simply wrapping that in a PendingIntent before adding it to our notification.In this case, since we have an exact action we know we want to perform, we construct a PendingIntent that cannot be modified by the app we pass it to by utilizing a flag called FLAG_IMMUTABLE.

Body:
Recently we released android application targets to 31 which has reported more crashes (only Android OS 12 users) in Firebase Messaging (PendingIntent). When Application is in Pause/Background state on Notification Receive its crashing.
I've tried possible solutions but no luck still crashing. As i understood is we have to add PendingIntent.FLAG_IMMUTABLE on PendingIntent start activity but not getting any idea how to add or fix this.

If anyone faced same issue and fixed. Share solution for this.

Thanks in advance...

dependencies{
    implementation platform('com.google.firebase:firebase-bom')
    implementation 'com.google.firebase:firebase-messaging'
    implementation 'com.google.firebase:firebase-iid'
    implementation 'com.google.firebase:firebase-analytics:17.4.4'
    implementation 'com.google.firebase:firebase-crashlytics:17.0.0'
}

E/AndroidRuntime( 7058): java.lang.IllegalArgumentException: com.package: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
E/AndroidRuntime( 7058): Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
E/AndroidRuntime( 7058):    at android.app.PendingIntent.checkFlags(PendingIntent.java:375)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:458)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:444)
E/AndroidRuntime( 7058):    at android.app.PendingIntent.getActivity(PendingIntent.java:408)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createContentIntent(com.google.firebase:firebase-messaging@@20.3.0:125)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.CommonNotificationBuilder.createNotificationInfo(com.google.firebase:firebase-messaging@@20.3.0:9)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.DisplayNotification.handleNotification(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.dispatchMessage(com.google.firebase:firebase-messaging@@20.3.0:65)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.passMessageIntentToSdk(com.google.firebase:firebase-messaging@@20.3.0:44)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleMessageIntent(com.google.firebase:firebase-messaging@@20.3.0:27)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.FirebaseMessagingService.handleIntent(com.google.firebase:firebase-messaging@@20.3.0:17)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService.lambda$processIntent$0$EnhancedIntentService(com.google.firebase:firebase-messaging@@20.3.0:43)
E/AndroidRuntime( 7058):    at com.google.firebase.messaging.EnhancedIntentService$$Lambda$0.run(Unknown Source:6)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/AndroidRuntime( 7058):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/AndroidRuntime( 7058):    at com.google.android.gms.common.util.concurrent.zza.run(com.google.android.gms:play-services-basement@@17.6.0:2)
E/AndroidRuntime( 7058):    at java.lang.Thread.run(Thread.java:920)
W/CrashlyticsCore( 7058): Cannot send reports. Settings are unavailable.
D/TransportRuntime.SQLiteEventStore( 7058): Storing event with priority=HIGHEST, name=FIREBASE_CRASHLYTICS_REPORT for destination cct

Body:
As per the official doc "If your app targets Android 12, you must specify the mutability of each PendingIntent object that your app creates. This additional requirement improves your app's security."

Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

PendingIntent contentIntent = PendingIntent.getActivity(context,NOTIFICATION_REQUEST_CODE, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

we’re constructing a standard type of Intent that will open our app, and then simply wrapping that in a PendingIntent before adding it to our notification.In this case, since we have an exact action we know we want to perform, we construct a PendingIntent that cannot be modified by the app we pass it to by utilizing a flag called FLAG_IMMUTABLE.


问:
What happens if you check for < condition in ternary or conditional operator(x < y ? num1 : num2) in c, but the input value is equal
So I was just trying to write a C code for comparing numbers, which one of the three number is largest and which one is the smallest.

Then I found that I can use the ternary operator (ex: x < y ? num1 : num2), so I thought yeah okay this will work and then I wrote this code:

```<code>#include <stdio.h>
int main(){
int num1, num2, num3, largest, smallest;

printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);

//largest among three integers.

largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("\nThe largest among the three is: %d", largest);

//smallest among three integers

smallest = num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
printf("\nThe smallest among the three is: %d", smallest);

return 0;
}
</code>```

So, if I give input like num1 = 10, num2 = 20 and num3 = 30, then the output is

```<code>Enter three integers: 10 20 30

The largest among the three is: 30
The smallest among the three is: 10
</code>```

But what happens when all these numbers are equal? Will the condition of the Ternary operator be true or false?

```<code>Enter three integers: 20 20 20

The largest among the three is: 20
The smallest among the three is: 20
</code>```

I don't know what the condition but the program works fine nothing wrong the output is correct.

I am using this on windows 10 latest and gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0

I am sorry if this is a lame question but I didn't found anything about this.

答:
Generally, boolean algebra goes: the opposite of a > b ("a greater than b") is a <= b ("a less or equal to b").

If you want to cover larger than, smaller than and equal, then you'd need something like this pseudo code:

```<code>(a < b) ? smaller : ( (a > b) ? larger : equal )
</code>```

Which is just an obscure and unreadable way of the equivalent preferred code:

```<code>if(a < b)
{}
else if(a > b)
{}
else // equal
{}
</code>```

Always use if-else if chains over ?: chains unless you have specialized requirements, such as when writing function-like macros.

Body:
So I was just trying to write a C code for comparing numbers, which one of the three number is largest and which one is the smallest.

Then I found that I can use the ternary operator (ex: x < y ? num1 : num2), so I thought yeah okay this will work and then I wrote this code:

#include <stdio.h>
int main(){
int num1, num2, num3, largest, smallest;

printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);

//largest among three integers.

largest = num1 > num2 ? (num1 > num3 ? num1 : num3) : (num2 > num3 ? num2 : num3);
printf("\nThe largest among the three is: %d", largest);

//smallest among three integers

smallest = num1 < num2 ? (num1 < num3 ? num1 : num3) : (num2 < num3 ? num2 : num3);
printf("\nThe smallest among the three is: %d", smallest);

return 0;
}

So, if I give input like num1 = 10, num2 = 20 and num3 = 30, then the output is

Enter three integers: 10 20 30

The largest among the three is: 30
The smallest among the three is: 10

But what happens when all these numbers are equal? Will the condition of the Ternary operator be true or false?

Enter three integers: 20 20 20

The largest among the three is: 20
The smallest among the three is: 20

I don't know what the condition but the program works fine nothing wrong the output is correct.

I am using this on windows 10 latest and gcc.exe (MinGW.org GCC-6.3.0-1) 6.3.0

I am sorry if this is a lame question but I didn't found anything about this.

Body:
Generally, boolean algebra goes: the opposite of a > b ("a greater than b") is a <= b ("a less or equal to b").

If you want to cover larger than, smaller than and equal, then you'd need something like this pseudo code:

(a < b) ? smaller : ( (a > b) ? larger : equal )

Which is just an obscure and unreadable way of the equivalent preferred code:

if(a < b)
{}
else if(a > b)
{}
else // equal
{}

Always use if-else if chains over ?: chains unless you have specialized requirements, such as when writing function-like macros.


问:
How to use openpgp.js on node.js (Cloudflare worker) - Error Uncaught ReferenceError: navigator is not defined?
I have a Cloudflare Worker (created from the Typescript template and with the build config barely changed) that needs to use openpgp.js, which as this link shows, is supposed to be supported when running on Node.js.

When I build it with npm run build it seems to work fine, but then when I try to build with wrangler dev, it throws this error:

```<code>webpack 5.38.1 compiled successfully in 1147 ms
Error: Something went wrong with the request to Cloudflare...
Uncaught ReferenceError: navigator is not defined
  at line 237 in ./node_modules/openpgp/dist/lightweight/openpgp.min.mjs
  at line 827 in __webpack_require__
  at line 625 in ./src/crypto.ts
  at line 827 in __webpack_require__
  at line 749 in ./src/handler.ts
  at line 827 in __webpack_require__
  at line 1064
  at line 1069
  at line 1071
 [API code: 10021]
</code>```

This question looks similar, but the solutions there don't seem to apply in my case.

One solution was to use browser-env to expose the global variable navigator to the node.js environment. When I tried that, I got an enormous error that ends like this:

```<code>ERROR in ./node_modules/window/node_modules/tough-cookie/lib/cookie.js 34:11-26
Module not found: Error: Can't resolve 'util' in '/Users/renato/programming/projects/renato-worker/node_modules/window/node_modules/tough-cookie/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
...
ERROR in ./node_modules/window/node_modules/tough-cookie/lib/memstore.js 35:11-26
Module not found: Error: Can't resolve 'util' in '/Users/renato/programming/projects/renato-worker/node_modules/window/node_modules/tough-cookie/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default
...

ERROR in /Users/renato/programming/projects/renato-worker/src/index.ts
./src/index.ts 4:23-36
[tsl] ERROR in /Users/renato/programming/projects/renato-worker/src/index.ts(4,24)
      TS7016: Could not find a declaration file for module 'browser-env'. '/Users/renato/programming/projects/renato-worker/node_modules/browser-env/src/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/browser-env` if it exists or add a new declaration (.d.ts) file containing `declare module 'browser-env';`
</code>```

Trying to install types/browser-env:

```<code>▶ npm i --save-dev @types/browser-env
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@types%2fbrowser-env - Not found
</code>```

Hm, I think this is not what I want anyway, in the docs for browser-env there's a stern warning against doing this:

https://github.com/jsdom/jsdom/wiki/Don't-stuff-jsdom-globals-onto-the-Node-global

A common antipattern we see when people use jsdom is copying globals from a jsdom window onto the Node.js global, and then trying to run the code---intended for a browser---inside Node.js. This is very bad and you should not do it.

The other suggested solution, to use detect-node doesn't apply in my case, I think, because it's not my code that needs to run something in case it's a browser or not... it's a compilation problem it seems, when running the build.

So I am completely stuck.

Is anyone more familiar with the myriad tools involved (webpack, node.js, Typescript, browser APIs, wrangler, Cloudflare API) able to tell me at least which one is causing this and what I can try to fix it?

答:
After a long struggle, I found that the problem originates from the way Cloudflare validates the Javascript code before deploying it on its environment (which it does even for running preview mode).

It does not allow certain APIs to be used, including the navigator object which is not usually available in backend Javascript.

This is a problem when using openpgp.js because it uses navigator to identify the userAgent and the number of cores available, unfortunately.

I made a pull request to move access to the navigator to a single place where it could be easily replaced with tools like webpack, but that PR was denied because it was not even necessary, you can just replace navigator with {} for example, and everything should work.

Check the pull request for more details, but in summary, add something like this to your webpack.config.json file:

  plugins: [
    new webpack.ProvidePlugin({
      'navigator': ['{}'],
    }),
  ]
```

The author of openpgp.js seems keen to remove the dependency on navigator in future versions, so in the near future, this hack may no longer be needed!

Body:
I have a Cloudflare Worker (created from the Typescript template and with the build config barely changed) that needs to use openpgp.js, which as this link shows, is supposed to be supported when running on Node.js.

When I build it with npm run build it seems to work fine, but then when I try to build with wrangler dev, it throws this error:

webpack 5.38.1 compiled successfully in 1147 ms
Error: Something went wrong with the request to Cloudflare...
Uncaught ReferenceError: navigator is not defined
  at line 237 in ./node_modules/openpgp/dist/lightweight/openpgp.min.mjs
  at line 827 in __webpack_require__
  at line 625 in ./src/crypto.ts
  at line 827 in __webpack_require__
  at line 749 in ./src/handler.ts
  at line 827 in __webpack_require__
  at line 1064
  at line 1069
  at line 1071
 [API code: 10021]

This question looks similar, but the solutions there don't seem to apply in my case.

One solution was to use browser-env to expose the global variable navigator to the node.js environment. When I tried that, I got an enormous error that ends like this:

ERROR in ./node_modules/window/node_modules/tough-cookie/lib/cookie.js 34:11-26
Module not found: Error: Can't resolve 'util' in '/Users/renato/programming/projects/renato-worker/node_modules/window/node_modules/tough-cookie/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
...
ERROR in ./node_modules/window/node_modules/tough-cookie/lib/memstore.js 35:11-26
Module not found: Error: Can't resolve 'util' in '/Users/renato/programming/projects/renato-worker/node_modules/window/node_modules/tough-cookie/lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default
...

ERROR in /Users/renato/programming/projects/renato-worker/src/index.ts
./src/index.ts 4:23-36
[tsl] ERROR in /Users/renato/programming/projects/renato-worker/src/index.ts(4,24)
      TS7016: Could not find a declaration file for module 'browser-env'. '/Users/renato/programming/projects/renato-worker/node_modules/browser-env/src/index.js' implicitly has an 'any' type.
  Try `npm i --save-dev @types/browser-env` if it exists or add a new declaration (.d.ts) file containing `declare module 'browser-env';`

Trying to install types/browser-env:

▶ npm i --save-dev @types/browser-env
npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@types%2fbrowser-env - Not found

Hm, I think this is not what I want anyway, in the docs for browser-env there's a stern warning against doing this:

https://github.com/jsdom/jsdom/wiki/Don't-stuff-jsdom-globals-onto-the-Node-global

A common antipattern we see when people use jsdom is copying globals from a jsdom window onto the Node.js global, and then trying to run the code---intended for a browser---inside Node.js. This is very bad and you should not do it.

The other suggested solution, to use detect-node doesn't apply in my case, I think, because it's not my code that needs to run something in case it's a browser or not... it's a compilation problem it seems, when running the build.

So I am completely stuck.

Is anyone more familiar with the myriad tools involved (webpack, node.js, Typescript, browser APIs, wrangler, Cloudflare API) able to tell me at least which one is causing this and what I can try to fix it?

Body:
After a long struggle, I found that the problem originates from the way Cloudflare validates the Javascript code before deploying it on its environment (which it does even for running preview mode).

It does not allow certain APIs to be used, including the navigator object which is not usually available in backend Javascript.

This is a problem when using openpgp.js because it uses navigator to identify the userAgent and the number of cores available, unfortunately.

I made a pull request to move access to the navigator to a single place where it could be easily replaced with tools like webpack, but that PR was denied because it was not even necessary, you can just replace navigator with {} for example, and everything should work.

Check the pull request for more details, but in summary, add something like this to your webpack.config.json file:

  plugins: [
    new webpack.ProvidePlugin({
      'navigator': ['{}'],
    }),
  ]

The author of openpgp.js seems keen to remove the dependency on navigator in future versions, so in the near future, this hack may no longer be needed!


问:
Heatmap of a correlation matrix
I want to create a heatmap of a correlation matrix of size 3*3. Each box of the heatmap represent the absolute value of a correlation. I have to use a colour gradient to represent the absolute value of the correlation : for the absolute value of the correlation from 0 to 0.75, I have to use a red colour gradient ; for the absolute value of the correlation from 0.75 to 0.85, I have to use a yellow colour gradient ; for the absolute value of the correlation from 0.85 to 1, I have to use a green colour gradient. I think I can use the ggplot function to create this heatmap. However, I do not manage to do the colour gradient and I need help to create this heatmap with this colour gradient.</p>

答:
I create the heatmapMatCor function which enables us to create the heatmap.
The mat_cor_comp parameter is the correlation matrix.</p>
```<code>heatmapMatCor <-function(mat_cor_comp,
                         limit = c(0, 1),
                         midpoint = 0.8)
{
names_blocks = rownames(mat_cor_comp)
vec_cor_comp = as.vector(abs(mat_cor_comp))
data_comp = data.frame(block1 = rep(names_blocks, dim(mat_cor_comp)[2]),
                         block2 = rep(names_blocks,
                                      each =    dim(mat_cor_comp)[1]),
                         value = vec_cor_comp)

ggplot(data = data_comp, aes(block1, block2, fill = value))+
geom_tile(color = "white")+
scale_colour_gradient2(low = "blue", high = "red", mid = "yellow",
                           midpoint = midpoint, limits = limit,
                           name="Pearson\nCorrelation") +
theme_minimal()+
theme(axis.text.x = element_text(angle = 45, vjust = 1,
                                     size = 12, hjust = 1))+
coord_fixed()

}
</code>```

Title: Heatmap of a correlation matrix

Body:
I create the heatmapMatCor function which enables us to create the heatmap.
The mat_cor_comp parameter is the correlation matrix.

heatmapMatCor <-function(mat_cor_comp,
                         limit = c(0, 1),
                         midpoint = 0.8)
{
names_blocks = rownames(mat_cor_comp)
vec_cor_comp = as.vector(abs(mat_cor_comp))
data_comp = data.frame(block1 = rep(names_blocks, dim(mat_cor_comp)[2]),
                         block2 = rep(names_blocks,
                                      each =    dim(mat_cor_comp)[1]),
                         value = vec_cor_comp)

ggplot(data = data_comp, aes(block1, block2, fill = value))+
geom_tile(color = "white")+
scale_colour_gradient2(low = "blue", high = "red", mid = "yellow",
                           midpoint = midpoint, limits = limit,
                           name="Pearson\nCorrelation") +
theme_minimal()+
theme(axis.text.x = element_text(angle = 45, vjust = 1,
                                     size = 12, hjust = 1))+
coord_fixed()

}


问:
Not able to Push React code in Github master
Not able to Push React code in Github master due to larger size.

```<code>git push -u origin master
Enumerating objects: 41025, done.
Counting objects: 100% (41025/41025), done.
Delta compression using up to 4 threads
Compressing objects: 100% (25146/25146), done.
Writing objects: 100% (41025/41025), 190.44 MiB | 5.20 MiB/s, done.
Total 41025 (delta 14626), reused 41025 (delta 14626), pack-reused 0
remote: Resolving deltas: 100% (14626/14626), done.
remote: warning: File node_modules/.cache/default-development/20.pack is 54.54 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File node_modules/.cache/default-development/101.pack is 79.78 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: Trace: 8dfc24e220167542a79ef96d0c9f68e0381fecd6e731ab98b3ad1c16716d2e46
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File node_modules/.cache/default-development/0.pack is 164.76 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File node_modules/.cache/default-development/65.pack is 164.10 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To https://github.com/u121/DemoPage.git
 ! [remote rejected]   master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/u121/DemoPage.git'
</code>```

Getting this error when i use git push -u origin master  in app

答:
On top of the above answer, I see your repo doesn't have master on Github. Just double-check if this was intentional or your repo has protection that prevents you from pushing to master

Git push error pre-receive hook declined

NB: I don't have access to comment.

Body:
Not able to Push React code in Github master due to larger size.

git push -u origin master
Enumerating objects: 41025, done.
Counting objects: 100% (41025/41025), done.
Delta compression using up to 4 threads
Compressing objects: 100% (25146/25146), done.
Writing objects: 100% (41025/41025), 190.44 MiB | 5.20 MiB/s, done.
Total 41025 (delta 14626), reused 41025 (delta 14626), pack-reused 0
remote: Resolving deltas: 100% (14626/14626), done.
remote: warning: File node_modules/.cache/default-development/20.pack is 54.54 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: warning: File node_modules/.cache/default-development/101.pack is 79.78 MB; this is larger than GitHub's recommended maximum file size of 50.00 MB
remote: error: Trace: 8dfc24e220167542a79ef96d0c9f68e0381fecd6e731ab98b3ad1c16716d2e46
remote: error: See http://git.io/iEPt8g for more information.
remote: error: File node_modules/.cache/default-development/0.pack is 164.76 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: File node_modules/.cache/default-development/65.pack is 164.10 MB; this exceeds GitHub's file size limit of 100.00 MB
remote: error: GH001: Large files detected. You may want to try Git Large File Storage - https://git-lfs.github.com.
To https://github.com/u121/DemoPage.git
 ! [remote rejected]   master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://github.com/u121/DemoPage.git'

Getting this error when i use git push -u origin master  in app


问:
How to get number of slot in a VueJS component
I need my component to get slots number are occupied by the parent component

For example:

This is the component:

```<code><template>
  <div>
    <slot/>
  </div>
</template>
<script>
  name: 'comp',
  data() {
    return {
      nslot: 0
    }
  }
</script>
</code>```

This is the parent

```<code><template>
  <div>
    <component>
      <button slot=""></button>
      <button slot=""></button>
      <button slot=""></button>
      <button slot=""></button>
      ...
    <component/>
  </div>
</template>
<script>
  name: 'comp'
</script>
</code>```

How i can do? I want to get number of used slot in the "nslot" variable

I prefer using method, (in the component) like:

```<code>mounthed() {
  this.nslot = this.getslotnumber()
}
</code>```

答:
You should use a scoped slot like :

<template>

    <slot :nslot="nslot" />

</template>

```
<p>in parent :</p>
<pre class="lang-html prettyprint-override"><code><template>
  <div>
    <compt v-slot="{nslot}">
      <button :slot="nslot">{{nslot}}</button>
    <comp/>
  </div>
</template>
<script>
  name: 'comp'
</script>

</code>```

Body:
I need my component to get slots number are occupied by the parent component

For example:

This is the component:

<template>

    <slot/>

</template>

This is the parent

<template>

    <component>
      <button slot=""></button>
      <button slot=""></button>
      <button slot=""></button>
      <button slot=""></button>
      ...
    <component/>

</template>

How i can do? I want to get number of used slot in the "nslot" variable

I prefer using method, (in the component) like:

mounthed() {
  this.nslot = this.getslotnumber()
}

Body:
You should use a scoped slot like :

<template>
  <div>
    <slot :nslot="nslot" />
  </div>
</template>
<script>
  name: 'comp',
  data() {
    return {
      nslot: 0
    }
  }
</script>

in parent :

<template>
  <div>
    <compt v-slot="{nslot}">
      <button :slot="nslot">{{nslot}}</button>
    <comp/>
  </div>
</template>
<script>
  name: 'comp'
</script>


问:
How can I dynamically set the array object to java object
I am new to java and I am stuck at one place.
I am taking xml request which is coming in array.

```<code><PassengersDetails>
 <Passenger>
  <passesngerName>ABC</passesngerName>
  <passengerAge>25</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>DEF</passesngerName>
  <passengerAge>28</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>GHI</passesngerName>
  <passengerAge>48</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>KLM</passesngerName>
  <passengerAge>18</passengerAge>
 </Passenger>
</PassengersDetails>
</code>```

My xml object is getting turned into array like below.

```<code>Passenger [] passenger= passengersDetails.getPassenger();
</code>```

And my java object looks like

```<code>class Passenger {
passengerName1;
passengerAge1;
passengerName2;
passengerAge2;
passengerName3;
passengerAge3;
passengerName4;
passengerAge4;
}
</code>```

with setter and getter.

I wanted to set all the data from array in java object.
I am able to set it individually after checking if array is preset or not.

```<code>if(arr[0] != null){
setPassengerName1 = arr[0].getPassengerName;
setPassengerAge1 = arr[0].getPassengerAge;
}
if(arr[1] != null){
setPassengerName2 = arr[1].getPassengerName;
setPassengerAge2 = arr[1].getPassengerAge;
}....
</code>```

How can I set passenger array into Passenger java object mentioned above.

But I wanted to know if there is any other way we can do this dynamically.

Something like in the same loop and setting it dynamically.

答:
Create a model class Passenger to hold the name and age only. Then you create an array that holds Passenger objects.

You then use:

```<code>getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))
</code>```

to iterate through string resources, given you know how many passengers there are.

Body:
I am new to java and I am stuck at one place.
I am taking xml request which is coming in array.

<PassengersDetails>
 <Passenger>
  <passesngerName>ABC</passesngerName>
  <passengerAge>25</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>DEF</passesngerName>
  <passengerAge>28</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>GHI</passesngerName>
  <passengerAge>48</passengerAge>
 </Passenger>
 <Passenger>
  <passesngerName>KLM</passesngerName>
  <passengerAge>18</passengerAge>
 </Passenger>
</PassengersDetails>

My xml object is getting turned into array like below.

Passenger [] passenger= passengersDetails.getPassenger();

And my java object looks like

class Passenger {
passengerName1;
passengerAge1;
passengerName2;
passengerAge2;
passengerName3;
passengerAge3;
passengerName4;
passengerAge4;
}

with setter and getter.

I wanted to set all the data from array in java object.
I am able to set it individually after checking if array is preset or not.

if(arr[0] != null){
setPassengerName1 = arr[0].getPassengerName;
setPassengerAge1 = arr[0].getPassengerAge;
}
if(arr[1] != null){
setPassengerName2 = arr[1].getPassengerName;
setPassengerAge2 = arr[1].getPassengerAge;
}....

How can I set passenger array into Passenger java object mentioned above.

But I wanted to know if there is any other way we can do this dynamically.

Something like in the same loop and setting it dynamically.

Body:
Create a model class Passenger to hold the name and age only. Then you create an array that holds Passenger objects.

You then use:

getResources().getString(getResources().getIdentifier("propertyName", "string", getPackageName()))

to iterate through string resources, given you know how many passengers there are.


问:
Rosyln.SDK missing from Visual Studio layout
I'm creating an offline network installer for VS2019, combined with VS config export/import to mirror my VS install between two machines.
I've selected specific workflows to reduce the layout from 50->15ish GB but when trying to install I get:

I cannot for the life of me see where this comes from.

It is not listed in https://learn.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-professional?view=vs-2019

It is not included in my exported vsconfig file:

{   "version": "1.0",   "components": [
"Microsoft.VisualStudio.Component.CoreEditor",
"Microsoft.VisualStudio.Workload.CoreEditor",
"Microsoft.NetCore.Component.Runtime.5.0",
"Microsoft.NetCore.Component.Runtime.3.1",
"Microsoft.NetCore.Component.SDK",
"Microsoft.VisualStudio.Component.NuGet",
"Microsoft.Net.Component.4.6.1.TargetingPack",
"Microsoft.VisualStudio.Component.Roslyn.Compiler",
"Microsoft.VisualStudio.Component.Roslyn.LanguageServices",
"Microsoft.VisualStudio.Component.FSharp",
"Microsoft.ComponentGroup.ClickOnce.Publish",
"Microsoft.NetCore.Component.DevelopmentTools",
"Microsoft.VisualStudio.Component.FSharp.WebTemplates",
"Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions",
"Microsoft.VisualStudio.Component.DockerTools",
"Microsoft.NetCore.Component.Web",
"Microsoft.Net.Component.4.8.SDK",
"Microsoft.Net.Component.4.7.2.TargetingPack",
"Microsoft.Net.ComponentGroup.DevelopmentPrerequisites",
"Microsoft.VisualStudio.Component.TypeScript.4.3",
"Microsoft.VisualStudio.Component.JavaScript.TypeScript",
"Microsoft.VisualStudio.Component.JavaScript.Diagnostics",
"Microsoft.Component.MSBuild",
"Microsoft.VisualStudio.Component.TextTemplating",
"Component.Microsoft.VisualStudio.RazorExtension",
"Microsoft.VisualStudio.Component.IISExpress",
"Microsoft.VisualStudio.Component.SQL.ADAL",
"Microsoft.VisualStudio.Component.SQL.LocalDB.Runtime",
"Microsoft.VisualStudio.Component.Common.Azure.Tools",
"Microsoft.VisualStudio.Component.SQL.CLR",
"Microsoft.VisualStudio.Component.MSODBC.SQL",
"Microsoft.VisualStudio.Component.MSSQL.CMDLnUtils",
"Microsoft.VisualStudio.Component.ManagedDesktop.Core",
"Microsoft.Net.Component.4.5.2.TargetingPack",
"Microsoft.Net.Component.4.5.TargetingPack",
"Microsoft.VisualStudio.Component.SQL.SSDT",
"Microsoft.VisualStudio.Component.SQL.DataSources",
"Component.Microsoft.Web.LibraryManager",
"Component.Microsoft.WebTools.BrowserLink.WebLivePreview",
"Microsoft.VisualStudio.ComponentGroup.Web",
"Microsoft.VisualStudio.Component.Web",
"Microsoft.Net.Component.4.TargetingPack",
"Microsoft.Net.Component.4.5.1.TargetingPack",
"Microsoft.Net.Component.4.6.TargetingPack",
"Microsoft.Net.ComponentGroup.TargetingPacks.Common",
"Component.Microsoft.VisualStudio.Web.AzureFunctions",
"Microsoft.VisualStudio.ComponentGroup.AzureFunctions",
"Microsoft.VisualStudio.Component.Azure.Compute.Emulator",
"Microsoft.VisualStudio.Component.Azure.Storage.Emulator",
"Microsoft.VisualStudio.Component.Azure.ClientLibs",
"Microsoft.VisualStudio.Component.Azure.AuthoringTools",
"Microsoft.VisualStudio.Component.CloudExplorer",
"Microsoft.VisualStudio.ComponentGroup.Web.CloudTools",
"Microsoft.VisualStudio.Component.DiagnosticTools",
"Microsoft.VisualStudio.Component.EntityFramework",
"Microsoft.VisualStudio.Component.AppInsights.Tools",
"Microsoft.VisualStudio.Component.WebDeploy",
"Microsoft.VisualStudio.Component.Debugger.JustInTime",
"Component.Microsoft.VisualStudio.LiveShare",
"Microsoft.VisualStudio.Component.WslDebugging",
"Microsoft.VisualStudio.Component.IntelliCode",
"Microsoft.Net.Core.Component.SDK.2.1",
"Microsoft.Component.PythonTools",
"Microsoft.VisualStudio.Component.VC.CoreIde",
"Microsoft.VisualStudio.Component.Windows10SDK",
"Microsoft.VisualStudio.Component.VC.Tools.x86.x64",
"Microsoft.VisualStudio.Component.Graphics.Tools",
"Microsoft.VisualStudio.Component.VC.DiagnosticTools",
"Microsoft.VisualStudio.Component.Windows10SDK.19041",
"Microsoft.ComponentGroup.PythonTools.NativeDevelopment",
"Microsoft.Component.PythonTools.Miniconda",
"Microsoft.Component.PythonTools.Web",
"Component.CPython39.x64",
"Microsoft.VisualStudio.Workload.Python",
"Microsoft.VisualStudio.Component.Node.Tools",
"Microsoft.VisualStudio.Workload.Node",
"Microsoft.VisualStudio.Component.ManagedDesktop.Prerequisites",
"Microsoft.ComponentGroup.Blend",
"Microsoft.VisualStudio.ComponentGroup.MSIX.Packaging",
"Microsoft.VisualStudio.Workload.ManagedDesktop",
"Microsoft.VisualStudio.Component.VC.Redist.14.Latest",
"Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core",
"Microsoft.VisualStudio.ComponentGroup.WebToolsExtensions.CMake",
"Microsoft.VisualStudio.Component.VC.CMake.Project",
"Microsoft.VisualStudio.Component.VC.ATL",
"Microsoft.VisualStudio.Component.VC.TestAdapterForBoostTest",
"Microsoft.VisualStudio.Component.VC.TestAdapterForGoogleTest",
"Microsoft.VisualStudio.Component.VC.ATLMFC",
"Microsoft.VisualStudio.Component.VC.ASAN",
"Microsoft.VisualStudio.Component.Windows10SDK.18362",
"Microsoft.VisualStudio.Workload.NativeDesktop",
"Microsoft.Component.NetFX.Native",
"Microsoft.VisualStudio.ComponentGroup.UWP.NetCoreAndStandard",
"Microsoft.VisualStudio.Component.Graphics",
"Microsoft.VisualStudio.ComponentGroup.UWP.Xamarin",
"Microsoft.VisualStudio.ComponentGroup.UWP.Support",
"Microsoft.VisualStudio.Workload.Universal",
"Microsoft.Component.CodeAnalysis.SDK",
"Microsoft.VisualStudio.Workload.NetCoreTools",
"Microsoft.VisualStudio.Component.Git",
"Microsoft.NetCore.ComponentGroup.DevelopmentTools.2.1",
"Microsoft.NetCore.ComponentGroup.Web.2.1"   ] }

I can see it exists in a full layout and doesn't in my custom layout but not which workflow it comes from. Or why it hasn't automatically been added, isn't this a core component?

When I try to --add Roslyn.SDK to my layout using the VS installer I get the error Error: The package 'Roslyn.SDK' is not recognized.

So where does it come from and how can I get it in a custom layout? Can I even hack it into my layout somehow?

How can I find which workflow/component to add to get this included?

答:
I eventually found that Rosyln.SDK is used by several workloads, as a non-documented dependency. Such as:

Visual Studio extension development ID:
Microsoft.VisualStudio.Workload.VisualStudioExtension Description:
Create add-ons and extensions for Visual Studio, including new
commands, code analyzers and tool windows.

ADding this resolves the issues I have but leaves me thinking it should have been there already for C#/.Net development.


问:
NameError: name 'array' is not defined in python
I get NameError: name 'array' is not defined in python error when I want to create array, for example:

```<code>a = array([1,8,3])
</code>```

What am I doing wrong? How to use arrays?

答:
For basic Python, you should just use a list (as others have already noted).

If you are trying to use NumPy and you want a NumPy array:

```<code>import numpy as np

a = np.array([1,8,3])
</code>```

If you don't know what NumPy is, you probably just want the list.

Body:
I get NameError: name 'array' is not defined in python error when I want to create array, for example:

a = array([1,8,3])

What am I doing wrong? How to use arrays?

Body:
For basic Python, you should just use a list (as others have already noted).

If you are trying to use NumPy and you want a NumPy array:

import numpy as np

a = np.array([1,8,3])

If you don't know what NumPy is, you probably just want the list.


问:
Stimulus nested (child) targets
Is it possible (and is it appropriate) to use nested/child targets of parent target?

For example i have “N+“ menu items, each item (wrapper) contain link and list.
I could add data-main-menu-target="menuItem" to each of parent items and then iterate over them in controller loop using this.menuItemTargets.forEach(...)

But what's the best practice to find menu-item-link and menu-item-list for each menu-item target on each loop iteration?

In general i could add targets also for those elements, e.g. menuItemLink & menuItemList, but how then i could select them from parent menuItem target, Is it possible to do something like menuItemTarget.find(this.this.menuListTarget)?

To visualise the structure is the following:

```<code>data-controller="main-menu"
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....
</code>```

How then select "menuLink" for certain "menuItem" target on each loop?

答:
You could structure your controller so that you have one menu controller that gets used on both the root menu and also the sub-menus within them. This could be recursively accessed from whatever is deemed to to be the root.

Example Code

In the HTML below we have a nav which contains ul for a menu, each child should be an item target.

Within each item we may have a link target OR another sub-menu which itself is another menu controller and the pattern continues.

      Team Settings

          Members

          Plugins

          Add a member

      Invitations

      Cloud Storage Environment Settings

```
<ul>
<li>In our controller we first determine if this controller's instance is the root, simply by checking <code>this.hasRootTarget</code>.</li>
<li>Controllers only get access to their 'scoped' elements so the root can only 'see' the children outside of the nested <code>data-controller='menu'</code>.</li>
<li>We need to use <code>setTimeout</code> to wait for any sub-controllers to connect, there may be a nicer event propagation way to do this.</li>
<li>You can access a controller on an element via the <code>getControllerForElementAndIdentifier</code> method.</li>
<li>From here we can determine the menu structure as an array of either a <code>link</code> target OR a nested array which itself will contain the sub <code>link</code> targets.</li>
<li>We can use the Node.contains method to map through each <code>item</code> and see what links are 'contained' within it.</li>
<li>This approach could be refined to get you the structure you need to work with.</li>
</ul>
<pre class="lang-js prettyprint-override"><code>class MenuController extends Controller {
  static targets = ['item', 'link', 'root'];

  connect() {
    if (this.hasRootTarget) {
      setTimeout(() => {
        // must use setTimeout to ensure any sub-menus are connected
        // alternative approach would be to fire a 'ready' like event on submenus
        console.log('main menu', this.getMenuStructure());
      });
    }
  }

  getMenuStructure() {
    const links = this.linkTargets;

    return this.itemTargets.map((item) => {
      const child = item.firstElementChild;
      const subMenu = this.application.getControllerForElementAndIdentifier(
        child,
        this.identifier
      );
      const menuLinks = links.filter((link) => item.contains(link));
      return subMenu ? subMenu.getMenuStructure() : menuLinks;
    });
  }
}
</code>```

Notes

We are accessing the DOM via the firstElementChild and this may not be the way we want to do things in Stimulus, but you could simply add another target type of 'sub-menu' to be more explicit and follow the pattern of finding the 'link' within each item this way.

A reminder that you cannot put the data-controller="menu" on a data-menu-target="item" as this will remove the item from the parent scope. As per the docs on scopes.

that element and all of its children make up the controller’s scope.

Title: Stimulus nested (child) targets

Body:
Is it possible (and is it appropriate) to use nested/child targets of parent target?

For example i have “N+“ menu items, each item (wrapper) contain link and list.
I could add data-main-menu-target="menuItem" to each of parent items and then iterate over them in controller loop using this.menuItemTargets.forEach(...)

But what's the best practice to find menu-item-link and menu-item-list for each menu-item target on each loop iteration?

In general i could add targets also for those elements, e.g. menuItemLink & menuItemList, but how then i could select them from parent menuItem target, Is it possible to do something like menuItemTarget.find(this.this.menuListTarget)?

To visualise the structure is the following:

data-controller="main-menu"
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....
    data-main-menu-target="menuItem"
        data-main-menu-target="menuLink"
        data-main-menu-target="menuList"
....

How then select "menuLink" for certain "menuItem" target on each loop?

Body:
You could structure your controller so that you have one menu controller that gets used on both the root menu and also the sub-menus within them. This could be recursively accessed from whatever is deemed to to be the root.

Example Code

In the HTML below we have a nav which contains ul for a menu, each child should be an item target.

Within each item we may have a link target OR another sub-menu which itself is another menu controller and the pattern continues.

<nav>
  <ul class="menu-list" data-controller="menu" data-menu-target="root">
    <li data-menu-target="item">
      <a data-menu-target="link">Team Settings</a>
    </li>
    <li data-menu-target="item">
      <ul data-controller="menu">
        <li data-menu-target="item">
          <a data-menu-target="link">Members</a>
        </li>
        <li data-menu-target="item">
          <a data-menu-target="link">Plugins</a>
        </li>
        <li data-menu-target="item">
          <a data-menu-target="link">Add a member</a>
        </li>
      </ul>
    </li>
    <li data-menu-target="item">
      <a data-menu-target="link">Invitations</a>
    </li>
    <li data-menu-target="item">
      <a data-menu-target="link">Cloud Storage Environment Settings</a>
    </li>
  </ul>
</nav>

In our controller we first determine if this controller's instance is the root, simply by checking this.hasRootTarget.

Controllers only get access to their 'scoped' elements so the root can only 'see' the children outside of the nested data-controller='menu'.

We need to use setTimeout to wait for any sub-controllers to connect, there may be a nicer event propagation way to do this.

You can access a controller on an element via the getControllerForElementAndIdentifier method.

From here we can determine the menu structure as an array of either a link target OR a nested array which itself will contain the sub link targets.

We can use the Node.contains method to map through each item and see what links are 'contained' within it.

This approach could be refined to get you the structure you need to work with.

class MenuController extends Controller {
  static targets = ['item', 'link', 'root'];

  connect() {
    if (this.hasRootTarget) {
      setTimeout(() => {
        // must use setTimeout to ensure any sub-menus are connected
        // alternative approach would be to fire a 'ready' like event on submenus
        console.log('main menu', this.getMenuStructure());
      });
    }
  }

  getMenuStructure() {
    const links = this.linkTargets;

    return this.itemTargets.map((item) => {
      const child = item.firstElementChild;
      const subMenu = this.application.getControllerForElementAndIdentifier(
        child,
        this.identifier
      );
      const menuLinks = links.filter((link) => item.contains(link));
      return subMenu ? subMenu.getMenuStructure() : menuLinks;
    });
  }
}

Notes

We are accessing the DOM via the firstElementChild and this may not be the way we want to do things in Stimulus, but you could simply add another target type of 'sub-menu' to be more explicit and follow the pattern of finding the 'link' within each item this way.

A reminder that you cannot put the data-controller="menu" on a data-menu-target="item" as this will remove the item from the parent scope. As per the docs on scopes.

that element and all of its children make up the controller’s scope.


问:
Property in type is not assignable to the same property in base type - Typescript bug?
Typescript complains because somehow the type of the abstract property is lost when extending. Is this a bug or am I doing something wrong?

```<code>type A = {
    bar: number,
    krass: Array<string>,
}

abstract class Foo<T> {
    protected abstract arr: (keyof T & string)[];
}

class Bar extends Foo<A> {
    arr = ["bar", "krass"];
}
</code>```

Error msg:

```<code>Property 'arr' in type 'Bar' is not assignable to the same property in base type 'Foo<A>'.
  Type 'string[]' is not assignable to type '("bar" | "krass")[]'.
    Type 'string' is not assignable to type '"bar" | "krass"'.
</code>```

答:
This is not a bug. It is by design. Members of derived classes are not contextually typed by the base class, so typescript will infer types based on whatever you are initializing with. This was discussed but I don't think it will get implemented anytime soon.

You can specify the type again in the derived class, or you could use an index access type to get the type from the base class:

```<code>class Bar extends Foo<A> {
    arr: Foo<A>['arr'] = ["bar", "krass"];
}
</code>```

Playground Link

Body:
Typescript complains because somehow the type of the abstract property is lost when extending. Is this a bug or am I doing something wrong?

type A = {
    bar: number,
    krass: Array<string>,
}

abstract class Foo<T> {
    protected abstract arr: (keyof T & string)[];
}

class Bar extends Foo {
    arr = ["bar", "krass"];
}

Error msg:

Property 'arr' in type 'Bar' is not assignable to the same property in base type 'Foo'.
  Type 'string[]' is not assignable to type '("bar" | "krass")[]'.
    Type 'string' is not assignable to type '"bar" | "krass"'.

Body:
This is not a bug. It is by design. Members of derived classes are not contextually typed by the base class, so typescript will infer types based on whatever you are initializing with. This was discussed but I don't think it will get implemented anytime soon.

You can specify the type again in the derived class, or you could use an index access type to get the type from the base class:

class Bar extends Foo<A> {
    arr: Foo<A>['arr'] = ["bar", "krass"];
}

Playground Link


问:
How to customize validation message for model?
I have a class TestClass and I want to customize the validation message instead of default one.

TestClass is the post model in the controller which inherits from ControllerBase.

Here is what I've tried:

TestClass.cs

```<code>public class TestClass
{
    [TestAtrribute(1.00, 99.99)]
    public double TestNumber { get; set; }
}
</code>```

TestAttribute.cs

```<code>public class TestAttribute : ValidationAttribute
{
    private double _min;
    private double _max;

    public TestAttribute(double min, double max)
    {
        _min = min;
        _max = max;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var error = $"{value} is invalid, must be between {_min} and {_max}";
        try
        {
            var convertNum = Convert.ToDouble(value);
            if (convertNum < _min || convertNum > _max)
                return new ValidationResult(errorMessage);
        }
        catch (Exception)
        {
            return new ValidationResult(error);
        }

        return ValidationResult.Success;
    }
}
</code>```

However, when I post string value, my custom attribute doesn't work.
It returns the default message:

Could not convert string to double: test. Path 'TestClass.TestNumber',
line 36, position 22.

What I expect is:

test is invalid, must be between 1.00 and 99.99

Please let me know how I can solve it.

答:
Please override FormatErrorMessage method:

```<code>    public override string FormatErrorMessage(string name)
    {
        return $"{name} is invalid, must be between {_min} and {_max}";
    }
</code>```

Difficult to say as I don't see line numbers and I'm not sure when exception is thrown. But you may to use TryParse instead of throwing exception and catching then.

```<code>int result;

if (double.TryParse(custBal.Text, out result))
{

            if (result< _min || result> _max)
                return new ValidationResult(errorMessage);
}
else
{
            return new ValidationResult(error);

}
</code>```

Body:
I have a class TestClass and I want to customize the validation message instead of default one.

TestClass is the post model in the controller which inherits from ControllerBase.

Here is what I've tried:

TestClass.cs

public class TestClass
{
    [TestAtrribute(1.00, 99.99)]
    public double TestNumber { get; set; }
}

TestAttribute.cs

public class TestAttribute : ValidationAttribute
{
    private double _min;
    private double _max;

    public TestAttribute(double min, double max)
    {
        _min = min;
        _max = max;
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        var error = $"{value} is invalid, must be between {_min} and {_max}";
        try
        {
            var convertNum = Convert.ToDouble(value);
            if (convertNum < _min || convertNum > _max)
                return new ValidationResult(errorMessage);
        }
        catch (Exception)
        {
            return new ValidationResult(error);
        }

        return ValidationResult.Success;
    }
}

However, when I post string value, my custom attribute doesn't work.
It returns the default message:

Could not convert string to double: test. Path 'TestClass.TestNumber',
line 36, position 22.

What I expect is:

test is invalid, must be between 1.00 and 99.99

Please let me know how I can solve it.

Body:
Please override FormatErrorMessage method:

    public override string FormatErrorMessage(string name)
    {
        return $"{name} is invalid, must be between {_min} and {_max}";
    }

Difficult to say as I don't see line numbers and I'm not sure when exception is thrown. But you may to use TryParse instead of throwing exception and catching then.

int result;

if (double.TryParse(custBal.Text, out result))
{

            if (result< _min || result> _max)
                return new ValidationResult(errorMessage);
}
else
{
            return new ValidationResult(error);

}