问:
Unable to update database to match the current model because there are pending changes
I have a project built in visual studio 2013 environment with the Db built using EF 5 code first.
I have had my APIs working fine for a long time but all of a sudden I started to get this error that says:

Unable to update database to match the current model because there are pending changes and automatic migration is disabled. Either write the pending model changes to a code-based migration or enable automatic migration. Set DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable automatic migration.

when I try to reach the end points of my APIs. I tried adding a new migration and then updating the database but still got the error. I then drop my entire database and recreated with EF. The end points of my APIs started working fine but then again I started getting this error on the web page. I have automatic migration set to true in the configuration file. I really have no idea why this is happening over and over. It's getting me really frustrated.
Here's the full stack trace of the error:

[AutomaticMigrationsDisabledException: Unable to update database to
  match the current model because there are pending changes and
  automatic migration is disabled. Either write the pending model
  changes to a code-based migration or enable automatic migration. Set
  DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable
  automatic migration.]

  System.Data.Entity.Migrations.DbMigrator.Upgrade(IEnumerable`1
  pendingMigrations, String targetMigrationId, String lastMigrationId)
  +579    System.Data.Entity.Migrations.DbMigrator.UpdateInternal(String targetMigration) +445

  System.Data.Entity.Migrations.<>c__DisplayClassc.b__b() +13

  System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action
  mustSucceedToKeepDatabase) +422

  System.Data.Entity.Migrations.DbMigrator.Update(String
  targetMigration) +78

  System.Data.Entity.Migrations.Infrastructure.MigratorBase.Update() +12
  YourTimeSite.Global.ApplyDatabaseMigrations() in
  c:\Users\Ahmed\Desktop\YourTimeSite\YourTimeSite\Global.asax.cs:55

  YourTimeSite.Global.Application_Start(Object sender, EventArgs e) in
  c:\Users\Ahmed\Desktop\YourTimeSite\YourTimeSite\Global.asax.cs:32

[HttpException (0x80004005): Unable to update database to match the
  current model because there are pending changes and automatic
  migration is disabled. Either write the pending model changes to a
  code-based migration or enable automatic migration. Set
  DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable
  automatic migration.]

  System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
  context, HttpApplication app) +9966013

  System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
  appContext, HttpContext context, MethodInfo[] handlers) +118

  System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
  MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172

  System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
  appContext, HttpContext context) +352

  System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
  appContext) +296

[HttpException (0x80004005): Unable to update database to match the
  current model because there are pending changes and automatic
  migration is disabled. Either write the pending model changes to a
  code-based migration or enable automatic migration. Set
  DbMigrationsConfiguration.AutomaticMigrationsEnabled to true to enable
  automatic migration.]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9947380
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +101

答:
In your database initializer turn AutomaticMigrations to true then revert it back to false, this would fix the issue:

```<code>internal class MyDatabaseInitializer : MigrateDatabaseToLatestVersion<MyDBContext, MyConfiguration>{

}

internal sealed class MyConfiguration : DbMigrationsConfiguration<MyDBContext>{

    public MyConfiguration(){
        AutomaticMigrationsEnabled = true;
    }
}
</code>```

Body:
In your database initializer turn AutomaticMigrations to true then revert it back to false, this would fix the issue:

internal class MyDatabaseInitializer : MigrateDatabaseToLatestVersion<MyDBContext, MyConfiguration>{

}

internal sealed class MyConfiguration : DbMigrationsConfiguration<MyDBContext>{

    public MyConfiguration(){
        AutomaticMigrationsEnabled = true;
    }
}


来源: stackexchange

问:
React.js: formData has no value when appending value from file using material-ui-dropzone
I'm trying to implement an upload function using a library called material-ui-dropzone

I think uploading the file is working fine, however, when I send a POST request using axios I always get an empty formData even before sending the request

Inward.js

```<code>import React, { useState, useEffect, forwardRef } from "react";
import useStyles from "./styles";
import { Paper, Button, Grid } from "@material-ui/core";
import { DropzoneDialog } from "material-ui-dropzone";
import MaterialTable from "material-table";
import {
  AddBox,
  ArrowDownward,
  Check,
  ChevronLeft,
  ChevronRight,
  Clear,
  DeleteOutline,
  Edit,
  FilterList,
  FirstPage,
  LastPage,
  Remove,
  SaveAlt,
  Search,
  ViewColumn,
  Publish,
} from "@material-ui/icons";
import InwardService from "../../services/InwardService";

export default function Inward() {
  const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => (
      <ChevronRight {...props} ref={ref} />
    )),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => (
      <ChevronLeft {...props} ref={ref} />
    )),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => (
      <ArrowDownward {...props} ref={ref} />
    )),
    ThirdStateCheck: forwardRef((props, ref) => (
      <Remove {...props} ref={ref} />
    )),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />),
  };

  var classes = useStyles();

  const [isDropzoneOpen, setIsDropzoneOpen] = useState(false);
  const [files, setFiles] = useState([]);

  var formData = new FormData();

  useEffect(() => {
    if (files.length > 0) {
      const newFilesMap = files.map(fileMap => {
        formData.append("file", fileMap);
      });
      InwardService.uploadPesonetFile(newFilesMap);
    }
  }, [files]);

  return (
    <>
      <Paper classes={{ root: classes.paperRoot }}>
        <MaterialTable icons={tableIcons} title="" />
        <Grid item xs={3}>
          <br />
          <Button
            variant="contained"
            color="default"
            className={classes.button}
            startIcon={<Publish />}
            onClick={() => setIsDropzoneOpen(true)}
          >
            Upload File
          </Button>
        </Grid>

        <DropzoneDialog
          acceptedFiles={[".inc"]}
          cancelButtonText={"cancel"}
          submitButtonText={"submit"}
          maxFileSize={5000000}
          open={isDropzoneOpen}
          onClose={() => setIsDropzoneOpen(false)}
          onSave={(files) => {
            setFiles(files);
            setIsDropzoneOpen(false);
          }}
          showPreviews={true}
          showFileNamesInPreview={true}
        />
      </Paper>
    </>
  );
}
</code>```

InwardService.js

```<code>import { Component } from "react";
import axios from "axios";
import { API_BASE_URL_UPLOAD } from "../constants/APIUtils";

class InwardService extends Component {

  uploadPesonetFile(files) {
    return axios.post(`${API_BASE_URL_UPLOAD}`, files, {headers: { 'Content-Type': 'multipart/form-data' }})
  }
}

export default new InwardService();
</code>```

Seems like this line does not take effect:

```<code>formData.append("file", fileMap);
</code>```

Any idea as to why I get no value in formData even after appending the file/file map into it?

答:
you should pass formData to uploadPesonetFile in InwardService, you are passing newFilesMap

so the code should be :

```<code>files.map(fileMap => {
   formData.append("file", fileMap);
});
InwardService.uploadPesonetFile(formData);
</code>```

instead of :

```<code>const newFilesMap = files.map(fileMap => {
   formData.append("file", fileMap);
});
InwardService.uploadPesonetFile(newFilesMap);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to implement an upload function using a library called material-ui-dropzone

I think uploading the file is working fine, however, when I send a POST request using axios I always get an empty formData even before sending the request

Inward.js

import React, { useState, useEffect, forwardRef } from "react";
import useStyles from "./styles";
import { Paper, Button, Grid } from "@material-ui/core";
import { DropzoneDialog } from "material-ui-dropzone";
import MaterialTable from "material-table";
import {
  AddBox,
  ArrowDownward,
  Check,
  ChevronLeft,
  ChevronRight,
  Clear,
  DeleteOutline,
  Edit,
  FilterList,
  FirstPage,
  LastPage,
  Remove,
  SaveAlt,
  Search,
  ViewColumn,
  Publish,
} from "@material-ui/icons";
import InwardService from "../../services/InwardService";

export default function Inward() {
  const tableIcons = {
    Add: forwardRef((props, ref) => <AddBox {...props} ref={ref} />),
    Check: forwardRef((props, ref) => <Check {...props} ref={ref} />),
    Clear: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Delete: forwardRef((props, ref) => <DeleteOutline {...props} ref={ref} />),
    DetailPanel: forwardRef((props, ref) => (
      <ChevronRight {...props} ref={ref} />
    )),
    Edit: forwardRef((props, ref) => <Edit {...props} ref={ref} />),
    Export: forwardRef((props, ref) => <SaveAlt {...props} ref={ref} />),
    Filter: forwardRef((props, ref) => <FilterList {...props} ref={ref} />),
    FirstPage: forwardRef((props, ref) => <FirstPage {...props} ref={ref} />),
    LastPage: forwardRef((props, ref) => <LastPage {...props} ref={ref} />),
    NextPage: forwardRef((props, ref) => <ChevronRight {...props} ref={ref} />),
    PreviousPage: forwardRef((props, ref) => (
      <ChevronLeft {...props} ref={ref} />
    )),
    ResetSearch: forwardRef((props, ref) => <Clear {...props} ref={ref} />),
    Search: forwardRef((props, ref) => <Search {...props} ref={ref} />),
    SortArrow: forwardRef((props, ref) => (
      <ArrowDownward {...props} ref={ref} />
    )),
    ThirdStateCheck: forwardRef((props, ref) => (
      <Remove {...props} ref={ref} />
    )),
    ViewColumn: forwardRef((props, ref) => <ViewColumn {...props} ref={ref} />),
  };

  var classes = useStyles();

  const [isDropzoneOpen, setIsDropzoneOpen] = useState(false);
  const [files, setFiles] = useState([]);

  var formData = new FormData();

  useEffect(() => {
    if (files.length > 0) {
      const newFilesMap = files.map(fileMap => {
        formData.append("file", fileMap);
      });
      InwardService.uploadPesonetFile(newFilesMap);
    }
  }, [files]);

  return (
    <>
      <Paper classes={{ root: classes.paperRoot }}>
        <MaterialTable icons={tableIcons} title="" />
        <Grid item xs={3}>

          <Button
            variant="contained"
            color="default"
            className={classes.button}
            startIcon={<Publish />}
            onClick={() => setIsDropzoneOpen(true)}
          >
            Upload File
          </Button>
        </Grid>

        <DropzoneDialog
          acceptedFiles={[".inc"]}
          cancelButtonText={"cancel"}
          submitButtonText={"submit"}
          maxFileSize={5000000}
          open={isDropzoneOpen}
          onClose={() => setIsDropzoneOpen(false)}
          onSave={(files) => {
            setFiles(files);
            setIsDropzoneOpen(false);
          }}
          showPreviews={true}
          showFileNamesInPreview={true}
        />
      </Paper>
    </>
  );
}

InwardService.js

import { Component } from "react";
import axios from "axios";
import { API_BASE_URL_UPLOAD } from "../constants/APIUtils";

class InwardService extends Component {

  uploadPesonetFile(files) {
    return axios.post(`${API_BASE_URL_UPLOAD}`, files, {headers: { 'Content-Type': 'multipart/form-data' }})
  }
}

export default new InwardService();

Seems like this line does not take effect:

formData.append("file", fileMap);

Any idea as to why I get no value in formData even after appending the file/file map into it?

Body:
you should pass formData to uploadPesonetFile in InwardService, you are passing newFilesMap

so the code should be :

files.map(fileMap => {
   formData.append("file", fileMap);
});
InwardService.uploadPesonetFile(formData);

instead of :

const newFilesMap = files.map(fileMap => {
   formData.append("file", fileMap);
});
InwardService.uploadPesonetFile(newFilesMap);


问:
create a reverse method where elements are reversed in array
Here list is the name of the array. I have a swap method so trying to use it to make a reverse method of an array string. so if the elements in an array are 1,2,3,4 they should become 4,3,2,1. I don;t understand where the flaw is in my logic as with my current code only the first and last elements are getting swapped.</p>

```<code> private void swap(int i, int j)

    {
        int temp;

        temp = list[i];
        list[i] = list[j];
        list[j] = temp;

    }

    public void reverse()
    {
        int y=1;
        for(int x =0; x<list.length-1; x++)
        {
        swap(x,list.length-y);
        ++y;
        }
    }
</code>```

答:
int y=1;
        // add and/or modify code to complete the method
        for(int x =0; x<list.length-1; x++)  //wrong, should only loop to len/2
        {
        swap(x,list.length-y);
        ++y;
        }
```

<p>the right code should be:</p>

<pre class="lang-java prettyprint-override"><code>int mid = (list.length - 1) / 2;
int len = list.length;
for (int i = 0; i <= mid; i++) {
  swap(i, len - 1 - i);
}

</code>```

Body:
Here list is the name of the array. I have a swap method so trying to use it to make a reverse method of an array string. so if the elements in an array are 1,2,3,4 they should become 4,3,2,1. I don;t understand where the flaw is in my logic as with my current code only the first and last elements are getting swapped.

 private void swap(int i, int j)

    {
        int temp;

        temp = list[i];
        list[i] = list[j];
        list[j] = temp;

    }

    public void reverse()
    {
        int y=1;
        for(int x =0; x<list.length-1; x++)
        {
        swap(x,list.length-y);
        ++y;
        }
    }

Body:
int y=1;
        // add and/or modify code to complete the method
        for(int x =0; x<list.length-1; x++)  //wrong, should only loop to len/2
        {
        swap(x,list.length-y);
        ++y;
        }

the right code should be:

int mid = (list.length - 1) / 2;
int len = list.length;
for (int i = 0; i <= mid; i++) {
  swap(i, len - 1 - i);
}


问:
ListPlot: (data from Table) is not a list of numbers or pairs of numbers
I was hoping you could help me solve this error. I have used the ListPlot function to plot the points from a table containing my data but there's an error saying that the data from that table is not a list of numbers or pairs of numbers. I looked at a similar question (ListPlot: Data is not a list of numbers or pairs of numbers) but I don't know how to cut my data to the previous value since I used the Table function instead of enumerating all my data.

Here is the code that I have:

```<code>ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]3[[i, 1]], Re\[Sigma]3[[i, 2]]}, {i, data}],
  TheoRe, TheoRe2, TheoRe3},
 Joined -> {False, False, False, True, True, True},
 PlotRange -> {{0.2, 1}, All},
 PlotStyle -> {Red, Green, Blue, Red, Green, Blue}, Frame -> True,
 FrameLabel -> {"Frequency (THz)", "Re[\[Sigma]](S/cm)"}]
</code>```

Here is the error message:

ListPlot:{{{0.195,542.817},{0.2025,537.982},{0.21,532.924},{0.2175,527.697},{0.225,522.354},{0.2325,516.942},<<40>>,{0.54,525.589},{0.5475,533.829},{0.555,542.419},{0.5625,551.344},<<58>>},{<<1>>},<<2>>,{},{}} is not a list of numbers or pairs of numbers.

Thanks in advance!

答:
Showing the exact contents of that error message was VERY helpful. Thank you for that.

Does

```<code>ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}]}]
</code>```

correctly display the first set of points?

Does

```<code>ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}]}]
</code>```

correctly display the first two sets of points?

Does

```<code>ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]3[[i, 1]], Re\[Sigma]3[[i, 2]]}, {i, data}]}]
</code>```

correctly display the first three sets of points?

Does

```<code>ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]3[[i, 1]], Re\[Sigma]3[[i, 2]]}, {i, data}],
  TheoRe}]
</code>```

correctly display the first four sets of points?

If you then insert TheoRe2 does the error appear? If you then insert TheoRe3 does the error appear?

The error message sort of hints that the last list or the last two or maybe the last three lists of points might be empty and that might be causing the error. Can you check to see that TheoReand TheoRe2 and TheoRe3 are lists of points that can be plotted, even by themselves?

Body:
I was hoping you could help me solve this error. I have used the ListPlot function to plot the points from a table containing my data but there's an error saying that the data from that table is not a list of numbers or pairs of numbers. I looked at a similar question (ListPlot: Data is not a list of numbers or pairs of numbers) but I don't know how to cut my data to the previous value since I used the Table function instead of enumerating all my data.

Here is the code that I have:

ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]3[[i, 1]], Re\[Sigma]3[[i, 2]]}, {i, data}],
  TheoRe, TheoRe2, TheoRe3},
 Joined -> {False, False, False, True, True, True},
 PlotRange -> {{0.2, 1}, All},
 PlotStyle -> {Red, Green, Blue, Red, Green, Blue}, Frame -> True,
 FrameLabel -> {"Frequency (THz)", "Re[\[Sigma]](S/cm)"}]

Here is the error message:

ListPlot:{{{0.195,542.817},{0.2025,537.982},{0.21,532.924},{0.2175,527.697},{0.225,522.354},{0.2325,516.942},<<40>>,{0.54,525.589},{0.5475,533.829},{0.555,542.419},{0.5625,551.344},<<58>>},{<<1>>},<<2>>,{},{}} is not a list of numbers or pairs of numbers.

Thanks in advance!

Body:
Showing the exact contents of that error message was VERY helpful. Thank you for that.

Does

ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}]}]

correctly display the first set of points?

Does

ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}]}]

correctly display the first two sets of points?

Does

ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]3[[i, 1]], Re\[Sigma]3[[i, 2]]}, {i, data}]}]

correctly display the first three sets of points?

Does

ListPlot[{Table[{Re\[Sigma][[i, 1]], Re\[Sigma][[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]2[[i, 1]], Re\[Sigma]2[[i, 2]]}, {i, data}],
  Table[{Re\[Sigma]3[[i, 1]], Re\[Sigma]3[[i, 2]]}, {i, data}],
  TheoRe}]

correctly display the first four sets of points?

If you then insert TheoRe2 does the error appear? If you then insert TheoRe3 does the error appear?

The error message sort of hints that the last list or the last two or maybe the last three lists of points might be empty and that might be causing the error. Can you check to see that TheoReand TheoRe2 and TheoRe3 are lists of points that can be plotted, even by themselves?


问:
In Haskell, can you create an object of a class?
In a Haskell program I'm trying to debug, there is a class defined:

```<code>class Dictionary d where
  lookupIn :: d -> Word -> String
</code>```

I'd like to create a variable called runs and make it of type Dictionary so I could use it in the lookupIn function. However, nothing is working. I've tried type runs = Dictionary, and even data runs = Dictionary but nothing is working.

答:
One way to think of it is this:

In an OO language a class defines both a type (i.e. a set of potential values) and a set of other types (i.e. the potential descendant classes).

In Haskell a typeclass defines only a set of types (i.e. the potential "instances" of the typeclass). A typeclass is not itself a type.

(Actually I'm skating over the distinction in set theory between a set and a class, which is why they are called "typeclasses" not "typesets". But that's not important here.)

ContentLicense: CC BY-SA 3.0

Body:
In a Haskell program I'm trying to debug, there is a class defined:

class Dictionary d where
  lookupIn :: d -> Word -> String

I'd like to create a variable called runs and make it of type Dictionary so I could use it in the lookupIn function. However, nothing is working. I've tried type runs = Dictionary, and even data runs = Dictionary but nothing is working.


问:
Mongodb findoneandupdate with aggregation pipeline
I have a data in MongoDB like this

```<code>    {"_id":{"$oid":"5ec4ed0b94996124187b95ce"},
           "cid":"245345323",
     "dtl":[
          {"_id":{"$oid":"5ed5ab655df7930ec424be1e"},
              "sid":"test",
              "amt":{"$numberInt":"48"},
              "Name":"test"},
          {"_id":{"$oid":"5ed5ac9f79a75423d4bc0270"},
             "sid":"s",
             "amt":{"$numberInt":"14"},
             "Name":"sfds"},
          {"_id":{"$oid":"5ed5ace7d204ab144863ed7a"},
             "sid":"wesad",
             "amt":{"$numberInt":"6"},
             "Name":"2sdad"
          },
        "updated":{"$date":{"$numberLong":"1589964043787"}},
        "__v":{"$numberInt":"6"},
       "TotalAmt":{"$numberInt":"68"}}
</code>```

I need to update the TotalAmt field only if amt field in the array has value greater than 10. I have used the below 2 options

```<code>PM.findOneAndUpdate(
      {
        _id: MongoId,
      },
      [
        {
          $set: {
            //TotalAmt: { $sum: '$dtl.amt' },
            /*TotalAmt: {
              $cond: {
                if: { $gte: ['$dtl.amt', 10] },
                then: { $sum: '$dtl.amt' },
                else: 0,
              },
            },*/
          },
        },
      ],
      { new: true }
    )
</code>```

It works fine without amt > 10 condition (first option commented).  But not working if I add the condition. Any help would be appreciated. Thanks

答:
Try using $map to change the $sum's input structure:

```<code>
PM.findOneAndUpdate(
    {
        _id: MongoId,
    },
    [
        {
            $set: {
                TotalAmt: {
                    $cond: {
                        if: {$gte: ['$dtl.amt', 10]},
                        then: {
                            $sum: {
                                $map: {
                                   input: '$dtl',
                                   as: "item",
                                   in: "$$item.amt"
                                }
                            },
                        },
                        else: 0, // 0 or "$TotalAmt" ?
                    },
                },
            },
        },
    ],
    {new: true}
)
</code>```

Body:
I have a data in MongoDB like this

    {"_id":{"$oid":"5ec4ed0b94996124187b95ce"},
           "cid":"245345323",
     "dtl":[
          {"_id":{"$oid":"5ed5ab655df7930ec424be1e"},
              "sid":"test",
              "amt":{"$numberInt":"48"},
              "Name":"test"},
          {"_id":{"$oid":"5ed5ac9f79a75423d4bc0270"},
             "sid":"s",
             "amt":{"$numberInt":"14"},
             "Name":"sfds"},
          {"_id":{"$oid":"5ed5ace7d204ab144863ed7a"},
             "sid":"wesad",
             "amt":{"$numberInt":"6"},
             "Name":"2sdad"
          },
        "updated":{"$date":{"$numberLong":"1589964043787"}},
        "__v":{"$numberInt":"6"},
       "TotalAmt":{"$numberInt":"68"}}

I need to update the TotalAmt field only if amt field in the array has value greater than 10. I have used the below 2 options

PM.findOneAndUpdate(
      {
        _id: MongoId,
      },
      [
        {
          $set: {
            //TotalAmt: { $sum: '$dtl.amt' },
            /*TotalAmt: {
              $cond: {
                if: { $gte: ['$dtl.amt', 10] },
                then: { $sum: '$dtl.amt' },
                else: 0,
              },
            },*/
          },
        },
      ],
      { new: true }
    )

It works fine without amt > 10 condition (first option commented).  But not working if I add the condition. Any help would be appreciated. Thanks

Body:
Try using $map to change the $sum's input structure:

PM.findOneAndUpdate(
    {
        _id: MongoId,
    },
    [
        {
            $set: {
                TotalAmt: {
                    $cond: {
                        if: {$gte: ['$dtl.amt', 10]},
                        then: {
                            $sum: {
                                $map: {
                                   input: '$dtl',
                                   as: "item",
                                   in: "$$item.amt"
                                }
                            },
                        },
                        else: 0, // 0 or "$TotalAmt" ?
                    },
                },
            },
        },
    ],
    {new: true}
)


问:
two sets were not equal, but are equal after casting to list and cast back to set
Does anyone got this weird outcome before?

>>> a == b
False
>>> list(sorted(a)) == list(sorted(b))
True
>>> set(list(a)) == set(list(b))
True
```

<p>Where <code>a</code> and <code>b</code> above are <code>set</code> containing custom class instances. </p>

<p>This custom class inherited from <code>MutableMapping</code> with both <code>__eq__()</code> and <code>__hash__()</code> implemented as follows:</p>

<pre class="lang-py prettyprint-override"><code>def to_json(self) -> dict:
    # Code returning the data of this class

def __eq__(self, other):
    if isinstance(other, Model):
        return self.to_json() == other.to_json() and type(self) == type(other)
    elif isinstance(other, MutableMapping):
        return self.to_json() == other
    else:
        return False

def __hash__(self):
    d = self.to_json()

    hash_list = []

    for k, v in d.items():
        if isinstance(v, list):
            v = tuple(v)
        elif isinstance(v, dict):
            v = tuple(v.items())
        elif isinstance(v, Model):
            v = hash(v)

        hash_list.append((k, v))

    return hash(tuple(hash_list))
</code>```

I also test the hash code of these elements, it turns out it is the same. Below is my script to test:

>>> [hash(m) for m in a]
[-1696378346402890742, 3465342798672228497, 5576155172607749152]
>>> [hash(m) for m in b]
[-1696378346402890742, 3465342798672228497, 5576155172607749152]
```

<p>I've found that there's some work to do with <code>in</code>, but I don't know what should I implement. I also don't know why this is its behavior.</p>

<pre class="lang-py prettyprint-override"><code>>>> [(m in b) for m in a]
[False, False, False]
>>> [(m in b) for m in set(list(a))]
[False, False, False]
>>> [(m in set(list(b))) for m in a]
[True, True, True]
>>> [(m in set(list(b))) for m in set(list(b))]
[True, True, True]
</code>```

Any fix that could potentially avoid/correct this weird behavior and the reason why this is how it works would be appreciated. Thanks!

答:
I think in the case of a list, the outcome is based on the result of __eq__ only, whereas in the case of sets, it depends on __hash__ as well.
In a minimal example like the following, you can see that lists of different objects with the same __eq__-value are evaluated to be the same, whereas sets are not. If you define a __hash__-function that depends on the value only (not on the instance), also the corresponding sets evaluate to equal.

```<code>class EA2:
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        if type(self) == type(other):
            return self.id == other.id
        else:
            return False

    def __hash__(self):
        #a = hash((id(self), self.id))
        a = self.id
        #a = randint(1,1000)
        print("hash= ", a)
        return a

print({EA2(1), EA2(2)} == {EA2(1), EA2(2)})
print(list({EA2(1), EA2(2)}) == list({EA2(1), EA2(2)}))
print(EA2(1) == EA2(1))
</code>```

If your comparisons evaluate to False despite equal hashes, maybe there is a different implementation of the __hash__-function around (due to subclassing)?

Body:
Does anyone got this weird outcome before?

>>> a == b
False
>>> list(sorted(a)) == list(sorted(b))
True
>>> set(list(a)) == set(list(b))
True

Where a and b above are set containing custom class instances.

This custom class inherited from MutableMapping with both __eq__() and __hash__() implemented as follows:

def to_json(self) -> dict:
    # Code returning the data of this class

def __eq__(self, other):
    if isinstance(other, Model):
        return self.to_json() == other.to_json() and type(self) == type(other)
    elif isinstance(other, MutableMapping):
        return self.to_json() == other
    else:
        return False

def __hash__(self):
    d = self.to_json()

    hash_list = []

    for k, v in d.items():
        if isinstance(v, list):
            v = tuple(v)
        elif isinstance(v, dict):
            v = tuple(v.items())
        elif isinstance(v, Model):
            v = hash(v)

        hash_list.append((k, v))

    return hash(tuple(hash_list))

I also test the hash code of these elements, it turns out it is the same. Below is my script to test:

>>> [hash(m) for m in a]
[-1696378346402890742, 3465342798672228497, 5576155172607749152]
>>> [hash(m) for m in b]
[-1696378346402890742, 3465342798672228497, 5576155172607749152]

I've found that there's some work to do with in, but I don't know what should I implement. I also don't know why this is its behavior.

>>> [(m in b) for m in a]
[False, False, False]
>>> [(m in b) for m in set(list(a))]
[False, False, False]
>>> [(m in set(list(b))) for m in a]
[True, True, True]
>>> [(m in set(list(b))) for m in set(list(b))]
[True, True, True]

Any fix that could potentially avoid/correct this weird behavior and the reason why this is how it works would be appreciated. Thanks!

Body:
I think in the case of a list, the outcome is based on the result of __eq__ only, whereas in the case of sets, it depends on __hash__ as well.
In a minimal example like the following, you can see that lists of different objects with the same __eq__-value are evaluated to be the same, whereas sets are not. If you define a __hash__-function that depends on the value only (not on the instance), also the corresponding sets evaluate to equal.

class EA2:
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        if type(self) == type(other):
            return self.id == other.id
        else:
            return False

    def __hash__(self):
        #a = hash((id(self), self.id))
        a = self.id
        #a = randint(1,1000)
        print("hash= ", a)
        return a

print({EA2(1), EA2(2)} == {EA2(1), EA2(2)})
print(list({EA2(1), EA2(2)}) == list({EA2(1), EA2(2)}))
print(EA2(1) == EA2(1))

If your comparisons evaluate to False despite equal hashes, maybe there is a different implementation of the __hash__-function around (due to subclassing)?


问:
ROC curve in ggplot calculation [r]
I am trying to create a ROC curve in ggplot

I wrote function myself, however when I compare my results to results from roc_curve function from community (that I believe more) I get different results.

I would like to ask where is mistake in the function below?

library(ggplot2)
library(dplyr)
library(yardstick)
n <- 300 # sample size
data <-
data.frame(
  real = sample(c(0,1), replace=TRUE, size=n),
  pred = sample(runif(n), replace=TRUE, size=n)
)

simple_roc <- function(labels, scores){
  labels <- labels[order(scores, decreasing=TRUE)]
  data.frame(TPR=cumsum(labels)/sum(labels), FPR=cumsum(!labels)/sum(!labels), labels)
}

simple_roc(data$real, data$pred) %>%
  ggplot(aes(TPR, FPR)) +
  geom_line()

yardstick::roc_curve(data, factor(real), pred) %>%
  ggplot(aes(1 - specificity, sensitivity)) +
  geom_line()

```

答:
First you need to anchor your ROC curve in the points (0, 0) and (1, 1).

```<code>simple_roc <- function(labels, scores){
  labels <- labels[order(scores, decreasing=TRUE)]
  data.frame(
             TPR = c(0, cumsum(labels)/sum(labels), 1),
             FPR = c(0, cumsum(!labels)/sum(!labels), 1)
  )
}
</code>```

Then the order in which your data is presented matters in ggplot2. Reversing the line direction should get you a bit closer:

```<code>yardstick::roc_curve(data, factor(real), pred) %>%
  ggplot(aes(rev(1 - specificity), rev(sensitivity))) +
  geom_line()
</code>```

I would recommend against using your own function for any serious work. There are many other things that can go wrong and that well-maintained packages will handle properly such as missing values, infinite values, absence of some labels, and others that I can't even think about right now.

Title: ROC curve in ggplot calculation [r]

Body:
First you need to anchor your ROC curve in the points (0, 0) and (1, 1).

simple_roc <- function(labels, scores){
  labels <- labels[order(scores, decreasing=TRUE)]
  data.frame(
             TPR = c(0, cumsum(labels)/sum(labels), 1),
             FPR = c(0, cumsum(!labels)/sum(!labels), 1)
  )
}

Then the order in which your data is presented matters in ggplot2. Reversing the line direction should get you a bit closer:

yardstick::roc_curve(data, factor(real), pred) %>%
  ggplot(aes(rev(1 - specificity), rev(sensitivity))) +
  geom_line()

I would recommend against using your own function for any serious work. There are many other things that can go wrong and that well-maintained packages will handle properly such as missing values, infinite values, absence of some labels, and others that I can't even think about right now.


问:
Copy entire directory contents to another directory?
Method to copy entire directory contents to another directory in java or groovy?</p>

答:
FileUtils.copyDirectory()

Copies a whole directory
  to a new location preserving the file
  dates. This method copies the
  specified directory and all its child
  directories and files to the specified
  destination. The destination is the
  new location and name of the
  directory.

The destination directory is created
  if it does not exist. If the
  destination directory did exist, then
  this method merges the source with the
  destination, with the source taking
  precedence.

To do so, here's the example code

```<code>String source = "C:/your/source";
File srcDir = new File(source);

String destination = "C:/your/destination";
File destDir = new File(destination);

try {
    FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

Body:
FileUtils.copyDirectory()

Copies a whole directory
  to a new location preserving the file
  dates. This method copies the
  specified directory and all its child
  directories and files to the specified
  destination. The destination is the
  new location and name of the
  directory.

The destination directory is created
  if it does not exist. If the
  destination directory did exist, then
  this method merges the source with the
  destination, with the source taking
  precedence.

To do so, here's the example code

String source = "C:/your/source";
File srcDir = new File(source);

String destination = "C:/your/destination";
File destDir = new File(destination);

try {
    FileUtils.copyDirectory(srcDir, destDir);
} catch (IOException e) {
    e.printStackTrace();
}


问:
Message "flutter run: No connected devices"
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

```<code>flutter run
No connected devices.
</code>```

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.
```

Is there a solution to this problem?

答:
Basically there are three common causes for this problem:

1. You don't have the ADB drivers installed on your computer. Make sure
you have the correct ADB drivers for your Android device installed
on your PC.

Even if your computer reads your device, you may not
have the ADB drivers installed. I recommend that you search and
download the correct ADB drivers for your Android device from Google
or download an ADB package. If you install an ADB and it doesn't
work, try installing another ADB, as it is common that not all ADBs
work.

If you're on Windows, when you've installed the correct ADB
drivers, maybe the O.S. run Windows Update to complete the ADB
installation.

2. Your device does not have debugger mode enabled. It depends on each version of Android. Generally, on your Android device,
you have
to go to the configuration menu, then open the developer options, activate the debugger mode, enable OEM unlocking and USB
debugger. Also make sure you allow the developer to sign on your
device

3. Incorrect cable or other physical problems.

Sometimes the problems are caused by the data transfer cable. Try using other
cables.

Body:
I am trying to create a sample application with Flutter (fresh installation). Android Studio is also installed (fresh installation).

Here is the output of flutter run

flutter run
No connected devices.

The output of flutter doctor:

Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v0.1.5, on Linux, locale en_US.UTF-8)
[✓] Android toolchain - develop for Android devices (Android SDK 27.0.3)
[✓] Android Studio (version 3.0)
[!] VS Code (version 1.20.1)
[!] Connected devices
! No devices available

! Doctor found issues in 2 categories.

Is there a solution to this problem?


问:
How to set caption on beforeShow - Fancybox 3
I face the issue where i add button to caption i need to change button depend of action i manage to do it with

```<code>        caption : function( instance, item ) {
              var id = item.opts.$orig.attr("data-id");
              var caption = $(this).data('caption') || '';

              if ( item.type === 'image' ) {

                if (item.opts.$orig.prop("class") == 'selected') {
                  caption = (caption.length ? caption + '<br />' : '') + '<button class="btn btn-success remove-color" data-name="'+item.opts.$orig.attr("data-name")+'" data-id="'+item.opts.$orig.attr("data-id")+'"> Remove</button>' ;
                }else {
                  caption = (caption.length ? caption + '<br />' : '') + '<button class="btn btn-success add-color" data-name="'+item.opts.$orig.attr("data-name")+'" data-id="'+item.opts.$orig.attr("data-id")+'"> Add</button>' ;

                }
              }
              return caption;
          }

// later in the code
$(document).on('click', '.add-color', function(e){
...................
.............

   $('.color-thumb-wrapper').find('a[data-id="'+id+'"]').addClass('selected');

.............
.......

});

// this part working correct
</code>```

but this is fire only one time when image is open and working correct if i close and open image again everything is correct i have button Remove there

The issue is comming when i click the button and slide next and prev image then i always getting button Add i tried with beforeShow but how to change caption from beforeshow ?

```<code> // This code working correct
 beforeShow: function( instance, current ) {

   if (current.opts.$orig.prop("class") == 'selected') {
       console.log('correct');

      // how to change caption here ?
    }
  },
</code>```

答:
I done it with

this.opts.caption =

```<code>  beforeShow: function( instance, current ) {

   if (current.opts.$orig.prop("class") == 'selected') {
       this.opts.caption = '<button class="btn btn-success remove-color" data-name="'+this.opts.$orig.attr("data-name")+'" data-id="'+this.opts.$orig.attr("data-id")+'"> Премахни </button>' ;
    }
  },
</code>```

Body:
I face the issue where i add button to caption i need to change button depend of action i manage to do it with

        caption : function( instance, item ) {
              var id = item.opts.$orig.attr("data-id");
              var caption = $(this).data('caption') || '';

              if ( item.type === 'image' ) {

                if (item.opts.$orig.prop("class") == 'selected') {
                  caption = (caption.length ? caption + '
' : '') + '<button class="btn btn-success remove-color" data-name="'+item.opts.$orig.attr("data-name")+'" data-id="'+item.opts.$orig.attr("data-id")+'"> Remove</button>' ;
                }else {
                  caption = (caption.length ? caption + '
' : '') + '<button class="btn btn-success add-color" data-name="'+item.opts.$orig.attr("data-name")+'" data-id="'+item.opts.$orig.attr("data-id")+'"> Add</button>' ;

                }
              }
              return caption;
          }

// later in the code
$(document).on('click', '.add-color', function(e){
...................
.............

   $('.color-thumb-wrapper').find('a[data-id="'+id+'"]').addClass('selected');

.............
.......

});

// this part working correct

but this is fire only one time when image is open and working correct if i close and open image again everything is correct i have button Remove there

The issue is comming when i click the button and slide next and prev image then i always getting button Add i tried with beforeShow but how to change caption from beforeshow ?

 // This code working correct
 beforeShow: function( instance, current ) {

   if (current.opts.$orig.prop("class") == 'selected') {
       console.log('correct');

      // how to change caption here ?
    }
  },

Body:
I done it with

this.opts.caption =

  beforeShow: function( instance, current ) {

   if (current.opts.$orig.prop("class") == 'selected') {
       this.opts.caption = '<button class="btn btn-success remove-color" data-name="'+this.opts.$orig.attr("data-name")+'" data-id="'+this.opts.$orig.attr("data-id")+'"> Премахни </button>' ;
    }
  },


问:
declearing a variable in dart and changing its value
Why i have an error in this case :

```<code>class Person {
  Person({name,age});
  var name,age = 5;
  name = "wael";
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}
</code>```

error

```
1.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
Try adding the name of the type of the variable or the keyword 'var'.
  name = "wael";
  ^^^^
1.dart:6:3: Error: 'name' is already declared in this scope.
  name = "wael";
  ^^^^
1.dart:5:7: Context: Previous declaration of 'name'.
  var name,age = 5;
      ^^^^
1.dart:7:26: Error: Can't use 'name' because it is declared more than once.
  void Xprint()=>print('$name is $age years old');
                         ^
```

答:
I'm not sure what you are trying to achieve here, but let me try to explain what is happening.

If you were declaring local variables (inside a function), then your approach would be sound:

void someFunction() {
  var name, age = 5; // Declaration of two local variables, initialize one of them.
  name = "wael"; // Statement assigning a value to `name`.
  void xprint() => print('$name is $age years old');  // Function declaration
  xprint(); // Statement performing a function call.
}
```

<p>However, you are declaring a <em>class</em>:</p>

<pre class="lang-dart prettyprint-override"><code>class Person {
  var name, age = 5; // Declaration of two instance variables.
  Person({name, age});  // constructor (needs more work);
  name = "wael"; // .... this is invalid. Statements are not allowed here.
  void Xprint()=>print('$name is $age years old');  // Instance method declaration.
}
</code>```

So the problem is that name = "wael"; is not allowed to occur where it does. Statements are only allowed inside functions, not as part of class declarations.

It's not clear what you want to do. So, let's declare the Person class the way I'd normally do it:

class Person {
  String name;
  int age;
  Person({this.name = "wael", this.age = 5}); // Parameters initialize variables directly.
  void xprint() {
    print("$name is $age years old");
  }
}
```

This class has "wael" as default value for the name and "5" as default value for the age, but uses the parameter instead if one is supplied.

(I'd probably not have a default value for name or age, but let's assume it makes sense in this case).

Body:
Why i have an error in this case :

class Person {
  Person({name,age});
  var name,age = 5;
  name = "wael";
  void Xprint()=>print('$name is $age years old');
}

main () {
  var x = Person();
  x.Xprint();
}

error

1.dart:6:3: Error: Variables must be declared using the keywords 'const', 'final', 'var' or a type name.
Try adding the name of the type of the variable or the keyword 'var'.
  name = "wael";
  ^^^^
1.dart:6:3: Error: 'name' is already declared in this scope.
  name = "wael";
  ^^^^
1.dart:5:7: Context: Previous declaration of 'name'.
  var name,age = 5;
      ^^^^
1.dart:7:26: Error: Can't use 'name' because it is declared more than once.
  void Xprint()=>print('$name is $age years old');
                         ^

Body:
I'm not sure what you are trying to achieve here, but let me try to explain what is happening.

If you were declaring local variables (inside a function), then your approach would be sound:

void someFunction() {
  var name, age = 5; // Declaration of two local variables, initialize one of them.
  name = "wael"; // Statement assigning a value to `name`.
  void xprint() => print('$name is $age years old');  // Function declaration
  xprint(); // Statement performing a function call.
}

However, you are declaring a class:

class Person {
  var name, age = 5; // Declaration of two instance variables.
  Person({name, age});  // constructor (needs more work);
  name = "wael"; // .... this is invalid. Statements are not allowed here.
  void Xprint()=>print('$name is $age years old');  // Instance method declaration.
}

So the problem is that name = "wael"; is not allowed to occur where it does. Statements are only allowed inside functions, not as part of class declarations.

It's not clear what you want to do. So, let's declare the Person class the way I'd normally do it:

class Person {
  String name;
  int age;
  Person({this.name = "wael", this.age = 5}); // Parameters initialize variables directly.
  void xprint() {
    print("$name is $age years old");
  }
}

This class has "wael" as default value for the name and "5" as default value for the age, but uses the parameter instead if one is supplied.

(I'd probably not have a default value for name or age, but let's assume it makes sense in this case).


问:
Pandas can't read csv file, it replace all to NaN
I try to read csv file

```<code> df = pd.read_csv("raccoons.csv", delimiter=":")
 df.head()
</code>```

and it returns to me

```<code> ��c    Unnamed: 1  Unnamed: 2
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN
</code>```

inside of file

```<code>corrds:time:raccoons_bought
55.771393 37.567392:4423O3138:2
55.705458 37.550926:442365718:0
55.83028 37.404815:442244596:0
55.799092 37.452157:442327511:148.00001
55.749785 37.763962:442248573:1
</code>```

答:
It probably has to do with the file encoding. You may have to set this when calling read_csv. Check the solutions to find your file encoding provided here: UnicodeDecodeError when reading CSV file in Pandas with Python

I had this same issue and finally solved it using:

```<code>pd.read_csv(..., encoding = 'utf-16')
</code>```

Body:
I try to read csv file

 df = pd.read_csv("raccoons.csv", delimiter=":")
 df.head()

and it returns to me

 ��c    Unnamed: 1  Unnamed: 2
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN
 NaN    NaN     NaN     NaN

inside of file

corrds:time:raccoons_bought
55.771393 37.567392:4423O3138:2
55.705458 37.550926:442365718:0
55.83028 37.404815:442244596:0
55.799092 37.452157:442327511:148.00001
55.749785 37.763962:442248573:1

Body:
It probably has to do with the file encoding. You may have to set this when calling read_csv. Check the solutions to find your file encoding provided here: UnicodeDecodeError when reading CSV file in Pandas with Python

I had this same issue and finally solved it using:

pd.read_csv(..., encoding = 'utf-16')


问:
Choose time using datetimepicker in propertygrid
I am trying to pick only a time (hour and minutes) using propertygrid and datetimepicker.

I have created my own editor.

The trouble is  that it is not showing the value in the text and the value can also have calendars:

Here have code:

```<code>public class Tests
    {
        private DateTimePicker time = new DateTimePicker();

        [Editor(typeof(MyEditor), typeof(UITypeEditor))]
        public DateTimePicker Time
        {
            get { return time; }
            set { time = value; }

        }

        public Tests()
        {
            time.Format = DateTimePickerFormat.Time;
            time.CustomFormat = "hh:mm";
            time.Value = DateTime.Now;
            DateTime t = new DateTime();

        }

    }

    class MyEditor : UITypeEditor
    {

        IWindowsFormsEditorService editorService;
        DateTimePicker picker = new DateTimePicker();

        public MyEditor()
        {

            picker.Format = DateTimePickerFormat.Custom;
            picker.CustomFormat = "hh:mm";
            picker.ShowUpDown = true;
            picker.ValueChanged += new EventHandler(picker_ValueChanged);
        }

        void picker_ValueChanged(object sender, EventArgs e)
        {
            this.editorService.CloseDropDown();
        }

        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {

            if (provider != null)
            {
                this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            }

            if (this.editorService != null)
            {

                DateTimePicker tmp = (DateTimePicker)value;
                tmp.CustomFormat = "hh:mm";
                tmp.Text = tmp.Value.ToString();
                picker = tmp;

                this.editorService.DropDownControl(picker);

            }

            return value;

        }

        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.DropDown;
        }

    }
</code>```

答:
I finally did it by using strings</p>

```<code>public class Tests {
  private string time;

  [Editor(typeof(TimePickerEditor), typeof(UITypeEditor))]
  public string Time {
    get { return time; }
    set { time = value; }
  }

  internal class TimePickerEditor : UITypeEditor {
    IWindowsFormsEditorService editorService;
    DateTimePicker picker = new DateTimePicker();
    string time;

    public TimePickerEditor() {
      picker.Format = DateTimePickerFormat.Custom;
      picker.CustomFormat = "mm:HH";
      picker.ShowUpDown = true;
    }

    public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value) {
      if (provider != null) {
        this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
      }
      if (this.editorService != null) {
        if (value == null) {
          time = DateTime.Now.ToString("HH:mm");
        }
        this.editorService.DropDownControl(picker);
        value = picker.Value.ToString("HH:mm");
      }
      return value;
    }

    public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) {
      return UITypeEditorEditStyle.DropDown;
    }
  }
}
</code>```

Body:
I am trying to pick only a time (hour and minutes) using propertygrid and datetimepicker.

I have created my own editor.

The trouble is  that it is not showing the value in the text and the value can also have calendars:

Here have code:

public class Tests
    {
        private DateTimePicker time = new DateTimePicker();

        [Editor(typeof(MyEditor), typeof(UITypeEditor))]
        public DateTimePicker Time
        {
            get { return time; }
            set { time = value; }

        }

        public Tests()
        {
            time.Format = DateTimePickerFormat.Time;
            time.CustomFormat = "hh:mm";
            time.Value = DateTime.Now;
            DateTime t = new DateTime();

        }

    }

    class MyEditor : UITypeEditor
    {

        IWindowsFormsEditorService editorService;
        DateTimePicker picker = new DateTimePicker();

        public MyEditor()
        {

            picker.Format = DateTimePickerFormat.Custom;
            picker.CustomFormat = "hh:mm";
            picker.ShowUpDown = true;
            picker.ValueChanged += new EventHandler(picker_ValueChanged);
        }

        void picker_ValueChanged(object sender, EventArgs e)
        {
            this.editorService.CloseDropDown();
        }

        public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
        {

            if (provider != null)
            {
                this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
            }

            if (this.editorService != null)
            {

                DateTimePicker tmp = (DateTimePicker)value;
                tmp.CustomFormat = "hh:mm";
                tmp.Text = tmp.Value.ToString();
                picker = tmp;

                this.editorService.DropDownControl(picker);

            }

            return value;

        }

        public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
        {
            return UITypeEditorEditStyle.DropDown;
        }

    }

Body:
I finally did it by using strings

public class Tests {
  private string time;

  [Editor(typeof(TimePickerEditor), typeof(UITypeEditor))]
  public string Time {
    get { return time; }
    set { time = value; }
  }

  internal class TimePickerEditor : UITypeEditor {
    IWindowsFormsEditorService editorService;
    DateTimePicker picker = new DateTimePicker();
    string time;

    public TimePickerEditor() {
      picker.Format = DateTimePickerFormat.Custom;
      picker.CustomFormat = "mm:HH";
      picker.ShowUpDown = true;
    }

    public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value) {
      if (provider != null) {
        this.editorService = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;
      }
      if (this.editorService != null) {
        if (value == null) {
          time = DateTime.Now.ToString("HH:mm");
        }
        this.editorService.DropDownControl(picker);
        value = picker.Value.ToString("HH:mm");
      }
      return value;
    }

    public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context) {
      return UITypeEditorEditStyle.DropDown;
    }
  }
}


问:
case insensitive issue while fetching records from child table using HQL
I have a parent table and a child table where I am only getting 1 record from child table but not getting case insensitive matched record which is a mixed string. I am expecting it should return 2 records.

Below is the code for the same.

//parent Table
@Entity
@Table(name = "employee")
public class Employee implements Serializable {

  @Id
  @Column(name = "employeeID")
  private String employeeID;

  @Column(name = "name_first")
  private String nameFirst;

  @Column(name = "name_last")
  private String nameLast;

}

//Child Table
@Entity
@Table(name = "employee_salary")
public class EmployeeSalary implements Serializable {

  @EmbeddedId
  private EmployeeSalaryPK employeeSalaryPKCompositeKey;

  @Column(name = "salaryBracket")
  private String salaryBracket;

}

@Embeddable
public class EmployeeSalaryPK implements Serializable {

  @Column(name = "employeeID")
  private String employeeID;

  @Column(name = "salary")
  private String salary;

}
```

<p>In employee_salary table I have two records (as shown below) but while fetching it using HQL only one record is coming with an actual match but case insensitive record is not coming.</p>

<blockquote>
  <p>Employee Record:-   ABC  John  Kramer</p>

  <p>employee_salary table record:-</p>

  <p>ABC  100900</p>

  <p>aBc  76770</p>
</blockquote>

<p>I am using simple HQL query (see below code) but getting only first record whenever I want to get both record as employeeID is abc.</p>

<pre class="lang-sql prettyprint-override"><code>String hqlQuery = " FROM " + Employee.class.getName() + " E WHERE E.employeeID= :EMPLOYEEID";
Session session = entityManager.unwrap(Session.class);
List<?> responseList = session.createQuery(hqlQuery).setParameter("EMPLOYEEID", "ABC").list();
</code>```

答:
To get all entities by case insensetive String id you have to convert id to same case (lowercase or uppercase) on both sides of the WHERE clause equality operator

```<code>String hqlQuery = " FROM " + Employee.class.getName() + " E WHERE lower(E.employeeID) = :EMPLOYEEID";
Session session = entityManager.unwrap(Session.class);
List<?> responseList = session.createQuery(hqlQuery).setParameter("EMPLOYEEID", "ABC".toLowerCase()).list();
</code>```

Body:
I have a parent table and a child table where I am only getting 1 record from child table but not getting case insensitive matched record which is a mixed string. I am expecting it should return 2 records.

Below is the code for the same.

//parent Table
@Entity
@Table(name = "employee")
public class Employee implements Serializable {

  @Id
  @Column(name = "employeeID")
  private String employeeID;

  @Column(name = "name_first")
  private String nameFirst;

  @Column(name = "name_last")
  private String nameLast;

}

//Child Table
@Entity
@Table(name = "employee_salary")
public class EmployeeSalary implements Serializable {

  @EmbeddedId
  private EmployeeSalaryPK employeeSalaryPKCompositeKey;

  @Column(name = "salaryBracket")
  private String salaryBracket;

}

@Embeddable
public class EmployeeSalaryPK implements Serializable {

  @Column(name = "employeeID")
  private String employeeID;

  @Column(name = "salary")
  private String salary;

}

In employee_salary table I have two records (as shown below) but while fetching it using HQL only one record is coming with an actual match but case insensitive record is not coming.

Employee Record:-   ABC  John  Kramer

employee_salary table record:-

ABC  100900

aBc  76770

I am using simple HQL query (see below code) but getting only first record whenever I want to get both record as employeeID is abc.

String hqlQuery = " FROM " + Employee.class.getName() + " E WHERE E.employeeID= :EMPLOYEEID";
Session session = entityManager.unwrap(Session.class);
List<?> responseList = session.createQuery(hqlQuery).setParameter("EMPLOYEEID", "ABC").list();

Body:
To get all entities by case insensetive String id you have to convert id to same case (lowercase or uppercase) on both sides of the WHERE clause equality operator

String hqlQuery = " FROM " + Employee.class.getName() + " E WHERE lower(E.employeeID) = :EMPLOYEEID";
Session session = entityManager.unwrap(Session.class);
List<?> responseList = session.createQuery(hqlQuery).setParameter("EMPLOYEEID", "ABC".toLowerCase()).list();


问:
Trouble, Driver class that implements the main method
I am trying to create a driver class that implements a main method. It must create and test an object to demonstrate all the program functions.

I think I have created the correct driver class but the tests I ran prove that I have bugs in my code, This is what I have so far.

```<code>{
public static void main(String[] args) {
    A00847872_Realtor testingPerfectMarks = new A00847872_Realtor(null, "", -2.2, "String", "String", "String", -1);

    System.out.println(testingPerfectMarks.getListingNumber());
    System.out.println(testingPerfectMarks.getAddress());
    System.out.println(testingPerfectMarks.getAskingPrice());
    System.out.println(testingPerfectMarks.getPropertyType());
    System.out.println(testingPerfectMarks.getBuildingType());
    System.out.println(testingPerfectMarks.getLandSize());
    System.out.println(testingPerfectMarks.getYearBuilt());
    System.out.println();
</code>```

}
}

i get more outputs that I have printed myself

Invalid value

Invalid value

Invalid Value

Invalid Value

null

null

0.0

String

String

String

0
////
public class A00847872_Realtor
{
    //primary fields

```<code>private String listingNumber;
private String address;
private double askingPrice;
private String propertyType;
private String buildingType;
private String landSize;
private int yearBuilt;

//secondary fields

private double taxes;
private int totalSquareFeet;
private int numberOfBedrooms;
private int numberOfBathrooms;
private String parkingType;

/**
 * Default constructor for creating realtor Objects
 */

public A00847872_Realtor(){

}

//constructor with paramaters for primary fields only

/**
 * Constructor for objects of class A00847872_Realtor
 * @param listingNumberParam used to set the listingNumber field
 *
 */

public A00847872_Realtor(String listingNumberParam, String addressParam, double askingPriceParam,
String propertyTypeParam, String buildingTypeParam, String landSizeParam, int yearBuiltParam)
{

    setListingNumber(listingNumberParam);
    setAddress(addressParam);
    setAskingPrice(askingPriceParam);
    setPropertyType(propertyTypeParam);
    setBuildingType(buildingTypeParam);
    setLandSize(landSizeParam);
    setYearBuilt(yearBuiltParam);

}

//providing accessor methods. getters for primary fields
public String getListingNumber(){
    return listingNumber;
}

public String getAddress(){
    return address;
}

public double getAskingPrice(){
    return askingPrice;
}

public String getPropertyType(){
    return propertyType;
}

public String getBuildingType(){
    return buildingType;
}

public String getLandSize(){
    return landSize;
}

public int getYearBuilt(){
    return yearBuilt;
}

//accessor methods for secondary fields

public double getTaxes(){
    return taxes;
}

public int getTotalSquareFeet(){
    return totalSquareFeet;
}

public int getNumberOfBedrooms(){
    return numberOfBedrooms;
}

public int getNumberOfBathrooms(){
    return numberOfBathrooms;
}

public String getparkingType(){
    return parkingType;
}

//setters for primary fields with checks for null, empty, and negative parameters.

public void setListingNumber(String newListingNumber){

    if( newListingNumber == null || newListingNumber.isEmpty()){
        System.out.println("Invalid value");

    } else {
        listingNumber = newListingNumber;

    }

}

public void setAddress(String newAddress){

    if( newAddress == null || newAddress.isEmpty()){

        System.out.println("Invalid value");

    } else {

        address = newAddress;

    }

}

public void setAskingPrice(double price){

    if( price >= 0 ){

        askingPrice = price;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setPropertyType(String newPropertyType){

    if( newPropertyType == null || newPropertyType.isEmpty()){

        System.out.println("Invalid value");

    } else {

        propertyType = newPropertyType;

    }

}

public void setBuildingType(String newBuildingType){

    if( newBuildingType == null || newBuildingType.isEmpty()){

        System.out.println("Invalid value");

    } else {

        buildingType = newBuildingType;

    }

}

public void setLandSize(String newLandSize){

    if( newLandSize == null || newLandSize.isEmpty()){

        System.out.println("Invalid value");

    } else {

        landSize = newLandSize;

    }

}

public void setYearBuilt(int newYearBuilt){

    if( newYearBuilt >= 0 ){

        yearBuilt = newYearBuilt;

    } else {

        System.out.println("Invalid Value");

    }

}

//Setters for Secondary fields

public void setTaxes(double newTaxes){

    if( newTaxes >= 0 ){

        taxes = newTaxes;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setTotalSquareFeet(int NewTotalSquareFeet){

    if( NewTotalSquareFeet >= 0 ){

        totalSquareFeet = NewTotalSquareFeet;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setNumberOfBedrooms(int newNumberOfBedrooms){

    if( newNumberOfBedrooms >= 0 ){

        numberOfBedrooms = newNumberOfBedrooms;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setNumberOfBathrooms(int newNumberOfBathrooms){

    if( newNumberOfBathrooms >= 0 ){

        numberOfBathrooms = newNumberOfBathrooms;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setParkingType(String newParkingType){

    if( newParkingType == null || newParkingType.isEmpty()){

        System.out.println("Invalid value");

    } else {

        parkingType = newParkingType;

    }

}

//method called printDetails() to display information in format

public void printDetails (){

    System.out.println("$" + askingPrice);
    System.out.println(address);
    System.out.println("MLS Number: " + listingNumber);
    System.out.println();
    System.out.println("Property Type: " + propertyType);
    System.out.println("Building Type: " + buildingType);
    System.out.println("Land Size: " + landSize);
    System.out.println("Built In: " + yearBuilt);
    System.out.println("Annual Taxes: " + taxes);
    System.out.println("Floor Space: " + totalSquareFeet);
    System.out.println("Bedrooms: " + numberOfBedrooms);
    System.out.println("Bathrooms: " + numberOfBathrooms);
    System.out.println("Parking Type: " + parkingType);

}
</code>```

}

答:
The method setListingNumber in your class A00847872_Realtor takes a String as an argument:

```<code>public void setListingNumber(String newListingNumber){
    // ...
}
</code>```

However, in your class RealtorDriver, where you call the method, you are not passing it any parameters:

```<code>homeworkObject.setListingNumber();
</code>```

The error you get tells you that the method setListingNumber needs to get passed a String. So you must pass it a String. Where you get that string from is something you'll have to find out and decide for yourself.

```<code>homeworkObject.setListingNumber("something");
</code>```

Body:
I am trying to create a driver class that implements a main method. It must create and test an object to demonstrate all the program functions.

I think I have created the correct driver class but the tests I ran prove that I have bugs in my code, This is what I have so far.

{
public static void main(String[] args) {
    A00847872_Realtor testingPerfectMarks = new A00847872_Realtor(null, "", -2.2, "String", "String", "String", -1);

    System.out.println(testingPerfectMarks.getListingNumber());
    System.out.println(testingPerfectMarks.getAddress());
    System.out.println(testingPerfectMarks.getAskingPrice());
    System.out.println(testingPerfectMarks.getPropertyType());
    System.out.println(testingPerfectMarks.getBuildingType());
    System.out.println(testingPerfectMarks.getLandSize());
    System.out.println(testingPerfectMarks.getYearBuilt());
    System.out.println();

}
}

i get more outputs that I have printed myself

Invalid value

Invalid value

Invalid Value

Invalid Value

null

null

0.0

String

String

String

0
////
public class A00847872_Realtor
{
    //primary fields

private String listingNumber;
private String address;
private double askingPrice;
private String propertyType;
private String buildingType;
private String landSize;
private int yearBuilt;

//secondary fields

private double taxes;
private int totalSquareFeet;
private int numberOfBedrooms;
private int numberOfBathrooms;
private String parkingType;

/**
 * Default constructor for creating realtor Objects
 */

public A00847872_Realtor(){

}

//constructor with paramaters for primary fields only

/**
 * Constructor for objects of class A00847872_Realtor
 * @param listingNumberParam used to set the listingNumber field
 *
 */

public A00847872_Realtor(String listingNumberParam, String addressParam, double askingPriceParam,
String propertyTypeParam, String buildingTypeParam, String landSizeParam, int yearBuiltParam)
{

    setListingNumber(listingNumberParam);
    setAddress(addressParam);
    setAskingPrice(askingPriceParam);
    setPropertyType(propertyTypeParam);
    setBuildingType(buildingTypeParam);
    setLandSize(landSizeParam);
    setYearBuilt(yearBuiltParam);

}

//providing accessor methods. getters for primary fields
public String getListingNumber(){
    return listingNumber;
}

public String getAddress(){
    return address;
}

public double getAskingPrice(){
    return askingPrice;
}

public String getPropertyType(){
    return propertyType;
}

public String getBuildingType(){
    return buildingType;
}

public String getLandSize(){
    return landSize;
}

public int getYearBuilt(){
    return yearBuilt;
}

//accessor methods for secondary fields

public double getTaxes(){
    return taxes;
}

public int getTotalSquareFeet(){
    return totalSquareFeet;
}

public int getNumberOfBedrooms(){
    return numberOfBedrooms;
}

public int getNumberOfBathrooms(){
    return numberOfBathrooms;
}

public String getparkingType(){
    return parkingType;
}

//setters for primary fields with checks for null, empty, and negative parameters.

public void setListingNumber(String newListingNumber){

    if( newListingNumber == null || newListingNumber.isEmpty()){
        System.out.println("Invalid value");

    } else {
        listingNumber = newListingNumber;

    }

}

public void setAddress(String newAddress){

    if( newAddress == null || newAddress.isEmpty()){

        System.out.println("Invalid value");

    } else {

        address = newAddress;

    }

}

public void setAskingPrice(double price){

    if( price >= 0 ){

        askingPrice = price;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setPropertyType(String newPropertyType){

    if( newPropertyType == null || newPropertyType.isEmpty()){

        System.out.println("Invalid value");

    } else {

        propertyType = newPropertyType;

    }

}

public void setBuildingType(String newBuildingType){

    if( newBuildingType == null || newBuildingType.isEmpty()){

        System.out.println("Invalid value");

    } else {

        buildingType = newBuildingType;

    }

}

public void setLandSize(String newLandSize){

    if( newLandSize == null || newLandSize.isEmpty()){

        System.out.println("Invalid value");

    } else {

        landSize = newLandSize;

    }

}

public void setYearBuilt(int newYearBuilt){

    if( newYearBuilt >= 0 ){

        yearBuilt = newYearBuilt;

    } else {

        System.out.println("Invalid Value");

    }

}

//Setters for Secondary fields

public void setTaxes(double newTaxes){

    if( newTaxes >= 0 ){

        taxes = newTaxes;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setTotalSquareFeet(int NewTotalSquareFeet){

    if( NewTotalSquareFeet >= 0 ){

        totalSquareFeet = NewTotalSquareFeet;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setNumberOfBedrooms(int newNumberOfBedrooms){

    if( newNumberOfBedrooms >= 0 ){

        numberOfBedrooms = newNumberOfBedrooms;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setNumberOfBathrooms(int newNumberOfBathrooms){

    if( newNumberOfBathrooms >= 0 ){

        numberOfBathrooms = newNumberOfBathrooms;

    } else {

        System.out.println("Invalid Value");

    }

}

public void setParkingType(String newParkingType){

    if( newParkingType == null || newParkingType.isEmpty()){

        System.out.println("Invalid value");

    } else {

        parkingType = newParkingType;

    }

}

//method called printDetails() to display information in format

public void printDetails (){

    System.out.println("$" + askingPrice);
    System.out.println(address);
    System.out.println("MLS Number: " + listingNumber);
    System.out.println();
    System.out.println("Property Type: " + propertyType);
    System.out.println("Building Type: " + buildingType);
    System.out.println("Land Size: " + landSize);
    System.out.println("Built In: " + yearBuilt);
    System.out.println("Annual Taxes: " + taxes);
    System.out.println("Floor Space: " + totalSquareFeet);
    System.out.println("Bedrooms: " + numberOfBedrooms);
    System.out.println("Bathrooms: " + numberOfBathrooms);
    System.out.println("Parking Type: " + parkingType);

}

}

Body:
The method setListingNumber in your class A00847872_Realtor takes a String as an argument:

public void setListingNumber(String newListingNumber){
    // ...
}

However, in your class RealtorDriver, where you call the method, you are not passing it any parameters:

homeworkObject.setListingNumber();

The error you get tells you that the method setListingNumber needs to get passed a String. So you must pass it a String. Where you get that string from is something you'll have to find out and decide for yourself.

homeworkObject.setListingNumber("something");


问:
update array when the user updates the text field in the cell
I was wondering if there's a way to update barcodeItemsQuantity array when the user updates the text field in a custom uitableviewcell. Below are my code snippets. and I want to update data from my array whenever the user changes the textfield from the custom tableviewcell.

viewcontroller.m

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Cell Initialized");
    static NSString *cellIdentifier = @"BarcodeItemsCell";

    BarcodeItemsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (cell == nil) {
        cell = [[BarcodeItemsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    // Configure the cell...

    if (indexPath.row == [barcodeItems count]) {
        // Add new row
        cell.barcodeLabel.text = @"scan SKU";
        cell.barcodeLabel.textColor = [UIColor lightGrayColor];
        UIImage *btnImage = [UIImage imageNamed:@"barcodeIcon"];
        [cell.leftButton setImage:btnImage forState:UIControlStateNormal];
        cell.leftButton.tintColor = [UIColor blackColor];
        cell.quantityTextField.userInteractionEnabled = NO;
        [cell.leftButton addTarget:self action:@selector(scanBarcode) forControlEvents:UIControlEventTouchUpInside];
        NSLog(@"Add another Item Requested");
    }
    else {
        // Display barcode items
        cell.barcodeLabel.text = [barcodeItems objectAtIndex:indexPath.row];
        UIImage *btnImage = [UIImage imageNamed:@"deleteIcon"];
        cell.leftButton.tintColor = [UIColor redColor];
        [cell.leftButton setImage:btnImage forState:UIControlStateNormal];
        cell.leftButton.tag = indexPath.row;
        [cell.leftButton addTarget:self action:@selector(deleteRow:) forControlEvents:UIControlEventTouchUpInside];
        [barcodeItemsQuantity addObject:cell.quantityTextField];
    }

    NSLog(@"Cell Populated");
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return true;
}

-(void) deleteRow:(id)sender {
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:photoCaptureView.itemsTableView];
    NSIndexPath *indexPath = [photoCaptureView.itemsTableView indexPathForRowAtPoint:buttonPosition];
    [barcodeItems removeObjectAtIndex:indexPath.row];
    [photoCaptureView.itemsTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    NSLog(@"Item Removed");
}
</code>```

barcodeitestableviewcell.h

```<code>@interface BarcodeItemsTableViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UIButton *leftButton;
@property (strong, nonatomic) IBOutlet UILabel *barcodeLabel;
@property (strong, nonatomic) IBOutlet UITextField *quantityTextField;

@end
</code>```

答:
Yes, you can update your data model value for the textfield text placed inside custom table cell.

STEP 1:

Add delegate in your current class "UITextFieldDelegate"

```<code>class ViewController: UIViewController,UITextFieldDelegate
</code>```

STEP 2:

on your "cellForRowAt indexPath" invoke the delegate to current textfield and also add the tag

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    // add the following lines
 cell.textField.delegate = self
 cell.textField.tag = indexPath.row
    return cell
}
</code>```

STEP 3:

call the UITextField Delegates

```<code>func textFieldDidEndEditing(textField: UITextField) {
if !textField.text.isEmpty {    // check textfield contains value or not
    if textField.tag == 0 {
        firstName = textField.text!
    } else {
        lastName = textField.text!
    }
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

func textFieldDidBeginEditing(textField: UITextField!) {
    if textField.tag == 0 {
        firstName = ""
    } else {
        lastName = ""
    }
}
</code>```

Here, you can replace the firstName and lastName with your desired model variables.

Hope this will work for you.

Body:
I was wondering if there's a way to update barcodeItemsQuantity array when the user updates the text field in a custom uitableviewcell. Below are my code snippets. and I want to update data from my array whenever the user changes the textfield from the custom tableviewcell.

viewcontroller.m

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"Cell Initialized");
    static NSString *cellIdentifier = @"BarcodeItemsCell";

    BarcodeItemsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    if (cell == nil) {
        cell = [[BarcodeItemsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    // Configure the cell...

    if (indexPath.row == [barcodeItems count]) {
        // Add new row
        cell.barcodeLabel.text = @"scan SKU";
        cell.barcodeLabel.textColor = [UIColor lightGrayColor];
        UIImage *btnImage = [UIImage imageNamed:@"barcodeIcon"];
        [cell.leftButton setImage:btnImage forState:UIControlStateNormal];
        cell.leftButton.tintColor = [UIColor blackColor];
        cell.quantityTextField.userInteractionEnabled = NO;
        [cell.leftButton addTarget:self action:@selector(scanBarcode) forControlEvents:UIControlEventTouchUpInside];
        NSLog(@"Add another Item Requested");
    }
    else {
        // Display barcode items
        cell.barcodeLabel.text = [barcodeItems objectAtIndex:indexPath.row];
        UIImage *btnImage = [UIImage imageNamed:@"deleteIcon"];
        cell.leftButton.tintColor = [UIColor redColor];
        [cell.leftButton setImage:btnImage forState:UIControlStateNormal];
        cell.leftButton.tag = indexPath.row;
        [cell.leftButton addTarget:self action:@selector(deleteRow:) forControlEvents:UIControlEventTouchUpInside];
        [barcodeItemsQuantity addObject:cell.quantityTextField];
    }

    NSLog(@"Cell Populated");
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return true;
}

-(void) deleteRow:(id)sender {
    CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:photoCaptureView.itemsTableView];
    NSIndexPath *indexPath = [photoCaptureView.itemsTableView indexPathForRowAtPoint:buttonPosition];
    [barcodeItems removeObjectAtIndex:indexPath.row];
    [photoCaptureView.itemsTableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    NSLog(@"Item Removed");
}

barcodeitestableviewcell.h

@interface BarcodeItemsTableViewCell : UITableViewCell

@property (strong, nonatomic) IBOutlet UIButton *leftButton;
@property (strong, nonatomic) IBOutlet UILabel *barcodeLabel;
@property (strong, nonatomic) IBOutlet UITextField *quantityTextField;

@end

Body:
Yes, you can update your data model value for the textfield text placed inside custom table cell.

STEP 1:

Add delegate in your current class "UITextFieldDelegate"

class ViewController: UIViewController,UITextFieldDelegate

STEP 2:

on your "cellForRowAt indexPath" invoke the delegate to current textfield and also add the tag

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
    // add the following lines
 cell.textField.delegate = self
 cell.textField.tag = indexPath.row
    return cell
}

STEP 3:

call the UITextField Delegates

func textFieldDidEndEditing(textField: UITextField) {
if !textField.text.isEmpty {    // check textfield contains value or not
    if textField.tag == 0 {
        firstName = textField.text!
    } else {
        lastName = textField.text!
    }
}

func textFieldShouldReturn(textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

func textFieldDidBeginEditing(textField: UITextField!) {
    if textField.tag == 0 {
        firstName = ""
    } else {
        lastName = ""
    }
}

Here, you can replace the firstName and lastName with your desired model variables.

Hope this will work for you.


问:
CSS3 Box-Shadow Showing Behind Sibling Div Element
I'm using:

```<code>box-shadow: 0px -1px 0px #333333;
</code>```

on my footer but it's hiding behind or disappearing where the div before it is... hard to explain but here's what it looks like: http://cl.ly/7HLy

Is there a way do have the box-shadow be on top of the other div before the footer? I've tried adding a z-index but it doesn't work.

答:
I'll repeat my comment here since it solved the problem.

When using z-index you should use position: relative;

Body:
I'm using:

box-shadow: 0px -1px 0px #333333;

on my footer but it's hiding behind or disappearing where the div before it is... hard to explain but here's what it looks like: http://cl.ly/7HLy

Is there a way do have the box-shadow be on top of the other div before the footer? I've tried adding a z-index but it doesn't work.


问:
Django Test Case Error 'WSGIRequest' object has no attribute 'session'
I'm trying to write some tests for my django app and it's throwing up an error:

```<code>File "/Users/croberts/.virtualenvs/litem/lib/python3.4/site-packages/django/contrib/auth/__init__.py", line 101, in login
    if SESSION_KEY in request.session:
AttributeError: 'WSGIRequest' object has no attribute 'session'
</code>```

Here's my code that I am trying to run:

```<code>class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

    def test_signup(self):
        request = self.request_factory.post("/signup/", {
            "email": "email@email.com",
            "password": "password",
            "password-confirm": "password",
            "firm": "big law firm"})
        response = signup_user(request)
        user = User.objects.get(email="email@email.com")
        self.assertEqual(user.username, "email@email.com")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.
</code>```

Here's my middleware's:

```<code>MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
</code>```

and my installed apps:

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'patents',
]
</code>```

答:
For anyone using Django 2.0 and up - the RequestFactory() doesn't have access to the Middleware:

It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

https://docs.djangoproject.com/en/2.2/topics/testing/advanced/#the-request-factory

Therefore, it needs to be added manually as follows:

```<code>from django.contrib.sessions.middleware import SessionMiddleware

class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

        middleware = SessionMiddleware()
        middleware.process_request(self.request_factory)
        self.request_factory.session.save()

    def test_signup(self):
        ...
</code>```

Body:
I'm trying to write some tests for my django app and it's throwing up an error:

File "/Users/croberts/.virtualenvs/litem/lib/python3.4/site-packages/django/contrib/auth/__init__.py", line 101, in login
    if SESSION_KEY in request.session:
AttributeError: 'WSGIRequest' object has no attribute 'session'

Here's my code that I am trying to run:

class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

    def test_signup(self):
        request = self.request_factory.post("/signup/", {
            "email": "email@email.com",
            "password": "password",
            "password-confirm": "password",
            "firm": "big law firm"})
        response = signup_user(request)
        user = User.objects.get(email="email@email.com")
        self.assertEqual(user.username, "email@email.com")
        self.assertEqual(user.firm, "big law firm")
        self.assertEqual(response.status_code, 302) #if it's successful it redirects.

Here's my middleware's:

MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

and my installed apps:

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'patents',
]

Body:
For anyone using Django 2.0 and up - the RequestFactory() doesn't have access to the Middleware:

It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

https://docs.djangoproject.com/en/2.2/topics/testing/advanced/#the-request-factory

Therefore, it needs to be added manually as follows:

from django.contrib.sessions.middleware import SessionMiddleware

class SimpleTest(TestCase):
    def setUp(self):
        self.request_factory = RequestFactory()

        middleware = SessionMiddleware()
        middleware.process_request(self.request_factory)
        self.request_factory.session.save()

    def test_signup(self):
        ...


问:
type 'Future<List<dynamic>>' is not a subtype of type 'Future<List<FoodModel>>'
So I'm trying to get my foodmodel data to show up on my screen, I don't know what is wrong with this code, it must be something about await async but I can't figure it out. It only says type Future<List<dynamic>> is not a subtype of type Future<List<FoodModel>>. I'm still new to flutter. Is there anyway to get data using async await from this code?

```<code>class FoodPage extends StatefulWidget {
  @override
  _FoodPageState createState() => _FoodPageState();
}
class _FoodPageState extends State<FoodPage> {
  Future<List<FoodModel>>  foods;
  @override
  initState()  {
    super.initState();
    setState(() {
      var db= DatabaseHelperFood();
      foods=db.getFoods();
    });
  }
  GridView  food_data (List<FoodModel> foods)
  {
    return  GridView.builder(

      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemCount: foods.length,
      itemBuilder: (_, int position)
      {
        return  Card(

          child:Container(
              decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(FoodModel.map(foods[position]).alamat),
                    fit: BoxFit.cover,
                  )),
              child: Container(
                  margin: EdgeInsets.fromLTRB(
                      0, 152, 0, 0),
                  child: Column(
                    children: <Widget>[
                      Container(
                          width: 500,
                          height: 25,
                          child: RaisedButton(
                            onPressed: () {

                            },
                            child: Text('Beli : $FoodModel.map(_foods[position]).harga',
                                textAlign: TextAlign
                                    .center,
                                style: TextStyle(
                                    color: Colors.white)),
                            color: Colors.black,
                          ))
                    ],
                  )
              )
          ),);
      },
    );
  }
  foodlist(){
    return Expanded(
        child:FutureBuilder(
            future:foods,
            builder:(context,datas)
            {
              if(datas.hasData)
              {
                return food_data(datas.data);
              }
              else if(null== datas.data || datas.data.length==0)
              {
                return Text("No data");
              }
              return CircularProgressIndicator();
            }
        )
    );
  }
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            backgroundColor: Colors.grey[900],
            leading: Icon(Icons.menu),
            actions: <Widget>[
              Padding(
                  padding: EdgeInsets.all(5),
                  child: Row(children: <Widget>[
                    Container(

                      child:Text("GoFlix",style:TextStyle(fontSize: 30)),
                      margin:EdgeInsets.only(right:90),
                    ),
                    Container(
                        child: Icon(Icons.shopping_cart, size: 30),
                        margin: EdgeInsets.only(top: 5)),
                    Container(
                      margin: EdgeInsets.only(top: 5),
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                          color: Colors.redAccent[800],
                          borderRadius: BorderRadius.circular(10)),
                      child: Center(child: Text("0")),
                    )
                  ]))
            ]),
        body:Container(
            color:Colors.grey[800],
            child: Column(
                children: <Widget>[
                  Image.asset('Asset/Movieabanner.jpg'),
                  foodlist(),

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

答:
If your Future value is List<FoodModel> you need to build your FutureBuilder as follows:

```<code>FutureBuilder<List<FoodModel>>(
  future: foods,
  builder: (context, datas) {

  }
)
</code>```

Since FutureBuilder handles async await things, instead of calling db.getFoods() inside your initState method, you can do it inside FutureBuilder as follows:

```<code>FutureBuilder<List<FoodModel>>(
  future: db.getFoods(),
  builder: (context, datas) {

  }
)
</code>```

But you are using foods in some other places, so you might need a little more refactoring.

Body:
So I'm trying to get my foodmodel data to show up on my screen, I don't know what is wrong with this code, it must be something about await async but I can't figure it out. It only says type Future<List<dynamic>> is not a subtype of type Future<List<FoodModel>>. I'm still new to flutter. Is there anyway to get data using async await from this code?

class FoodPage extends StatefulWidget {
  @override
  _FoodPageState createState() => _FoodPageState();
}
class _FoodPageState extends State<FoodPage> {
  Future<List<FoodModel>>  foods;
  @override
  initState()  {
    super.initState();
    setState(() {
      var db= DatabaseHelperFood();
      foods=db.getFoods();
    });
  }
  GridView  food_data (List<FoodModel> foods)
  {
    return  GridView.builder(

      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemCount: foods.length,
      itemBuilder: (_, int position)
      {
        return  Card(

          child:Container(
              decoration: BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(FoodModel.map(foods[position]).alamat),
                    fit: BoxFit.cover,
                  )),
              child: Container(
                  margin: EdgeInsets.fromLTRB(
                      0, 152, 0, 0),
                  child: Column(
                    children: <Widget>[
                      Container(
                          width: 500,
                          height: 25,
                          child: RaisedButton(
                            onPressed: () {

                            },
                            child: Text('Beli : $FoodModel.map(_foods[position]).harga',
                                textAlign: TextAlign
                                    .center,
                                style: TextStyle(
                                    color: Colors.white)),
                            color: Colors.black,
                          ))
                    ],
                  )
              )
          ),);
      },
    );
  }
  foodlist(){
    return Expanded(
        child:FutureBuilder(
            future:foods,
            builder:(context,datas)
            {
              if(datas.hasData)
              {
                return food_data(datas.data);
              }
              else if(null== datas.data || datas.data.length==0)
              {
                return Text("No data");
              }
              return CircularProgressIndicator();
            }
        )
    );
  }
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
            backgroundColor: Colors.grey[900],
            leading: Icon(Icons.menu),
            actions: <Widget>[
              Padding(
                  padding: EdgeInsets.all(5),
                  child: Row(children: <Widget>[
                    Container(

                      child:Text("GoFlix",style:TextStyle(fontSize: 30)),
                      margin:EdgeInsets.only(right:90),
                    ),
                    Container(
                        child: Icon(Icons.shopping_cart, size: 30),
                        margin: EdgeInsets.only(top: 5)),
                    Container(
                      margin: EdgeInsets.only(top: 5),
                      width: 40,
                      height: 40,
                      decoration: BoxDecoration(
                          color: Colors.redAccent[800],
                          borderRadius: BorderRadius.circular(10)),
                      child: Center(child: Text("0")),
                    )
                  ]))
            ]),
        body:Container(
            color:Colors.grey[800],
            child: Column(
                children: <Widget>[
                  Image.asset('Asset/Movieabanner.jpg'),
                  foodlist(),

                ])
        )
    );
  }
}

Body:
If your Future value is List<FoodModel> you need to build your FutureBuilder as follows:

FutureBuilder<List<FoodModel>>(
  future: foods,
  builder: (context, datas) {

  }
)

Since FutureBuilder handles async await things, instead of calling db.getFoods() inside your initState method, you can do it inside FutureBuilder as follows:

FutureBuilder<List<FoodModel>>(
  future: db.getFoods(),
  builder: (context, datas) {

  }
)

But you are using foods in some other places, so you might need a little more refactoring.