问:
React not closing dialog box
Im using materialUI to click a menu item that then opens a dialog box(child component) however after the dialogbox opens it wont seem to close and wont update the data for noticeModal. There are not any errors being thrown and i belive it has to do with using useEffect to setNoticeModal(props.open) for the initial state. Ive tried removing the useEffect() and throwing props.open into the default useDate() for the noticeModal however upon doing that then my dialogbox wont open anymore at all. What am i over looking here?

holidaySettings.js

```<code>    ...
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const handleDialogOpen = (dataElement) => {
      setDialogData(dataElement);
      setDialogOpen(true);
      setOpen(false);
    }

    ...
    <ClickAwayListener onClickAway={handleClose}>
       <MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
          <MenuItem onClick={handleDialogOpen}>Add Holiday</MenuItem>
        </MenuList>
     </ClickAwayListener>

    ...

    <div className="card-body">
      <div className="row">
         <div className="text-left col-12">
            <Styles>
               <Table columns={columns} data={data} />
               <HolidayDialog open={dialogOpen} onClose={handleDialogClose} data={dialogData}/>
            </Styles>
         </div>
       </div>
     </div>
    ...
</code>```

holidayDialog.js

```<code>const HolidayDialog = (props) => {
    const [noticeModal, setNoticeModal] = useState(false);
    const [selectedDate, setSelectedDate] = useState(new Date());
    const [holidayData, setHolidayData] = useState(props.data);

    useEffect(() => {
        setNoticeModal(props.open)
    });

    const handleDateChange = (date) => {
        setSelectedDate(date);
    };

    const handleClose = () => {
        setNoticeModal(false);
        console.log(noticeModal);
    };

    const handleChange = (e) => {
        const { name, checked } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
      };

    const updateValues = (e) => {
        const { name, value } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: value }));
    }
    return (
        <Dialog
            open={noticeModal}
            TransitionComponent={Transition}
            keepMounted
            onClose={handleClose}
            aria-labelledby="notice-modal-slide-title"
            aria-describedby="notice-modal-slide-description"
        >
            <DialogTitle id="customized-dialog-title" onClose={handleClose}>
                {holidayData.HolidayName ? holidayData.HolidayName : 'Create New Holiday'}
            </DialogTitle>
            <DialogContent dividers>
                <form noValidate autoComplete="off">
                    <div className="row">
                        <div className="col">
                            <TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''}/>
                        </div>
                        <div className="col">
                            <TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || 'ALL'}/>
                        </div>
                    </div>
                    <div className="row mt-3">
                        <div className="col">
                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDatePicker
                                disableToolbar
                                variant="inline"
                                format="MM/dd/yyyy"
                                margin="normal"
                                id="date-picker-inline"
                                label="Date picker inline"
                                value={selectedDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                            />
                        </MuiPickersUtilsProvider>
                        </div>
                        <div className="col">
                            <TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || 'Closed'}/>
                        </div>
                    </div>
                    <div className="row mt-3">
                        <div className="col d-flex flex-column">
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Web || false}
                                    value={holidayData.Web}
                                    onChange={handleChange}
                                    name="Web"
                                    color="primary"
                                />
                                }
                                label="Show on Web?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.CoOp || false}
                                    value={holidayData.CoOp}
                                    onChange={handleChange}
                                    name="CoOp"
                                    color="primary"
                                />
                                }
                                label="CoOp Holiday?"
                            />
                        </div>
                        <div className="col d-flex flex-column">
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Phone || false}
                                    value={holidayData.Phone}
                                    onChange={handleChange}
                                    name="Phone"
                                    color="primary"
                                />
                                }
                                label="Use in IVR?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Active || true}
                                    value={holidayData.Active}
                                    onChange={handleChange}
                                    disabled
                                    name="Active"
                                    color="primary"
                                />
                                }
                                label="Active"
                            />
                        </div>
                    </div>
                </form>
            </DialogContent>
            <DialogActions>
                <Button autoFocus onClick={handleClose} color="default">
                    Cancel
                </Button>
                <Button autoFocus onClick={handleClose} color="primary">
                    Create Holiday
                </Button>
            </DialogActions>
        </Dialog>
    )
}

export default HolidayDialog;
</code>```

答:
Inside the useEffect, you are resetting the noticeModal value to props.open which i believe is true?

I believe what you are trying to do is set the initial value of noticeModal.
Try changing to the code below and remove the useEffect

```<code>const [noticeModal, setNoticeModal] = useState(props.open);
</code>```

Title: React not closing dialog box

Body:
Im using materialUI to click a menu item that then opens a dialog box(child component) however after the dialogbox opens it wont seem to close and wont update the data for noticeModal. There are not any errors being thrown and i belive it has to do with using useEffect to setNoticeModal(props.open) for the initial state. Ive tried removing the useEffect() and throwing props.open into the default useDate() for the noticeModal however upon doing that then my dialogbox wont open anymore at all. What am i over looking here?

holidaySettings.js

    ...
    const [dialogOpen, setDialogOpen] = React.useState(false);
    const handleDialogOpen = (dataElement) => {
      setDialogData(dataElement);
      setDialogOpen(true);
      setOpen(false);
    }

    ...
    <ClickAwayListener onClickAway={handleClose}>
       <MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
          <MenuItem onClick={handleDialogOpen}>Add Holiday</MenuItem>
        </MenuList>
     </ClickAwayListener>

    ...

    ...

holidayDialog.js

const HolidayDialog = (props) => {
    const [noticeModal, setNoticeModal] = useState(false);
    const [selectedDate, setSelectedDate] = useState(new Date());
    const [holidayData, setHolidayData] = useState(props.data);

    useEffect(() => {
        setNoticeModal(props.open)
    });

    const handleDateChange = (date) => {
        setSelectedDate(date);
    };

    const handleClose = () => {
        setNoticeModal(false);
        console.log(noticeModal);
    };

    const handleChange = (e) => {
        const { name, checked } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: checked }));
      };

    const updateValues = (e) => {
        const { name, value } = e.target;
        setHolidayData((prevState) => ({ ...prevState, [name]: value }));
    }
    return (
        <Dialog
            open={noticeModal}
            TransitionComponent={Transition}
            keepMounted
            onClose={handleClose}
            aria-labelledby="notice-modal-slide-title"
            aria-describedby="notice-modal-slide-description"
        >
            <DialogTitle id="customized-dialog-title" onClose={handleClose}>
                {holidayData.HolidayName ? holidayData.HolidayName : 'Create New Holiday'}
            </DialogTitle>
            <DialogContent dividers>
                <form noValidate autoComplete="off">

                            <TextField required name="HolidayName" id="outlined-basic" label="Holiday Name" variant="outlined" onChange={updateValues} value={holidayData.HolidayName || ''}/>

                            <TextField id="outlined-basic" name="Branch" label="Branch" variant="outlined" onChange={updateValues} value={holidayData.Branch || 'ALL'}/>

                        <MuiPickersUtilsProvider utils={DateFnsUtils}>
                            <KeyboardDatePicker
                                disableToolbar
                                variant="inline"
                                format="MM/dd/yyyy"
                                margin="normal"
                                id="date-picker-inline"
                                label="Date picker inline"
                                value={selectedDate}
                                onChange={handleDateChange}
                                KeyboardButtonProps={{
                                    'aria-label': 'change date',
                                }}
                            />
                        </MuiPickersUtilsProvider>

                            <TextField id="outlined-basic" name="Hours" label="Hours" variant="outlined" onChange={updateValues} value={holidayData.Hours || 'Closed'}/>

                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Web || false}
                                    value={holidayData.Web}
                                    onChange={handleChange}
                                    name="Web"
                                    color="primary"
                                />
                                }
                                label="Show on Web?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.CoOp || false}
                                    value={holidayData.CoOp}
                                    onChange={handleChange}
                                    name="CoOp"
                                    color="primary"
                                />
                                }
                                label="CoOp Holiday?"
                            />

                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Phone || false}
                                    value={holidayData.Phone}
                                    onChange={handleChange}
                                    name="Phone"
                                    color="primary"
                                />
                                }
                                label="Use in IVR?"
                            />
                            <FormControlLabel
                                control={
                                <Checkbox
                                    checked={holidayData.Active || true}
                                    value={holidayData.Active}
                                    onChange={handleChange}
                                    disabled
                                    name="Active"
                                    color="primary"
                                />
                                }
                                label="Active"
                            />

                </form>
            </DialogContent>
            <DialogActions>
                <Button autoFocus onClick={handleClose} color="default">
                    Cancel
                </Button>
                <Button autoFocus onClick={handleClose} color="primary">
                    Create Holiday
                </Button>
            </DialogActions>
        </Dialog>
    )
}

export default HolidayDialog;

Body:
Inside the useEffect, you are resetting the noticeModal value to props.open which i believe is true?

I believe what you are trying to do is set the initial value of noticeModal.
Try changing to the code below and remove the useEffect

const [noticeModal, setNoticeModal] = useState(props.open);


来源: stackexchange

问:
Change the select tag from AntDesign
I have the next component in my application:

const Demo = () => {
  const [value, setValue] = useState(null);

  const clear = () => setValue(null);

  return (

      <Select
        mode={"multiple"}
        value={value}
        onChange={setValue}
        allowClear={false}
        placeholder="PERMANENT TEXT"  //i want to make vissibile this text permanent even i select an item from select tag
        style={{ width: "200px" }}
        showSearch={false}
        //  defaultActiveFirstOption={false}
      >
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="tom">Tom</Option>
      </Select>
      <button onClick={clear}>reset</button>

  );
};

```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const Demo = () => {
  const [value, setValue] = useState(null);

  const clear = () => setValue(null);

  return (
    <div>
      <Select
        mode={"multiple"}
        value={value}
        onChange={setValue}
        allowClear={false}
        placeholder="PERMANENT TEXT"  //i want to make vissibile this text permanent even i select an item from select tag
        style={{ width: "200px" }}
        showSearch={false}
        //  defaultActiveFirstOption={false}
      >
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="tom">Tom</Option>
      </Select>
      <button onClick={clear}>reset</button>
    </div>
  );
};</code>```

I try to achieve next:

 1. I try to make the placeholder visible  permanent when i open the application, but  now a tag still as the first item, but i want to hide it.

And to  show every time:

I tried defaultActiveFirstOption={false} but it does not happens.

When i will choose one of the option i don't want do output the value in Select input like this:

But i want to see PERMANENT TEXT like in the image before this.

Question: How to achieve the the above targets?

 demo: https://codesandbox.io/s/select-with-search-field-ant-design-demo-03506?file=/index.js:186-787

答:
I think the problem is useState(null);. The default state should be undefined. You just need to change it to useState();

https://codesandbox.io/s/select-with-search-field-ant-design-demo-mew2p

ContentLicense: CC BY-SA 4.0

Title: Change the select tag from AntDesign

Body:
I have the next component in my application:

const Demo = () => {
  const [value, setValue] = useState(null);

  const clear = () => setValue(null);

  return (

      <Select
        mode={"multiple"}
        value={value}
        onChange={setValue}
        allowClear={false}
        placeholder="PERMANENT TEXT"  //i want to make vissibile this text permanent even i select an item from select tag
        style={{ width: "200px" }}
        showSearch={false}
        //  defaultActiveFirstOption={false}
      >
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="tom">Tom</Option>
      </Select>
      <button onClick={clear}>reset</button>

  );
};

const Demo = () => {
  const [value, setValue] = useState(null);

  const clear = () => setValue(null);

  return (

      <Select
        mode={"multiple"}
        value={value}
        onChange={setValue}
        allowClear={false}
        placeholder="PERMANENT TEXT"  //i want to make vissibile this text permanent even i select an item from select tag
        style={{ width: "200px" }}
        showSearch={false}
        //  defaultActiveFirstOption={false}
      >
        <Option value="jack">Jack</Option>
        <Option value="lucy">Lucy</Option>
        <Option value="tom">Tom</Option>
      </Select>
      <button onClick={clear}>reset</button>

  );
};

I try to achieve next:

 1. I try to make the placeholder visible  permanent when i open the application, but  now a tag still as the first item, but i want to hide it.

And to  show every time:

I tried defaultActiveFirstOption={false} but it does not happens.

When i will choose one of the option i don't want do output the value in Select input like this:

But i want to see PERMANENT TEXT like in the image before this.

Question: How to achieve the the above targets?

 demo: https://codesandbox.io/s/select-with-search-field-ant-design-demo-03506?file=/index.js:186-787


问:
How to dynamically load linkedin share button?
I am loading dynamically content on my web site and I need to create social media buttons after the ajax function, when i get necessary information. I found great solutions for facebook and twitter, but I can't find the working solution for linkedin.
Hope my question is clear... Thanks in advance for smart answers!

EDIT: I found a solution.

```<code>var din ='<script id="holderLink" type="IN/Share" data-url="http://kitchenprague.com/news.php?id='+val.id+'" data-counter="right"></script>';
$(".linkedinDetail").html(din);
IN.parse();
</code>```

答:
The full solution as stated by hjuster is...

```<code>var din ='<script id="holderLink" type="IN/Share" data-url="http://kitchenprague.com/news.php?id='+val.id+'" data-counter="right"></script>';
$(".linkedinDetail").html(din);
IN.parse();
</code>```

But let me provide some explanation, because explanation is great!

Build a script tag to hold your share URL data...

```<code>var din ='<script id="holderLink" type="IN/Share" data-url="http://kitchenprague.com/news.php?id='+val.id+'" data-counter="right"></script>';
</code>```

Simply append the URL data to the page...

```<code>$(".linkedinDetail").html(din);
</code>```

According to the Official LinkedIn Documentation, "In order to reload the widget on a single page application, use in.parse()," so...

```<code>IN.parse();
</code>```

Hope this helps someone out there!

ContentLicense: CC BY-SA 3.0

Body:
I am loading dynamically content on my web site and I need to create social media buttons after the ajax function, when i get necessary information. I found great solutions for facebook and twitter, but I can't find the working solution for linkedin.
Hope my question is clear... Thanks in advance for smart answers!

EDIT: I found a solution.

var din ='';
$(".linkedinDetail").html(din);
IN.parse();

Body:
The full solution as stated by hjuster is...

var din ='<script id="holderLink" type="IN/Share" data-url="http://kitchenprague.com/news.php?id='+val.id+'" data-counter="right"></script>';
$(".linkedinDetail").html(din);
IN.parse();

But let me provide some explanation, because explanation is great!

Build a script tag to hold your share URL data...

var din ='<script id="holderLink" type="IN/Share" data-url="http://kitchenprague.com/news.php?id='+val.id+'" data-counter="right"></script>';

Simply append the URL data to the page...

$(".linkedinDetail").html(din);

According to the Official LinkedIn Documentation, "In order to reload the widget on a single page application, use in.parse()," so...

IN.parse();

Hope this helps someone out there!


问:
Why does the VBA IDE's Intellisense in Microsoft Word 2007 keep on changing the case of the name of a particular variable type?
This is the most bizarre question I've ever asked. I'm not even sure how to phrase it. I remember something like this happening way back in the VB6 IDE, but I've forgotten the fix. If this is the case, then this is a really old bug in the VB IDE.

Here's the problem:

I'm writing a simple MS Word macro when I accidently typed:

```<code>Dim cell as Cell
</code>```

This activated the dreaded IDE bug. Now, no matter what I do; remove the module, edit it outside the IDE or whatever, the IDE's intellisense formats the variable type "Cell" as "cell"

If I name a new variable:

```<code>Dim tcell as Cell
</code>```

The IDE changes it to:

```<code>Dim tcell As cell
</code>```

This infuriates me to no end. I've tried everything to no avail.
This happens even if I edit the module file (.bas) outside of the IDE and reimport it back.

How can I stop this madness?

Updated

Apparently this behavior is not a bug, but by design. See answer.

答:
VB/VBA variable names are not case sensitive so cell and Cell are the same. I would suggest you name your variables something else - I personally use a letter in front: e.g.

```<code>Dim sString as String 's for string
Dim iInt as Integer 'i for integer
Dim oCell as Cell 'o for objects
</code>```

Hope this helps

Body:
This is the most bizarre question I've ever asked. I'm not even sure how to phrase it. I remember something like this happening way back in the VB6 IDE, but I've forgotten the fix. If this is the case, then this is a really old bug in the VB IDE.

Here's the problem:

I'm writing a simple MS Word macro when I accidently typed:

Dim cell as Cell

This activated the dreaded IDE bug. Now, no matter what I do; remove the module, edit it outside the IDE or whatever, the IDE's intellisense formats the variable type "Cell" as "cell"

If I name a new variable:

Dim tcell as Cell

The IDE changes it to:

Dim tcell As cell

This infuriates me to no end. I've tried everything to no avail.
This happens even if I edit the module file (.bas) outside of the IDE and reimport it back.

How can I stop this madness?

Updated

Apparently this behavior is not a bug, but by design. See answer.

Body:
VB/VBA variable names are not case sensitive so cell and Cell are the same. I would suggest you name your variables something else - I personally use a letter in front: e.g.

Dim sString as String 's for string
Dim iInt as Integer 'i for integer
Dim oCell as Cell 'o for objects

Hope this helps


问:
how to write a spark scala schema for complex datatypes like map,struct,array
Please find the data format

```<code>c3f36c25-2546-48b2-bd72-1b5e5dcae2ab/1620247529/{6032:{"advertisers":{"Amoma":[{"eurocents":17256,"breakfast":false}]
</code>```

tried the below

```<code>valsschema=List(
                ("Userid", StringType, true),
                ("unix_time", IntegerType, true),
("hotelresults",MapType(IntegerType,true,StructType(("advertisers",MapType(StringType,true,ArrayType(StructType("eurocents",IntegerType,true,"breakfast",BooleanType,true))))))
              )
</code>```

答:
It may be easier to make a StructType using the add method.

It seems like your overall file is a CSV format with "/" (slash) delimiter:

// create initial DataFrame with JSON data inside of 3rd column
val df:DataFrame = spark.read.format("csv").option("delimiter", "/").option("header", "false").option("inferSchema", "false").load("62132524.txt").toDF("UserId", "UnixTime", "HotelResults")
```

<p>Your 3rd column JSON was invalid so it is changed here:</p>

```c3f36c25-2546-48b2-bd72-1b5e5dcae2ab/1620247529/{"advertisers":{"Amoma":[{"eurocents":17256,"breakfast":false}]}}
```

<p>Create a schema to parse the JSON using the <code>from_json</code> method (uses wildcard imports to make sure everything is imported):</p>

```import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._

// prepare StructType with inner StructType
val detailType:StructType = new StructType().add("eurocents", IntegerType).add("breakfast", BooleanType)
val jsonSchema:StructType = new StructType().add("advertisers", MapType(StringType, ArrayType(detailType, false)))

// Now, the JSON Schema can be used:
df.select(from_json(col("HotelResults"), jsonSchema) as "HotelResults2").select(col("HotelResults2.*")).show
```

<p><strong>Edited based on comments (parse flat file directly)</strong></p>

<p>The built-in CSV parser can only parse a file with one delimiter. A workaround is to use the split Scala String method. </p>

<pre class="lang-scala prettyprint-override"><code>// Read data into a flat RDD
val rawDF = spark.sparkContext.textFile("rawdata.dat")

// Create case class (I added 3 fields, but you will need to add the rest)
case class Record(id: Int, advertiser: String, euroCents: Int)

// Create function converting an array of values to the case class
def arrToRecord(a:Array[String]): Record = Record(a(0).toInt, a(1), a(2).toInt)

// Use one of the approaches below - they should be equivalent in your case
val mappedDF:DataFrame = rawDF.map((s:String) => arrToRecord(s.split("[\u0006\u0003\u0005\u0007\u0008\u0002]"))).toDF()
// OR
val mappedDF:DataFrame = rawDF.map((s:String) => arrToRecord(s.split(Array('\u0006','\u0003','\u0005','\u0007','\u0008','\u0002')))).toDF()

</code>```

Result

```<code>
mappedArr.show
+----+----------+---------+
|  id|advertiser|euroCents|
+----+----------+---------+
|6032|     Amoma|    17256|
+----+----------+---------+
</code>```

Body:
Please find the data format

c3f36c25-2546-48b2-bd72-1b5e5dcae2ab/1620247529/{6032:{"advertisers":{"Amoma":[{"eurocents":17256,"breakfast":false}]

tried the below

valsschema=List(
                ("Userid", StringType, true),
                ("unix_time", IntegerType, true),
("hotelresults",MapType(IntegerType,true,StructType(("advertisers",MapType(StringType,true,ArrayType(StructType("eurocents",IntegerType,true,"breakfast",BooleanType,true))))))
              )

Body:
It may be easier to make a StructType using the add method.

It seems like your overall file is a CSV format with "/" (slash) delimiter:

// create initial DataFrame with JSON data inside of 3rd column
val df:DataFrame = spark.read.format("csv").option("delimiter", "/").option("header", "false").option("inferSchema", "false").load("62132524.txt").toDF("UserId", "UnixTime", "HotelResults")

Your 3rd column JSON was invalid so it is changed here:

c3f36c25-2546-48b2-bd72-1b5e5dcae2ab/1620247529/{"advertisers":{"Amoma":[{"eurocents":17256,"breakfast":false}]}}

Create a schema to parse the JSON using the from_json method (uses wildcard imports to make sure everything is imported):

import org.apache.spark.sql.types._
import org.apache.spark.sql.functions._

// prepare StructType with inner StructType
val detailType:StructType = new StructType().add("eurocents", IntegerType).add("breakfast", BooleanType)
val jsonSchema:StructType = new StructType().add("advertisers", MapType(StringType, ArrayType(detailType, false)))

// Now, the JSON Schema can be used:
df.select(from_json(col("HotelResults"), jsonSchema) as "HotelResults2").select(col("HotelResults2.*")).show

Edited based on comments (parse flat file directly)

The built-in CSV parser can only parse a file with one delimiter. A workaround is to use the split Scala String method.

// Read data into a flat RDD
val rawDF = spark.sparkContext.textFile("rawdata.dat")

// Create case class (I added 3 fields, but you will need to add the rest)
case class Record(id: Int, advertiser: String, euroCents: Int)

// Create function converting an array of values to the case class
def arrToRecord(a:Array[String]): Record = Record(a(0).toInt, a(1), a(2).toInt)

// Use one of the approaches below - they should be equivalent in your case
val mappedDF:DataFrame = rawDF.map((s:String) => arrToRecord(s.split("[\u0006\u0003\u0005\u0007\u0008\u0002]"))).toDF()
// OR
val mappedDF:DataFrame = rawDF.map((s:String) => arrToRecord(s.split(Array('\u0006','\u0003','\u0005','\u0007','\u0008','\u0002')))).toDF()

Result

mappedArr.show
+----+----------+---------+
|  id|advertiser|euroCents|
+----+----------+---------+
|6032|     Amoma|    17256|
+----+----------+---------+


问:
Switching from OpenCV 3 to OpenCV 4 causes webcam to record at a max of 5 fps instead the usual 30 fps
I'm having some trouble since I changed from OpenCV 3.x to 4.x (compiled from source) in my C++ project. I've replicated this behaviour in a small example that just opens a webcam and records for 5 seconds.

With 3.x I am able to set the webcam framerate to 30 at full hd, but the same code with 4.x just ignores the camera.set(cv::CAP_PROP_FPS,30) and sets it to 5 instead. If I use 720p, the fps is set to 10.

Maybe the code is not relevant here, as it's a classical example, but just in case I'll leave it here.

```<code>#include "opencv2/opencv.hpp"
#include "iostream"
#include "thread"
#include <unistd.h>

using namespace cv;

VideoCapture camera(0);
bool stop = false;
int fc = 0;

void saveFrames()
{
    while(!stop)
    {
        Mat frame;
        camera >> frame;
        cv::imwrite("/tmp/frames/frame" + std::to_string(fc) + ".jpg", frame);
        fc++;
    }
}

int main()
{
    if(!camera.isOpened())
        return -1;

    camera.set(cv::CAP_PROP_FRAME_WIDTH,1920);
    camera.set(cv::CAP_PROP_FRAME_HEIGHT,1080);
    camera.set(cv::CAP_PROP_FPS,30);

    double fps = camera.get(cv::CAP_PROP_FPS);
    std::cout << "FPS setting: " << fps << std::endl; // 5 with OCV4, 30 with OCV3

    std::thread tr(saveFrames);
    int waitSeconds = 5;
    usleep(waitSeconds * 1e6);
    stop = true;
    tr.join();

    std::cout << "Written " << fc << " frames of " << fps * waitSeconds << std::endl;
    return 0;
}
</code>```

Edit: more tests with other computers yield the same result except in a Macbook Pro (but running the same distribution) where OpenCV 4.3 seems to work. The other 2 computers are desktops with usb webcams.

Edit 2: same problem with version 3.4 building from source code. For now, only 3.2 from the repo works ok in the two computers with usbcams.

答: This is a known bug that affects OpenCV > 3.3</p>

Body:
I'm having some trouble since I changed from OpenCV 3.x to 4.x (compiled from source) in my C++ project. I've replicated this behaviour in a small example that just opens a webcam and records for 5 seconds.

With 3.x I am able to set the webcam framerate to 30 at full hd, but the same code with 4.x just ignores the camera.set(cv::CAP_PROP_FPS,30) and sets it to 5 instead. If I use 720p, the fps is set to 10.

Maybe the code is not relevant here, as it's a classical example, but just in case I'll leave it here.

#include "opencv2/opencv.hpp"
#include "iostream"
#include "thread"
#include <unistd.h>

using namespace cv;

VideoCapture camera(0);
bool stop = false;
int fc = 0;

void saveFrames()
{
    while(!stop)
    {
        Mat frame;
        camera >> frame;
        cv::imwrite("/tmp/frames/frame" + std::to_string(fc) + ".jpg", frame);
        fc++;
    }
}

int main()
{
    if(!camera.isOpened())
        return -1;

    camera.set(cv::CAP_PROP_FRAME_WIDTH,1920);
    camera.set(cv::CAP_PROP_FRAME_HEIGHT,1080);
    camera.set(cv::CAP_PROP_FPS,30);

    double fps = camera.get(cv::CAP_PROP_FPS);
    std::cout << "FPS setting: " << fps << std::endl; // 5 with OCV4, 30 with OCV3

    std::thread tr(saveFrames);
    int waitSeconds = 5;
    usleep(waitSeconds * 1e6);
    stop = true;
    tr.join();

    std::cout << "Written " << fc << " frames of " << fps * waitSeconds << std::endl;
    return 0;
}

Edit: more tests with other computers yield the same result except in a Macbook Pro (but running the same distribution) where OpenCV 4.3 seems to work. The other 2 computers are desktops with usb webcams.

Edit 2: same problem with version 3.4 building from source code. For now, only 3.2 from the repo works ok in the two computers with usbcams.


问:
Development server of create-react-app does not auto refresh
I am following a tutorial on React using create-react-app.
The application is created by create-react-app v1.3.0

```<code>create-react-app my-app
</code>```

The dev server is run by

```<code>npm start
</code>```

After changing the code several times, the browser is not updated live / hot reload with the changes. Refreshing the browser does not help. Only stopping the dev server and starting it over again capture the new changes to the code.

答:
Find your index.js and change something in this file, for example add a white space, then save.
It should show "compiling..." in your console.

Then you can modify other files and react will refresh on save.

It seems that npm is looking for changes in the index.js at the very first time, if you refactor your folder structure the index.js could be missed. Force an update in index.js file get the problem solved.

At least this has worked to me

Body:
I am following a tutorial on React using create-react-app.
The application is created by create-react-app v1.3.0

create-react-app my-app

The dev server is run by

npm start

After changing the code several times, the browser is not updated live / hot reload with the changes. Refreshing the browser does not help. Only stopping the dev server and starting it over again capture the new changes to the code.


问:
How to get the Enum Index value in C#
In C, enums, internally equates to an integer. Therefore we can treat data types of enum as integer also.

How to achieve the same with C#?

答:
Use simple casting:

```<code>int value = (int) enum.item;
</code>```

Refer to enum (C# Reference)

Title: How to get the Enum Index value in C#

Body:
Use simple casting:

int value = (int) enum.item;

Refer to enum (C# Reference)


问:
Lua read chunked request body if header specified
we use Nginx + Lua and want to support chunked upload according this workaround which is generally works. My question is how I can process upload request as usual - work with headers, body, eof:

```<code>                local form, err = upload:new(chunk_size)
                if not form then
                    ngx.log(ngx.ERR, "failed to new upload: ", err)
                    ngx.exit(500)
                end

                form:set_timeout(1000) -- 1 sec

                while true do
                    local typ, res, err = form:read()
                    if not typ then
                        ngx.say("failed to read: ", err)
                        return
                    end

                    ngx.say("read: ", cjson.encode({typ, res}))

                    if typ == "eof" then
                        break
                    end
                end
</code>```

and just when I have chunked upload header -H "Transfer-Encoding: chunked" use that chunk script.

Sorry if it is something obvious, but after couple days of googling I don't see any example.
But my suggesting is:

```<code># read headers
ngx.req.get_headers()

#read body:
ngx.req.get_body_data()
</code>```

and then I don't need form:read() and iterate over form array until eof. Appreciate any links, examples.

curl example:

```<code>curl -X PUT localhost:8080/test -F file=@./myfile -H "Transfer-Encoding: chunked"
</code>```

答:
Unfornunately, ngx.req.socket (https://github.com/openresty/lua-nginx-module#ngxreqsocket), which is used by lua-resty-upload under the hood, does not handle body encodings at the moment. That is, when you read from the socket object, you'll receive request body as is, therefore, you need to decode it by yourself. lua-resty-upload doesn't do it, it expects a plain formdata body without any additional encoding. See https://github.com/openresty/lua-resty-upload/issues/32#issuecomment-266301684 for further explanation.

As it mentioned at the link above, you can use ngx.req.read_body/ngx.re.get_body_data that are backed by “nginx's built-in request body reader with chunked encoding support”. The ngx.re.get_body_data method returns an already decoded body. You can feed the body to some formdata parser that accepts a body as a byte string rather than reads it from the cosocket (as lua-resty-upload does). For example, you can use lua-resty-multipart-parser: https://github.com/agentzh/lua-resty-multipart-parser

There is a significant downside – the request body need to be read to Lua string at once, that is, the whole request body is stored in memory as Lua string object.

Theoretically, it could be fixed. We can modify lua-resty-upload to accept a socket-like object instead of hardcoded one (https://github.com/openresty/lua-resty-upload/blob/v0.10/lib/resty/upload.lua#L60) and write some sort of buffer that lazily reads bytes from an iterator and provides the socket-like interface. Maybe I'll try it later.

Here is the example of usage both libraries. It does exactly what you asked for (but remember, it reads the whole body to string if request body is chunked–encoded).

```<code># nginx.conf
http {
    server {
        listen 8888;
        location = /upload {
            content_by_lua_block {
                require('upload').handler()
            }
        }
    }
}
</code>```

-- upload.lua
local upload = require('resty.upload')
local multipart_parser = require('resty.multipart.parser')

local get_header = function(headers, name)
    local header = headers[name]
    if not header then
        return nil
    end
    if type(header) == 'table' then
        return header[1]
    end
    return header
end

local handler = function()
    -- return 405 if HTTP verb is not POST
    if ngx.req.get_method() ~= 'POST' then
        return ngx.exit(ngx.HTTP_NOT_ALLOWED)
    end
    local headers = ngx.req.get_headers()
    local content_type = get_header(headers, 'content-type')
    -- return 400 if the body is not a formdata
    if not content_type or not string.find(content_type, '^multipart/form%-data') then
        return ngx.exit(ngx.HTTP_BAD_REQUEST)
    end
    local transfer_encoding = get_header(headers, 'transfer-encoding')
    if transfer_encoding == 'chunked' then
        -- parse form using `lua-resty-multipart-parser`
        ngx.say('*** chunked')
        -- read the body, chunked encoding will be decoded by nginx
        ngx.req.read_body()
        local body = ngx.req.get_body_data()
        if not body then
            local filename = ngx.req.get_body_file()
            if not filename then
                return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
            end
            -- WARNING
            -- don't use this code in production, file I/O is blocking,
            -- you are going to block nginx event loop at this point!
            local fd = io.open(filename, 'rb')
            if not fd then
                return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
            end
            body = fd:read('*a')
        end
        local parser = multipart_parser.new(body, content_type)
        while true do
            local part = parser:parse_part()
            if not part then
                break
            end
            ngx.say('>>> ', part)
        end
    else
        -- parse form using `lua-resty-upload` (in a streaming fashion)
        ngx.say('*** not chunked')
        local chunk_size = 8 -- for demo purposes only, use 4096 or 8192
        local form = upload:new(chunk_size)
        while true do
            local typ, res = form:read()
            if typ == 'eof' then
                break
            elseif typ == 'body' then
                ngx.say('>>> ', res)
            end
        end
    end
end

return {
    handler = handler
}
```

```$ curl -X POST localhost:8888/upload -F file='binary file content'

*** not chunked
>>> binary f
>>> ile cont
>>> ent
```

<p>As you can see, the body is read and processed chunk by chunk.</p>

```$ curl -X POST localhost:8888/upload -F file='binary file content' -H transfer-encoding:chunked

*** chunked
>>> binary file content
```

Here, conversely, the body is processed at once.

Body:
we use Nginx + Lua and want to support chunked upload according this workaround which is generally works. My question is how I can process upload request as usual - work with headers, body, eof:

                local form, err = upload:new(chunk_size)
                if not form then
                    ngx.log(ngx.ERR, "failed to new upload: ", err)
                    ngx.exit(500)
                end

                form:set_timeout(1000) -- 1 sec

                while true do
                    local typ, res, err = form:read()
                    if not typ then
                        ngx.say("failed to read: ", err)
                        return
                    end

                    ngx.say("read: ", cjson.encode({typ, res}))

                    if typ == "eof" then
                        break
                    end
                end

and just when I have chunked upload header -H "Transfer-Encoding: chunked" use that chunk script.

Sorry if it is something obvious, but after couple days of googling I don't see any example.
But my suggesting is:

# read headers
ngx.req.get_headers()

#read body:
ngx.req.get_body_data()

and then I don't need form:read() and iterate over form array until eof. Appreciate any links, examples.

curl example:

curl -X PUT localhost:8080/test -F file=@./myfile -H "Transfer-Encoding: chunked"

Body:
Unfornunately, ngx.req.socket (https://github.com/openresty/lua-nginx-module#ngxreqsocket), which is used by lua-resty-upload under the hood, does not handle body encodings at the moment. That is, when you read from the socket object, you'll receive request body as is, therefore, you need to decode it by yourself. lua-resty-upload doesn't do it, it expects a plain formdata body without any additional encoding. See https://github.com/openresty/lua-resty-upload/issues/32#issuecomment-266301684 for further explanation.

As it mentioned at the link above, you can use ngx.req.read_body/ngx.re.get_body_data that are backed by “nginx's built-in request body reader with chunked encoding support”. The ngx.re.get_body_data method returns an already decoded body. You can feed the body to some formdata parser that accepts a body as a byte string rather than reads it from the cosocket (as lua-resty-upload does). For example, you can use lua-resty-multipart-parser: https://github.com/agentzh/lua-resty-multipart-parser

There is a significant downside – the request body need to be read to Lua string at once, that is, the whole request body is stored in memory as Lua string object.

Theoretically, it could be fixed. We can modify lua-resty-upload to accept a socket-like object instead of hardcoded one (https://github.com/openresty/lua-resty-upload/blob/v0.10/lib/resty/upload.lua#L60) and write some sort of buffer that lazily reads bytes from an iterator and provides the socket-like interface. Maybe I'll try it later.

Here is the example of usage both libraries. It does exactly what you asked for (but remember, it reads the whole body to string if request body is chunked–encoded).

# nginx.conf
http {
    server {
        listen 8888;
        location = /upload {
            content_by_lua_block {
                require('upload').handler()
            }
        }
    }
}

-- upload.lua
local upload = require('resty.upload')
local multipart_parser = require('resty.multipart.parser')

local get_header = function(headers, name)
    local header = headers[name]
    if not header then
        return nil
    end
    if type(header) == 'table' then
        return header[1]
    end
    return header
end

local handler = function()
    -- return 405 if HTTP verb is not POST
    if ngx.req.get_method() ~= 'POST' then
        return ngx.exit(ngx.HTTP_NOT_ALLOWED)
    end
    local headers = ngx.req.get_headers()
    local content_type = get_header(headers, 'content-type')
    -- return 400 if the body is not a formdata
    if not content_type or not string.find(content_type, '^multipart/form%-data') then
        return ngx.exit(ngx.HTTP_BAD_REQUEST)
    end
    local transfer_encoding = get_header(headers, 'transfer-encoding')
    if transfer_encoding == 'chunked' then
        -- parse form using `lua-resty-multipart-parser`
        ngx.say('*** chunked')
        -- read the body, chunked encoding will be decoded by nginx
        ngx.req.read_body()
        local body = ngx.req.get_body_data()
        if not body then
            local filename = ngx.req.get_body_file()
            if not filename then
                return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
            end
            -- WARNING
            -- don't use this code in production, file I/O is blocking,
            -- you are going to block nginx event loop at this point!
            local fd = io.open(filename, 'rb')
            if not fd then
                return ngx.exit(ngx.HTTP_INTERNAL_SERVER_ERROR)
            end
            body = fd:read('*a')
        end
        local parser = multipart_parser.new(body, content_type)
        while true do
            local part = parser:parse_part()
            if not part then
                break
            end
            ngx.say('>>> ', part)
        end
    else
        -- parse form using `lua-resty-upload` (in a streaming fashion)
        ngx.say('*** not chunked')
        local chunk_size = 8 -- for demo purposes only, use 4096 or 8192
        local form = upload:new(chunk_size)
        while true do
            local typ, res = form:read()
            if typ == 'eof' then
                break
            elseif typ == 'body' then
                ngx.say('>>> ', res)
            end
        end
    end
end

return {
    handler = handler
}

$ curl -X POST localhost:8888/upload -F file='binary file content'

*** not chunked
>>> binary f
>>> ile cont
>>> ent

As you can see, the body is read and processed chunk by chunk.

$ curl -X POST localhost:8888/upload -F file='binary file content' -H transfer-encoding:chunked

*** chunked
>>> binary file content

Here, conversely, the body is processed at once.


问:
Bootstrap toggle buttons not accessible
I was trying to test implementation of the Bootstrap toggle button and something in the their js doesn't allow me to 'tab' to them with the keyboard. When I remove the js I can 'tab' to the checkbox just fine. Can anyone help me extend this so that I can 'tab' to each toggle button?

HTML

```<code><div class="checkbox">
  <label>
    <input type="checkbox" data-toggle="toggle">
    Option one is enabled
  </label>
</div>
</code>```

JS
https://cdnjs.cloudflare.com/ajax/libs/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js

JSFIDDLE
https://jsfiddle.net/galnova/s2x57t2u/

答:
A slightly different approach</p>

```<code>var $toggle = $('input:checkbox');
var $toggleDiv = $toggle.parent();
$toggleDiv.attr('tabindex','0');                // allow focus
$toggleDiv.unbind('keypress').keypress((e) => { // have enter trigger toggle
    if (e.which===13) {
        e.preventDefault();
        var newState = $toggle.is(':checked') ? 'off' : 'on';
        $toggle.bootstrapToggle(newState);
    }
})
</code>```

Title: Bootstrap toggle buttons not accessible

Body:
I was trying to test implementation of the Bootstrap toggle button and something in the their js doesn't allow me to 'tab' to them with the keyboard. When I remove the js I can 'tab' to the checkbox just fine. Can anyone help me extend this so that I can 'tab' to each toggle button?

HTML

    <input type="checkbox" data-toggle="toggle">
    Option one is enabled

JS
https://cdnjs.cloudflare.com/ajax/libs/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js

JSFIDDLE
https://jsfiddle.net/galnova/s2x57t2u/

Body:
A slightly different approach

var $toggle = $('input:checkbox');
var $toggleDiv = $toggle.parent();
$toggleDiv.attr('tabindex','0');                // allow focus
$toggleDiv.unbind('keypress').keypress((e) => { // have enter trigger toggle
    if (e.which===13) {
        e.preventDefault();
        var newState = $toggle.is(':checked') ? 'off' : 'on';
        $toggle.bootstrapToggle(newState);
    }
})


问:
What is the best way to create own Ranking Tiers in a ELO system
Suppose all Players start with a Score of 1000 Points, how should i create specific Ranking Tiers Like silver/gold/Diamond. How do Games Like Rocket League calculate the ELO Points needed for certain ranks e.g 1000-1100 silver 1. </p>

答:
You could do it with percentages.

F.e. if I win a game, I get 10 points, when I lose, I lose 5-7 points. Then get all points of all players in that server, an f.e. the top 10% are platin, the top 25% gold, the top 50% silver and the rest bronze or something like that. Of course this would need a big playerbase.

Or you could just do it like in League of Legends, but in a different way. Everyone starts at Bronze (lowest rank), and needs 100 points to get to the next elo (or something like that). That is (in my opinion) the fairest ranking system. Winning gives you 10 points, losing leads to losing 5-7 points.


问:
"A fatal error occurred while creating a TLS client credential. The internal error state is 10013." every 10 seconds
This has been asked before, but I've been through all the answers provided elsewhere so far, i.e. checking permissions on c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys, adjusting protocols using IISCrypto and turning use of FIPS algorithms on (and off) and I'm still getting batches of 4 events every 10 seconds which swamps the System event log.

I'm running Windows Insider Preview 10 Build 19592.rs_prerelease.200321-1719 (64-bit) so this could be a preview specific issue, however, is there anything else I can try to correct this error?

答: The answer I finally got from a comment on anothersite was that this was a known issue in the Insider Preview and it's now been fixed in the latest releases.</p>


问:
Xcode / iOS simulator: Trigger significant location change manually
Is there a way to manually tell the device to dispatch a significant location change notification that will wake up any applications registered for this notification?
This is for testing only, and I realize this private API call would get rejected upon submission to the app store.</p>

答:
Depending on your scenario I would suggest two solutions:

Use a Timer or LocalNotification that periodically calls stopMonitoringSignificantLocationChanges followed by startMonitoringSignificantLocationChanges which should trigger a new location to be sent to your code (might be the same Location as before).

Build your own GPS Simulator that you start in debug builds and that will call the same delegate methods like CLLocationManager would do.


问:
process.env.API_URL is undefined
I built a project using React at the front and Strapi (based on Node.js) at the back.

On the client side, I'm trying to access my api url like so:

```<code>const apiUrl = process.env.API_URL || 'http://localhost:1337'
const strapi = new Strapi(apiUrl);
</code>```

But process.env.API_URL is undefined. If I log process.env all I get is an object containing:

```<code>NODE_ENV: "development"
PUBLIC_URL: ""
</code>```

How can I access my api_url ?
I'm guessing there is a file where I should define API_URL myself?

答:
It is important to understand what is happening behind the scenes.

Your project can consume variables declared in your environment as if they were declared locally in your JS files.
By default you will have NODE_ENV defined for you, and any other environment variables starting with REACT_APP_.

You must create custom environment variables beginning with REACT_APP_.

Any other variables except NODE_ENV will be ignored to avoid accidentally exposing a private key on the machine that could have the same name.

Changing any environment variables will require you to restart the development server if it is running.

These environment variables will be defined for you on process.env.

For example, having an environment variable named REACT_APP_NOT_SECRET_CODE will be exposed in your JS as process.env.REACT_APP_NOT_SECRET_CODE.

Read more in here and in here.

Title: process.env.API_URL is undefined

Body:
I built a project using React at the front and Strapi (based on Node.js) at the back.

On the client side, I'm trying to access my api url like so:

const apiUrl = process.env.API_URL || 'http://localhost:1337'
const strapi = new Strapi(apiUrl);

But process.env.API_URL is undefined. If I log process.env all I get is an object containing:

NODE_ENV: "development"
PUBLIC_URL: ""

How can I access my api_url ?
I'm guessing there is a file where I should define API_URL myself?


问:
Extract multiple json fields using nifi
I'm new to Nifi. I have below json structure to be implemented using Nifi..

```<code>
{
  "jobs": [
      {
            "jid": "1",
            "name": "job1",
            "state": "FAILED",
            "start-time": 12243
      },
      {
            "jid": "2",
            "name": "job2",
            "state": "FAILED",
            "start-time": 1233
      },
      {
            "jid": "3",
            "name": "job2",
            "state": "RUNNING",
            "start-time": 1223213
      }

  ]
}

</code>```

I need the output to be like below filtered only FAILED job details

```<code>{
  [
  job1,
  job2
  ]
}
</code>```

Please help and thanks in advance.

答:
This spec will output a JSON array [job1,job2]:

```<code>[
  {
    "operation": "shift",
    "spec": {
      "jobs": {
        "*": {
          "state": {
            "FAILED": {
              "@(2,name)": "[]"
            }
          }
        }
      }
    }
  }
]
</code>```

Your desired output of an array inside braces is not valid JSON, as objects need key/value pairs. If instead you want the array in an object, let's call the key failed_jobs and you can use the following spec:

```<code>[
  {
    "operation": "shift",
    "spec": {
      "jobs": {
        "*": {
          "state": {
            "FAILED": {
              "@(2,name)": "failed_jobs[]"
            }
          }
        }
      }
    }
  }
]
</code>```

Title: Extract multiple json fields using nifi

Body:
I'm new to Nifi. I have below json structure to be implemented using Nifi..

{
  "jobs": [
      {
            "jid": "1",
            "name": "job1",
            "state": "FAILED",
            "start-time": 12243
      },
      {
            "jid": "2",
            "name": "job2",
            "state": "FAILED",
            "start-time": 1233
      },
      {
            "jid": "3",
            "name": "job2",
            "state": "RUNNING",
            "start-time": 1223213
      }

  ]
}

I need the output to be like below filtered only FAILED job details

{
  [
  job1,
  job2
  ]
}

Please help and thanks in advance.

Body:
This spec will output a JSON array [job1,job2]:

[
  {
    "operation": "shift",
    "spec": {
      "jobs": {
        "*": {
          "state": {
            "FAILED": {
              "@(2,name)": "[]"
            }
          }
        }
      }
    }
  }
]

Your desired output of an array inside braces is not valid JSON, as objects need key/value pairs. If instead you want the array in an object, let's call the key failed_jobs and you can use the following spec:

[
  {
    "operation": "shift",
    "spec": {
      "jobs": {
        "*": {
          "state": {
            "FAILED": {
              "@(2,name)": "failed_jobs[]"
            }
          }
        }
      }
    }
  }
]


问:
Big-o complexity problem - Linear cumulative power

Background

I am trying to work through some problems I found from Stanfords "Design & Analysis of Algorithms" course from 2013. In particular, problem 3 from problem set 1 here.

In summary it states:

You are stuck on a desert island with a radio that can transmit a distress signal at integer power levels (i.e. 1W, 2W, 3W, etc.).

If you transmit a signal with high enough power, you will receive a response and be rescued.

Unfortunately you do not know how much power, n, is needed.

The problem requests you design an algorithm that uses Θ(n)W total power.

Being a 5pt question from problem set 1, I presume this is easier than I am finding it.

My question is

...what is this algorithm?....or how can I change my thinking to find one?

Where I'm stuck

The question states that the strategy "just increase power by 1 watt each time" will result in an Θ(n^2)W total power. Indeed, this is true, as the total power used by any n is n * (n+1) / 2.

However, I can't think of any strategy that isn't:

greater than linear; or

a strategy where I cheat by "not doing anything for a few consecutive n's".

Also, if I ignore the discreteness of the radio for a minute and analyse the problem as a continuous linear function, the total power should be generalisable to a function g(n) of the form g(n) = Kn + B (where K and B are constants). This linear function would represent the integral of the function we need to use for controlling the radio.

Then, if I take the derivative of this function, dg(n)/dn, I'm left with K. I.e. If I want to have linear total power, I should just drive the radio at a constant power for n times...but this would only result in a rescue if I happened to guess K correctly the first time.

EDIT

Yes, I had already thought of doubling etc....but the answers here pointed out the error in my thinking. I had been trying to solve the question "design an algorithm that has linear cumulative power consumption"...which I think is impossible. As pointed out by the answers, I should have thought about it as "for a given n, design an algorithm that will consume Kn"...i.e. what the question posed.

答:
Well here is a simple algorithm and complexity analysis:

Initialy try with power=1W

If it wasn't received try with power=2*previous_power until it is received

Complexity:

So basically we stop when power p>= n, where n is the desired threshold.
We know that:

```<code>p>=n and p/2<n => n<=p<2n
</code>```

In order to reach the pW (i.e the desired level in order to be received) this means you tried previously with p/2, prior to that p/4... and initially with 1, so let's sum up all the steps:

```<code>1+2+4+...+p/2+p -> 2*p ~ Θ(p) = Θ(n)
</code>```

Body:
Well here is a simple algorithm and complexity analysis:

Initialy try with power=1W

If it wasn't received try with power=2*previous_power until it is received

Complexity:

So basically we stop when power p>= n, where n is the desired threshold.
We know that:

p>=n and p/2<n => n<=p<2n

In order to reach the pW (i.e the desired level in order to be received) this means you tried previously with p/2, prior to that p/4... and initially with 1, so let's sum up all the steps:

1+2+4+...+p/2+p -> 2*p ~ Θ(p) = Θ(n)


问:
ASP.NET MVC render partial view from type IEnumerable<cart> inside view from type IEnumerable<products>
Edit: the product view contains some products so I'm trying to add them one by one to the cart using a button for each product, the added products shall appear in a table in the partial view (cart) which is working fine, I'm trying now to render this cart inside a popup modal so when i press the popup button it should show me what products i added,when i still inside the product view.

I'm trying to do something like this inside the modal body:

```<code>@Html.Partial("_ShowCart", new List<InternetApp.Models.Cart>())
</code>```

but this retrieves an empty list.

So I want something like this but I don't know how I could do this with different models:

```<code>@Html.Partial("_ShowCart", Model)
</code>```

I have 3 models: product, cart and viewmodel:

```<code>public class Product
{
    public int id { get; set; }
    public String name { get; set; }
    public float price { get; set; }
    public String image { get; set; }
    public String description { get; set; }
    public int? CategoryId { get; set; }
}

public class Cart
{
    public int product_id { get; set; }
    public DateTime added_at { get; set; }
    public virtual Product product { get; set; }
}

public class ProductCart
{
    public Product Product { get; set; }
    public Cart Cart { get; set; }
}
</code>```

The cart and the product each one has controller, I have the cart as a partial view which takes IEnumerable<Cart> and a product view which takes IEnumerable<Product>.

This is the cart index action

```<code>public ActionResult Index()
{
    List<Cart> Cart = db.Cart.Include(a => a.product).ToList();
    return PartialView("_ShowCart", Cart);
}
</code>```

I don't know how to render the cart inside the product because each one has a different IEnumerable model...

答:
Your Entity Framework (EF) models would look like the following.  I modified for suggested standardization and clarity purposes only:

```<code>public class Product
{
    [Key] //This is only needed by EF if you don't call the primary key "Id".
    public int Id { get; set; }
    public String Name { get; set; }
    public float Price { get; set; }
    public String Image { get; set; }
    public String Description { get; set; }
    //Add any additional properties.
}

public class Cart
{
    [Key]
    public int Id { get; set; }
    //Add any additional properties
}

public class CartProduct
{
    [Key]
    public int Id { get; set; }
    public int CartId {get; set; } //References Id property in Cart entity.
    public int ProductId {get; set; } //References Id property in Product entity.
    public DateTime AddedAt { get; set; }

    //These are navigation properties.
    //The foreign key attribute lets EF know what property to reference
    [ForeignKey("CartId")]
    public virtual Cart Cart { get; set; }

    [ForeignKey("ProductId")]
    public virtual Product Product { get; set; }
}
</code>```

You should create a separate set of models.  The EF models should only be used to represent your database tables and properties.  Place these models separate from your EF models...  maybe a ViewModel folder.

```<code>    public class CartProductsViewModel
    {
        public int CartId { get; set; } //Persist the cart you are adding to.
        public IEnumerable<ProductModel> Products {get; set; } //Available products

        public class ProductModel
        {
            public int Id { get; set; }
            public String Name { get; set; }
            public float Price { get; set; }
            public String Image { get; set; }
            public String Description { get; set; }
            //Add any additional properties.
         }

    }
</code>```

Now you can have ONE controller and ONE view.

```<code>public ActionResult Index(int cartId) //passing cartId for cart you are working with.
{
    var viewModel = new CartProductsViwModel();

    viewModel.CartId = cartId;
    //Get available products that you can add to cart.
    viewModel.Products = db.Products //pluralized in DbSet in EF context.
                  .Select(p => new ProductModel
                     {
                        Id = p.Id,
                        Name p.Name,
                        Price = p.Price,
                        Image = p.Image
                        Description = p.Description
                     });

    return View(viewModel);
}
</code>```

In the return, I am not specifying the viewModel name.  This is only made possible if you follow MVC guidelines and name the view the same name as the method calling, in this case index.cshtml.  And also add following to top:

```<code>@model CartProductsViwModel //may need to be fully qualified (add namespace).
</code>```

You should be able to loop through the Products in this model to show in table.  This avoids having to deal with a separate product and cart view.  As far as adding the product to the view, this can be done on the client-side.  I would suggest to try to get this working first, and then you can create a new question dedicated to the client-side work.

If you really need a dialog, you can look up JQuery dialogs.
JQuery UI dialog

You will then need to perform ajax calls to post the added product and the cartId.  The method will be something like this.

```<code>[HttpPost]
public JsonResult AddProductToCart(int cartId, ProductModel product) {}
</code>```

That would also be a separate question.  I hope this helps get you started.

Body:
Edit: the product view contains some products so I'm trying to add them one by one to the cart using a button for each product, the added products shall appear in a table in the partial view (cart) which is working fine, I'm trying now to render this cart inside a popup modal so when i press the popup button it should show me what products i added,when i still inside the product view.

I'm trying to do something like this inside the modal body:

@Html.Partial("_ShowCart", new List<InternetApp.Models.Cart>())

but this retrieves an empty list.

So I want something like this but I don't know how I could do this with different models:

@Html.Partial("_ShowCart", Model)

I have 3 models: product, cart and viewmodel:

public class Product
{
    public int id { get; set; }
    public String name { get; set; }
    public float price { get; set; }
    public String image { get; set; }
    public String description { get; set; }
    public int? CategoryId { get; set; }
}

public class Cart
{
    public int product_id { get; set; }
    public DateTime added_at { get; set; }
    public virtual Product product { get; set; }
}

public class ProductCart
{
    public Product Product { get; set; }
    public Cart Cart { get; set; }
}

The cart and the product each one has controller, I have the cart as a partial view which takes IEnumerable<Cart> and a product view which takes IEnumerable<Product>.

This is the cart index action

public ActionResult Index()
{
    List<Cart> Cart = db.Cart.Include(a => a.product).ToList();
    return PartialView("_ShowCart", Cart);
}

I don't know how to render the cart inside the product because each one has a different IEnumerable model...

Body:
Your Entity Framework (EF) models would look like the following.  I modified for suggested standardization and clarity purposes only:

public class Product
{
    [Key] //This is only needed by EF if you don't call the primary key "Id".
    public int Id { get; set; }
    public String Name { get; set; }
    public float Price { get; set; }
    public String Image { get; set; }
    public String Description { get; set; }
    //Add any additional properties.
}

public class Cart
{
    [Key]
    public int Id { get; set; }
    //Add any additional properties
}

public class CartProduct
{
    [Key]
    public int Id { get; set; }
    public int CartId {get; set; } //References Id property in Cart entity.
    public int ProductId {get; set; } //References Id property in Product entity.
    public DateTime AddedAt { get; set; }

    //These are navigation properties.
    //The foreign key attribute lets EF know what property to reference
    [ForeignKey("CartId")]
    public virtual Cart Cart { get; set; }

    [ForeignKey("ProductId")]
    public virtual Product Product { get; set; }
}

You should create a separate set of models.  The EF models should only be used to represent your database tables and properties.  Place these models separate from your EF models...  maybe a ViewModel folder.

    public class CartProductsViewModel
    {
        public int CartId { get; set; } //Persist the cart you are adding to.
        public IEnumerable<ProductModel> Products {get; set; } //Available products

        public class ProductModel
        {
            public int Id { get; set; }
            public String Name { get; set; }
            public float Price { get; set; }
            public String Image { get; set; }
            public String Description { get; set; }
            //Add any additional properties.
         }

    }

Now you can have ONE controller and ONE view.

public ActionResult Index(int cartId) //passing cartId for cart you are working with.
{
    var viewModel = new CartProductsViwModel();

    viewModel.CartId = cartId;
    //Get available products that you can add to cart.
    viewModel.Products = db.Products //pluralized in DbSet in EF context.
                  .Select(p => new ProductModel
                     {
                        Id = p.Id,
                        Name p.Name,
                        Price = p.Price,
                        Image = p.Image
                        Description = p.Description
                     });

    return View(viewModel);
}

In the return, I am not specifying the viewModel name.  This is only made possible if you follow MVC guidelines and name the view the same name as the method calling, in this case index.cshtml.  And also add following to top:

@model CartProductsViwModel //may need to be fully qualified (add namespace).

You should be able to loop through the Products in this model to show in table.  This avoids having to deal with a separate product and cart view.  As far as adding the product to the view, this can be done on the client-side.  I would suggest to try to get this working first, and then you can create a new question dedicated to the client-side work.

If you really need a dialog, you can look up JQuery dialogs.
JQuery UI dialog

You will then need to perform ajax calls to post the added product and the cartId.  The method will be something like this.

[HttpPost]
public JsonResult AddProductToCart(int cartId, ProductModel product) {}

That would also be a separate question.  I hope this helps get you started.


问:
How to define a pytest fixture to be used by all tests within a given tests subdirectory?
Given a directory tests with a few subdirectories each containing test modules, how can one create a pytest fixture to be run before each test found in a particular subdirectory only?

```<code>tests
├── __init__.py
├── subdirXX
│   ├── test_module1.py
│   ├── test_module2.py
│   ├── __init__.py
├── subdirYY
│   ├── test_module3.py
│   ├── test_module4.py
│   ├── __init__.py
</code>```

I'd like to have a fixture that will run before each test found in modules within the subdirYY only (in this case, in modules test_module3.py and test_module4.py).

I currently have a fixture defined twice, once inside each module within the subdirYY which works but is redundant:

```<code>@pytest.fixture(autouse=True)
def clean_directory():
   ...
</code>```

If this is not possible to achieve, each of the tests within the subdirYY is decorated with a custom mark (@pytest.mark.mycustommark) so making sure that a certain fixture will run before each test marked with a particular custom mark is a viable option, too.

答:
Put your autouse fixture in a conftest.py file inside subdirYY.

For more information, see the pytest docs about sharing fixtures and the docs on autouse fixtures which specifically mention conftest.py:

if an autouse fixture is defined in a conftest.py file then all tests in all test modules belows its directory will invoke the fixture.

Body:
Given a directory tests with a few subdirectories each containing test modules, how can one create a pytest fixture to be run before each test found in a particular subdirectory only?

tests
├── __init__.py
├── subdirXX
│   ├── test_module1.py
│   ├── test_module2.py
│   ├── __init__.py
├── subdirYY
│   ├── test_module3.py
│   ├── test_module4.py
│   ├── __init__.py

I'd like to have a fixture that will run before each test found in modules within the subdirYY only (in this case, in modules test_module3.py and test_module4.py).

I currently have a fixture defined twice, once inside each module within the subdirYY which works but is redundant:

@pytest.fixture(autouse=True)
def clean_directory():
   ...

If this is not possible to achieve, each of the tests within the subdirYY is decorated with a custom mark (@pytest.mark.mycustommark) so making sure that a certain fixture will run before each test marked with a particular custom mark is a viable option, too.


问:
How do i return the parent based on the value from child key?
Im trying to find a way of returning the parent(s) in an array. I have tried pickBy and other solutions on stack but it either return the whole parent array, or nothing.

This is how my array looks like, and i want to find the parents based on tags.

```<code>    {
        'fraga': "Question 1",
        'svar' : "This is this explanation",
        'tags' : ['knowledge'],
    },
    {
        'fraga': "Question 2",
        'svar' : "This is this explanation for question 2",
        'tags' : ['knowledge', 'code'],
    },
</code>```

So if i want the parents with tag knowledge i would get both "question 1" and "question 2", but if i want the parent with tags code i would only get "question 2".

答:
I wrote a simple wrapper function in case you are calling it multiple times to search for multiple tags separateliy, but you could easily just use the Lodash code from within the function.

const arr = [
  {
    'fraga': "Question 1",
    'svar' : "This is this explanation",
    'tags' : ['knowledge'],
  },
  {
    'fraga': "Question 2",
    'svar' : "This is this explanation for question 2",
    'tags' : ['knowledge', 'code'],
  }
];

console.log(getByTag(arr, 'knowledge'));
console.log(getByTag(arr, 'code'));

function getByTag(objectArray, tagName) {
  return _.filter(objectArray, (obj) => _.includes(obj.tags, tagName));
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script></code>```

Body:
Im trying to find a way of returning the parent(s) in an array. I have tried pickBy and other solutions on stack but it either return the whole parent array, or nothing.

This is how my array looks like, and i want to find the parents based on tags.

    {
        'fraga': "Question 1",
        'svar' : "This is this explanation",
        'tags' : ['knowledge'],
    },
    {
        'fraga': "Question 2",
        'svar' : "This is this explanation for question 2",
        'tags' : ['knowledge', 'code'],
    },

So if i want the parents with tag knowledge i would get both "question 1" and "question 2", but if i want the parent with tags code i would only get "question 2".

Body:
I wrote a simple wrapper function in case you are calling it multiple times to search for multiple tags separateliy, but you could easily just use the Lodash code from within the function.

const arr = [
  {
    'fraga': "Question 1",
    'svar' : "This is this explanation",
    'tags' : ['knowledge'],
  },
  {
    'fraga': "Question 2",
    'svar' : "This is this explanation for question 2",
    'tags' : ['knowledge', 'code'],
  }
];

console.log(getByTag(arr, 'knowledge'));
console.log(getByTag(arr, 'code'));

function getByTag(objectArray, tagName) {
  return _.filter(objectArray, (obj) => _.includes(obj.tags, tagName));
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>


问:
Encode String of 20 characters to 8 characters, and Decode it back
I want to know a way to encode a Plain Text of 20 characters to a Cipher of 8 characters and Decode it back to 20 characters.

The possible constituent characters are :

Like how in HexaDecimal number, the characters ranges from '0 to F', for our PlainText it ranges from '0 - A' (base 11).

The required Cipher can have combination of letters and numbers only. It should not have symbols in it.

I want a compression technique or even a program would be more helpful to both encode and decode the above requirements.

Thank You!

答:
I think it's impossible.
11^20 (672749994932560009201) is too bigger than 36^8 (2821109907456).
(11 means count of '0-A', 36 means count of 'A-Z' & '0-9').
At least 238469969 (11^20/36^8) of the plan texts will be encoded as the same output.</p>


问:
Jquery: Update only the next div with a specific class
I have a form that submits a jQuery .ajax event every time  menu's value is changed. The jQuery function queries the database for the price of an product, and then updates a div with a class of ".price" with the result. There are five of these forms on the page, and each one has a div with a class of ".price"

```<code>/* Variation Price Query */
$(".varSel").live("change", function(){
    var formdata = $(this).parents('form').serialize();
    $.ajax({
        type: "POST",
        url: "library/varPrice.php",
        data: formdata,
        success: function(html){
    $('.price').html(html);

      }
    });
});
</code>```

The problem i am having is that the function updates all of the divs with the class of ".price" and not just the next div. I have tried something like:

```<code>$(this).next('div.price').html(html);
</code>```

But it is not returning anything.

The following is an example of the html form:

```<code><form name='addToCart' id='addToCart7' action='cart.php?action=add' method='post'>
<ul class='vars' id='varlist_p7'>
    <li><label for="Size">Size</label>
    <select id="Size" name="Size" class='varSel'>
        <option>
            1oz
        </option>

        <option>
            4oz
        </option>

        <option>
            8oz
        </option>
    </select>
    </li>

    <li>
        <div class='price'>
            $ 3.00
        </div>
    </li>

    <li><input type='submit' class='buynow' value=''></li>
</ul>
</form>
</code>```

答:
since div.varSel and div.price are not siblings, you would have to go deeper than next()

```<code>$(this).parent().next("li:has(.price)").children(".price").html(html)
</code>```

should work

OwnerDisplayName: superUntitled

ContentLicense: CC BY-SA 2.5

Body:
I have a form that submits a jQuery .ajax event every time  menu's value is changed. The jQuery function queries the database for the price of an product, and then updates a div with a class of ".price" with the result. There are five of these forms on the page, and each one has a div with a class of ".price"

/* Variation Price Query */
$(".varSel").live("change", function(){
    var formdata = $(this).parents('form').serialize();
    $.ajax({
        type: "POST",
        url: "library/varPrice.php",
        data: formdata,
        success: function(html){
    $('.price').html(html);

      }
    });
});

The problem i am having is that the function updates all of the divs with the class of ".price" and not just the next div. I have tried something like:

$(this).next('div.price').html(html);

But it is not returning anything.

The following is an example of the html form:

<form name='addToCart' id='addToCart7' action='cart.php?action=add' method='post'>

Size
    <select id="Size" name="Size" class='varSel'>
        <option>
            1oz
        </option>

        <option>
            4oz
        </option>

        <option>
            8oz
        </option>
    </select>

            $ 3.00

<input type='submit' class='buynow' value=''>

</form>

Body:
since div.varSel and div.price are not siblings, you would have to go deeper than next()

$(this).parent().next("li:has(.price)").children(".price").html(html)

should work


问:
Saving Files c# - without overwriting?
I am saving data to a file every 60 secs, I have it saving every 60 secs ok but it deletes the previous data added. Is there a way in which it would add to the file rather than overwrite it. And without using save dialog as it is done in the background.

Any feedback is greatly appreciated

答:
Try,</p>

```<code>using (StreamWriter writer = new StreamWriter(@"C:\somefile.txt", true))
            {
                writer.WriteLine("Hello line..");
            }
</code>```

Title: Saving Files c# - without overwriting?

Body:
Try,

using (StreamWriter writer = new StreamWriter(@"C:\somefile.txt", true))
            {
                writer.WriteLine("Hello line..");
            }


问:
Is it right to display the table of digit?
I want to display the multiplication table of input digit but this code is not working well by using switch statement.
Please tell me where is mistake in this code.

const tables = (num) => {
  switch (num.value) {
    case num.value.match(/[0-9]+$/):
      for (var i = 1; i <= 10; i++) {
        document.write(`${num.value} * ${i} = ${num.value * i}<br>`)
      }
      break;
    default:
      return alert(`Invalid Entry!`)
      break;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>

  <p>Enter a number to get table: </p>
  <input id="number" type="text">
  <input type="submit" onclick="tables(number)">

</body></code>```

答:
This is a classic use case for an if statement:

const input = document.getElementById('number')
const button = document.getElementById('button')

button.addEventListener('click', tables)

function tables() {
  const value = input.value

  if (null === value.match(/^[0-9]+$/)) {
    // if the value doesn't only consist of numeric symbols
    // alert a message and return (stop executing the function)
    alert(`Invalid Entry!`)
    return
  }

  // if the user input is valid, proceed with the output
  for (let i = 1; i <= 10; i++) {
    document.write(`${value} × ${i} = ${value * i}<br>`)
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Enter a number to get table: </p>
<input id="number" type="text">
<input id="button" type="submit"></code>```

Read about the difference between if and switch here.

Please also note that the regular expression you provided will not always work as intended, since it asserts that any number of digits can be found at the end of the string, without accounting for anything that comes before that. I added the start position symbol (^) to make sure that only strings containing only numbers from start to finish pass the test.

Body:
I want to display the multiplication table of input digit but this code is not working well by using switch statement.
Please tell me where is mistake in this code.

const tables = (num) => {
  switch (num.value) {
    case num.value.match(/[0-9]+$/):
      for (var i = 1; i <= 10; i++) {
        document.write(`${num.value} * ${i} = ${num.value * i}<br>`)
      }
      break;
    default:
      return alert(`Invalid Entry!`)
      break;
  }
}

Enter a number to get table:

  <input id="number" type="text">
  <input type="submit" onclick="tables(number)">

Body:
This is a classic use case for an if statement:

const input = document.getElementById('number')
const button = document.getElementById('button')

button.addEventListener('click', tables)

function tables() {
  const value = input.value

  if (null === value.match(/^[0-9]+$/)) {
    // if the value doesn't only consist of numeric symbols
    // alert a message and return (stop executing the function)
    alert(`Invalid Entry!`)
    return
  }

  // if the user input is valid, proceed with the output
  for (let i = 1; i <= 10; i++) {
    document.write(`${value} &times; ${i} = ${value * i}<br>`)
  }
}

<p>Enter a number to get table: </p>
<input id="number" type="text">
<input id="button" type="submit">

Read about the difference between if and switch here.

Please also note that the regular expression you provided will not always work as intended, since it asserts that any number of digits can be found at the end of the string, without accounting for anything that comes before that. I added the start position symbol (^) to make sure that only strings containing only numbers from start to finish pass the test.


问:
Error Cannot insert explicit value for identity column in table in C#
I am trying to save multiple records in the database, the data is stored correctly in the list, but when I press the button to save into the database, it does not work.

Having only one record in the lists and pressing the button2 nothing happens, but having more than 2 records in the list and pressing the button2 the program crashes with the following error code:

Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'

SqlException: Cannot insert explicit value for identity column in table 'roll' when IDENTITY_INSERT is set to OFF

What is my mistake?

Variables:

```<code>    int p = 0;
    string x = "";
    decimal xx = 0;
    string v = "";
    decimal vv = 0;
    string f = "";
    decimal ff = 0;
    decimal pp = 0;
    List<int> piece = new List<int>();
    List<string> protein = new List<string>();
    List<string> vegetable = new List<string>();
    List<string> wrapped = new List<string>();
    List<decimal> piecePrice = new List<decimal>();
    List<decimal> proteinPrice = new List<decimal>();
    List<decimal> vegetablePrice = new List<decimal>();
    List<decimal> wrappedPrice = new List<decimal>();
</code>```

Button Click:

```<code>private void button1_Click(object sender, EventArgs e)
{
        piece.Add(Convert.ToInt32(comboBox1.SelectedValue.ToString()));
        protein.Add(comboBox2.SelectedValue.ToString());
        vegetable.Add(comboBox3.SelectedValue.ToString());
        wrapped.Add(comboBox4.SelectedValue.ToString());

        for (int i = 0; i < piece.Count(); i++)
        {
            var p = piece[piece.Count - 1];
            var h = protein[protein.Count - 1];
            var v = vegetable[vegetable.Count - 1];
            var f = wrapped[ wrapped.Count - 1];

            using (var context = new AppDbContext())
            {
                 piecePrice.Add(Convert.ToDecimal(context.piece.SingleOrDefault(x => x.quantity == p)?.price));
                proteinPrice.Add(Convert.ToDecimal(context.protein.SingleOrDefault(x => x.name == h)?.price));
                vegetablePrice.Add(Convert.ToDecimal(context.vegetable.SingleOrDefault(x => x.name == h)?.price));
                wrappedPrice.Add(Convert.ToDecimal(context. wrapped.SingleOrDefault(x => x.name == f)?.price));
            }
        }
}
</code>```

Save button click handler:

```<code>private void button2_Click(object sender, EventArgs e)
{
        List<rolls> rolls = new List<rolls>();

        for (int i = 0; i < piece.Count(); i++)
        {
            p = piece[i];
            pp = piecePrice[i];
            x = protein[i];
            v = vegetable[i];
            f =  wrapped[i];
            xx = proteinPrice[i];
            vv = vegetablePrice[i];
            ff =  wrappedPrice[i];

            using (var context = new AppDbContext())
            {
                rolls.Add(new rolls()
                    {
                        quantity = p,
                        quantity_price = pp,
                        protein = x,
                        protein_price = xx,
                        vegetable = v,
                        vegetable_price = vv,
                        wrapped = f,
                        wrapped_price = ff
                    });

                context.AddRange(rolls);
                context.SaveChanges();
            }
        }
}
</code>```

Rolls table:

```<code> public class rolls
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int rollId { get; set; }

        public int quantity { get; set; }
        public decimal quantity_price { get; set; }
        public string protein { get; set; }

        public decimal protein_price { get; set; }
        public string vegetable { get; set; }

        public decimal vegetable_price { get; set; }
        public string wrapped { get; set; }

        public decimal wrapped_price { get; set; }

    }
</code>```

答:
My first impression is that you want to insert the same values with your Rolls list. Remove "using(){...}" code lines from for loop. Just prepare your list for the inserting process. When for loop ended you can insert your list data with AddRange functions.

```<code>private void button2_Click(object sender, EventArgs e)
{
    List<rolls> rolls = new List<rolls>();
    for (int i = 0; i < piece.Count(); i++)
    {
        p = piece[i];
        pp = piecePrice[i];
        x = protein[i];
        v = vegetable[i];
        f =  wrapped[i];
        xx = proteinPrice[i];
        vv = vegetablePrice[i];
        ff =  wrappedPrice[I];

        rolls.Add(new rolls()
                {
                    quantity = p,
                    quantity_price = pp,
                    protein=x,
                    protein_price=xx,
                    vegetable=v,
                    vegetable_price=vv,
                    wrapped=f,
                     wrapped_price = ff

        });
    }

    using (var context = new AppDbContext())
    {
       context.AddRange(rolls);
       context.SaveChanges();
    }
}
</code>```

The other option is you want to insert a record with an identity column (an ID or one of the columns your Rolls table) but this column cannot be insertable. Please check it.

Body:
I am trying to save multiple records in the database, the data is stored correctly in the list, but when I press the button to save into the database, it does not work.

Having only one record in the lists and pressing the button2 nothing happens, but having more than 2 records in the list and pressing the button2 the program crashes with the following error code:

Microsoft.EntityFrameworkCore.DbUpdateException: 'An error occurred while updating the entries. See the inner exception for details.'

SqlException: Cannot insert explicit value for identity column in table 'roll' when IDENTITY_INSERT is set to OFF

What is my mistake?

Variables:

    int p = 0;
    string x = "";
    decimal xx = 0;
    string v = "";
    decimal vv = 0;
    string f = "";
    decimal ff = 0;
    decimal pp = 0;
    List<int> piece = new List<int>();
    List<string> protein = new List<string>();
    List<string> vegetable = new List<string>();
    List<string> wrapped = new List<string>();
    List<decimal> piecePrice = new List<decimal>();
    List<decimal> proteinPrice = new List<decimal>();
    List<decimal> vegetablePrice = new List<decimal>();
    List<decimal> wrappedPrice = new List<decimal>();

Button Click:

private void button1_Click(object sender, EventArgs e)
{
        piece.Add(Convert.ToInt32(comboBox1.SelectedValue.ToString()));
        protein.Add(comboBox2.SelectedValue.ToString());
        vegetable.Add(comboBox3.SelectedValue.ToString());
        wrapped.Add(comboBox4.SelectedValue.ToString());

        for (int i = 0; i < piece.Count(); i++)
        {
            var p = piece[piece.Count - 1];
            var h = protein[protein.Count - 1];
            var v = vegetable[vegetable.Count - 1];
            var f = wrapped[ wrapped.Count - 1];

            using (var context = new AppDbContext())
            {
                 piecePrice.Add(Convert.ToDecimal(context.piece.SingleOrDefault(x => x.quantity == p)?.price));
                proteinPrice.Add(Convert.ToDecimal(context.protein.SingleOrDefault(x => x.name == h)?.price));
                vegetablePrice.Add(Convert.ToDecimal(context.vegetable.SingleOrDefault(x => x.name == h)?.price));
                wrappedPrice.Add(Convert.ToDecimal(context. wrapped.SingleOrDefault(x => x.name == f)?.price));
            }
        }
}

Save button click handler:

private void button2_Click(object sender, EventArgs e)
{
        List<rolls> rolls = new List<rolls>();

        for (int i = 0; i < piece.Count(); i++)
        {
            p = piece[i];
            pp = piecePrice[i];
            x = protein[i];
            v = vegetable[i];
            f =  wrapped[i];
            xx = proteinPrice[i];
            vv = vegetablePrice[i];
            ff =  wrappedPrice[i];

            using (var context = new AppDbContext())
            {
                rolls.Add(new rolls()
                    {
                        quantity = p,
                        quantity_price = pp,
                        protein = x,
                        protein_price = xx,
                        vegetable = v,
                        vegetable_price = vv,
                        wrapped = f,
                        wrapped_price = ff
                    });

                context.AddRange(rolls);
                context.SaveChanges();
            }
        }
}

Rolls table:

 public class rolls
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int rollId { get; set; }

        public int quantity { get; set; }
        public decimal quantity_price { get; set; }
        public string protein { get; set; }

        public decimal protein_price { get; set; }
        public string vegetable { get; set; }

        public decimal vegetable_price { get; set; }
        public string wrapped { get; set; }

        public decimal wrapped_price { get; set; }

    }

Body:
My first impression is that you want to insert the same values with your Rolls list. Remove "using(){...}" code lines from for loop. Just prepare your list for the inserting process. When for loop ended you can insert your list data with AddRange functions.

private void button2_Click(object sender, EventArgs e)
{
    List<rolls> rolls = new List<rolls>();
    for (int i = 0; i < piece.Count(); i++)
    {
        p = piece[i];
        pp = piecePrice[i];
        x = protein[i];
        v = vegetable[i];
        f =  wrapped[i];
        xx = proteinPrice[i];
        vv = vegetablePrice[i];
        ff =  wrappedPrice[I];

        rolls.Add(new rolls()
                {
                    quantity = p,
                    quantity_price = pp,
                    protein=x,
                    protein_price=xx,
                    vegetable=v,
                    vegetable_price=vv,
                    wrapped=f,
                     wrapped_price = ff

        });
    }

    using (var context = new AppDbContext())
    {
       context.AddRange(rolls);
       context.SaveChanges();
    }
}

The other option is you want to insert a record with an identity column (an ID or one of the columns your Rolls table) but this column cannot be insertable. Please check it.


问:
Join table with null in all group
im new in stack. I cant found problem like this.

I have two tables.

One table x with transactions

```<code>Hour (approximation to full hour)   id_seler     expenses
1:00                                    1             3,04
2:00                                    2             4,04
3:00                                    3             5,03
4:00                                    4             6,04
3:00                                    4             7,04
</code>```

Second table y with limit seler id:

```<code>seler_id
   1
   2
   4
   5
</code>```

I try to join table y to table x to get score like this

```<code>id_seler      hour            sum expensex
   1        1:00              3,04
   1        2:00              null
   1        3:00              null
   1        4:00              null
   2        1:00              null
   2        2:00              4,04
   2        3:00              null
   2        4:00              null
   4        1:00              null
   4        2:00              null
   4       3:00               7,04
   4        4:00              6,04
   5        1:00              null
   5        2:00              null
   5       3:00               null
   5       4:00               null
</code>```

I want that query back me all id_seler for all hours with expenses.

I tried to use left join

```<code>from y left join x on x.id_seller=y.id_seller
group by hour
</code>```

but it back me null only for this id_seler which is dosent exist in table x next of last hour - In this exaple for id_seler=5

答:
You need to extract the distinct hour and cross join it with Y table, Then you will need to left join it with X table as follows:

```<code>SELECT
    Y.SELER_ID,
    XX.HOUR,
    X.EXPENSES
FROM
    Y CROSS JOIN (
        SELECT DISTINCT HOUR AS HOUR
          FROM X
    ) XX
    LEFT JOIN X ON X.HOUR = XX.HOUR AND X.ID_SELER = Y.SELER_ID
</code>```

Title: Join table with null in all group

Body:
im new in stack. I cant found problem like this.

I have two tables.

One table x with transactions

Hour (approximation to full hour)   id_seler     expenses
1:00                                    1             3,04
2:00                                    2             4,04
3:00                                    3             5,03
4:00                                    4             6,04
3:00                                    4             7,04

Second table y with limit seler id:

seler_id
   1
   2
   4
   5

I try to join table y to table x to get score like this

id_seler      hour            sum expensex
   1        1:00              3,04
   1        2:00              null
   1        3:00              null
   1        4:00              null
   2        1:00              null
   2        2:00              4,04
   2        3:00              null
   2        4:00              null
   4        1:00              null
   4        2:00              null
   4       3:00               7,04
   4        4:00              6,04
   5        1:00              null
   5        2:00              null
   5       3:00               null
   5       4:00               null

I want that query back me all id_seler for all hours with expenses.

I tried to use left join

from y left join x on x.id_seller=y.id_seller
group by hour

but it back me null only for this id_seler which is dosent exist in table x next of last hour - In this exaple for id_seler=5

Body:
You need to extract the distinct hour and cross join it with Y table, Then you will need to left join it with X table as follows:

SELECT
    Y.SELER_ID,
    XX.HOUR,
    X.EXPENSES
FROM
    Y CROSS JOIN (
        SELECT DISTINCT HOUR AS HOUR
          FROM X
    ) XX
    LEFT JOIN X ON X.HOUR = XX.HOUR AND X.ID_SELER = Y.SELER_ID