问:
How to make avail of antlr package of odata-server-core as the latest version of 4.9.0 doesn't contain it?
We're using odata-server-core-4.0.0 in our code.But,as it has vulnerabilities in maven till the version 4.6.0,we are trying to replace it with the latest version,4.9.0.
But,we use antlr(org.apache.olingo.server.core.uri.antlr) package classes such as UriLexer,UriParserParser.AllEOFContext etc.,
Latest version odata-server-core-4.9.0 doesn't contain antlr package.
Can anyone please help how to substitute antlr package classes in our code?</p>
```<code>import org.apache.olingo.server.core.uri.antlr.UriLexer;
import org.apache.olingo.server.core.uri.antlr.UriParserParser;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.AllEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.BatchEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.CrossjoinEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.EntityEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.ExpandItemsEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.FilterExpressionEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.MetadataEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.OrderByEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.PathSegmentEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.SelectEOFContext;

UriContext context = new UriContext();
        UriParseTreeVisitor uriParseTreeVisitor = new UriParseTreeVisitor(edm, context);

            final RawUri uri = UriDecoder.decodeUri(path, query, fragment, 0); // ->0 segments are before the service url

            // first, read the decoded path segments
            final String firstSegment = uri.pathSegmentListDecoded.isEmpty() ? "" : uri.pathSegmentListDecoded.get(0);

            if (firstSegment.isEmpty()) {
                ensureLastSegment(firstSegment, 0, uri.pathSegmentListDecoded.size());
                context.contextUriInfo = new UriInfoImpl().setKind(UriInfoKind.service);

            } else if (firstSegment.startsWith("$batch")) {
                ensureLastSegment(firstSegment, 1, uri.pathSegmentListDecoded.size());
                BatchEOFContext ctxBatchEOF = (BatchEOFContext) parseRule(uri.pathSegmentListDecoded.get(0), ParserEntryRules.Batch);
                uriParseTreeVisitor.visitBatchEOF(ctxBatchEOF);

            } else if (firstSegment.startsWith("$metadata")) {
                ensureLastSegment(firstSegment, 1, uri.pathSegmentListDecoded.size());
                MetadataEOFContext ctxMetadataEOF = (MetadataEOFContext) parseRule(uri.pathSegmentListDecoded.get(0),ParserEntryRules.Metadata);
                uriParseTreeVisitor.visitMetadataEOF(ctxMetadataEOF);
                context.contextUriInfo.setFragment(uri.fragment);

            } else if (firstSegment.startsWith("$entity")) {
                context.contextUriInfo = new UriInfoImpl().setKind(UriInfoKind.entityId);
                if (uri.pathSegmentListDecoded.size() > 1) {
                    final String typeCastSegment = uri.pathSegmentListDecoded.get(1);
                    ensureLastSegment(typeCastSegment, 2, uri.pathSegmentListDecoded.size());
                    EntityEOFContext ctxEntityEOF = (EntityEOFContext) parseRule(typeCastSegment, ParserEntryRules.Entity);
                    uriParseTreeVisitor.visitEntityEOF(ctxEntityEOF);
                }
                //Todo need todo the parameters

            } else if (firstSegment.startsWith("$all")) {
                ensureLastSegment(firstSegment, 1, uri.pathSegmentListDecoded.size());
                AllEOFContext ctxResourcePathEOF = (AllEOFContext) parseRule(uri.pathSegmentListDecoded.get(0), ParserEntryRules.All);
                uriParseTreeVisitor.visitAllEOF(ctxResourcePathEOF);
                //Todo Need todo the parameters

            }
</code>```

Body:
We're using odata-server-core-4.0.0 in our code.But,as it has vulnerabilities in maven till the version 4.6.0,we are trying to replace it with the latest version,4.9.0.
But,we use antlr(org.apache.olingo.server.core.uri.antlr) package classes such as UriLexer,UriParserParser.AllEOFContext etc.,
Latest version odata-server-core-4.9.0 doesn't contain antlr package.
Can anyone please help how to substitute antlr package classes in our code?

import org.apache.olingo.server.core.uri.antlr.UriLexer;
import org.apache.olingo.server.core.uri.antlr.UriParserParser;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.AllEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.BatchEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.CrossjoinEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.EntityEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.ExpandItemsEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.FilterExpressionEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.MetadataEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.OrderByEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.PathSegmentEOFContext;
import org.apache.olingo.server.core.uri.antlr.UriParserParser.SelectEOFContext;

UriContext context = new UriContext();
        UriParseTreeVisitor uriParseTreeVisitor = new UriParseTreeVisitor(edm, context);

            final RawUri uri = UriDecoder.decodeUri(path, query, fragment, 0); // ->0 segments are before the service url

            // first, read the decoded path segments
            final String firstSegment = uri.pathSegmentListDecoded.isEmpty() ? "" : uri.pathSegmentListDecoded.get(0);

            if (firstSegment.isEmpty()) {
                ensureLastSegment(firstSegment, 0, uri.pathSegmentListDecoded.size());
                context.contextUriInfo = new UriInfoImpl().setKind(UriInfoKind.service);

            } else if (firstSegment.startsWith("$batch")) {
                ensureLastSegment(firstSegment, 1, uri.pathSegmentListDecoded.size());
                BatchEOFContext ctxBatchEOF = (BatchEOFContext) parseRule(uri.pathSegmentListDecoded.get(0), ParserEntryRules.Batch);
                uriParseTreeVisitor.visitBatchEOF(ctxBatchEOF);

            } else if (firstSegment.startsWith("$metadata")) {
                ensureLastSegment(firstSegment, 1, uri.pathSegmentListDecoded.size());
                MetadataEOFContext ctxMetadataEOF = (MetadataEOFContext) parseRule(uri.pathSegmentListDecoded.get(0),ParserEntryRules.Metadata);
                uriParseTreeVisitor.visitMetadataEOF(ctxMetadataEOF);
                context.contextUriInfo.setFragment(uri.fragment);

            } else if (firstSegment.startsWith("$entity")) {
                context.contextUriInfo = new UriInfoImpl().setKind(UriInfoKind.entityId);
                if (uri.pathSegmentListDecoded.size() > 1) {
                    final String typeCastSegment = uri.pathSegmentListDecoded.get(1);
                    ensureLastSegment(typeCastSegment, 2, uri.pathSegmentListDecoded.size());
                    EntityEOFContext ctxEntityEOF = (EntityEOFContext) parseRule(typeCastSegment, ParserEntryRules.Entity);
                    uriParseTreeVisitor.visitEntityEOF(ctxEntityEOF);
                }
                //Todo need todo the parameters

            } else if (firstSegment.startsWith("$all")) {
                ensureLastSegment(firstSegment, 1, uri.pathSegmentListDecoded.size());
                AllEOFContext ctxResourcePathEOF = (AllEOFContext) parseRule(uri.pathSegmentListDecoded.get(0), ParserEntryRules.All);
                uriParseTreeVisitor.visitAllEOF(ctxResourcePathEOF);
                //Todo Need todo the parameters

            }


来源: stackexchange

问:
Two multivalued attributes in one entity
I am trying to create an entity (order) with a primary key: order ID. Foreign Key: customer ID, and with two multivalued attributes, Product ID and Quantity. Because an order may have multiple products, and each product has specific quantity. The idea is that since they are multivalued then a separate table will be created for them in this way [orderID,ProductID,Quantity]. Is it a correct reasoning?

ER diagram

ContentLicense: CC BY-SA 4.0


问:
changing font (from default) to Calibri (or other) and bold the text (ggplot)
I would like to use Calibri instead of Arial and bold the title.

I used showtext package and was successfully get calibri font.
However, I could not bold the text (as title).
I also used ggtext to customize color and font size but was not able to incorporate the new font (such as Calibri). The code chunk is as follow

text = element_text(family = "Calibri"),
plot.title = element_markdown(size = 18, color = "black",  face = "bold", margin = margin(t= 0, r= 0, b = 10,l = 0)),
plot.title.position = "plot",

Thank you very much
Cheers


问:
CannotResolveService, Microsoft.Extensions.Caching.Memory.IMemoryCache doesn't work in blazer client, ok in Blazor server
I am using Memorycache in blazer server. But same not working in Blazor client, getting resolve issue.

```<code>public PrcService(HttpClient httpClient,
    IMemoryCache memoryCache,
    IMapper mapper)
{
    HttpClient = httpClient;
    Mapper = mapper;
    _memoryCache = memoryCache;

}
</code>```

get data

```<code>    public async Task<Registers> GetRegisters()
    {
        Registers output;

        output = _memoryCache.Get<Registers>("aaa");

        if (output == null)
        {
            var url = "/api/GetRegisters";
            output = await GetJsonAsync<Registers>(url);

            _memoryCache.Set("aaa", output, TimeSpan.FromHours(8));
        }

        return output;
    }
</code>```

error

```<code>Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: CannotResolveService, Microsoft.Extensions.Caching.Memory.IMemoryCache, Invoicing.PrcInvoice.Service.PrcInvoiceService
System.InvalidOperationException: CannotResolveService, Microsoft.Extensions.Caching.Memory.IMemoryCache,
</code>```

Body:
I am using Memorycache in blazer server. But same not working in Blazor client, getting resolve issue.

public PrcService(HttpClient httpClient,
    IMemoryCache memoryCache,
    IMapper mapper)
{
    HttpClient = httpClient;
    Mapper = mapper;
    _memoryCache = memoryCache;

}

get data

    public async Task<Registers> GetRegisters()
    {
        Registers output;

        output = _memoryCache.Get<Registers>("aaa");

        if (output == null)
        {
            var url = "/api/GetRegisters";
            output = await GetJsonAsync<Registers>(url);

            _memoryCache.Set("aaa", output, TimeSpan.FromHours(8));
        }

        return output;
    }

error

Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: CannotResolveService, Microsoft.Extensions.Caching.Memory.IMemoryCache, Invoicing.PrcInvoice.Service.PrcInvoiceService
System.InvalidOperationException: CannotResolveService, Microsoft.Extensions.Caching.Memory.IMemoryCache,


问:
How do I completely ignore labels when using Keras image_dataset_from_directory?
When trying to load my image dataset for an unsupervised problem, without labels, the image_dataset_from_directory function from Keras assumes they belong to a class. The resulting dataset has shape:

(batch_size, None, image_height, image_width, n_channels)

The code:

```<code>data_dir = pathlib.Path(path_to_image)

train_dataset = (keras.utils.image_dataset_from_directory
                  (
                    data_dir,
                    labels=None,
                    validation_split=validation_split,
                    subset="training",
                    shuffle=False,
                    image_size=(image_size, image_size)
                  )

            .map(preprocess_image, num_parallel_calls=tf.data.AUTOTUNE)
            .cache()
            .batch(batch_size, drop_remainder=True)
            .prefetch(buffer_size=tf.data.AUTOTUNE))
</code>```

I believe the dimension with None should be 2 in the case of a dataset with both inputs and target pairs. However, I only wish to load my images from a folder, without labels.

Body:
When trying to load my image dataset for an unsupervised problem, without labels, the image_dataset_from_directory function from Keras assumes they belong to a class. The resulting dataset has shape:

(batch_size, None, image_height, image_width, n_channels)

The code:

data_dir = pathlib.Path(path_to_image)

train_dataset = (keras.utils.image_dataset_from_directory
                  (
                    data_dir,
                    labels=None,
                    validation_split=validation_split,
                    subset="training",
                    shuffle=False,
                    image_size=(image_size, image_size)
                  )

            .map(preprocess_image, num_parallel_calls=tf.data.AUTOTUNE)
            .cache()
            .batch(batch_size, drop_remainder=True)
            .prefetch(buffer_size=tf.data.AUTOTUNE))

I believe the dimension with None should be 2 in the case of a dataset with both inputs and target pairs. However, I only wish to load my images from a folder, without labels.


问:
vtk NIFTI image to tensor/3d matrix representation
I'm  trying to implement a medical images (MRI .nii files) processing tool(c++) for educational purpose.

Specifically, apply a version of FFT on those images. I already did if for 2D images and I was wondering if the same approach is possible for the 4D case:

Transform image in matrix

Apply FFT on 4D matrix and do computation on the transformed matrix

Inverse FFT and print out modified image

I've found this, but having a tensor for each cell I think is not efficient for my specific problem.

To recap: is there a way to, given a vtkImageReader, retrieve a 4D tensor?

EDIT: I was thinking if is possible to cut the "cubic" image into a dimension to retrieve a 2D matrix, and do this for every "dx" to get a vector of images. It's not a very elegant solution but if that's the only way is it possible to split 3D images in vtk?


问:
Can I use the data from the param method received asynchronously in the get method in express.js?
I got data from a local file. In response, I recieved the array with objects where I found the object I needed by ID. I understood that the object I need is in the data[user] by using the console.log.

```<code>router.param("id", (req, res, next, id) => {
  const fetchData = async () => {
    return await fs
      .readFile("backend/data/loggedUsers.json", "utf-8")
      .then((res) => {
        const data = JSON.parse(res);
        const user = data.findIndex((el) => el.id == id);
        req.user = data[user];
      });
  };
  fetchData();
  next();
});
</code>```

But now I have to use this data in the get method, it doesn’t work out there.

```<code>router.get("/logged/:id", (req, res) => {
    res.json(req.user);
});
</code>```

This code worked just with setTimeout, but I think that is not a good idea.

```<code>router.get("/logged/:id", (req, res) => {
  setTimeout(() => {
    res.json(req.user);
  }, 100);
});
</code>```

Body:
I got data from a local file. In response, I recieved the array with objects where I found the object I needed by ID. I understood that the object I need is in the data[user] by using the console.log.

router.param("id", (req, res, next, id) => {
  const fetchData = async () => {
    return await fs
      .readFile("backend/data/loggedUsers.json", "utf-8")
      .then((res) => {
        const data = JSON.parse(res);
        const user = data.findIndex((el) => el.id == id);
        req.user = data[user];
      });
  };
  fetchData();
  next();
});

But now I have to use this data in the get method, it doesn’t work out there.

router.get("/logged/:id", (req, res) => {
    res.json(req.user);
});

This code worked just with setTimeout, but I think that is not a good idea.

router.get("/logged/:id", (req, res) => {
  setTimeout(() => {
    res.json(req.user);
  }, 100);
});


问:
Import cartopy or basemap in python
I'am trying to make a map with basemap or cartopy. But I can't manage to import one of these packages. For basemap I tried the following:

pip install numpy

```<code>brew install geos
</code>```

pip install proj

pip install basemap

I couldn't  find a clear overview anywhere on how to import basemaps or cartopy without getting errors while importing these packages.

Title: Import cartopy or basemap in python

Body:
I'am trying to make a map with basemap or cartopy. But I can't manage to import one of these packages. For basemap I tried the following:

pip install numpy

brew install geos

pip install proj

pip install basemap

I couldn't  find a clear overview anywhere on how to import basemaps or cartopy without getting errors while importing these packages.


问:
I tried many time to install requests python module but I cant, how I fix the path error on linux pop os?
I tried to install requests python module but i had a problem with PATH, I am using pop os linux

tried to being able to install moudles but seems I have a problem with my OS.


问:
Indexing past lexsort depth may impact performance on sorted index
I have the following index:

import pandas as pd  # version 1.5.2

idx = pd.MultiIndex.from_product(([str(i) for i in (1, 2, 10, 20, 100, 200)], list('ab'), list('X'))).swaplevel(0,2)
```
<br>
```MultiIndex([('X', 'a',   '1'),
            ('X', 'b',   '1'),
            ('X', 'a',   '2'),
            ('X', 'b',   '2'),
            ('X', 'a',  '10'),
            ('X', 'b',  '10'),
            ('X', 'a',  '20'),
            ('X', 'b',  '20'),
            ('X', 'a', '100'),
            ('X', 'b', '100'),
            ('X', 'a', '200'),
            ('X', 'b', '200')],
           )
```
<p>(this is a minimal example, in real there are multiple values on the first level too)</p>
<p>I now sort the index on the first two levels (last level remains unsorted) using <code>idx_sorted = idx.sortlevel([0, 1], sort_remaining=False)[0]</code>:</p>
```MultiIndex([('X', 'a',   '1'),
            ('X', 'a',   '2'),
            ('X', 'a',  '10'),
            ('X', 'a',  '20'),
            ('X', 'a', '100'),
            ('X', 'a', '200'),
            ('X', 'b',   '1'),
            ('X', 'b',   '2'),
            ('X', 'b',  '10'),
            ('X', 'b',  '20'),
            ('X', 'b', '100'),
            ('X', 'b', '200')],
           )
```
<p>When I select from that sorted index like <code>pd.DataFrame(index=idx_sorted).loc[('X', 'a')]</code> I get a <code>PerformanceWarning: indexing past lexsort depth may impact performance.</code></p>
<p>My question is: <strong>why do I get the warning when indexing on two levels using an index that is sorted on these very two levels?</strong> As far as I understand I don't index <em><strong>past</strong></em> the lexsort depth.</p>
<p>Of course there is no warning when sorting all three levels like <code>idx.sortlevel([0,1], sort_remaining=True)</code> or simply <code>idx.sortlevel()</code> but I need the last level unsorted.</p>
<hr>
<p><strong>Update</strong>: comment to Jamiu's answer (too long for a comment):<br />
Timings for larger dataframes:</p>
```idx = pd.MultiIndex.from_product(([str(i) for i in range(100)], list('abcde'), list('ABCDE'))).swaplevel(0,2)
df_unsorted =  pd.DataFrame(index=idx)
idx_sorted = idx.sortlevel([0, 1], sort_remaining=False)[0]
df_sorted = pd.DataFrame(index=idx_sorted)

df_sorted.loc[('A', 'a')]                 # 484 µs
df_unsorted.loc[('A', 'a')]               # 506 µs
df_sorted.xs(('A', 'a'), level=[0, 1])    # 907 µs
df_unsorted.xs(('A', 'a'), level=[0, 1])  # 869 µs
```

loc appears to be faster than xs despite the performance warning

selection using sorted or unsorted indices takes the same time (no matter if loc or xs) ➜ it seems there's something I completely got wrong here?

Body:
I have the following index:

import pandas as pd  # version 1.5.2

idx = pd.MultiIndex.from_product(([str(i) for i in (1, 2, 10, 20, 100, 200)], list('ab'), list('X'))).swaplevel(0,2)

MultiIndex([('X', 'a',   '1'),
            ('X', 'b',   '1'),
            ('X', 'a',   '2'),
            ('X', 'b',   '2'),
            ('X', 'a',  '10'),
            ('X', 'b',  '10'),
            ('X', 'a',  '20'),
            ('X', 'b',  '20'),
            ('X', 'a', '100'),
            ('X', 'b', '100'),
            ('X', 'a', '200'),
            ('X', 'b', '200')],
           )

(this is a minimal example, in real there are multiple values on the first level too)

I now sort the index on the first two levels (last level remains unsorted) using idx_sorted = idx.sortlevel([0, 1], sort_remaining=False)[0]:

MultiIndex([('X', 'a',   '1'),
            ('X', 'a',   '2'),
            ('X', 'a',  '10'),
            ('X', 'a',  '20'),
            ('X', 'a', '100'),
            ('X', 'a', '200'),
            ('X', 'b',   '1'),
            ('X', 'b',   '2'),
            ('X', 'b',  '10'),
            ('X', 'b',  '20'),
            ('X', 'b', '100'),
            ('X', 'b', '200')],
           )

When I select from that sorted index like pd.DataFrame(index=idx_sorted).loc[('X', 'a')] I get a PerformanceWarning: indexing past lexsort depth may impact performance.

My question is: why do I get the warning when indexing on two levels using an index that is sorted on these very two levels? As far as I understand I don't index past the lexsort depth.

Of course there is no warning when sorting all three levels like idx.sortlevel([0,1], sort_remaining=True) or simply idx.sortlevel() but I need the last level unsorted.

Update: comment to Jamiu's answer (too long for a comment):

Timings for larger dataframes:

idx = pd.MultiIndex.from_product(([str(i) for i in range(100)], list('abcde'), list('ABCDE'))).swaplevel(0,2)
df_unsorted =  pd.DataFrame(index=idx)
idx_sorted = idx.sortlevel([0, 1], sort_remaining=False)[0]
df_sorted = pd.DataFrame(index=idx_sorted)

df_sorted.loc[('A', 'a')]                 # 484 µs
df_unsorted.loc[('A', 'a')]               # 506 µs
df_sorted.xs(('A', 'a'), level=[0, 1])    # 907 µs
df_unsorted.xs(('A', 'a'), level=[0, 1])  # 869 µs

loc appears to be faster than xs despite the performance warning

selection using sorted or unsorted indices takes the same time (no matter if loc or xs) ➜ it seems there's something I completely got wrong here?


问:
with react DND only one element accepts the drag reference
with react DND only one element accepts the drag reference   i fetch data with firebase and put them in an array then map through the items and generate a card but only the last element accepts the drag ref

this is the place where I'm trying to implement it

```<code>
import { useDrag } from "react-dnd";

const db = getFirestore(app);
export default function Projects({ currentUid }) {

  const [projects, setProjects] = useState([]);
  const [doneProjects, setDoneProjects] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [dropDown, setDropDown] = useState(false);
  const [key, setKey] = useState();
  const [documentId, setDocumentId] = useState();
  const [progressPercentage, setProgressPercentage] = useState(0);

  const [{ isDragging }, dragRef] = useDrag(
    () => ({
      type: itemTypes.CARD,
     item: { type: itemTypes.CARD },
      collect: (monitor) => ({
        isDragging: monitor.isDragging(),
      })
    }),
    []
  )

  useEffect(() => {
    // amay xwarawa bo aw projecta naya ka tawaw bwn
    // const docRef3 = query(collection(db, "assignedProjects", currentUid, "projects"),where("isDone", "==", true));
    const getProjects = async () => {
      const docRef3 = query(
        collection(db, "assignedProjects", currentUid, "projects"),
        where("isDone", "==", true)
        );
        const docDoneSnap = await getDocs(docRef3);

     onSnapshot(docRef3, (docDoneSnap) => {
      const projectsDoneArr = [];
      docDoneSnap.forEach((doc) => {
        projectsDoneArr.push(doc.data());

      });

      setDoneProjects(projectsDoneArr);
    });

        const docRef = query(
          collection(db, "assignedProjects", currentUid, "projects"),
          where("isDone", "==", false)
        );
      // const docSnap = await getDocs(docRef);
      // const projectsArr = [];
      // docSnap.forEach((doc) => {
      //   projectsArr.push(
      //     {
      //       projects:doc.data(),
      //       projectId:doc.id
      //     }
      //     );
      //     documentId = doc.id;

      //     // console.log(doc.data());
      //   });

        onSnapshot(docRef, (docSnap) => {
          const projectsArr = [];
        docSnap.forEach((doc) => {
          projectsArr.push(
            {
              projects:doc.data(),
              projectId:doc.id
            }
          );
          setDocumentId(doc.id);

          // console.log(doc.data());
        });
        setProjects(projectsArr);
      });

      console.log(documentId)
      const taskRef = query(
        collection(db, "assignedProjects", currentUid, "tasks"),
        where("projectId", "==", documentId)
      );
      const taskSnap = await getDocs(taskRef);
      const tasksArr = taskSnap.docs.map((doc) => doc.data());
      setTasks(tasksArr);
    };
    getProjects();

  }, []);

  console.log(tasks)
  useEffect(() => {
    const getProgressPercentage = () => {
      if (projects.length === 0) {
        setProgressPercentage(100);
        return;

      }
      const totalProjects = projects.length;
      const totalDoneProjects = doneProjects.length;
      const totalTasks = tasks.length;
      const totalDoneTasks = tasks.filter((task) => task.isDone === true)
        .length;
      const totalProgress = totalDoneProjects + totalDoneTasks;
      const total = totalProjects + totalTasks;
      const percentage = Math.round((totalProgress / total) * 100);
      setProgressPercentage(percentage);
    };
    getProgressPercentage();
  }, [projects, doneProjects, tasks]);
  function markProjectDone(project) {
    const projectRef = collection(
      db,
      "assignedProjects",
      currentUid,
      "projects"
    );

    const docRef = doc(projectRef, project.projectId);
    updateDoc(docRef, {
      isDone: true,
    });
  }

  const tasksToShow=tasks.map((task) => (
    <div className={""}>
      <p className="h-fit px-10 my-2 py-2 bg-slate-200 dark:bg-[#252525] rounded-2xl  text-xl text-start">
        {task.task1}
      </p>
      <p className="h-fit px-10 my-2 py-2 bg-slate-200 dark:bg-[#252525] rounded-2xl  text-xl text-start">
        {task.task2}
      </p>
      <p className="h-fit px-10 my-2 py-2 bg-slate-200 dark:bg-[#252525] rounded-2xl  text-xl text-start">
        {task.task3}
      </p>
    </div>
  ))

  return (
    <motion.div

      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.75, ease: "easeOut" }}
      className="w-full min-h-full   items-center font-Main text-[#121212] dark:text-[#ffffff] flex justify-between"
    >
      <div className="flex flex-col gap-20 h-full justify-around">
         {/* <Progress value={50} label="Completed" className="bg-cyan-500" /> */}

         {/* {isNaN(progressPercentage)?"Loading ...":<div className='h-5 w-full bg-gray-300'>
            <div
                style={{ width: `${progressPercentage}%`}}
                className={`h-full ${
                    progressPercentage < 70 ? 'bg-red-600' : 'bg-green-600'}`}>
                    {progressPercentage}%
            </div>
        </div>} */}
        <h1 className="text-6xl">Projects in progress</h1>
        {projects.map((project) => (

          <div ref={dragRef}  key={project.id} className=" text-[#121212] dark:text-[#ffffff] flex flex-col gap-2"  draggable={true} >
            <div  className="bg-slate-200 dark:bg-[#252525] w-[35rem] items-center h-32 rounded-2xl py-2 flex justify-between  px-10" >
              <div  className="flex flex-col items-start justify-start gap-2" >
                <h1 className="text-4xl text-[#018786]   dark:text-[#03dac6] ">
                  {project.projects.title}
                </h1>
                <p className="text-lg  text-[#12121247] dark:text-[#ffffff70]">
                  Due date :{" "}
                  <span className="text-[#121212c5] dark:text-[#ffffffb5] ">
                    {project.projects.dueDate}
                  </span>
                </p>
              </div>
              <div className="text-5xl">
                <button
                  onClick={() => {
                    setKey(project.title);
                    setDropDown(dropDown === false ? true : false);
                  }}
                  className="mx-5 dark:text-[#bb86fc] text-[#6200ee]"
                >
                  {dropDown && key === project.title ? (
                    <ion-icon name="chevron-up-circle-outline"></ion-icon>
                  ) : (
                    <ion-icon name="chevron-down-circle-outline"></ion-icon>
                  )}
                </button>

                <button className="text-[#018786]   dark:text-[#03dac6]" onClick={()=>{
                  markProjectDone(project)
                }}>
                  <ion-icon name="checkmark-circle-outline"></ion-icon>
                </button>
              </div>
            </div>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.75, ease: "easeOut" }}
              className={`h-fit transition-all ${
                dropDown && key === project.title ? "" : "hidden"
              }  w-full py-2`}
            >
              <div
                className={`h-fit px-10 py-2 dark:bg-[#3700b3] bg-[#6200ee] rounded-2xl   w-full flex flex-col justify-start`}
              >
                <div className="h-fit  w-full ">
                  <p className="text-xl flex  text-[#ffffffc1]">
                    Description :{" "}
                    <span className=" text-[#ffffff] ">
                      <p>{project.projects.description}</p>
                    </span>
                  </p>
                </div>

                <p>{project.projects.status}</p>
              </div>

              {tasksToShow}

            </motion.div>
          </div>
        ))}
      </div>
      <div className="flex flex-col gap-20 h-full justify-around">
        <h1 className="text-6xl">Done Projects</h1>
        {doneProjects.map((project) => (
          <div className="">
            <div className=" bg-[#0187878e]   dark:bg-[#03dac579]  w-[35rem] items-center h-32 rounded-2xl py-2 flex justify-between  px-10">
              <div className="flex flex-col items-start justify-start gap-2">
                <h1 className="text-4xl  text-[#121212]">{project.title}</h1>
                <p className="text-lg  text-[#12121247] ">
                  Due date :{" "}
                  <span className="text-[#121212c5] ">{project.dueDate}</span>
                </p>
              </div>
            </div>
          </div>
        ))}
      </div>
    </motion.div>
  );
}
</code>```

and this is the index.js

```<code>import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import {DndProvider} from "react-dnd";
import {HTML5Backend} from "react-dnd-html5-backend";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
    <DndProvider backend={HTML5Backend}>
      <App />
    </DndProvider>
    </BrowserRouter>
  </React.StrictMode>
);

</code>```

I tried putting the reference in different divs but still the same.

Body:
with react DND only one element accepts the drag reference   i fetch data with firebase and put them in an array then map through the items and generate a card but only the last element accepts the drag ref

this is the place where I'm trying to implement it

import { useDrag } from "react-dnd";

const db = getFirestore(app);
export default function Projects({ currentUid }) {

  const [projects, setProjects] = useState([]);
  const [doneProjects, setDoneProjects] = useState([]);
  const [tasks, setTasks] = useState([]);
  const [dropDown, setDropDown] = useState(false);
  const [key, setKey] = useState();
  const [documentId, setDocumentId] = useState();
  const [progressPercentage, setProgressPercentage] = useState(0);

  const [{ isDragging }, dragRef] = useDrag(
    () => ({
      type: itemTypes.CARD,
     item: { type: itemTypes.CARD },
      collect: (monitor) => ({
        isDragging: monitor.isDragging(),
      })
    }),
    []
  )

  useEffect(() => {
    // amay xwarawa bo aw projecta naya ka tawaw bwn
    // const docRef3 = query(collection(db, "assignedProjects", currentUid, "projects"),where("isDone", "==", true));
    const getProjects = async () => {
      const docRef3 = query(
        collection(db, "assignedProjects", currentUid, "projects"),
        where("isDone", "==", true)
        );
        const docDoneSnap = await getDocs(docRef3);

     onSnapshot(docRef3, (docDoneSnap) => {
      const projectsDoneArr = [];
      docDoneSnap.forEach((doc) => {
        projectsDoneArr.push(doc.data());

      });

      setDoneProjects(projectsDoneArr);
    });

        const docRef = query(
          collection(db, "assignedProjects", currentUid, "projects"),
          where("isDone", "==", false)
        );
      // const docSnap = await getDocs(docRef);
      // const projectsArr = [];
      // docSnap.forEach((doc) => {
      //   projectsArr.push(
      //     {
      //       projects:doc.data(),
      //       projectId:doc.id
      //     }
      //     );
      //     documentId = doc.id;

      //     // console.log(doc.data());
      //   });

        onSnapshot(docRef, (docSnap) => {
          const projectsArr = [];
        docSnap.forEach((doc) => {
          projectsArr.push(
            {
              projects:doc.data(),
              projectId:doc.id
            }
          );
          setDocumentId(doc.id);

          // console.log(doc.data());
        });
        setProjects(projectsArr);
      });

      console.log(documentId)
      const taskRef = query(
        collection(db, "assignedProjects", currentUid, "tasks"),
        where("projectId", "==", documentId)
      );
      const taskSnap = await getDocs(taskRef);
      const tasksArr = taskSnap.docs.map((doc) => doc.data());
      setTasks(tasksArr);
    };
    getProjects();

  }, []);

  console.log(tasks)
  useEffect(() => {
    const getProgressPercentage = () => {
      if (projects.length === 0) {
        setProgressPercentage(100);
        return;

      }
      const totalProjects = projects.length;
      const totalDoneProjects = doneProjects.length;
      const totalTasks = tasks.length;
      const totalDoneTasks = tasks.filter((task) => task.isDone === true)
        .length;
      const totalProgress = totalDoneProjects + totalDoneTasks;
      const total = totalProjects + totalTasks;
      const percentage = Math.round((totalProgress / total) * 100);
      setProgressPercentage(percentage);
    };
    getProgressPercentage();
  }, [projects, doneProjects, tasks]);
  function markProjectDone(project) {
    const projectRef = collection(
      db,
      "assignedProjects",
      currentUid,
      "projects"
    );

    const docRef = doc(projectRef, project.projectId);
    updateDoc(docRef, {
      isDone: true,
    });
  }

  const tasksToShow=tasks.map((task) => (

        {task.task1}

        {task.task2}

        {task.task3}

  ))

  return (
    <motion.div

      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.75, ease: "easeOut" }}
      className="w-full min-h-full   items-center font-Main text-[#121212] dark:text-[#ffffff] flex justify-between"
    >

         {/* <Progress value={50} label="Completed" className="bg-cyan-500" /> */}

         {/* {isNaN(progressPercentage)?"Loading ...":

            <div
                style={{ width: `${progressPercentage}%`}}
                className={`h-full ${
                    progressPercentage < 70 ? 'bg-red-600' : 'bg-green-600'}`}>
                    {progressPercentage}%

} */}

Projects in progress

        {projects.map((project) => (

                  {project.projects.title}

                  Due date :{" "}

                    {project.projects.dueDate}

                <button
                  onClick={() => {
                    setKey(project.title);
                    setDropDown(dropDown === false ? true : false);
                  }}
                  className="mx-5 dark:text-[#bb86fc] text-[#6200ee]"
                >
                  {dropDown && key === project.title ? (
                    <ion-icon name="chevron-up-circle-outline"></ion-icon>
                  ) : (
                    <ion-icon name="chevron-down-circle-outline"></ion-icon>
                  )}
                </button>

                <button className="text-[#018786]   dark:text-[#03dac6]" onClick={()=>{
                  markProjectDone(project)
                }}>
                  <ion-icon name="checkmark-circle-outline"></ion-icon>
                </button>

            <motion.div
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ duration: 0.75, ease: "easeOut" }}
              className={`h-fit transition-all ${
                dropDown && key === project.title ? "" : "hidden"
              }  w-full py-2`}
            >
              <div
                className={`h-fit px-10 py-2 dark:bg-[#3700b3] bg-[#6200ee] rounded-2xl   w-full flex flex-col justify-start`}
              >

                    Description :{" "}

{project.projects.description}

{project.projects.status}

              {tasksToShow}

            </motion.div>

        ))}

Done Projects

        {doneProjects.map((project) => (

{project.title}

                  Due date :{" "}
                  {project.dueDate}

        ))}

    </motion.div>
  );
}

and this is the index.js

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
import {DndProvider} from "react-dnd";
import {HTML5Backend} from "react-dnd-html5-backend";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <BrowserRouter>
    <DndProvider backend={HTML5Backend}>
      <App />
    </DndProvider>
    </BrowserRouter>
  </React.StrictMode>
);

I tried putting the reference in different divs but still the same.


问:
Salesforce - Row Level Formula
I'm looking for some help with writing a row level formula in Salesforce. I'm looking to find records where the difference between the date of birth and the date of vaccine administration is less than or equal to 6573.5 days (17 years and 364 days). Image attached is where I am trying to write my formula.

I'm having trouble scripting the formula as Salesforce is quite new to me

I have gotten the below formula to work for me:

However I now need the application to check that the result of this formula is less than or equal to 6573.5 days, any help appreciated.

Title: Salesforce - Row Level Formula


问:
r function for classifying calendar dates as spring or neap tide
I want to classify each calendar day from 2005-2025 as spring or neap tide. Is there another function or package to do this?

Spring tide also known as king tide is when the tides are most extreme (higher high tides and lower low tides). Spring tide occurs during the full moon and new moon. Neap tide is the less extreme tides encourage during the half moon phases (waxing and waning moon). I am using this website to determine when the lunar cycle is https://www.calendar-12.com/moon_phases/2022#:~:text=Dates%20of%20Moon%20Phases%20in%202022%20Year%20,%2001%3A42%20PM%20%2028%20more%20rows%20. I also tried using the lunar package to figure out when the dates of the lunar phase are, but ran into issues getting this to work, namely I keep getting the error of an invalid trim argument, but I have already coerced the dates to be in a date format, so I'm not sure why that is happening.

The lunar cycle generally changes the moon phases every week, but there is variation. Typically whenever the moon phase would be spring tide, I will assign three days on either side of the date of the full or new moon to be spring tide days. Days assigned to neap tide are three days on either side of the half moon. Sometimes I have to give or take a day for either assignment when the moon phase change is not exactly 7 days.

So far I have only coded each day by hand in excel (physically typed the word spring or neap in a new column in excel beside the calendar date), but I have 20 years of data to do this for and wanted to find a way to automate it in R. That's why I wondered if a package existed.
Thanks for the help.

What I want my data to look like. In the example, May 8 is a half moon, May 16th is a full moon, May 22nd is a half moon, and May 30th is a new moon.

Code I tried.

```<code>dates <- format(seq(as.Date("2005-01-01"), as.Date("2025-01-01"), by="days"), format="%m/%d/%Y")
as.vector(dates)
library(lunar)
lunar.phase(dates, name = TRUE)
</code>```

Body:
I want to classify each calendar day from 2005-2025 as spring or neap tide. Is there another function or package to do this?

Spring tide also known as king tide is when the tides are most extreme (higher high tides and lower low tides). Spring tide occurs during the full moon and new moon. Neap tide is the less extreme tides encourage during the half moon phases (waxing and waning moon). I am using this website to determine when the lunar cycle is https://www.calendar-12.com/moon_phases/2022#:~:text=Dates%20of%20Moon%20Phases%20in%202022%20Year%20,%2001%3A42%20PM%20%2028%20more%20rows%20. I also tried using the lunar package to figure out when the dates of the lunar phase are, but ran into issues getting this to work, namely I keep getting the error of an invalid trim argument, but I have already coerced the dates to be in a date format, so I'm not sure why that is happening.

The lunar cycle generally changes the moon phases every week, but there is variation. Typically whenever the moon phase would be spring tide, I will assign three days on either side of the date of the full or new moon to be spring tide days. Days assigned to neap tide are three days on either side of the half moon. Sometimes I have to give or take a day for either assignment when the moon phase change is not exactly 7 days.

So far I have only coded each day by hand in excel (physically typed the word spring or neap in a new column in excel beside the calendar date), but I have 20 years of data to do this for and wanted to find a way to automate it in R. That's why I wondered if a package existed.
Thanks for the help.

What I want my data to look like. In the example, May 8 is a half moon, May 16th is a full moon, May 22nd is a half moon, and May 30th is a new moon.

Code I tried.

dates <- format(seq(as.Date("2005-01-01"), as.Date("2025-01-01"), by="days"), format="%m/%d/%Y")
as.vector(dates)
library(lunar)
lunar.phase(dates, name = TRUE)


问:
How to add emojis in MUI v4 TexField of type password?
I'm trying to allow a TextField to read if the user inputs an emoji, but it doesn't work. It doesn't even trigger the event. For normal TextFields it works, but for TextFields with type="password" it doesn't.

My TextField and onChange function look like this:

```<code><TextField
    required
    margin="dense"
    id="password1"
    label="Contraseña"
    type="password"
    value={password1}
    onChange={handlePassword1Change}
    fullWidth
/>
</code>```
```<code>const handlePassword1Change = (event) => {
    console.log('event target: ', event.target.value)
    setPassword1(event.target.value);
};
</code>```

Any help is appreciated, thank you!

Note: I want to do this, because it's one of NISTs recommendations, to allow ASCII/Unicode characters, like spaces and emojis, in passwords.

Body:
I'm trying to allow a TextField to read if the user inputs an emoji, but it doesn't work. It doesn't even trigger the event. For normal TextFields it works, but for TextFields with type="password" it doesn't.

My TextField and onChange function look like this:

<TextField
    required
    margin="dense"
    id="password1"
    label="Contraseña"
    type="password"
    value={password1}
    onChange={handlePassword1Change}
    fullWidth
/>

const handlePassword1Change = (event) => {
    console.log('event target: ', event.target.value)
    setPassword1(event.target.value);
};

Any help is appreciated, thank you!

Note: I want to do this, because it's one of NISTs recommendations, to allow ASCII/Unicode characters, like spaces and emojis, in passwords.


问:
React i18next - Custom formatter doesn't work
I'm using ICU format and would like to add a custom formatter that will lowercase a string.

To do so I've used this configuration

```<code>
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import enTranslation from "./locales/en/translation.json"
import LanguageDetector from 'i18next-browser-languagedetector';
import ICU from 'i18next-icu';

i18n
    .use(LanguageDetector)
    .use(ICU)
    .use(initReactI18next)
    .init({
        fallbackLng: 'en',
        debug: true,
        initImmediate: false,
        resources: {
            en: enTranslation
        },
        lng: "en", // if you're using a language detector, do not define the lng option
        interpolation: {
            escapeValue: false, // not needed for react as it escapes by default
        }
    });

i18n.services.formatter?.add("lowercase", (value, lng, options) => {
    return value.toLowerCase();
});

export default i18n;
</code>```

I load this configration into my index.tsx

```<code>import './i18n';
</code>```

translation.json

```<code>{
  "translation": {
    "custom-format": "Example {value, lowercase}."
  }
}
</code>```

If I try and use this message it just prints out the options. E.g.

```<code>// Prints as "Example {value, lowercase}."
<Trans i18nKey="custom-format" values={{value: "MiXtUrE"}}/>
</code>```

I've checked if the formatter exists in the i18next object and it does. It is however missing its name.

Why won't it use the custom formatter?

Body:
I'm using ICU format and would like to add a custom formatter that will lowercase a string.

To do so I've used this configuration

import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';

import enTranslation from "./locales/en/translation.json"
import LanguageDetector from 'i18next-browser-languagedetector';
import ICU from 'i18next-icu';

i18n
    .use(LanguageDetector)
    .use(ICU)
    .use(initReactI18next)
    .init({
        fallbackLng: 'en',
        debug: true,
        initImmediate: false,
        resources: {
            en: enTranslation
        },
        lng: "en", // if you're using a language detector, do not define the lng option
        interpolation: {
            escapeValue: false, // not needed for react as it escapes by default
        }
    });

i18n.services.formatter?.add("lowercase", (value, lng, options) => {
    return value.toLowerCase();
});

export default i18n;

I load this configration into my index.tsx

import './i18n';

translation.json

{
  "translation": {
    "custom-format": "Example {value, lowercase}."
  }
}

If I try and use this message it just prints out the options. E.g.

// Prints as "Example {value, lowercase}."
<Trans i18nKey="custom-format" values={{value: "MiXtUrE"}}/>

I've checked if the formatter exists in the i18next object and it does. It is however missing its name.

Why won't it use the custom formatter?


问:
how to remove duplicate list and get the new list in for loop operation
I have the following list of maps:

[
   {
      "ExtendedDutyId":1,
      "DutyName":"Overtime duties",
      "DutyDate":"2022-10-26",
      "FromTime":"0:00",
      "ToTime":"36:00",
      "Allowance":0,
      "ShiftType":-1,
      "ShiftCode":-1,

      "Employee":{
         "EmployeeId":1025,
         "FirstName":"Daniel",
         "LastName":"Hansen-Hansen",
         "CompanyCode":"BY"
      }
   },
   {
      "ExtendedDutyId":1,
      "DutyName":"Overtime duties",
      "DutyDate":"2022-10-26",
      "FromTime":"5:11",
      "ToTime":"10:29",
      "Allowance":0,
      "ShiftType":-1,
      "ShiftCode":1314679,
      "Employee":{
         "EmployeeId":1025,
         "FirstName":"Daniel",
         "LastName":"Hansen-Hansen",
         "CompanyCode":"BY"
      }
   },
   {
      "ExtendedDutyId":1,
      "DutyName":"Overtime duties",
      "DutyDate":"2022-10-27",
      "FromTime":"0:00",
      "ToTime":"36:00",
      "Allowance":0,
      "ShiftType": -1,
      "ShiftCode":-1,
      "Employee":{
         "EmployeeId":1025,
         "FirstName":"Daniel",
         "LastName":"Hansen-Hansen",
         "CompanyCode":"BY"
      }
   }
]
```
<p>I would like to manipulate the above data such that data are grouped by their <code>DateOfBirth</code>, so that result would look like this:</p>
<pre class="lang-dart prettyprint-override"><code>{
   "employeeTimeRegStatus":[
      {
         "supervisor":1035,
         "employeeId":1025,
         "companyCode":"BY",
         "statusId":1,
         "timeRegs":[
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-27",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":311,
               "ToTime":629,
               "ShiftType":-1,
               "ShiftCode":1314679,
               "Allowance":0
            }
         ]
      },
      {
         "supervisor":1035,
         "employeeId":1025,
         "companyCode":"BY",
         "statusId":1,
         "timeRegs":[
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-27",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":311,
               "ToTime":629,
               "ShiftType":-1,
               "ShiftCode":1314679,
               "Allowance":0
            }
         ]
      },
      {
         "supervisor":1035,
         "employeeId":1025,
         "companyCode":"BY",
         "statusId":1,
         "timeRegs":[
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-27",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":311,
               "ToTime":629,
               "ShiftType":-1,
               "ShiftCode":1314679,
               "Allowance":0
            }
         ]
      }
   ],

}
</code>```

I have tried to solve this but getting the error:

```<code>The operator '[]' isn't defined for the class 'Object?'
</code>```

When I tried to insert putIfAbsent employee:

    final value = xdata.fold(Map<String, List<dynamic>>(),
       (Map<String, List<dynamic>> a, b) {
           a.putIfAbsent(b["Employee"]!["FirstName"].toString(), ()
             => []).add(b);
               return a;
             }).values
                .where((l) => l.isNotEmpty)
                .map((l) => {

                'Supervisor': l.first["Supervisor"],
                'employeeId': l.first["employeeId"],
                'companyCode': l.first["companyCode"],
                'statusId': l.first["statusId"],

                'TimeRegs': l.map((e) => {
                'ExtendedDutyId': e['ExtendedDutyId'],
                'DutyName': e['DutyName'],
                'DutyDate': e['DutyDate'],
                'FromTime': e['FromTime'],
                'ToTime': e['ToTime'],
                'ShiftType': e['ShiftType'],
                'ShiftCode': e['ShiftCode'],
                'Allowance': e['Allowance'],
              }).toList()
            }).toList();
```
<p>As I am new to dart and flutter, I am not sure what to do. Can anybody help me with this?</p>
<p>model for employeeTimeRegstatus:</p>
```class EmployeeTimeRegStatus {
      int? supervisor;
      int? employeeId;
      String? companyCode;
      int? statusId;
      List<TimeRegs>? timeRegs;

   EmployeeTimeRegStatus(
         {this.supervisor,
         this.employeeId,
         this.companyCode,
         this.statusId,
         this.timeRegs});}
```

Thanks

Body:
I have the following list of maps:

[
   {
      "ExtendedDutyId":1,
      "DutyName":"Overtime duties",
      "DutyDate":"2022-10-26",
      "FromTime":"0:00",
      "ToTime":"36:00",
      "Allowance":0,
      "ShiftType":-1,
      "ShiftCode":-1,

      "Employee":{
         "EmployeeId":1025,
         "FirstName":"Daniel",
         "LastName":"Hansen-Hansen",
         "CompanyCode":"BY"
      }
   },
   {
      "ExtendedDutyId":1,
      "DutyName":"Overtime duties",
      "DutyDate":"2022-10-26",
      "FromTime":"5:11",
      "ToTime":"10:29",
      "Allowance":0,
      "ShiftType":-1,
      "ShiftCode":1314679,
      "Employee":{
         "EmployeeId":1025,
         "FirstName":"Daniel",
         "LastName":"Hansen-Hansen",
         "CompanyCode":"BY"
      }
   },
   {
      "ExtendedDutyId":1,
      "DutyName":"Overtime duties",
      "DutyDate":"2022-10-27",
      "FromTime":"0:00",
      "ToTime":"36:00",
      "Allowance":0,
      "ShiftType": -1,
      "ShiftCode":-1,
      "Employee":{
         "EmployeeId":1025,
         "FirstName":"Daniel",
         "LastName":"Hansen-Hansen",
         "CompanyCode":"BY"
      }
   }
]

I would like to manipulate the above data such that data are grouped by their DateOfBirth, so that result would look like this:

{
   "employeeTimeRegStatus":[
      {
         "supervisor":1035,
         "employeeId":1025,
         "companyCode":"BY",
         "statusId":1,
         "timeRegs":[
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-27",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":311,
               "ToTime":629,
               "ShiftType":-1,
               "ShiftCode":1314679,
               "Allowance":0
            }
         ]
      },
      {
         "supervisor":1035,
         "employeeId":1025,
         "companyCode":"BY",
         "statusId":1,
         "timeRegs":[
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-27",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":311,
               "ToTime":629,
               "ShiftType":-1,
               "ShiftCode":1314679,
               "Allowance":0
            }
         ]
      },
      {
         "supervisor":1035,
         "employeeId":1025,
         "companyCode":"BY",
         "statusId":1,
         "timeRegs":[
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-27",
               "FromTime":0,
               "ToTime":2160,
               "ShiftType":-1,
               "ShiftCode":-1,
               "Allowance":0
            },
            {
               "ExtendedDutyId":1,
               "DutyName":"Overtime duties",
               "DutyDate":"2022-10-26",
               "FromTime":311,
               "ToTime":629,
               "ShiftType":-1,
               "ShiftCode":1314679,
               "Allowance":0
            }
         ]
      }
   ],

}

I have tried to solve this but getting the error:

The operator '[]' isn't defined for the class 'Object?'

When I tried to insert putIfAbsent employee:

    final value = xdata.fold(Map<String, List<dynamic>>(),
       (Map<String, List<dynamic>> a, b) {
           a.putIfAbsent(b["Employee"]!["FirstName"].toString(), ()
             => []).add(b);
               return a;
             }).values
                .where((l) => l.isNotEmpty)
                .map((l) => {

                'Supervisor': l.first["Supervisor"],
                'employeeId': l.first["employeeId"],
                'companyCode': l.first["companyCode"],
                'statusId': l.first["statusId"],

                'TimeRegs': l.map((e) => {
                'ExtendedDutyId': e['ExtendedDutyId'],
                'DutyName': e['DutyName'],
                'DutyDate': e['DutyDate'],
                'FromTime': e['FromTime'],
                'ToTime': e['ToTime'],
                'ShiftType': e['ShiftType'],
                'ShiftCode': e['ShiftCode'],
                'Allowance': e['Allowance'],
              }).toList()
            }).toList();

As I am new to dart and flutter, I am not sure what to do. Can anybody help me with this?

model for employeeTimeRegstatus:

class EmployeeTimeRegStatus {
      int? supervisor;
      int? employeeId;
      String? companyCode;
      int? statusId;
      List<TimeRegs>? timeRegs;

   EmployeeTimeRegStatus(
         {this.supervisor,
         this.employeeId,
         this.companyCode,
         this.statusId,
         this.timeRegs});}

Thanks


问:
Latitude and Longitude
I have table 1 that has North, South, East and West coordinates for a specific region.

On each record in table 2, I have Latitude and Longitude coordinates.  How do I write a query to see if these coordinates are in the designated range specified in table 1

Table 1:

```<code>MapNorthLat MapSouthLat MapEastLong MapWestLong
36.912220   33.738137   -76.189200  -82.380500
</code>```

Table 2

```<code>_Geo_Lat    _Geo_Lon
34.23184    -77.929218
</code>```

Not having any luck with the logic of this code

Title: Latitude and Longitude

Body:
I have table 1 that has North, South, East and West coordinates for a specific region.

On each record in table 2, I have Latitude and Longitude coordinates.  How do I write a query to see if these coordinates are in the designated range specified in table 1

Table 1:

MapNorthLat MapSouthLat MapEastLong MapWestLong
36.912220   33.738137   -76.189200  -82.380500

Table 2

_Geo_Lat    _Geo_Lon
34.23184    -77.929218

Not having any luck with the logic of this code


问:
timeout missing permissions when it has the timeout members permission in discord.py
im trying to make an anti spam but when i try to timeout the spammer it doesnt work instead i get the missing permission error when i made sure it had the timeout members permission

code:

```<code>    async def on_message(self,message):
        if type(message.channel) is not discord.TextChannel or message.author.bot:return
        bucket = self.anti_spam.get_bucket(message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            await message.delete()
            await message.channel.send(f"{message.author.mention}, Stop spammming Please", delete_after=7)
            viol = self.TMV.get_bucket(message)
            check = viol.update_rate_limit()
            if check:
                await message.author.timeout(timedelta(minutes=10), reason="Spamming")
                try: await message.author.send("You have been muted for 10 minutes becuse of spamming")
                except: pass
</code>```

error:
the error

(the bot has every permission but it doesnt have administrator, ban and kick permissions)

it used to work before but now it doesnt

so please tell me what im doing wrong

Body:
im trying to make an anti spam but when i try to timeout the spammer it doesnt work instead i get the missing permission error when i made sure it had the timeout members permission

code:

    async def on_message(self,message):
        if type(message.channel) is not discord.TextChannel or message.author.bot:return
        bucket = self.anti_spam.get_bucket(message)
        retry_after = bucket.update_rate_limit()
        if retry_after:
            await message.delete()
            await message.channel.send(f"{message.author.mention}, Stop spammming Please", delete_after=7)
            viol = self.TMV.get_bucket(message)
            check = viol.update_rate_limit()
            if check:
                await message.author.timeout(timedelta(minutes=10), reason="Spamming")
                try: await message.author.send("You have been muted for 10 minutes becuse of spamming")
                except: pass

error:
the error

(the bot has every permission but it doesnt have administrator, ban and kick permissions)

it used to work before but now it doesnt

so please tell me what im doing wrong


问:
Does pyinvoke support defining "default" arguments that are injected into all tasks automatically?
I like how simple it is to create a cli runnable task like this:

```<code>@task
def my_command(ctx, myarg="abc"):
    ctx.run('some command')
</code>```

I really want to maintain that simplicity if possible, but I also want to define a default set of params ALL my tasks will support.

For example all of my invoke commands should support switches like --human-readable, --filter=<expression>, --limit=<number>, etc.

Is there a way to define my default switches in one place and not have to add them to every one of my task functions definitions? Is there an aspect oriented-ish way to do this where they get injected somehow? Does pyinvoke support using a decorator for something like this?

Body:
I like how simple it is to create a cli runnable task like this:

@task
def my_command(ctx, myarg="abc"):
    ctx.run('some command')

I really want to maintain that simplicity if possible, but I also want to define a default set of params ALL my tasks will support.

For example all of my invoke commands should support switches like --human-readable, --filter=<expression>, --limit=<number>, etc.

Is there a way to define my default switches in one place and not have to add them to every one of my task functions definitions? Is there an aspect oriented-ish way to do this where they get injected somehow? Does pyinvoke support using a decorator for something like this?


问:
Pandas Multiindex Including Intervals Returns Series Sometimes
I'm trying to identify during which activity a certain event occurred.
Since there can be multiple activities going on in different rooms at the same time, the activities are assigned to a room through ah room_id.

As such, I have a series (intervals) using a multiindex keeping track of which activity went on in which room during a period.
More concrete:

```<code>room_id  duration
1        [2022-12-01 23:19:00, 2022-12-01 23:19:00]    activity_1
2        [2022-11-27 23:54:00, 2022-11-27 23:54:00]    activity_2
3        [2022-11-29 23:21:00, 2022-11-29 23:21:00]    activity_3
4        [2022-11-27 22:13:00, 2022-11-28 11:07:00]    activity_4
Name: activity, dtype: object
</code>```

Now, to lookup which activity it is, I'm using the following command:

```<code>intervals.loc[(1, '2022-12-01 23:19:00')]
</code>```

and I get the expected result:

```<code>'activity_1'
</code>```

However, the same query returns a series when the periods of two activities overlap.
This is illustrated by the following example:

```<code>intervals.loc[(2, '2022-11-27 23:54:00')]
</code>```

yielding:

```<code>room_id  duration
2        [2022-11-27 23:54:00, 2022-11-27 23:54:00]    activity_2
Name: activity, dtype: object
</code>```

This leaves me a clueless. I would have expected to enforce a match on both arguments (room_id and duration) when using .loc and wrap the two criteria within parentheses...
This assumption is based on how indexing, as far as I understand, is explained in the pandas documentation on indexing and the handling of time spans.
Anyway, the problem clearly occurs only if two durations overlap as it is the case here between activity 2 and 4.

My current workaround is using .loc[room_id].loc[date] which works, but is not optimal as it uses chained indexing.

```<code>intervals.loc[2].loc['2022-11-27 23:54:00']
</code>```

Any suggestions how, and if, I can force pandas to match both criteria without chained indexing?

Below the code for a full MWE:

```<code>import pandas as pd

intervals = pd.Series({
    (1, pd.Interval(pd.Timestamp("2022-12-01 23:19:00"), pd.Timestamp("2022-12-01 23:19:00"), closed="both")): "activity_1",
    (2, pd.Interval(pd.Timestamp("2022-11-27 23:54:00"), pd.Timestamp("2022-11-27 23:54:00"), closed="both")): "activity_2",
    (3, pd.Interval(pd.Timestamp("2022-11-29 23:21:00"), pd.Timestamp("2022-11-29 23:21:00"), closed="both")): "activity_3",
    (4, pd.Interval(pd.Timestamp("2022-11-27 22:13:00"), pd.Timestamp("2022-11-28 11:07:00"), closed="both")): "activity_4",
})

intervals.index.names = ['room_id', 'duration']
intervals.name = 'activity'
queries = pd.DataFrame([
    (1, '2022-12-01 23:19:00'),
    (2, '2022-11-27 23:54:00'),
    (3, '2022-11-29 23:21:00'),
    (4, '2022-11-27 22:13:00')
], columns=['room_id', 'date'])

queries.apply(lambda q: intervals.loc[(q.room_id, q.date)], axis='columns')
</code>```

which should output something along the lines:

```<code>0                                           activity_1
1    room_id  duration                             ...
2                                           activity_3
3                                           activity_4
dtype: object
</code>```

Body:
I'm trying to identify during which activity a certain event occurred.
Since there can be multiple activities going on in different rooms at the same time, the activities are assigned to a room through ah room_id.

As such, I have a series (intervals) using a multiindex keeping track of which activity went on in which room during a period.
More concrete:

room_id  duration
1        [2022-12-01 23:19:00, 2022-12-01 23:19:00]    activity_1
2        [2022-11-27 23:54:00, 2022-11-27 23:54:00]    activity_2
3        [2022-11-29 23:21:00, 2022-11-29 23:21:00]    activity_3
4        [2022-11-27 22:13:00, 2022-11-28 11:07:00]    activity_4
Name: activity, dtype: object

Now, to lookup which activity it is, I'm using the following command:

intervals.loc[(1, '2022-12-01 23:19:00')]

and I get the expected result:

'activity_1'

However, the same query returns a series when the periods of two activities overlap.
This is illustrated by the following example:

intervals.loc[(2, '2022-11-27 23:54:00')]

yielding:

room_id  duration
2        [2022-11-27 23:54:00, 2022-11-27 23:54:00]    activity_2
Name: activity, dtype: object

This leaves me a clueless. I would have expected to enforce a match on both arguments (room_id and duration) when using .loc and wrap the two criteria within parentheses...
This assumption is based on how indexing, as far as I understand, is explained in the pandas documentation on indexing and the handling of time spans.
Anyway, the problem clearly occurs only if two durations overlap as it is the case here between activity 2 and 4.

My current workaround is using .loc[room_id].loc[date] which works, but is not optimal as it uses chained indexing.

intervals.loc[2].loc['2022-11-27 23:54:00']

Any suggestions how, and if, I can force pandas to match both criteria without chained indexing?

Below the code for a full MWE:

import pandas as pd

intervals = pd.Series({
    (1, pd.Interval(pd.Timestamp("2022-12-01 23:19:00"), pd.Timestamp("2022-12-01 23:19:00"), closed="both")): "activity_1",
    (2, pd.Interval(pd.Timestamp("2022-11-27 23:54:00"), pd.Timestamp("2022-11-27 23:54:00"), closed="both")): "activity_2",
    (3, pd.Interval(pd.Timestamp("2022-11-29 23:21:00"), pd.Timestamp("2022-11-29 23:21:00"), closed="both")): "activity_3",
    (4, pd.Interval(pd.Timestamp("2022-11-27 22:13:00"), pd.Timestamp("2022-11-28 11:07:00"), closed="both")): "activity_4",
})

intervals.index.names = ['room_id', 'duration']
intervals.name = 'activity'
queries = pd.DataFrame([
    (1, '2022-12-01 23:19:00'),
    (2, '2022-11-27 23:54:00'),
    (3, '2022-11-29 23:21:00'),
    (4, '2022-11-27 22:13:00')
], columns=['room_id', 'date'])

queries.apply(lambda q: intervals.loc[(q.room_id, q.date)], axis='columns')

which should output something along the lines:

0                                           activity_1
1    room_id  duration                             ...
2                                           activity_3
3                                           activity_4
dtype: object


问:
Flutter: How do I open "local" files?
I am trying to figure out how to access "local" files in my Flutter Android app. What I mean by "local" is a file that has been bundled in with the app package. I am using Android Studio as my IDE.

I created an "assets" directory in the base of my project, and added a txt file to that directory.

I then added the following to my pubspec.yaml file and did a pub get:

```<code>  assets:
    - assets/data.txt
</code>```

Here is my main.dart code:

```<code>import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter File Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _buttonPressed() {
    File file = File('assets/data.txt');
    Future<String> futureContent = file.readAsString();
    futureContent.then((c) => print(c));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _buttonPressed,
        tooltip: 'Press me!',
        child: const Icon(Icons.add),
      ),
    );
  }
}
</code>```

When I run the app and press the button, I get the following error:

```<code>E/flutter (15392): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/data.txt' (OS Error: No such file or directory, errno = 2)
E/flutter (15392): #0      _File.open.<anonymous closure> (dart:io/file_impl.dart:356:9)
E/flutter (15392): <asynchronous suspension>
E/flutter (15392):
</code>```

What am I missing?

Title: Flutter: How do I open "local" files?

Body:
I am trying to figure out how to access "local" files in my Flutter Android app. What I mean by "local" is a file that has been bundled in with the app package. I am using Android Studio as my IDE.

I created an "assets" directory in the base of my project, and added a txt file to that directory.

I then added the following to my pubspec.yaml file and did a pub get:

  assets:
    - assets/data.txt

Here is my main.dart code:

import 'package:flutter/material.dart';
import 'dart:io';
import 'dart:async' show Future;
import 'package:flutter/services.dart' show rootBundle;

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter File Test'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _buttonPressed() {
    File file = File('assets/data.txt');
    Future<String> futureContent = file.readAsString();
    futureContent.then((c) => print(c));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _buttonPressed,
        tooltip: 'Press me!',
        child: const Icon(Icons.add),
      ),
    );
  }
}

When I run the app and press the button, I get the following error:

E/flutter (15392): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: FileSystemException: Cannot open file, path = 'assets/data.txt' (OS Error: No such file or directory, errno = 2)
E/flutter (15392): #0      _File.open.<anonymous closure> (dart:io/file_impl.dart:356:9)
E/flutter (15392): <asynchronous suspension>
E/flutter (15392):

What am I missing?


问:
Sanity v3 studio related issue getting this after running yarn run dev
i am getting this message
import {defineConfig} from 'sanity'or its corresponding  type declaration
import {deskTool} from 'sanity/desk' or its corresponding  type declaration
import {visionTool} from '@sanity/vision'   --cannot find module 'sanity/vision' or its corresponding type declaration

tried to run sanity but im getting this above message


问:
Why i can't update a realmObject that has a realmList inside it ? (I get an error)
I want to update a RealmObject that contains RealmList and I faced this error : (look at the images)

So why I faced this error? and what's the solution?

Also why RealmObject has duplicate parameters (image 2)

My code and the error are below

InvoiceModel :

```<code>open class PurchaseDatabase : RealmObject {
    @PrimaryKey
    var id: Int? = 0
    var date: String? = ""
    var supplier: String? = ""
    var products: RealmList<ProductBuyModel> = realmListOf()
    var totalPrice: Int? = 0
    var paymentMethod: String? = ""
    var paymentPrice: Int? = 0
    var restPrice: Int? = 0
}
</code>```

Error :

```<code>FATAL EXCEPTION: main

Process: com.bakirdev.gestiondestock, PID: 9705
java.lang.IllegalArgumentException: Cannot import an outdated object. Use findLatest(object) to find an
up-to-date version of the object in the given context before importing it.

at io.realm.kotlin.internal.RealmObjectListOperator.insert(RealmListInternal.k:370)
at io.realm.kotlin.internal.ListOperator$DefaultImpls.insertAll(RealmListInternal.kt:202)
at io.realm.kotlin.internal.BaseRealmObjectListOperator.insertAll(RealmListInternal.kt:258)
at com.bakirdev.gestiondestock.ui.purchases.PurchaseDatabase.setProducts(PurchaseDatabase.kt:150)
at com.bakirdev.gestiondestock.ui.purchases.AddNewInvoice$initListenerEdit$2$1.invoke(AddNewInvoice.kt:168)
at com.bakirdev.gestiondestock.ui.purchases.AddNewInvoice$initListenerEdit$2$1.invoke(AddNewInvoice.kt:162)
at io.realm.kotlin.internal.SuspendableWriter$write$2.invokeSuspend(SuspendableWriter.kt:109)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.os.HandlerThread.run(HandlerThread.java:67)
</code>```

My Code :

```<code>           var invoiceModel: PurchaseDatabase? = purchasesList[position]

            realm.writeBlocking {
                // fetch a frog from the realm by primary key
                invoiceModel = this.query<PurchaseDatabase>("id == ${model.id}").first().find()
                // modify the frog's age in the write transaction to persist the new age to the realm
                invoiceModel?.supplier = purchasesSupplier
                invoiceModel?.products?.clear()
                invoiceModel?.products = products
                invoiceModel?.totalPrice = totalPrice
                invoiceModel?.paymentMethod = paymentMethod
                invoiceModel?.paymentPrice = purchasesPaymentPrice.trim().toInt()
                invoiceModel?.restPrice = purchasesRestPrice.trim().toInt()
            }
            Purchases.invoiceModel = invoiceModel
            val returnedValue = Intent().apply {
                putExtra("position", position)
            }
            setResult(RESULT_OK, returnedValue)
            finish()
</code>```

Body:
I want to update a RealmObject that contains RealmList and I faced this error : (look at the images)

So why I faced this error? and what's the solution?

Also why RealmObject has duplicate parameters (image 2)

My code and the error are below

InvoiceModel :

open class PurchaseDatabase : RealmObject {
    @PrimaryKey
    var id: Int? = 0
    var date: String? = ""
    var supplier: String? = ""
    var products: RealmList<ProductBuyModel> = realmListOf()
    var totalPrice: Int? = 0
    var paymentMethod: String? = ""
    var paymentPrice: Int? = 0
    var restPrice: Int? = 0
}

Error :

FATAL EXCEPTION: main

Process: com.bakirdev.gestiondestock, PID: 9705
java.lang.IllegalArgumentException: Cannot import an outdated object. Use findLatest(object) to find an
up-to-date version of the object in the given context before importing it.

at io.realm.kotlin.internal.RealmObjectListOperator.insert(RealmListInternal.k:370)
at io.realm.kotlin.internal.ListOperator$DefaultImpls.insertAll(RealmListInternal.kt:202)
at io.realm.kotlin.internal.BaseRealmObjectListOperator.insertAll(RealmListInternal.kt:258)
at com.bakirdev.gestiondestock.ui.purchases.PurchaseDatabase.setProducts(PurchaseDatabase.kt:150)
at com.bakirdev.gestiondestock.ui.purchases.AddNewInvoice$initListenerEdit$2$1.invoke(AddNewInvoice.kt:168)
at com.bakirdev.gestiondestock.ui.purchases.AddNewInvoice$initListenerEdit$2$1.invoke(AddNewInvoice.kt:162)
at io.realm.kotlin.internal.SuspendableWriter$write$2.invokeSuspend(SuspendableWriter.kt:109)
at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:236)
at android.os.HandlerThread.run(HandlerThread.java:67)

My Code :

           var invoiceModel: PurchaseDatabase? = purchasesList[position]

            realm.writeBlocking {
                // fetch a frog from the realm by primary key
                invoiceModel = this.query<PurchaseDatabase>("id == ${model.id}").first().find()
                // modify the frog's age in the write transaction to persist the new age to the realm
                invoiceModel?.supplier = purchasesSupplier
                invoiceModel?.products?.clear()
                invoiceModel?.products = products
                invoiceModel?.totalPrice = totalPrice
                invoiceModel?.paymentMethod = paymentMethod
                invoiceModel?.paymentPrice = purchasesPaymentPrice.trim().toInt()
                invoiceModel?.restPrice = purchasesRestPrice.trim().toInt()
            }
            Purchases.invoiceModel = invoiceModel
            val returnedValue = Intent().apply {
                putExtra("position", position)
            }
            setResult(RESULT_OK, returnedValue)
            finish()


问:
R Markdown producing error: Input must be a vector, not an environment?
I have to update some reports I created a while ago using Markdown and when I even try to just create a title page I get an error. Running the code below

```<code>---
title: "Report"
author: "Author"
date: "12/16/2022"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
</code>```

produces this error message:

processing file: Testing.Rmd
Error in stop_vctrs():
! Input must be a vector, not an environment.
Backtrace:

rmarkdown::render(...)

vctrs:::stop_scalar_type(<fn>(<env>), "")

vctrs:::stop_vctrs(msg, "vctrs_error_scalar_type", actual = x)
Execution halted

Any idea what's going on? Been searching online for an hour and can't find anything

Body:
I have to update some reports I created a while ago using Markdown and when I even try to just create a title page I get an error. Running the code below

---
title: "Report"
author: "Author"
date: "12/16/2022"
output: word_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

produces this error message:

processing file: Testing.Rmd
Error in stop_vctrs():
! Input must be a vector, not an environment.
Backtrace:

rmarkdown::render(...)

vctrs:::stop_scalar_type(<fn>(<env>), "")

vctrs:::stop_vctrs(msg, "vctrs_error_scalar_type", actual = x)
Execution halted

Any idea what's going on? Been searching online for an hour and can't find anything


问:
Kubernetes NGINX Ingress Exact pathType not working as expected, what can I do to achieve what I want?
I am running Kubernetes locally, on Windows, where I have the following Ingress:

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-sample-service
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: mydomain.com
    http:
      paths:
      - path: /api/a
        pathType: Exact
        backend:
          service:
            name: a-clusterip-service
            port:
              number: 80
      - path: /api/b
        pathType: Prefix
        backend:
          service:
            name: b-clusterip-service
            port:
              number: 80

</code>```

On my setup, if I:

hit /api/a, a-clusterip-service is hit, which is what I expected;

hit /api/a/, a-clusterip-service is also hit, which is not what I expected, since I am using pathType: Exact.

According to the K8S Docs below, this behaviour is not what should happen:

https://kubernetes.io/docs/concepts/services-networking/ingress/#examples

PathType
path
request
Match

Exact
/foo
/foo/
No Match

My goal is to not have subpaths available outside the cluster.

Is there something missing from my ingress? Or is this a bug with Kubernetes?

I tried following the documentation which I mention in my answer, with no results.

Kubernetes version:

```<code>Client Version: v1.24.2
Kustomize Version: v4.5.4
Server Version: v1.24.2
</code>```

Body:
I am running Kubernetes locally, on Windows, where I have the following Ingress:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: ingress-sample-service
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: mydomain.com
    http:
      paths:
      - path: /api/a
        pathType: Exact
        backend:
          service:
            name: a-clusterip-service
            port:
              number: 80
      - path: /api/b
        pathType: Prefix
        backend:
          service:
            name: b-clusterip-service
            port:
              number: 80

On my setup, if I:

hit /api/a, a-clusterip-service is hit, which is what I expected;

hit /api/a/, a-clusterip-service is also hit, which is not what I expected, since I am using pathType: Exact.

According to the K8S Docs below, this behaviour is not what should happen:

https://kubernetes.io/docs/concepts/services-networking/ingress/#examples

PathType
path
request
Match

Exact
/foo
/foo/
No Match

My goal is to not have subpaths available outside the cluster.

Is there something missing from my ingress? Or is this a bug with Kubernetes?

I tried following the documentation which I mention in my answer, with no results.

Kubernetes version:

Client Version: v1.24.2
Kustomize Version: v4.5.4
Server Version: v1.24.2


问:
Body was inferred to be an attribute in one code snippet, but the other runs fine. Can't find the difference between the two
The bottom, currently commented out section was what I got from a guide in Microsoft's documentation. It runs perfectly fine and using Postman I can submit get, post, put, and delete requests as expected.

I tried to make my own using the documentation as a guide, but I get an error. I don't know what the difference is between the two, so any help would be massively appreciated.

Error:

```<code>An unhandled exception occurred while processing the request.
InvalidOperationException: Body was inferred but the method does not allow inferred body parameters.
Below is the list of parameters that we found:

Parameter | Source
---------------------------------------------------------------------------------
db1 | Body (Inferred)

Did you mean to register the "Body (Inferred)" parameter(s) as a Service or apply the [FromServices] or [FromBody] attribute?
</code>```

Code:

```<code>using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase("UserList"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();

app.MapGet("/users/all", async (UserDB db1) =>
    await db1.Users.ToListAsync());

app.MapGet("/users/current", async (UserDB db2) =>
    await db2.Users.Where(u => u.lastOffense.ToString("yyyy MMMM") == DateTime.Now.ToString("yyyy MMMM")).ToListAsync());

app.MapGet("/login/{username}", async (string username, UserDB db3) =>
{
    var user = await db3.Users.FindAsync(username);
    if (user is null)
    {
        user = new User();
        user.username = username;
        user.lastOffense = DateTime.Now;
        user.offenses = 1;
        await db3.Users.AddAsync(user);
    } else
    {
        user.offenses += 1;
    }

    await db3.SaveChangesAsync();

    return Results.NoContent();

});

app.Run();

 /*

app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync());

app.MapGet("/todoitems/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());

app.MapGet("/todoitems/incomplete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());

app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
            ? Results.Ok(todo)
            : Results.NotFound());

app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todo.Id}", todo);
});

app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
    var todo = await db.Todos.FindAsync(id);

    if (todo is null) return Results.NotFound();

    todo.name = inputTodo.name;
    todo.IsComplete = inputTodo.IsComplete;

    await db.SaveChangesAsync();

    return Results.NoContent();

});

app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
    if (await db.Todos.FindAsync(id) is Todo todo)
    {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }

    return Results.NotFound();
});

app.Run();

*/
</code>```

I've tried changing from MapGet() to MapPost(), and it does work, but from my understanding, that's not what I'm supposed to do in this scenario when I'm just trying to retrieve information. Even if MapPost() was fine to use, I still don't quite understand what the difference between mine and the documentation is to be throwing an error.

Body:
The bottom, currently commented out section was what I got from a guide in Microsoft's documentation. It runs perfectly fine and using Postman I can submit get, post, put, and delete requests as expected.

I tried to make my own using the documentation as a guide, but I get an error. I don't know what the difference is between the two, so any help would be massively appreciated.

Error:

An unhandled exception occurred while processing the request.
InvalidOperationException: Body was inferred but the method does not allow inferred body parameters.
Below is the list of parameters that we found:

Parameter | Source
---------------------------------------------------------------------------------
db1 | Body (Inferred)

Did you mean to register the "Body (Inferred)" parameter(s) as a Service or apply the [FromServices] or [FromBody] attribute?

Code:

using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<TodoDb>(opt => opt.UseInMemoryDatabase("UserList"));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();
var app = builder.Build();

app.MapGet("/users/all", async (UserDB db1) =>
    await db1.Users.ToListAsync());

app.MapGet("/users/current", async (UserDB db2) =>
    await db2.Users.Where(u => u.lastOffense.ToString("yyyy MMMM") == DateTime.Now.ToString("yyyy MMMM")).ToListAsync());

app.MapGet("/login/{username}", async (string username, UserDB db3) =>
{
    var user = await db3.Users.FindAsync(username);
    if (user is null)
    {
        user = new User();
        user.username = username;
        user.lastOffense = DateTime.Now;
        user.offenses = 1;
        await db3.Users.AddAsync(user);
    } else
    {
        user.offenses += 1;
    }

    await db3.SaveChangesAsync();

    return Results.NoContent();

});

app.Run();

 /*

app.MapGet("/todoitems", async (TodoDb db) =>
    await db.Todos.ToListAsync());

app.MapGet("/todoitems/complete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());

app.MapGet("/todoitems/incomplete", async (TodoDb db) =>
    await db.Todos.Where(t => t.IsComplete).ToListAsync());

app.MapGet("/todoitems/{id}", async (int id, TodoDb db) =>
    await db.Todos.FindAsync(id)
        is Todo todo
            ? Results.Ok(todo)
            : Results.NotFound());

app.MapPost("/todoitems", async (Todo todo, TodoDb db) =>
{
    db.Todos.Add(todo);
    await db.SaveChangesAsync();

    return Results.Created($"/todoitems/{todo.Id}", todo);
});

app.MapPut("/todoitems/{id}", async (int id, Todo inputTodo, TodoDb db) =>
{
    var todo = await db.Todos.FindAsync(id);

    if (todo is null) return Results.NotFound();

    todo.name = inputTodo.name;
    todo.IsComplete = inputTodo.IsComplete;

    await db.SaveChangesAsync();

    return Results.NoContent();

});

app.MapDelete("/todoitems/{id}", async (int id, TodoDb db) =>
{
    if (await db.Todos.FindAsync(id) is Todo todo)
    {
        db.Todos.Remove(todo);
        await db.SaveChangesAsync();
        return Results.Ok(todo);
    }

    return Results.NotFound();
});

app.Run();

*/

I've tried changing from MapGet() to MapPost(), and it does work, but from my understanding, that's not what I'm supposed to do in this scenario when I'm just trying to retrieve information. Even if MapPost() was fine to use, I still don't quite understand what the difference between mine and the documentation is to be throwing an error.


问:
dotnet publish: how to pass runtime identifier & self-contained options to referenced projects
I have a main project to which I'm adding a project reference for a worker executable:

Main.csproj:

```<code>    <ProjectReference Include="Worker.csproj" />
</code>```

Worker.csproj sets OutputType to exe, and does not set any RuntimeIdentifier or SelfContained property.

In my dev environment I build Main.csproj with dotnet build, and this works fine. The Worker.exe executable is generated and pulled into the Main project, and Main can run Worker.exe via Process.Start().

The problem is that for release builds, I publish self-contained executables via dotnet publish -r runtime (where runtime can be win-x64, osx-x64, etc.). Using the -r runtime option implies --self-contained. However after adding the project reference to Worker.csproj I now get an error:

```<code>error NETSDK1150: The referenced project 'Worker.csproj' is a non self-contained executable.
A non self-contained executable cannot be referenced by a self-contained executable.  For more information, see https://aka.ms/netsdk1150
</code>```

It seems the publish -r runtime option or the implied --self-contained option does not pass through to the build config of the referenced project.

If I define <SelfContained>true</SelfContained> and <RuntimeIdentifier>win-x64</RuntimeIdentifier> in Worker.csproj, then dotnet publish -r win-x64 succeeds, but dotnet build now fails with the opposite error:

```<code>error NETSDK1151: The referenced project 'Worker.csproj' is a self-contained executable.
A self-contained executable cannot be referenced by a non self-contained executable.  For more information, see https://aka.ms/netsdk1151
</code>```

I can understand why a self contained executable should not be allowed to reference a non-self contained executable (the non-self contained exe wouldn't work if the dotnet runtime isn't installed), but I don't understand why a non-self contained executable is not allowed to reference a self contained executable.

I tried adding conditional properties to Worker.csproj try to detect if it is in publish mode or not and conditionally set the SelfContained & RuntimeIdentifier properties, with no success.

Body:
I have a main project to which I'm adding a project reference for a worker executable:

Main.csproj:

    <ProjectReference Include="Worker.csproj" />

Worker.csproj sets OutputType to exe, and does not set any RuntimeIdentifier or SelfContained property.

In my dev environment I build Main.csproj with dotnet build, and this works fine. The Worker.exe executable is generated and pulled into the Main project, and Main can run Worker.exe via Process.Start().

The problem is that for release builds, I publish self-contained executables via dotnet publish -r runtime (where runtime can be win-x64, osx-x64, etc.). Using the -r runtime option implies --self-contained. However after adding the project reference to Worker.csproj I now get an error:

error NETSDK1150: The referenced project 'Worker.csproj' is a non self-contained executable.
A non self-contained executable cannot be referenced by a self-contained executable.  For more information, see https://aka.ms/netsdk1150

It seems the publish -r runtime option or the implied --self-contained option does not pass through to the build config of the referenced project.

If I define <SelfContained>true</SelfContained> and <RuntimeIdentifier>win-x64</RuntimeIdentifier> in Worker.csproj, then dotnet publish -r win-x64 succeeds, but dotnet build now fails with the opposite error:

error NETSDK1151: The referenced project 'Worker.csproj' is a self-contained executable.
A self-contained executable cannot be referenced by a non self-contained executable.  For more information, see https://aka.ms/netsdk1151

I can understand why a self contained executable should not be allowed to reference a non-self contained executable (the non-self contained exe wouldn't work if the dotnet runtime isn't installed), but I don't understand why a non-self contained executable is not allowed to reference a self contained executable.

I tried adding conditional properties to Worker.csproj try to detect if it is in publish mode or not and conditionally set the SelfContained & RuntimeIdentifier properties, with no success.