问:
How to save in the DB multiple images along with text using Reactjs and Django Rest Framework?
I am creating an e-commerce like app and I am stuck on implementing the feature to add the item (text + multiple images). I am sending a POST request from a Reactjs form, containing text and multiple images and I am able to save the text to the DB, and the images to the media folder, but I cannot save the images (path to media folder) in the DB (Psql).

This is the error message: "IntegrityError at /api/image/multiple_upload/
null value in column "item_id_id" of relation "api_image" violates not-null constraint"

My assumption is, as I am sending 2 different fetch POST requests on submit, one for the text and the other one for the images, and as each image has a FK to the item_id, the image's column cannot be filled as the item has not been yet created. Am I wrong? Is there any suggestion on how to implement that?

models.py

```<code>class Image(models.Model):
    image = models.ImageField(blank=True, null=True, upload_to='%Y/%m/%d')
    item_id = models.ForeignKey('Item', default="", on_delete=models.CASCADE)

class Item(models.Model):
    item_name = models.CharField(max_length=200, default="")
    user_id = models.ForeignKey('User', on_delete=models.CASCADE,)
</code>```

serializers.py

```<code>class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ['id', 'item_name', 'user_id', 'details', 'desire']

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = "__all__"

class MultipleImageSerializer(serializers.Serializer):
    images = serializers.ListField(
        child=serializers.ImageField()
    )
</code>```

views.py

```<code>class ImageView(viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

    # --> detail=false is not sending ids in the url
    @action(detail=False, methods=["POST"])
    def multiple_upload(self, request, *args, **kwargs):
        serializer = MultipleImageSerializer(data=request.data)
        # --> if serializer is valid and if it is an image
        if serializer.is_valid(raise_exception=True):
            images = serializer.validated_data.get('images')
            print(images)
            image_list = []
            for img in images:
                image_list.append(
                    Image(image=img)
                )

            if image_list:  # --> if imagelist exists
                Image.objects.bulk_create(image_list)

            return Response(status=status.HTTP_201_CREATED)
        print(serializer.errors)
</code>```

AddItem.js (component)

```<code>#import...

function AddItem() {
    const [itemName, setItemName] = useState("");
    const [details, setDetails] = useState('');
    const [desire, setDesire] = useState('');

    const uploadData = new FormData();
    const uploadImages = new FormData()

    const newItem = async () => {
        uploadData.append('item_name', itemName);
        uploadData.append('details', details);
        uploadData.append('user_id', 1);

        let newItem = fetch('/api/item', {
            method: 'POST',
            body: uploadData,
        });

        let newImages = axios.post(
            '/api/image/multiple_upload/',
            uploadImages,
        );
        Promise.all([newItem, newImages])
            .then(res => console.log(res))
            .catch(error => console.log(error));

        const handleChange = (e) => {
            _.forEach(e.target.files, file => {
            uploadImages.append('images', file)
        })

        return (
        <div className="App">
            <h3>Add an Item</h3>
            <label>
                Title
                <input type="text" value={itemName} onChange={(e) =>
                 setItemName(e.target.value)} />
            </label>
            <br />
            <label>
                Description:
                <input type="text" value={details} onChange={(e) =>
                setDetails(e.target.value)} />
            </label>
            <br />
            <label>
                Desire:
                <input type="text" value={desire} onChange={(e) =>
                setDesire(e.target.value)} />
            </label>
            <br />
            <label>
                Image
                <input type="file" accept="image/*" multiple onChange={handleChange} />
            </label>
            <br />
            <button onClick={newItem}>New item</button>
        </div>
    );
}
</code>```

Body:
I am creating an e-commerce like app and I am stuck on implementing the feature to add the item (text + multiple images). I am sending a POST request from a Reactjs form, containing text and multiple images and I am able to save the text to the DB, and the images to the media folder, but I cannot save the images (path to media folder) in the DB (Psql).

This is the error message: "IntegrityError at /api/image/multiple_upload/
null value in column "item_id_id" of relation "api_image" violates not-null constraint"

My assumption is, as I am sending 2 different fetch POST requests on submit, one for the text and the other one for the images, and as each image has a FK to the item_id, the image's column cannot be filled as the item has not been yet created. Am I wrong? Is there any suggestion on how to implement that?

models.py

class Image(models.Model):
    image = models.ImageField(blank=True, null=True, upload_to='%Y/%m/%d')
    item_id = models.ForeignKey('Item', default="", on_delete=models.CASCADE)

class Item(models.Model):
    item_name = models.CharField(max_length=200, default="")
    user_id = models.ForeignKey('User', on_delete=models.CASCADE,)

serializers.py

class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ['id', 'item_name', 'user_id', 'details', 'desire']

class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = "__all__"

class MultipleImageSerializer(serializers.Serializer):
    images = serializers.ListField(
        child=serializers.ImageField()
    )

views.py

class ImageView(viewsets.ModelViewSet):
    queryset = Image.objects.all()
    serializer_class = ImageSerializer

    # --> detail=false is not sending ids in the url
    @action(detail=False, methods=["POST"])
    def multiple_upload(self, request, *args, **kwargs):
        serializer = MultipleImageSerializer(data=request.data)
        # --> if serializer is valid and if it is an image
        if serializer.is_valid(raise_exception=True):
            images = serializer.validated_data.get('images')
            print(images)
            image_list = []
            for img in images:
                image_list.append(
                    Image(image=img)
                )

            if image_list:  # --> if imagelist exists
                Image.objects.bulk_create(image_list)

            return Response(status=status.HTTP_201_CREATED)
        print(serializer.errors)

AddItem.js (component)

#import...

function AddItem() {
    const [itemName, setItemName] = useState("");
    const [details, setDetails] = useState('');
    const [desire, setDesire] = useState('');

    const uploadData = new FormData();
    const uploadImages = new FormData()

    const newItem = async () => {
        uploadData.append('item_name', itemName);
        uploadData.append('details', details);
        uploadData.append('user_id', 1);

        let newItem = fetch('/api/item', {
            method: 'POST',
            body: uploadData,
        });

        let newImages = axios.post(
            '/api/image/multiple_upload/',
            uploadImages,
        );
        Promise.all([newItem, newImages])
            .then(res => console.log(res))
            .catch(error => console.log(error));

        const handleChange = (e) => {
            _.forEach(e.target.files, file => {
            uploadImages.append('images', file)
        })

        return (

Add an Item

                Title
                <input type="text" value={itemName} onChange={(e) =>
                 setItemName(e.target.value)} />

                Description:
                <input type="text" value={details} onChange={(e) =>
                setDetails(e.target.value)} />

                Desire:
                <input type="text" value={desire} onChange={(e) =>
                setDesire(e.target.value)} />

                Image
                <input type="file" accept="image/*" multiple onChange={handleChange} />

            <button onClick={newItem}>New item</button>

    );
}


来源: stackexchange

问:
Use fabricjs to markup cesium
When I use fabricjs to markup for ceisum, I have a question. cesiumjs can auto scale when window resize. I set fabaricjs canvas width and height when window resize, but it's objects position and scale are fixed. How can this be solved?

let markupDom = document.getElementsByClassName("markup-container")[0];
this.canvas.setDimensions({width:markupDom.clientWidth,height:markupDom.clientHeight});
```

ContentLicense: CC BY-SA 4.0

Title: Use fabricjs to markup cesium


问:
How to remount a component on action from another component
both of these components are child component of Home.js and what I want is on onSubmit in StudentCreateComponent, ListStudentComponent to mount again and fetch data, and render without refreshing the page.

Here's my StudentCreateForm component submit.

```<code> const handleSubmit = (e) => {
 e.preventDefault();
 axios
  .post("http://localhost:8000/api/", data)
  .then((response) => console.log(response.data));
};
</code>```

and here's my ListStudent component.

```<code>useEffect(() => {
    axios
      .get("http://localhost:8000/api/")
      .then((response) => setStudents(response.data));
  }, []);
</code>```

Body:
both of these components are child component of Home.js and what I want is on onSubmit in StudentCreateComponent, ListStudentComponent to mount again and fetch data, and render without refreshing the page.

Here's my StudentCreateForm component submit.

 const handleSubmit = (e) => {
 e.preventDefault();
 axios
  .post("http://localhost:8000/api/", data)
  .then((response) => console.log(response.data));
};

and here's my ListStudent component.

useEffect(() => {
    axios
      .get("http://localhost:8000/api/")
      .then((response) => setStudents(response.data));
  }, []);


问:
Why python code with list comprehension take less time than the one without?
I wrote following code:

```<code>def meth3(history_list, fromDate, toDate):
    active = {}
    chart_data =  [0] * (daysDiff + 1)
    activityData = [(_activityData.user_id, timezone.localtime(_activityData.last_save_time).date())
                        for item in history_list for _activityData in item.user.activeData
                    ]
    for iActivityData in activityData:
        if ((iActivityData[0], iActivityData[1]) not in active
            and fromDate < iActivityData[1] and iActivityData[1] < toDate):
            chart_data[(iActivityData[1]-fromDate).days] += 1
            active[(iActivityData[0], iActivityData[1])] = None
    return chart_data
</code>```

This function runs in max 1.8s consistently. Note that it iterates through the elements twice:

in list comprehension to create activityData array

in for loop

So to make it faster, I done away with explicitly creating activityData array, thus requiring only single iteration:

```<code>def meth4(history_list, fromDate, toDate):
    active = {}
    chart_data =  [0] * (daysDiff + 1)
    for history_i in history_list:
        for activityData_i in history_i.user.activeData:
            userId = activityData_i.user_id
            recordLastsaveTime = timezone.localtime(activityData_i.last_save_time).date()
             if ((userId, recordLastsaveTime) not in active
                and fromDate < recordLastsaveTime and recordLastsaveTime < toDate):
                chart_data[(recordLastsaveTime-fromDate).days] += 1
                active[(userId, recordLastsaveTime)] = None
    return chart_data
</code>```

But this function takes 2.4+ seconds consistently. Why is this version taking more time than the earlier despite requiring only single iteration?

Body:
I wrote following code:

def meth3(history_list, fromDate, toDate):
    active = {}
    chart_data =  [0] * (daysDiff + 1)
    activityData = [(_activityData.user_id, timezone.localtime(_activityData.last_save_time).date())
                        for item in history_list for _activityData in item.user.activeData
                    ]
    for iActivityData in activityData:
        if ((iActivityData[0], iActivityData[1]) not in active
            and fromDate < iActivityData[1] and iActivityData[1] < toDate):
            chart_data[(iActivityData[1]-fromDate).days] += 1
            active[(iActivityData[0], iActivityData[1])] = None
    return chart_data

This function runs in max 1.8s consistently. Note that it iterates through the elements twice:

in list comprehension to create activityData array

in for loop

So to make it faster, I done away with explicitly creating activityData array, thus requiring only single iteration:

def meth4(history_list, fromDate, toDate):
    active = {}
    chart_data =  [0] * (daysDiff + 1)
    for history_i in history_list:
        for activityData_i in history_i.user.activeData:
            userId = activityData_i.user_id
            recordLastsaveTime = timezone.localtime(activityData_i.last_save_time).date()
             if ((userId, recordLastsaveTime) not in active
                and fromDate < recordLastsaveTime and recordLastsaveTime < toDate):
                chart_data[(recordLastsaveTime-fromDate).days] += 1
                active[(userId, recordLastsaveTime)] = None
    return chart_data

But this function takes 2.4+ seconds consistently. Why is this version taking more time than the earlier despite requiring only single iteration?


问:
How to codegen a one-to-one relationship with SeaORM?
I am using SeaORM automated code generation (based on a PostgreSQL database) to generate my entities code, my issue is that while one-to-many relationships seem to be properly detected, it looks like one-to-one isn't.

My schema looks like the following:
My post table:

```<code>                                 Table "public.post"
 Column |       Type        | Collation | Nullable |             Default
--------+-------------------+-----------+----------+----------------------------------
 id     | integer           |           | not null | nextval('post_id_seq'::regclass)
 title  | character varying |           | not null |
 text   | character varying |           | not null |
Indexes:
    "post_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "illustration" CONSTRAINT "illustration_id_fkey" FOREIGN KEY (id) REFERENCES post(id)
</code>```

My illustration table:

```<code>                 Table "public.illustration"
 Column |       Type        | Collation | Nullable | Default
--------+-------------------+-----------+----------+---------
 id     | integer           |           | not null |
 url    | character varying |           | not null |
Indexes:
    "illustration_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "illustration_id_fkey" FOREIGN KEY (id) REFERENCES post(id)
</code>```

But the generated Post::Relation is the following:

```<code>#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
    #[sea_orm(has_many = "super::illustration::Entity")]
    Illustration,
}
</code>```

While Entity::Relation looks like this:

```<code>pub enum Relation {
    #[sea_orm(
        belongs_to = "super::post::Entity",
        from = "Column::Id",
        to = "super::post::Column::Id",
        on_update = "NoAction",
        on_delete = "NoAction"
    )]
    Post,
}
</code>```

Did I miss anything in my schema? Should I just change has_many to has_one in Post::Relation?

Body:
I am using SeaORM automated code generation (based on a PostgreSQL database) to generate my entities code, my issue is that while one-to-many relationships seem to be properly detected, it looks like one-to-one isn't.

My schema looks like the following:
My post table:

                                 Table "public.post"
 Column |       Type        | Collation | Nullable |             Default
--------+-------------------+-----------+----------+----------------------------------
 id     | integer           |           | not null | nextval('post_id_seq'::regclass)
 title  | character varying |           | not null |
 text   | character varying |           | not null |
Indexes:
    "post_pkey" PRIMARY KEY, btree (id)
Referenced by:
    TABLE "illustration" CONSTRAINT "illustration_id_fkey" FOREIGN KEY (id) REFERENCES post(id)

My illustration table:

                 Table "public.illustration"
 Column |       Type        | Collation | Nullable | Default
--------+-------------------+-----------+----------+---------
 id     | integer           |           | not null |
 url    | character varying |           | not null |
Indexes:
    "illustration_pkey" PRIMARY KEY, btree (id)
Foreign-key constraints:
    "illustration_id_fkey" FOREIGN KEY (id) REFERENCES post(id)

But the generated Post::Relation is the following:

#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {
    #[sea_orm(has_many = "super::illustration::Entity")]
    Illustration,
}

While Entity::Relation looks like this:

pub enum Relation {
    #[sea_orm(
        belongs_to = "super::post::Entity",
        from = "Column::Id",
        to = "super::post::Column::Id",
        on_update = "NoAction",
        on_delete = "NoAction"
    )]
    Post,
}

Did I miss anything in my schema? Should I just change has_many to has_one in Post::Relation?


问:
How to set updateMask parameter in Google Play Developer API
I'm trying to use the google play developer API to patch a subscription using the endpoint:

[PATCH https://androidpublisher.googleapis.com/androidpublisher/v3/applications/{subscription.packageName}/subscriptions/{subscription.productId}

The documentation doesn't provide any useful information about how to use the updateMask query parameter so I'm not sure what to set it as.

When trying to use the API, I keep getting the following error:

{ "error": { "code": 400, "message": "Request contains an invalid argument.", "status": "INVALID_ARGUMENT" } }

Can someone please help guide me through using this endpoint to patch the subscription? An example of the query parameters and body of the API would be great help as well, thanks!


问:
Accessing device hardware programmatically
I'm looking to simply turn on and off a laser point which is a device hardware feature and use this within a kotlin andriod application.

More boadly, how do you access non standard hardware (features not supported via andriod contexts) from within an andriod app.

I tried looking at - https://developer.android.com/reference/android/content/Context to see if there was anything vaguely matching a laser pointer but there isnt any thing that jumps out at me immediately.


问:
React FullCalendar not working properly inside iframe
I'm working on a chrome extension where in the content script I'm injecting the app inside an iframe and then injecting that iframe into the page whenever that content script is loaded onto the page

content.js (Content script)

```<code>import React from "react";
import ReactDOM from "react-dom";
import Frame, { FrameContextConsumer } from "react-frame-component";

import App from "./App";

class Main extends React.Component {
  render() {
    return (
      <Frame
        id="calendar-iframe"
        head={[
          <link
            type="text/css"
            rel="stylesheet"
            href={chrome.runtime.getURL("/static/css/content.css")}
          ></link>,
          <link rel="preconnect" href={"https://fonts.googleapis.com"}></link>,
          <link rel="preconnect" href={"https://fonts.gstatic.com"}></link>,
        ]}
      >
        <FrameContextConsumer>
          {({ document }) => {
            return (
              <App
                iframeDocument={document}
                isExt={true}
                chrome={chrome}
                removeApp={removeApp}
              />
            );
          }}
        </FrameContextConsumer>
      </Frame>
    );
  }
}

const app = document.createElement("div");
app.id = "extension-root";

document.body.appendChild(app);

app.style.display = "none";

ReactDOM.render(<Main />, app);

function removeApp() {
  document.body.removeChild(app);
}

const toggleApp = () => {
  if (app.style.display === "none") {
    app.style.display = "block";
  } else {
    app.style.display = "none";
  }
};

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.message === "icon_clicked") {
    toggleApp();
    sendResponse({ response: "Message received" });
  }
});
</code>```

This is the App.js

```<code>import React from "react";

import "./App.css";

import Calendar from "./components/Calendar";

function App({ iframeDocument }) {
  return (
    <div className="app-container">
      <Calendar />
    </div>
  );
}

export default App;
</code>```

This is Calendar.js

```<code>import React, { useEffect, useRef, useState } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import "./index.css";

let eventGuid = 0;
let todayStr = new Date().toISOString().replace(/T.*$/, ""); // YYYY-MM-DD of today

export const INITIAL_EVENTS = [
  {
    id: createEventId(),
    title: "All-day event",
    start: todayStr,
  },
  {
    id: createEventId(),
    title: "Timed event",
    start: todayStr + "T12:00:00",
  },
];

export function createEventId() {
  return String(eventGuid++);
}

const Calendar = () => {
  const [state, setState] = useState({
    weekendsVisible: true,
    currentEvents: [],
  });

  const calendarRef = useRef(null);

  useEffect(() => {
    setTimeout(() => {
      console.log("Changing view");
      calendarRef?.current?.getApi()?.changeView("timeGridWeek");
      calendarRef?.current?.getApi()?.changeView("timeGridDay");
      calendarRef?.current?.getApi()?.changeView("timeGridWeek");
    }, [2000]);
  }, []);

  const handleEventClick = (clickInfo) => {
    alert("Removing event");
    clickInfo.event.remove();
  };

  const handleEvents = (events) => {
    setState({
      ...state,
      currentEvents: events,
    });
  };

  return (
    <div id="calendar">
      <FullCalendar
        ref={calendarRef}
        plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
        headerToolbar={{
          left: "prev,next today",
          center: "title",
          right: "timeGridWeek,timeGridDay",
        }}
        initialView={"timeGridDay"}
        editable={true}
        selectable={true}
        selectMirror={true}
        dayMaxEvents={true}
        weekends={state.weekendsVisible}
        initialEvents={INITIAL_EVENTS} // alternatively, use the `events` setting to fetch from a feed
        eventContent={renderEventContent} // custom render function
        eventClick={handleEventClick}
        eventsSet={handleEvents}
        nowIndicator={true}
        dragScroll={false}
        // called after events are initialized/added/changed/removed
        /* you can update a remote database when these fire:
            eventAdd={function(){}}
            eventChange={function(){}}
            eventRemove={function(){}}
            */
      />
    </div>
  );
};

function renderEventContent(eventInfo) {
  return (
    <>
      <b>{eventInfo.timeText}</b>
      <i>{eventInfo.event.title}</i>
    </>
  );
}
export default Calendar;
</code>```

But the issue I'm facing is when I try to drag onto the calendar to add events it doesn't consider the document inside the iframe but rather the document of the page into which the iframe is injected. Clicking works fine but only drag and drop are causing issues

Instead of Iframe, I tried injecting the app into a shadow root but it still causes the page CSS to override the styling inside the chrome extension.

Body:
I'm working on a chrome extension where in the content script I'm injecting the app inside an iframe and then injecting that iframe into the page whenever that content script is loaded onto the page

content.js (Content script)

import React from "react";
import ReactDOM from "react-dom";
import Frame, { FrameContextConsumer } from "react-frame-component";

import App from "./App";

class Main extends React.Component {
  render() {
    return (
      <Frame
        id="calendar-iframe"
        head={[
          <link
            type="text/css"
            rel="stylesheet"
            href={chrome.runtime.getURL("/static/css/content.css")}
          ></link>,
          <link rel="preconnect" href={"https://fonts.googleapis.com"}></link>,
          <link rel="preconnect" href={"https://fonts.gstatic.com"}></link>,
        ]}
      >
        <FrameContextConsumer>
          {({ document }) => {
            return (
              <App
                iframeDocument={document}
                isExt={true}
                chrome={chrome}
                removeApp={removeApp}
              />
            );
          }}
        </FrameContextConsumer>
      </Frame>
    );
  }
}

const app = document.createElement("div");
app.id = "extension-root";

document.body.appendChild(app);

app.style.display = "none";

ReactDOM.render(, app);

function removeApp() {
  document.body.removeChild(app);
}

const toggleApp = () => {
  if (app.style.display === "none") {
    app.style.display = "block";
  } else {
    app.style.display = "none";
  }
};

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  if (request.message === "icon_clicked") {
    toggleApp();
    sendResponse({ response: "Message received" });
  }
});

This is the App.js

import React from "react";

import "./App.css";

import Calendar from "./components/Calendar";

function App({ iframeDocument }) {
  return (

      <Calendar />

  );
}

export default App;

This is Calendar.js

import React, { useEffect, useRef, useState } from "react";
import FullCalendar from "@fullcalendar/react";
import dayGridPlugin from "@fullcalendar/daygrid";
import timeGridPlugin from "@fullcalendar/timegrid";
import interactionPlugin from "@fullcalendar/interaction";
import "./index.css";

let eventGuid = 0;
let todayStr = new Date().toISOString().replace(/T.*$/, ""); // YYYY-MM-DD of today

export const INITIAL_EVENTS = [
  {
    id: createEventId(),
    title: "All-day event",
    start: todayStr,
  },
  {
    id: createEventId(),
    title: "Timed event",
    start: todayStr + "T12:00:00",
  },
];

export function createEventId() {
  return String(eventGuid++);
}

const Calendar = () => {
  const [state, setState] = useState({
    weekendsVisible: true,
    currentEvents: [],
  });

  const calendarRef = useRef(null);

  useEffect(() => {
    setTimeout(() => {
      console.log("Changing view");
      calendarRef?.current?.getApi()?.changeView("timeGridWeek");
      calendarRef?.current?.getApi()?.changeView("timeGridDay");
      calendarRef?.current?.getApi()?.changeView("timeGridWeek");
    }, [2000]);
  }, []);

  const handleEventClick = (clickInfo) => {
    alert("Removing event");
    clickInfo.event.remove();
  };

  const handleEvents = (events) => {
    setState({
      ...state,
      currentEvents: events,
    });
  };

  return (

      <FullCalendar
        ref={calendarRef}
        plugins={[dayGridPlugin, timeGridPlugin, interactionPlugin]}
        headerToolbar={{
          left: "prev,next today",
          center: "title",
          right: "timeGridWeek,timeGridDay",
        }}
        initialView={"timeGridDay"}
        editable={true}
        selectable={true}
        selectMirror={true}
        dayMaxEvents={true}
        weekends={state.weekendsVisible}
        initialEvents={INITIAL_EVENTS} // alternatively, use the `events` setting to fetch from a feed
        eventContent={renderEventContent} // custom render function
        eventClick={handleEventClick}
        eventsSet={handleEvents}
        nowIndicator={true}
        dragScroll={false}
        // called after events are initialized/added/changed/removed
        /* you can update a remote database when these fire:
            eventAdd={function(){}}
            eventChange={function(){}}
            eventRemove={function(){}}
            */
      />

  );
};

function renderEventContent(eventInfo) {
  return (
    <>
      {eventInfo.timeText}
      {eventInfo.event.title}
    </>
  );
}
export default Calendar;

But the issue I'm facing is when I try to drag onto the calendar to add events it doesn't consider the document inside the iframe but rather the document of the page into which the iframe is injected. Clicking works fine but only drag and drop are causing issues

Instead of Iframe, I tried injecting the app into a shadow root but it still causes the page CSS to override the styling inside the chrome extension.


问:
Running Google Mock from an Erlang NIF
I work on a complex Erlang NIF written in C++. I want to be able to run unit tests and mocks by calling an exported NIF function that will initialise the google mock/test framework, passing in the correct arguments, and then call RUN_ALL_TESTS.

bool
run_tests(std::string filter)
{

#ifdef BUILD_GTEST
    const int argc = 3;
    std::string flt = "--gtest_filter=" + filter;
    const char* argv[argc] = { "libalalgo", "--gtest_output=xml:report.xml", flt.c_str() };

    ::testing::InitGoogleTest((int*) &argc, (char**) argv);
    ::testing::InitGoogleMock((int*) &argc, (char**) argv);
    int r = RUN_ALL_TESTS();
    if (r == 0)
        return true;

#endif
    return false;
}
```
<p>The exported function is marked as</p>
<pre class="lang-c++ prettyprint-override"><code>{"nif_run_cpp_tests", 1, pn_run_cpp_tests, ERL_NIF_DIRTY_JOB_CPU_BOUND}
</code>```

The function is called from an exported method in the main erlang module call_cpp_test , which is called from a test suite run in the Erlang Common Test Framework. This works for the Google Test framework but fails when mocks are used.

```<code>%%% cpp_SUITE: [==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from test_unit_test
[ RUN      ] test_unit_test.test_unit_tests_work
[       OK ] test_unit_test.test_unit_tests_work (0 ms)
[ RUN      ] test_unit_test.test_mock_framework
/Users/barry.robinson/.cache/rebar3/bin/rebar3: line 4: 57525 Segmentation fault: 11  erl -pz /Users/barry.robinson/.cache/rebar3/vsns/${VSN}/lib/*/ebin +sbtu +A1 -noshell -boot start_clean -s rebar3 main $REBAR3_ERL_ARGS -extra "$@"
make: *** [ct] Error 139
</code>```

Running it in the debugger gives me the failure point, even though GTest and GMock are built with  -Dgtest_disable_pthreads=ON

```<code>* thread #37, name = '12_dirty_cpu_sc', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
    frame #0: 0x000000005d9c98d1 libalalgo.so`testing::internal::ThreadLocal<testing::Sequence*>::ValueHolder* testing::internal::CheckedDowncastToActualType<testing::internal::ThreadLocal<testing::Sequence*>::ValueHolder, testing::internal::ThreadLocalValueHolderBase>(base=0x0000700009b70000) at gtest-port.h:1127:3
   1124 template <class Derived, class Base>
   1125 Derived* CheckedDowncastToActualType(Base* base) {
   1126 #if GTEST_HAS_RTTI
-> 1127   GTEST_CHECK_(typeid(*base) == typeid(Derived));
   1128 #endif
   1129
   1130 #if GTEST_HAS_DOWNCAST_
</code>```

The worrying part of that beoing EXC_BAD_ACCESS (code=EXC_I386_GPFLT). Is this just a general incompatibility with the Erlang VM? (What's the meaning of exception code "EXC_I386_GPFLT"? doesn't seem good).

The code that causes this problem works when compiled as a stand-alone executable, and running the same Mock test, which is provided below (and taken from an example on StackOverflow).

TEST(examples,mocks)
{
    class FooChild
    {
    public:
        virtual void doThis() {}
        virtual bool doThat(int n, double x) { return false; }
    };

    class MockFooChild : public FooChild
    {
    public:
        MOCK_METHOD(void, doThis, (), (override));
        MOCK_METHOD(bool, doThat, (int n, double x), (override));
    };

    class FooFighter
    {
    public:
        void doSomething(FooChild &fooChild)
        {
            fooChild.doThis();
            fooChild.doThat(4, 5);
        }
    };

    MockFooChild mockFooChild;
    FooFighter fooFighter;

    // doThis() must be called exactly 1 time.
    EXPECT_CALL(mockFooChild, doThis).Times(::testing::Exactly(1));

    // doThat() must be called exactly 1 time with parameters 4,5
    EXPECT_CALL(mockFooChild, doThat(4,5)).Times(::testing::Exactly(1));

    fooFighter.doSomething(mockFooChild);
}
```

I have built and run the same code as a stand-alone project with -fsanitize=address without problems. Does anyone have any ideas about what could be happening here?

Is the Google Mock framework simply incompatible with a NIF?

Title: Running Google Mock from an Erlang NIF

Body:
I work on a complex Erlang NIF written in C++. I want to be able to run unit tests and mocks by calling an exported NIF function that will initialise the google mock/test framework, passing in the correct arguments, and then call RUN_ALL_TESTS.

bool
run_tests(std::string filter)
{

#ifdef BUILD_GTEST
    const int argc = 3;
    std::string flt = "--gtest_filter=" + filter;
    const char* argv[argc] = { "libalalgo", "--gtest_output=xml:report.xml", flt.c_str() };

    ::testing::InitGoogleTest((int*) &argc, (char**) argv);
    ::testing::InitGoogleMock((int*) &argc, (char**) argv);
    int r = RUN_ALL_TESTS();
    if (r == 0)
        return true;

#endif
    return false;
}

The exported function is marked as

{"nif_run_cpp_tests", 1, pn_run_cpp_tests, ERL_NIF_DIRTY_JOB_CPU_BOUND}

The function is called from an exported method in the main erlang module call_cpp_test , which is called from a test suite run in the Erlang Common Test Framework. This works for the Google Test framework but fails when mocks are used.

%%% cpp_SUITE: [==========] Running 2 tests from 1 test suite.
[----------] Global test environment set-up.
[----------] 2 tests from test_unit_test
[ RUN      ] test_unit_test.test_unit_tests_work
[       OK ] test_unit_test.test_unit_tests_work (0 ms)
[ RUN      ] test_unit_test.test_mock_framework
/Users/barry.robinson/.cache/rebar3/bin/rebar3: line 4: 57525 Segmentation fault: 11  erl -pz /Users/barry.robinson/.cache/rebar3/vsns/${VSN}/lib/*/ebin +sbtu +A1 -noshell -boot start_clean -s rebar3 main $REBAR3_ERL_ARGS -extra "$@"
make: *** [ct] Error 139

Running it in the debugger gives me the failure point, even though GTest and GMock are built with  -Dgtest_disable_pthreads=ON

* thread #37, name = '12_dirty_cpu_sc', stop reason = EXC_BAD_ACCESS (code=EXC_I386_GPFLT)
    frame #0: 0x000000005d9c98d1 libalalgo.so`testing::internal::ThreadLocal<testing::Sequence*>::ValueHolder* testing::internal::CheckedDowncastToActualType<testing::internal::ThreadLocal<testing::Sequence*>::ValueHolder, testing::internal::ThreadLocalValueHolderBase>(base=0x0000700009b70000) at gtest-port.h:1127:3
   1124 template <class Derived, class Base>
   1125 Derived* CheckedDowncastToActualType(Base* base) {
   1126 #if GTEST_HAS_RTTI
-> 1127   GTEST_CHECK_(typeid(*base) == typeid(Derived));
   1128 #endif
   1129
   1130 #if GTEST_HAS_DOWNCAST_

The worrying part of that beoing EXC_BAD_ACCESS (code=EXC_I386_GPFLT). Is this just a general incompatibility with the Erlang VM? (What's the meaning of exception code "EXC_I386_GPFLT"? doesn't seem good).

The code that causes this problem works when compiled as a stand-alone executable, and running the same Mock test, which is provided below (and taken from an example on StackOverflow).

TEST(examples,mocks)
{
    class FooChild
    {
    public:
        virtual void doThis() {}
        virtual bool doThat(int n, double x) { return false; }
    };

    class MockFooChild : public FooChild
    {
    public:
        MOCK_METHOD(void, doThis, (), (override));
        MOCK_METHOD(bool, doThat, (int n, double x), (override));
    };

    class FooFighter
    {
    public:
        void doSomething(FooChild &fooChild)
        {
            fooChild.doThis();
            fooChild.doThat(4, 5);
        }
    };

    MockFooChild mockFooChild;
    FooFighter fooFighter;

    // doThis() must be called exactly 1 time.
    EXPECT_CALL(mockFooChild, doThis).Times(::testing::Exactly(1));

    // doThat() must be called exactly 1 time with parameters 4,5
    EXPECT_CALL(mockFooChild, doThat(4,5)).Times(::testing::Exactly(1));

    fooFighter.doSomething(mockFooChild);
}

I have built and run the same code as a stand-alone project with -fsanitize=address without problems. Does anyone have any ideas about what could be happening here?

Is the Google Mock framework simply incompatible with a NIF?


问:
You need to finish the lesson first before you can proceed to quiz( Android Studio)
So I'm creating an android application and I want to know how to make the quiz in my application inaccessible at first and you need to finish the lessons first I'm not very good at coding so I can't proceed on what to do next.

I have tried looking in YouTube and other websites for tutorial to no avail


问:
Text Classification roBERTA word embedding to CNN, accuracy not improving
I am learning CNN and roBERTa word embedding, I create a sentiment analysis with 3 label, -1 for negative, 0 for neutral, 1 for positive. I already have word embedding from roBERTa but when processing with CNN, the accuracy just stay at 30-34 % how to solve it ? the length of word embedding is 1024 with 1500 data and this is my code :

```<code>x_train, x_test, y_train, y_test = train_test_split(dtroBerta, dthasil, test_size=0.4, random_state=42)

from yellowbrick.target import ClassBalance
visualizer = ClassBalance(labels=[-1, 0, 1])
visualizer.fit(y_train, y_test)
visualizer.poof()
plt.show()

from keras.layers import Dense, Dropout, Activation, Convolution1D, GlobalMaxPooling1D, GlobalAveragePooling1D, Embedding, Input, SpatialDropout1D, Flatten
from keras.models import Sequential

model2 = Sequential()
model2.add(Input((x_train.shape[1],)))
model2.add(Embedding(1500, 1025, input_length=100, trainable=True)) #weights=[dtBert]
model2.add(SpatialDropout1D(0.3))
model2.add(Convolution1D(32, 3, activation="relu"))
model2.add(GlobalMaxPooling1D())
model2.add(Flatten())
model2.add(Dense(512, activation="relu"))
model2.add(Dense(256, activation="softmax"))
model2.add(Dense(3, activation="sigmoid"))
model2.add(Dropout(0.2))
model2.compile(optimizer='adam', loss='binary_crossentropy', metrics = ['accuracy'])
</code>```

i already tried to change the activation but still same accuracy

Body:
I am learning CNN and roBERTa word embedding, I create a sentiment analysis with 3 label, -1 for negative, 0 for neutral, 1 for positive. I already have word embedding from roBERTa but when processing with CNN, the accuracy just stay at 30-34 % how to solve it ? the length of word embedding is 1024 with 1500 data and this is my code :

x_train, x_test, y_train, y_test = train_test_split(dtroBerta, dthasil, test_size=0.4, random_state=42)

from yellowbrick.target import ClassBalance
visualizer = ClassBalance(labels=[-1, 0, 1])
visualizer.fit(y_train, y_test)
visualizer.poof()
plt.show()

from keras.layers import Dense, Dropout, Activation, Convolution1D, GlobalMaxPooling1D, GlobalAveragePooling1D, Embedding, Input, SpatialDropout1D, Flatten
from keras.models import Sequential

model2 = Sequential()
model2.add(Input((x_train.shape[1],)))
model2.add(Embedding(1500, 1025, input_length=100, trainable=True)) #weights=[dtBert]
model2.add(SpatialDropout1D(0.3))
model2.add(Convolution1D(32, 3, activation="relu"))
model2.add(GlobalMaxPooling1D())
model2.add(Flatten())
model2.add(Dense(512, activation="relu"))
model2.add(Dense(256, activation="softmax"))
model2.add(Dense(3, activation="sigmoid"))
model2.add(Dropout(0.2))
model2.compile(optimizer='adam', loss='binary_crossentropy', metrics = ['accuracy'])

i already tried to change the activation but still same accuracy


问:
AJAX form not submitting with wp_mail()
I have a form on my page. I am sending data without plugins, using wp_mail(). The submit code is in function.php and I am pasting the form as a shortcode on the page. The form works, submits data without AJAX. When I add AJAX code, in devtools it shows that the form has been sent, an alert pops up, but the form does not come to the mail. How can this problem be solved?

// my ajax

$("#contact-form-submit").click(function(event) {
  event.preventDefault();
  var userName = $('#full-name').val();
  var userEmail = $('#email').val();
  var userMessage = $('#message').val();
  $.ajax({
    type: "POST",
    dataType: "html",
    url: "/wp-admin/admin-ajax.php",
    data: {
      action: "display_contact_form",
      contact_form: hiddenInput,
      full_name: userName,
      email: userEmail,
      message: userMessage,
    },
    success: function(response) {
      alert("success");
    }
  });
});```
</div>
</div>
</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//function.php

add_shortcode( 'contact-form', 'display_contact_form' );

function display_contact_form() {

    $validation_messages = [];
    $success_message = '';

    if ( isset( $_POST['contact_form'] ) ) {

        //Sanitize the data
        $full_name = isset( $_POST['full_name'] ) ? sanitize_text_field( $_POST['full_name'] ) : '';
        $email     = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
        $message   = isset( $_POST['message'] ) ? sanitize_textarea_field( $_POST['message'] ) : '';

        //Validate the data
        if ( strlen( $full_name ) === 0 ) {
            $validation_messages[] = esc_html__( 'Please enter a valid name.' );
        }

        if ( strlen( $email ) === 0 or
             ! is_email( $email ) ) {
            $validation_messages[] = esc_html__( 'Please enter a valid email address.' );
        }

        if ( strlen( $message ) === 0 ) {
            $validation_messages[] = esc_html__( 'Please enter a valid message.');
        }

        //Send an email to the WordPress administrator if there are no validation errors
        if ( empty( $validation_messages ) ) {

            $mail    = get_option( 'admin_email' );
            $subject = 'New message from ' . $full_name;
            $message = $message . ' - The email address of the customer is: ' . $mail;

            wp_mail( $mail, $subject, $message );

            $success_message = esc_html__( 'Your message has been successfully sent.' );

        }

    }

    //Display the validation errors
    if ( ! empty( $validation_messages ) ) {
        foreach ( $validation_messages as $validation_message ) {
            echo '<div class="validation-message">' . esc_html( $validation_message ) . '</div>';
        }
    }

    //Display the success message
    if ( strlen( $success_message ) > 0 ) {
        echo '<div class="success-message">' . esc_html( $success_message ) . '</div>';
    }

    ?>

    <!-- Echo a container used that will be used for the JavaScript validation -->
    <div id="validation-messages-container"></div>

    <form id="contact-form" action="<?php echo esc_url( get_permalink() ); ?>"
          method="post">

        <input type="hidden name="contact_form">

        <div class="form-section">
            <label for="full-name"><?php echo esc_html( 'Full Name'); ?></label>
            <input type="text" id="full-name" name="full_name">
        </div>

        <div class="form-section">
            <label for="email"><?php echo esc_html( 'Email' ); ?></label>
            <input type="text" id="email" name="email">
        </div>

        <div class="form-section">
            <label for="message"><?php echo esc_html( 'Message'); ?></label>
            <textarea id="message" name="message"></textarea>
        </div>

        <button type="submit" id="contact-form-submit">Submit</button>

    </form>

    <?php

}

add_action('wp_ajax_display_contact_form', 'display_contact_form');
add_action('wp_ajax_nopriv_display_contact_form', 'display_contact_form');</code>```

Title: AJAX form not submitting with wp_mail()

Body:
I have a form on my page. I am sending data without plugins, using wp_mail(). The submit code is in function.php and I am pasting the form as a shortcode on the page. The form works, submits data without AJAX. When I add AJAX code, in devtools it shows that the form has been sent, an alert pops up, but the form does not come to the mail. How can this problem be solved?

// my ajax

$("#contact-form-submit").click(function(event) {
  event.preventDefault();
  var userName = $('#full-name').val();
  var userEmail = $('#email').val();
  var userMessage = $('#message').val();
  $.ajax({
    type: "POST",
    dataType: "html",
    url: "/wp-admin/admin-ajax.php",
    data: {
      action: "display_contact_form",
      contact_form: hiddenInput,
      full_name: userName,
      email: userEmail,
      message: userMessage,
    },
    success: function(response) {
      alert("success");
    }
  });
});

//function.php

add_shortcode( 'contact-form', 'display_contact_form' );

function display_contact_form() {

    $validation_messages = [];
    $success_message = '';

    if ( isset( $_POST['contact_form'] ) ) {

        //Sanitize the data
        $full_name = isset( $_POST['full_name'] ) ? sanitize_text_field( $_POST['full_name'] ) : '';
        $email     = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
        $message   = isset( $_POST['message'] ) ? sanitize_textarea_field( $_POST['message'] ) : '';

        //Validate the data
        if ( strlen( $full_name ) === 0 ) {
            $validation_messages[] = esc_html__( 'Please enter a valid name.' );
        }

        if ( strlen( $email ) === 0 or
             ! is_email( $email ) ) {
            $validation_messages[] = esc_html__( 'Please enter a valid email address.' );
        }

        if ( strlen( $message ) === 0 ) {
            $validation_messages[] = esc_html__( 'Please enter a valid message.');
        }

        //Send an email to the WordPress administrator if there are no validation errors
        if ( empty( $validation_messages ) ) {

            $mail    = get_option( 'admin_email' );
            $subject = 'New message from ' . $full_name;
            $message = $message . ' - The email address of the customer is: ' . $mail;

            wp_mail( $mail, $subject, $message );

            $success_message = esc_html__( 'Your message has been successfully sent.' );

        }

    }

    //Display the validation errors
    if ( ! empty( $validation_messages ) ) {
        foreach ( $validation_messages as $validation_message ) {
            echo '
' . esc_html( $validation_message ) . '
';
        }
    }

    //Display the success message
    if ( strlen( $success_message ) > 0 ) {
        echo '
' . esc_html( $success_message ) . '
';
    }

    ?>

    <form id="contact-form" action="<?php echo esc_url( get_permalink() ); ?>"
          method="post">

        <input type="hidden name="contact_form">

            <?php echo esc_html( 'Full Name'); ?>
            <input type="text" id="full-name" name="full_name">

            <?php echo esc_html( 'Email' ); ?>
            <input type="text" id="email" name="email">

            <?php echo esc_html( 'Message'); ?>
            <textarea id="message" name="message"></textarea>

        <button type="submit" id="contact-form-submit">Submit</button>

    </form>

    <?php

}

add_action('wp_ajax_display_contact_form', 'display_contact_form');
add_action('wp_ajax_nopriv_display_contact_form', 'display_contact_form');


问:
Running Application even if it is closed
I wrote an application using Python which receives data via Bluetooth, I need it to work even if it is closed. I can manage on_pause and on_stop functions by returning True or False. But when I added on_pause, on_resume and on_stop functions to my code, app does not continue receiving data (in the background and when it is closed), and restarts (on_resume). I need the application to work on_pause (in the background) and on_stop (when it is closed) and even when the user restarted his/her phone (and did not open it). And I read I should use Services to run my app when it is not opened. I use buildozer to debug my code, it is unclear to me, what I should add to my Python code and buildozer.
Any help is greatly appreciated.


问:
ReactorNettyHttpTracing (deprecated) equivalent in Micrometer Tracing
What would be the equivalent of ReactorNettyHttpTracing (deprecated) in Spring Boot 3 with Micrometer + Brave?

```<code>@Bean
public ReactorNettyHttpTracing reactorNettyHttpTracing(HttpTracing httpTracing) {
    return ReactorNettyHttpTracing.create(httpTracing);
}

.......
return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(reactorNettyHttpTracing(null).decorateHttpClient(httpClient)))
</code>```

Body:
What would be the equivalent of ReactorNettyHttpTracing (deprecated) in Spring Boot 3 with Micrometer + Brave?

@Bean
public ReactorNettyHttpTracing reactorNettyHttpTracing(HttpTracing httpTracing) {
    return ReactorNettyHttpTracing.create(httpTracing);
}

.......
return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(reactorNettyHttpTracing(null).decorateHttpClient(httpClient)))


问:
Android Studio: I wanted to create multiple table for SQLite but one table show this error ,database error : no such table
Im trying to use sqlite as my database for my app. At first i have create a table for the user when they sign up. But when i create the second table for the booking, it says no such table
Below is my code

```<code>public class DBhelper extends SQLiteOpenHelper {
    public static final  String DBNAME="database.db";

    public DBhelper(@Nullable Context context) {
        super(context,"database.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

         db.execSQL("create table users(username TEXT primary key, password TEXT )");
         db.execSQL("create table booking(serviceID INTEGER primary key, name TEXT,email TEXT,phone TEXT )");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("drop table if exists users");
        db.execSQL("drop table if exists booking");
        onCreate(db);
    }

    public Boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username",username);
        values.put("password", password);

        long result  = db.insert("users",null,values);
        if(result==-1)return false;
        else
            return true;
    }

    public void addNewBooking( int serviceID, String name,String notes, String phone, String email) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        // on below line we are passing all values
        // along with its key and value pair.
        values.put("serviceID", serviceID);
        values.put("name", name);
        values.put("notes", notes);
        values.put("phone", phone);
        values.put("email", email);
        // after adding all values we are passing
        // content values to our table.
        db.insert("booking", null, values);
        // at last we are closing our
        // database after adding database.
    }

    public Boolean checkusername(String username){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username = ?", new String[] {username});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;
    }

    public Boolean checkuserpass(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username =? and password =?", new String[] {username,password});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;
    }
}
</code>```

below is the error shown

```<code>E/SQLiteLog: (1) table booking has no column named serviceID in "INSERT INTO booking(serviceID,name,email,notes,phone) VALUES (?,?,?,?,?)"
E/SQLiteDatabase: Error inserting serviceID=0 name=name email=em notes=no phone=12
    android.database.sqlite.SQLiteException: table booking has no column named serviceID (code 1 SQLITE_ERROR): , while compiling: INSERT INTO booking(serviceID,name,email,notes,phone) VALUES (?,?,?,?,?)
</code>```

Body:
Im trying to use sqlite as my database for my app. At first i have create a table for the user when they sign up. But when i create the second table for the booking, it says no such table
Below is my code

public class DBhelper extends SQLiteOpenHelper {
    public static final  String DBNAME="database.db";

    public DBhelper(@Nullable Context context) {
        super(context,"database.db", null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

         db.execSQL("create table users(username TEXT primary key, password TEXT )");
         db.execSQL("create table booking(serviceID INTEGER primary key, name TEXT,email TEXT,phone TEXT )");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int i, int i1) {
        db.execSQL("drop table if exists users");
        db.execSQL("drop table if exists booking");
        onCreate(db);
    }

    public Boolean insertData(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("username",username);
        values.put("password", password);

        long result  = db.insert("users",null,values);
        if(result==-1)return false;
        else
            return true;
    }

    public void addNewBooking( int serviceID, String name,String notes, String phone, String email) {

        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();

        // on below line we are passing all values
        // along with its key and value pair.
        values.put("serviceID", serviceID);
        values.put("name", name);
        values.put("notes", notes);
        values.put("phone", phone);
        values.put("email", email);
        // after adding all values we are passing
        // content values to our table.
        db.insert("booking", null, values);
        // at last we are closing our
        // database after adding database.
    }

    public Boolean checkusername(String username){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username = ?", new String[] {username});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;
    }

    public Boolean checkuserpass(String username, String password){
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery("select * from users where username =? and password =?", new String[] {username,password});
        if(cursor.getCount()>0){
            return true;
        }else
            return false;
    }
}

below is the error shown

E/SQLiteLog: (1) table booking has no column named serviceID in "INSERT INTO booking(serviceID,name,email,notes,phone) VALUES (?,?,?,?,?)"
E/SQLiteDatabase: Error inserting serviceID=0 name=name email=em notes=no phone=12
    android.database.sqlite.SQLiteException: table booking has no column named serviceID (code 1 SQLITE_ERROR): , while compiling: INSERT INTO booking(serviceID,name,email,notes,phone) VALUES (?,?,?,?,?)


问:
require('fs') to read/write with vuejs
i want to read/write text local file
I'm using fs like this

```<code>import * as fs from "fs";
const result = fs.readFileSync("sCode.txt", { encoding: "utf-8" });
console.log(result);
</code>```

but i got this console error TypeError: fs__WEBPACK_IMPORTED_MODULE_1__.readFileSync is not a function

how can i use fs with vuejs or if there another way to read/write local file

Title: require('fs') to read/write with vuejs

Body:
i want to read/write text local file
I'm using fs like this

import * as fs from "fs";
const result = fs.readFileSync("sCode.txt", { encoding: "utf-8" });
console.log(result);

but i got this console error TypeError: fs__WEBPACK_IMPORTED_MODULE_1__.readFileSync is not a function

how can i use fs with vuejs or if there another way to read/write local file


问:
iOS How to receive changes of SPM in the app automatically
I have created Swift package manager, uploaded in Github and I use it in my project, it works fine.
When I make some changes in SPM I must update the package from my project in order to get changes. Is it possible to make updating process automatically so users that already installed the app will get changes when launchs the app?

Updated
I worked on project where are swift packages and the role of package was keeping resources (fonts, text styles etc.).
So I would like to know is it possible to provide some info for uses and then change it after while without using API requests?

Second question: If the project is big (2000+ files) can I decrease compilation time by moving some codes to frameworks or swift package? Or framework files compiles every time when we compile the project?

Thanks.


问:
Camel Java - MIME Message with Signature file as attachment - gives incorrect base64 encoded value
I a trying to send a MIME Multipart message using Camel Java. The MIME message has a Signature file as an attachment. In the final MIME message (source), the signature file is encoded incorrectly.

Here is my code:

```<code>from(source)
    .bean(this, "populatedestinationDetails(*)")
.bean(this, "attachSignature(*)")
.marshal().mimeMultipart()
.to(destination);

public void attachSignature(Exchange exchange) throws Exception {
    AttachmentMessage in = exchange.getIn(AttachmentMessage.class);
String body = in.getBody().toString();
String signature = messageSignature.generateSignature(body);
in.addAttachment("Signature.sig", new DataHandler(signature, "application/octet-stream"));
}
</code>```

Also, Is there any way to avoid the base64 encoding while marshalling the mimeMultiPart message?

Body:
I a trying to send a MIME Multipart message using Camel Java. The MIME message has a Signature file as an attachment. In the final MIME message (source), the signature file is encoded incorrectly.

Here is my code:

from(source)
    .bean(this, "populatedestinationDetails(*)")
.bean(this, "attachSignature(*)")
.marshal().mimeMultipart()
.to(destination);

public void attachSignature(Exchange exchange) throws Exception {
    AttachmentMessage in = exchange.getIn(AttachmentMessage.class);
String body = in.getBody().toString();
String signature = messageSignature.generateSignature(body);
in.addAttachment("Signature.sig", new DataHandler(signature, "application/octet-stream"));
}

Also, Is there any way to avoid the base64 encoding while marshalling the mimeMultiPart message?


问:
yocto build error, cmake-native_3.16.5.bb:do_compile) failed with exit code '1'
Error screenshot

I'm facing that problem since a while
I'm using ubuntu 20.04 LTS.

here is the error message, also shown in attatched picture

```<code>ERROR: Task (/home/ahmedshindy/yocto-labs/poky/meta/recipes-devtools/cmake/cmake-native_3.16.5.bb:do_compile) failed with exit code '1'
</code>```

tutorial I'm following:
Getting started with Embedded Linux and Yocto project - building for vexpress-a9 target complete with u-boot bootloader and sdcard emulation

I'm expecting to build successfully

Body:
Error screenshot

I'm facing that problem since a while
I'm using ubuntu 20.04 LTS.

here is the error message, also shown in attatched picture

ERROR: Task (/home/ahmedshindy/yocto-labs/poky/meta/recipes-devtools/cmake/cmake-native_3.16.5.bb:do_compile) failed with exit code '1'

tutorial I'm following:
Getting started with Embedded Linux and Yocto project - building for vexpress-a9 target complete with u-boot bootloader and sdcard emulation

I'm expecting to build successfully


问:
php + windows servers: remote transfer
I need to have a file-uploader on a website that puts the uploaded file to a specific directory on a db server (unfortunately both are Windows).

The web server has apache2.2 and php (plus cURL).
The Db server is running MySQL.

How do I do that/which secure protocol should I use (that is not FTP-based)?
(soon, but not soon enough, everything will be moved to Linux, so it doesn't have to be pretty—just secure)

Thanks!

Edit I can have users added to either system if necessary for authentication

ContentLicense: CC BY-SA 3.0

Title: php + windows servers: remote transfer


问:
Laravel validation "Present" does not work
I have created a FormRequest for updating a BlogPost as UpdateBlogRequest.

I set thumbnail as a "present" for validation. but when this input is empty I get "The thumbnail field must be present."

Also I added input file with thumbnail name in HTML form.

UpdateBlogRequest:

```<code><?php

namespace App\Http\Requests\Blog;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateBlogRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name' => [
                'required',
                Rule::unique('blogs', 'name')->ignore($this->blog),
            ],
            'body' => ['required'],
            'excerpt' => ['present'],
            'thumbnail' => ['present'],
        ];
    }
}

</code>```

I expected does not show error message for thumbnail when is empty

Body:
I have created a FormRequest for updating a BlogPost as UpdateBlogRequest.

I set thumbnail as a "present" for validation. but when this input is empty I get "The thumbnail field must be present."

Also I added input file with thumbnail name in HTML form.

UpdateBlogRequest:

<?php

namespace App\Http\Requests\Blog;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UpdateBlogRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array<string, mixed>
     */
    public function rules()
    {
        return [
            'name' => [
                'required',
                Rule::unique('blogs', 'name')->ignore($this->blog),
            ],
            'body' => ['required'],
            'excerpt' => ['present'],
            'thumbnail' => ['present'],
        ];
    }
}

I expected does not show error message for thumbnail when is empty


问:
RTK Query: How to make the spinner component work until a response is received from both requests: mutation and refetch by tag
I have recently started to learn RTK Query, and encountered a problem, in my application, if you click add album - it will run mutation by function addAlbum()

Button:

```<code><button onClick={handleCreateAlbum} className="border-slate-700 border-2 px-4 py-1 mb-3 transition hover:bg-green-400 rounded-lg">Add album</button>
</code>```

Function:

```<code>const handleCreateAlbum = () => {
      createAlbum(user)
    }
</code>```

but within the function handleCreateAlbum I can only interact with this mutation, which does not allow me to wait for refetch request which is called by the tag

```<code>createAlbum: builder.mutation<IAlbum, IUser>({
        invalidatesTags : (result, error, user) => {
          return [{type : 'Album', id : user.id}]
        },
        query: (user) => {
          return {
            url : '/albums',
            method: 'POST',
            body : {
              userId: user.id,
              name: faker.commerce.productName()
            }
          }
        }
      }),
fetchAlbums : builder.query<IAlbum[], IUser>({
        providesTags : (result, error, user) => {
          return [{type : 'Album', id : user.id}]
        },
        query: (user) => {
          return {
            url: 'albums',
            method : 'GET',
            params : {
              userId : user.id
            },
          }
        }
      })
</code>```

Because of this, I get what I think is a crusty logical expression to make my spinner component work when BOTH queries work:

```<code>const {data, error, isLoading, isSuccess, isFetching, status} = useFetchAlbumsQuery(user);
const [createAlbum, { isLoading : albumIsLoading, isSuccess : albumIsSuccess }] = useCreateAlbumMutation();
{(!isLoading && isFetching) || albumIsLoading && <Spinner />}
</code>```

Can you please tell me how to make the code better or what is the way to track other requests dependent on the tag from mutation, so that the spinner spins until both requests are worked out?

I tried adding a logical expression
{(!isLoading && isFetching) || albumIsLoading && <Spinner />}
But I would like to know a way to track the end of dependent queries in a different way

Body:
I have recently started to learn RTK Query, and encountered a problem, in my application, if you click add album - it will run mutation by function addAlbum()

Button:

<button onClick={handleCreateAlbum} className="border-slate-700 border-2 px-4 py-1 mb-3 transition hover:bg-green-400 rounded-lg">Add album</button>

Function:

const handleCreateAlbum = () => {
      createAlbum(user)
    }

but within the function handleCreateAlbum I can only interact with this mutation, which does not allow me to wait for refetch request which is called by the tag

createAlbum: builder.mutation<IAlbum, IUser>({
        invalidatesTags : (result, error, user) => {
          return [{type : 'Album', id : user.id}]
        },
        query: (user) => {
          return {
            url : '/albums',
            method: 'POST',
            body : {
              userId: user.id,
              name: faker.commerce.productName()
            }
          }
        }
      }),
fetchAlbums : builder.query<IAlbum[], IUser>({
        providesTags : (result, error, user) => {
          return [{type : 'Album', id : user.id}]
        },
        query: (user) => {
          return {
            url: 'albums',
            method : 'GET',
            params : {
              userId : user.id
            },
          }
        }
      })

Because of this, I get what I think is a crusty logical expression to make my spinner component work when BOTH queries work:

const {data, error, isLoading, isSuccess, isFetching, status} = useFetchAlbumsQuery(user);
const [createAlbum, { isLoading : albumIsLoading, isSuccess : albumIsSuccess }] = useCreateAlbumMutation();
{(!isLoading && isFetching) || albumIsLoading && <Spinner />}

Can you please tell me how to make the code better or what is the way to track other requests dependent on the tag from mutation, so that the spinner spins until both requests are worked out?

I tried adding a logical expression
{(!isLoading && isFetching) || albumIsLoading && <Spinner />}
But I would like to know a way to track the end of dependent queries in a different way


问:
Alternative to ResourceBundleViewResolver
I have a legacy jsp application with views.properties file, from which I use ResourceBundleViewResolver to load all the views. As ResourceBundleViewResolver has been deprecated from Spring 5.3,  I have checked the spring documentation and it says "as of 5.3, in favor of Spring's common view resolver variants and/or custom resolver implementations". I would like to know the alternative to use the BundleViewResolver. Apologies in advance, I am very new to dealing with legacy applications.

Edit

Config.java

```<code>public class Configuration_place extends WebMvcConfigurerAdapter {

@Bean
public ResourceBundleViewResolver viewResolver(){
ResourceBundleViewResolver tilesViewResolver = new ResourceBundleViewResolver();
tilesViewResolver.setBasename("views");
return tilesViewResolver;
}

@Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions("/tiles-def.xml");
        return tilesConfigurer;
    }
</code>```

views.properties

```<code>index.(class) = org.springframework.web.servlet.view.tiles3.TilesView
index.url = index

login.(class) = org.springframework.web.servlet.view.tiles3.TilesView
login.url = login
</code>```

tiles-def.xml

```<code><?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
        "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3.0.dtd">

<tiles-definitions>
<definition name = "master.page" template = "/views/templates/layout_main.jsp">
<put-attribute name = "title" value = "JSP Application" />
<put-attribute name = "header" value = "/views/templates/header.jsp" />
<put-attribute name = "menu" value = "/views/templates/menubar.jsp" />
<put-attribute name = "error" value = "/views/templates/errorMessage.jsp" />
<put-attribute name = "content" value = "" />
<put-attribute name = "footer" value = "/views/templates/footer.jsp" />
</definition>

<definition name = "index" extends="master.page">
<put-attribute name="content" value="/views/intro.jsp" />

</definition>

<definition name = "login" extends="master.page">
<put-attribute name="content" value="/views/login.jsp" />
</definition>

</tiles-definitions>
</code>```

Body:
I have a legacy jsp application with views.properties file, from which I use ResourceBundleViewResolver to load all the views. As ResourceBundleViewResolver has been deprecated from Spring 5.3,  I have checked the spring documentation and it says "as of 5.3, in favor of Spring's common view resolver variants and/or custom resolver implementations". I would like to know the alternative to use the BundleViewResolver. Apologies in advance, I am very new to dealing with legacy applications.

Edit

Config.java

public class Configuration_place extends WebMvcConfigurerAdapter {

@Bean
public ResourceBundleViewResolver viewResolver(){
ResourceBundleViewResolver tilesViewResolver = new ResourceBundleViewResolver();
tilesViewResolver.setBasename("views");
return tilesViewResolver;
}

@Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer tilesConfigurer = new TilesConfigurer();
        tilesConfigurer.setDefinitions("/tiles-def.xml");
        return tilesConfigurer;
    }

views.properties

index.(class) = org.springframework.web.servlet.view.tiles3.TilesView
index.url = index

login.(class) = org.springframework.web.servlet.view.tiles3.TilesView
login.url = login

tiles-def.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE tiles-definitions PUBLIC
        "-//Apache Software Foundation//DTD Tiles Configuration 3.0//EN"
"http://tiles.apache.org/dtds/tiles-config_3.0.dtd">

<tiles-definitions>
<definition name = "master.page" template = "/views/templates/layout_main.jsp">
<put-attribute name = "title" value = "JSP Application" />
<put-attribute name = "header" value = "/views/templates/header.jsp" />
<put-attribute name = "menu" value = "/views/templates/menubar.jsp" />
<put-attribute name = "error" value = "/views/templates/errorMessage.jsp" />
<put-attribute name = "content" value = "" />
<put-attribute name = "footer" value = "/views/templates/footer.jsp" />
</definition>

<definition name = "index" extends="master.page">
<put-attribute name="content" value="/views/intro.jsp" />

</definition>

<definition name = "login" extends="master.page">
<put-attribute name="content" value="/views/login.jsp" />
</definition>

</tiles-definitions>


问:
Python floating-point equations
I want to know how to make floating-point equations correctly in Python3.

I am trying to solve a linear equation problem and have variables and statements below.

slope = float(70 / 23)
c = 9
(slope * -161) + c == -481 # False
print((slope * -161) + c) # -481.00000000000006
```

If you manually evaluate (slope * -161) + c, you will get -481. However, python evaluates it as -481.00000000000006 when I use float. How do I resolve this issue?

Title: Python floating-point equations

Body:
I want to know how to make floating-point equations correctly in Python3.

I am trying to solve a linear equation problem and have variables and statements below.

slope = float(70 / 23)
c = 9
(slope * -161) + c == -481 # False
print((slope * -161) + c) # -481.00000000000006

If you manually evaluate (slope * -161) + c, you will get -481. However, python evaluates it as -481.00000000000006 when I use float. How do I resolve this issue?


问:
LSTM model performs poor on the test data while the contrary on the train data
I have created an lstm model to train it on time series data, but during training it performs well on the training set, however it is not the case for the test data, it has a problem of overfitting,

here is my code, could you please indicate which parameter i should change to overcome this issue?

(just to note that the data is sampled at  100 hz frequencey)

```<code>

TIME_PERIODS = 20  # window size
STEP_DISTANCE = 10 # moving step

hidden_size = 180  # 60 units
batch_size = 280 # 256
Lr   = 1e-4
Epchs = 150

Itest  = np.array(np.linspace(10,1,10),dtype='int32')

for i in range(len(Itest)):
#for i in range(len(Itest)):
    display('Sequence ' + str(Itest[i]))

    dfDL_train = dfDL_normalized[dfDL_normalized['Subject Id'].isin(list(Itrain[i,:]))]

    dfDL_train.reset_index(drop = True, inplace=True)

    dfDL_test = dfDL_normalized[dfDL_normalized['Subject Id']  == Itest[i]]

    x_train, y_train= Create_sequences_T(dfDL_train,f,LABEL,TIME_PERIODS)

#x_train, y_train = create_segments_and_labels(x_train,
                                          #     TIME_PERIODS,
                                              #  STEP_DISTANCE,
                                              #  LABEL)

    x_test, y_test =Create_sequences_T(dfDL_test,f,LABEL,TIME_PERIODS)
    # one hot representation of output labels
    y_train = to_categorical(y_train)
    y_test = to_categorical(y_test)

    adam = optimizers.Adam(learning_rate=Lr, beta_1=0.9, beta_2=0.999, amsgrad=False)

    model = Sequential()
    model.add(LSTM(hidden_size,
                   input_shape=(x_train.shape[1],x_train.shape[2]),
                   return_sequences=True,
                   recurrent_dropout=0.2,dropout=0.2,
                   kernel_regularizer=regularizers.l2(1e-7),
                   recurrent_regularizer=regularizers.l2(1e-7),
                   bias_regularizer=regularizers.l2(1e-7),
                   activity_regularizer=regularizers.l1(1e-7)
                   ))

    model.add(LSTM(hidden_size,recurrent_dropout=0.2,dropout=0.2
                   ))
    model.add(Dense(y_train.shape[1]))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy',
                  optimizer=adam,
                  metrics=['accuracy']#['categorical_accuracy']
                  )

    model_fit.append(model.fit(x_train,
                               y_train,
                               batch_size=batch_size,
                               validation_data=(x_test, y_test),
                               epochs=Epchs,
                               shuffle=False, verbose=1))
    model.save('model_'+str(Itest[i])+'.h5')

</code>```

Body:
I have created an lstm model to train it on time series data, but during training it performs well on the training set, however it is not the case for the test data, it has a problem of overfitting,

here is my code, could you please indicate which parameter i should change to overcome this issue?

(just to note that the data is sampled at  100 hz frequencey)

TIME_PERIODS = 20  # window size
STEP_DISTANCE = 10 # moving step

hidden_size = 180  # 60 units
batch_size = 280 # 256
Lr   = 1e-4
Epchs = 150

Itest  = np.array(np.linspace(10,1,10),dtype='int32')

for i in range(len(Itest)):
#for i in range(len(Itest)):
    display('Sequence ' + str(Itest[i]))

    dfDL_train = dfDL_normalized[dfDL_normalized['Subject Id'].isin(list(Itrain[i,:]))]

    dfDL_train.reset_index(drop = True, inplace=True)

    dfDL_test = dfDL_normalized[dfDL_normalized['Subject Id']  == Itest[i]]

    x_train, y_train= Create_sequences_T(dfDL_train,f,LABEL,TIME_PERIODS)

#x_train, y_train = create_segments_and_labels(x_train,
                                          #     TIME_PERIODS,
                                              #  STEP_DISTANCE,
                                              #  LABEL)

    x_test, y_test =Create_sequences_T(dfDL_test,f,LABEL,TIME_PERIODS)
    # one hot representation of output labels
    y_train = to_categorical(y_train)
    y_test = to_categorical(y_test)

    adam = optimizers.Adam(learning_rate=Lr, beta_1=0.9, beta_2=0.999, amsgrad=False)

    model = Sequential()
    model.add(LSTM(hidden_size,
                   input_shape=(x_train.shape[1],x_train.shape[2]),
                   return_sequences=True,
                   recurrent_dropout=0.2,dropout=0.2,
                   kernel_regularizer=regularizers.l2(1e-7),
                   recurrent_regularizer=regularizers.l2(1e-7),
                   bias_regularizer=regularizers.l2(1e-7),
                   activity_regularizer=regularizers.l1(1e-7)
                   ))

    model.add(LSTM(hidden_size,recurrent_dropout=0.2,dropout=0.2
                   ))
    model.add(Dense(y_train.shape[1]))
    model.add(Activation('softmax'))

    model.compile(loss='categorical_crossentropy',
                  optimizer=adam,
                  metrics=['accuracy']#['categorical_accuracy']
                  )

    model_fit.append(model.fit(x_train,
                               y_train,
                               batch_size=batch_size,
                               validation_data=(x_test, y_test),
                               epochs=Epchs,
                               shuffle=False, verbose=1))
    model.save('model_'+str(Itest[i])+'.h5')


问:
How can I only get specific buckets returned by S3 in ListBuckets?
I am trying to get a specific list of buckets in S3 with a simple function using IAM role credentials, in .NET 6:

```<code>_s3ServiceClient= new AmazonS3Client(); // The default is IAM role credentials in this init

ListBucketsResponse bucketsResponse = await
_s3ServiceClient.ListBucketsAsync(CancellationToken.None); // Getting buckets

foreach (S3Bucket bucket in bucketsResponse.Buckets)
{
  Console.WriteLine($"Bucket name: {bucket.BucketName}");
}
</code>```

when the EC2 policy is:

```<code>{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Sid":"VisualEditor0",
         "Effect":"Allow",
         "Action":"*",
         "Resource":"*"
      }
   ]
}
</code>```

I get all of the buckets from the S3.

But when I enter the EC2's Permissions policies section I want to limit the IAM role of that EC2 to get only the permitted buckets of the policy I configure.
For example:

```<code>{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Sid":"VisualEditor0",
         "Effect":"Allow",
         "Action":"*",
         "Resource":[
            "arn:aws:s3:::example-bucket/*",
            "arn:aws:s3:::example-bucket2/*"
         ]
      }
   ]
}
</code>```

I have about 30 buckets on my S3 and in this case I expect that the ListBucketsAsync function will return me only "example-bucket" and "example-bucket2"
instead it throws and error:

Reason: Access Denied (Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.). Amazon.S3.AmazonS3Exception: Access Denied  ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.    at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken)    at Amazon.Runtime.Internal.HttpHandler1.InvokeAsync[T](IExecutionContext executionContext)at Amazon.Runtime.Internal.RedirectHandler.InvokeAsync[T](IExecutionContext executionContext)at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)at Amazon.S3.Internal.AmazonS3ResponseHandler.InvokeAsync[T](IExecutionContext executionContext)at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)--- End of inner exception stack trace ---

I tried to configure the policy in many ways with no success:

```<code>`"Resource": [`
`"arn:aws:s3:::example-bucket/",`
`"arn:aws:s3:::example-bucket2/"`
`]`

`"Resource": [`
`"arn:aws:s3:::example-bucket",`
`"arn:aws:s3:::example-bucket2"`
`]`
</code>```

How can I only get the buckets that are configured in the IAM policy?

Body:
I am trying to get a specific list of buckets in S3 with a simple function using IAM role credentials, in .NET 6:

_s3ServiceClient= new AmazonS3Client(); // The default is IAM role credentials in this init

ListBucketsResponse bucketsResponse = await
_s3ServiceClient.ListBucketsAsync(CancellationToken.None); // Getting buckets

foreach (S3Bucket bucket in bucketsResponse.Buckets)
{
  Console.WriteLine($"Bucket name: {bucket.BucketName}");
}

when the EC2 policy is:

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Sid":"VisualEditor0",
         "Effect":"Allow",
         "Action":"*",
         "Resource":"*"
      }
   ]
}

I get all of the buckets from the S3.

But when I enter the EC2's Permissions policies section I want to limit the IAM role of that EC2 to get only the permitted buckets of the policy I configure.
For example:

{
   "Version":"2012-10-17",
   "Statement":[
      {
         "Sid":"VisualEditor0",
         "Effect":"Allow",
         "Action":"*",
         "Resource":[
            "arn:aws:s3:::example-bucket/*",
            "arn:aws:s3:::example-bucket2/*"
         ]
      }
   ]
}

I have about 30 buckets on my S3 and in this case I expect that the ListBucketsAsync function will return me only "example-bucket" and "example-bucket2"
instead it throws and error:

Reason: Access Denied (Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.). Amazon.S3.AmazonS3Exception: Access Denied  ---> Amazon.Runtime.Internal.HttpErrorResponseException: Exception of type 'Amazon.Runtime.Internal.HttpErrorResponseException' was thrown.    at Amazon.Runtime.HttpWebRequestMessage.GetResponseAsync(CancellationToken cancellationToken)    at Amazon.Runtime.Internal.HttpHandler1.InvokeAsync[T](IExecutionContext executionContext)at Amazon.Runtime.Internal.RedirectHandler.InvokeAsync[T](IExecutionContext executionContext)at Amazon.Runtime.Internal.Unmarshaller.InvokeAsync[T](IExecutionContext executionContext)at Amazon.S3.Internal.AmazonS3ResponseHandler.InvokeAsync[T](IExecutionContext executionContext)at Amazon.Runtime.Internal.ErrorHandler.InvokeAsync[T](IExecutionContext executionContext)--- End of inner exception stack trace ---

I tried to configure the policy in many ways with no success:

`"Resource": [`
`"arn:aws:s3:::example-bucket/",`
`"arn:aws:s3:::example-bucket2/"`
`]`

`"Resource": [`
`"arn:aws:s3:::example-bucket",`
`"arn:aws:s3:::example-bucket2"`
`]`

How can I only get the buckets that are configured in the IAM policy?


问:
how to save the command prompt output to an Microsoft 365 Excel or google spreadsheets (online)
hello everyone i used a .bat file get all devise information and start to data entry it manually in google spreadsheet

https://github.com/hegazytarek/Device-information

but now i want this .bat file to import this data to Microsoft 365 Excel sheet or google spreadsheet
every new run recoded in new Row in same sheet

but i don't want just a code i want to learn how to achieve this thing but really i don't know from where should i start or how could i achieve my target
any help please and thanks for your time

my .bat file now can extartct the data in .txt file in the same dir. like this

my target to save this data in Microsoft 365 Excel sheet or google spreadsheet with the same format


问:
Upload Image to Existing doc in Firebase/Firestore v9 with React
I am currently having trouble uploading an image/file to firestore. I have been stuck on this for hours now. I am using the latest version as well as the latest version of nextJS and reactJS. I am tried copying the docs but using both uploadString and uploadBytesResumable yield no success. I also tried various online tutorials. My rules are set in firestore such that anyone can read or write.

I can upload when there is no image selected in the filePickerRef/imgFile; however, when I include a file input along with my text input, only the text is uploaded. I am using a form with a button and an input to submit the text, when this is submitted, I check if there is a file uploaded (imgFile is a state that gets set when the file input tag is changed -- filePickerRef.current.files[0] should also have the file but neither work...), if there is, I attempt to upload the file to the document I just added the message and timestamp to (Note: this file is uploaded to a file input outside of the form and when the input changes, it calls setImgFile(event.target.files[0]). the input also has the prop ref='filePickerRef' which was generated by the useRef() hook).

The error I get is:

FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)

with the response:

```<code>{
  "error": {
    "code": 404,
    "message": "Not Found."
  }
}
</code>```

When I run the web tools debugger, I can see that both imgFile and filePickerRef.current.files[0] have the File object of the file I selected to be uploaded, but the upload still fails.

Here is my code below:

```<code>const uploadMessage = (event) => {
    event.preventDefault()

    // no text input
    if (!inputRef.current.value) return

    addDoc(collection(db, 'msgs'), {
        message: inputRef.current.value,
        timestamp: serverTimestamp()
    }).then(docRef => {
        if (imgFile) {
            //const file = filePickerRef.current.files[0]
            const file = imgFile

            // upload image
            const storafeRef = ref(storage, `msgs/${docRef.id}`)
            const uploadTask = uploadBytesResumable(storafeRef, file)

            // note: imageToPost is state set by a file reader using readAsDataURL() when the file input changes
            //uploadString(storafeRef, imageToPost, 'data_url').then(() => console.log('submitted image!'))

            uploadTask.on("state_changed",
            snapshot => {
                const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
                setProgresspercent(progress)
            },
            error => {
                alert(error)
            },
            () => {
                getDownloadURL(uploadTask.snapshot.ref).then(url => {
                    setDoc(doc(db, 'msgs', docRef.id), { url }, { merge: true })
                })
            })

            console.log('image uploaded.')

        } else {
            console.log('no image.')
        }

        console.log('Added doc: ', docRef.id)
    }).then(() => {
        inputRef.current.value = ''
        setImageToPost(null)
        setImgFile(null)
        filePickerRef.current.value = ''

        console.log('removed image.')
    }).catch(error => {
        console.error("Error adding document: ", error);
    })
}
</code>```

These are my firestore rules:

```<code>rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}
</code>```

Body:
I am currently having trouble uploading an image/file to firestore. I have been stuck on this for hours now. I am using the latest version as well as the latest version of nextJS and reactJS. I am tried copying the docs but using both uploadString and uploadBytesResumable yield no success. I also tried various online tutorials. My rules are set in firestore such that anyone can read or write.

I can upload when there is no image selected in the filePickerRef/imgFile; however, when I include a file input along with my text input, only the text is uploaded. I am using a form with a button and an input to submit the text, when this is submitted, I check if there is a file uploaded (imgFile is a state that gets set when the file input tag is changed -- filePickerRef.current.files[0] should also have the file but neither work...), if there is, I attempt to upload the file to the document I just added the message and timestamp to (Note: this file is uploaded to a file input outside of the form and when the input changes, it calls setImgFile(event.target.files[0]). the input also has the prop ref='filePickerRef' which was generated by the useRef() hook).

The error I get is:

FirebaseError: Firebase Storage: An unknown error occurred, please check the error payload for server response. (storage/unknown)

with the response:

{
  "error": {
    "code": 404,
    "message": "Not Found."
  }
}

When I run the web tools debugger, I can see that both imgFile and filePickerRef.current.files[0] have the File object of the file I selected to be uploaded, but the upload still fails.

Here is my code below:

const uploadMessage = (event) => {
    event.preventDefault()

    // no text input
    if (!inputRef.current.value) return

    addDoc(collection(db, 'msgs'), {
        message: inputRef.current.value,
        timestamp: serverTimestamp()
    }).then(docRef => {
        if (imgFile) {
            //const file = filePickerRef.current.files[0]
            const file = imgFile

            // upload image
            const storafeRef = ref(storage, `msgs/${docRef.id}`)
            const uploadTask = uploadBytesResumable(storafeRef, file)

            // note: imageToPost is state set by a file reader using readAsDataURL() when the file input changes
            //uploadString(storafeRef, imageToPost, 'data_url').then(() => console.log('submitted image!'))

            uploadTask.on("state_changed",
            snapshot => {
                const progress = Math.round((snapshot.bytesTransferred / snapshot.totalBytes) * 100)
                setProgresspercent(progress)
            },
            error => {
                alert(error)
            },
            () => {
                getDownloadURL(uploadTask.snapshot.ref).then(url => {
                    setDoc(doc(db, 'msgs', docRef.id), { url }, { merge: true })
                })
            })

            console.log('image uploaded.')

        } else {
            console.log('no image.')
        }

        console.log('Added doc: ', docRef.id)
    }).then(() => {
        inputRef.current.value = ''
        setImageToPost(null)
        setImgFile(null)
        filePickerRef.current.value = ''

        console.log('removed image.')
    }).catch(error => {
        console.error("Error adding document: ", error);
    })
}

These are my firestore rules:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}


问:
how to do you count manually CART algorithm and gini index for decision tree using excel
I've been learning about CART algorithm, and now i want to do counting manually CART algorithm  using excel. But i still dont know how to do it. can someone help me how to do manual counting for CART algorithm and Gini index using excel ? I appreciate every help.</p>


问:
update or delete on table "sessions" violates foreign key constraint "session_schedule_session_id_fkey"
I have to entities modeled Session and Speaker, with ManyToMany relationship, and I wanted to delete an instance of Session, but in the DB it is the foreign key of another table. Below is the entity model

```<code>@Entity(name = "sessions")
public class Session {
    // attributes do not respect camel case notations because they
    // need to match table notations in order to auto bind without annotations
    // otherwise that is done with @Column annotation
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long session_id;
    private String session_name;
    private String session_description;
    private String session_length;
    @OnDelete(action = OnDeleteAction.CASCADE)
    @ManyToMany()
    @JoinTable(
            name = "session_speakers",
            joinColumns = @JoinColumn(name = "session_id"),
            inverseJoinColumns = @JoinColumn(name = "speaker_id")
    )
    private List<Speaker> speakers;

    public Session() {
    }

</code>```

I tried to use OnDelete Cascade, but it still didn't work. (I did read that it is not advised to use on ManyToMany relationship)

```<code>    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)

    public void delete(@PathVariable Long id){
        sessionRepo.deleteById(id);
    }
</code>```

EDIT:

here is also the Speaker entity

```<code>@Entity(name = "speakers")
public class Speaker {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long speaker_id;

    private String first_name;
    private String last_name;
    private String title;
    private String company;
    private String speaker_bio;

    @Lob
    @Type(type = "org.hibernate.type.BinaryType")
    private Byte[] speaker_photo;

    public Byte[] getSpeaker_photo() {
        return speaker_photo;
    }

    public void setSpeaker_photo(Byte[] speaker_photo) {
        this.speaker_photo = speaker_photo;
    }

    @ManyToMany(mappedBy = "speakers")
    @JsonIgnore// added to resolve serialization issues
    private List<Session> sessions;
</code>```

Body:
I have to entities modeled Session and Speaker, with ManyToMany relationship, and I wanted to delete an instance of Session, but in the DB it is the foreign key of another table. Below is the entity model

@Entity(name = "sessions")
public class Session {
    // attributes do not respect camel case notations because they
    // need to match table notations in order to auto bind without annotations
    // otherwise that is done with @Column annotation
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long session_id;
    private String session_name;
    private String session_description;
    private String session_length;
    @OnDelete(action = OnDeleteAction.CASCADE)
    @ManyToMany()
    @JoinTable(
            name = "session_speakers",
            joinColumns = @JoinColumn(name = "session_id"),
            inverseJoinColumns = @JoinColumn(name = "speaker_id")
    )
    private List<Speaker> speakers;

    public Session() {
    }

I tried to use OnDelete Cascade, but it still didn't work. (I did read that it is not advised to use on ManyToMany relationship)

    @RequestMapping(value = "{id}", method = RequestMethod.DELETE)

    public void delete(@PathVariable Long id){
        sessionRepo.deleteById(id);
    }

EDIT:

here is also the Speaker entity

@Entity(name = "speakers")
public class Speaker {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long speaker_id;

    private String first_name;
    private String last_name;
    private String title;
    private String company;
    private String speaker_bio;

    @Lob
    @Type(type = "org.hibernate.type.BinaryType")
    private Byte[] speaker_photo;

    public Byte[] getSpeaker_photo() {
        return speaker_photo;
    }

    public void setSpeaker_photo(Byte[] speaker_photo) {
        this.speaker_photo = speaker_photo;
    }

    @ManyToMany(mappedBy = "speakers")
    @JsonIgnore// added to resolve serialization issues
    private List<Session> sessions;


问:
For predicting new observations from a multiple regression model, can I drop any predictors used in the new observation?
I have a prediction model with several categorical and numerical variables. I am needing to forecast the mpg of a car given a list of all the main effects and their values. These main effects are cylinders, horsepower, weight, model year, displacement, and acceleration. I started with a model of all main effects and two way interactions. With backward selection, my model has dropped displacement and model year main effects. The model also dropped most interaction terms so there are no interaction terms with either displacement or model year. My main reason for this analysis is to perform predictions of new observations for mpg and I am given a list of values for all main effects, but my final model doesn't have some of the main effects. Is it okay if I make predictions of new observations with a model that has dropped some of the main effects even though the new observations rely on values from those dropped main effects?

I've tried creating another model using forward selection starting with the additive model so all main effects are represented within the prediction model, but the RMSE was absurdly large.