问:
How to avoid unnecessary copies when initializing vectors with variadic templates
In my project, I'm facing the initializing vectors with variadic template. However, I found that some unnecessary or unexpected copies could happen in follow code (in function create_elements and create_dummies).

#include <iostream>
#include <vector>
#include <any>

struct Dummy {
  int x;
  Dummy() = default;
  Dummy(Dummy&&) = default;
  Dummy(const Dummy& d) {
    x = d.x;
    static int count = 0;
    printf("copy dummy %d, times: %d\n", x, ++count);
  }
  Dummy(int x) : x(x) {}
};

template<typename... Comps> std::vector<std::any> create_elements (Comps&&... value) {
  return {std::make_any<Comps>(std::forward<Comps>(value))...};
}

template<typename... Dummies> std::vector<Dummy> create_dummies (Dummies&&... value) {
  return {std::forward<Dummies>(value)...};
}

int main() {
  create_dummies(Dummy(1));
  create_elements(Dummy(2));
  std::vector<Dummy> w;
  w.emplace_back(std::move(Dummy(3)));
  return 0;
}
```
<p>In above example, after compiling and running will result in</p>
```copy dummy 1, times: 1
copy dummy 2, times: 2
```

, which means that create_elements and create_dummies call the copy constructor of Dummy.
What I expect is that these two methods will have the same behaviors as the emplace_back solution (no copy called). What should I do, or why can't I do that? thanks!

Body:
In my project, I'm facing the initializing vectors with variadic template. However, I found that some unnecessary or unexpected copies could happen in follow code (in function create_elements and create_dummies).

#include <iostream>
#include <vector>
#include <any>

struct Dummy {
  int x;
  Dummy() = default;
  Dummy(Dummy&&) = default;
  Dummy(const Dummy& d) {
    x = d.x;
    static int count = 0;
    printf("copy dummy %d, times: %d\n", x, ++count);
  }
  Dummy(int x) : x(x) {}
};

template<typename... Comps> std::vector<std::any> create_elements (Comps&&... value) {
  return {std::make_any<Comps>(std::forward<Comps>(value))...};
}

template<typename... Dummies> std::vector<Dummy> create_dummies (Dummies&&... value) {
  return {std::forward<Dummies>(value)...};
}

int main() {
  create_dummies(Dummy(1));
  create_elements(Dummy(2));
  std::vector<Dummy> w;
  w.emplace_back(std::move(Dummy(3)));
  return 0;
}

In above example, after compiling and running will result in

copy dummy 1, times: 1
copy dummy 2, times: 2

, which means that create_elements and create_dummies call the copy constructor of Dummy.
What I expect is that these two methods will have the same behaviors as the emplace_back solution (no copy called). What should I do, or why can't I do that? thanks!


来源: stackexchange

问:
Property in class method has different value than outside
I am currently working on a Vue3 project where we use classes.

Since axios does not return class instances, we need to transform them and sometimes we even need to transform some properties.

Now I am working on an ActivityLog where I have a function convertChildrenToClasses:

```<code>export class ActivityLog extends BaseModel {
    user?: any = undefined
    activity = ''
    activityResource = ''
    oldValues: Record<string, string> = {}
    newValues: Record<string, string> = {}
    createdAt = ''

    constructor() {
        super();
    }

    get createdAtStr() {
        if (this.createdAt) {
            return moment(this.createdAt).format(dateTimeFormatString);
        }

        return null;
    }

    convertChildrenToClasses = () => {
        console.log(this.user); // returns undefined, although previously filled
        if (this.user) {
            this.user = convertToClass<User>(new User(), {...this.user});
        }
    }
}
</code>```

As you can see, we also have a method that recursively transforms the classes and their children, which is called before the previous one:

```<code>export function convertToClass<T>(emptyObject: T, entity: any): T {
    const entityClass = Object.assign(emptyObject, entity);

    if (entityClass.convertChildrenToClasses) {
        if (entityClass instanceof ActivityLog) {
            console.log(entityClass.user); // Returns an object with values and is not manipulated anywhere else
        }

        entityClass.convertChildrenToClasses() // console.log inside the class method returns undefined
    }

    return entityClass as T;
}
</code>```

Now iam wondering, why the console.log() in convertToClass returns an object with values:

```<code>{@id: '/api/users/7', @type: 'User', id: 7, email: 'artur.smolen@explicatis.com', firstName: 'Artur', …}
</code>```

and the console.log() in convertChildrenToClasses returns undefined

This is the method, where all starts:

```<code>function pushToCollection(entities: T[]) {
    collection.value.push(...entities.map(entity => convertToClass(Object.create(initialValue.value), entity)))
}
</code>```

In the current case initialValue has new ActivityLog() as value and the entities are the server-reponse

ContentLicense: CC BY-SA 4.0

Body:
I am currently working on a Vue3 project where we use classes.

Since axios does not return class instances, we need to transform them and sometimes we even need to transform some properties.

Now I am working on an ActivityLog where I have a function convertChildrenToClasses:

export class ActivityLog extends BaseModel {
    user?: any = undefined
    activity = ''
    activityResource = ''
    oldValues: Record<string, string> = {}
    newValues: Record<string, string> = {}
    createdAt = ''

    constructor() {
        super();
    }

    get createdAtStr() {
        if (this.createdAt) {
            return moment(this.createdAt).format(dateTimeFormatString);
        }

        return null;
    }

    convertChildrenToClasses = () => {
        console.log(this.user); // returns undefined, although previously filled
        if (this.user) {
            this.user = convertToClass<User>(new User(), {...this.user});
        }
    }
}

As you can see, we also have a method that recursively transforms the classes and their children, which is called before the previous one:

export function convertToClass<T>(emptyObject: T, entity: any): T {
    const entityClass = Object.assign(emptyObject, entity);

    if (entityClass.convertChildrenToClasses) {
        if (entityClass instanceof ActivityLog) {
            console.log(entityClass.user); // Returns an object with values and is not manipulated anywhere else
        }

        entityClass.convertChildrenToClasses() // console.log inside the class method returns undefined
    }

    return entityClass as T;
}

Now iam wondering, why the console.log() in convertToClass returns an object with values:

{@id: '/api/users/7', @type: 'User', id: 7, email: 'artur.smolen@explicatis.com', firstName: 'Artur', …}

and the console.log() in convertChildrenToClasses returns undefined

This is the method, where all starts:

function pushToCollection(entities: T[]) {
    collection.value.push(...entities.map(entity => convertToClass(Object.create(initialValue.value), entity)))
}

In the current case initialValue has new ActivityLog() as value and the entities are the server-reponse


问:
Selecting output from multchoicebox
I'm using a multchoicebox from easygui.

Is it possible to have two different beavhiours when nothing is selected or when 'Cancel' is pressed?

For example, when 'Cancel' is pressed, exit the script and when nothing is select a pop warning to select something before proceding.

```<code>if len(xref_list) > 1:
    output = multchoicebox(text, title, xref_list, preselect=None)
else:
    output = xref_list

# sair se cancel ou nada for selecionado
if output is None:
    sys.exit()

</code>```

Title: Selecting output from multchoicebox

Body:
I'm using a multchoicebox from easygui.

Is it possible to have two different beavhiours when nothing is selected or when 'Cancel' is pressed?

For example, when 'Cancel' is pressed, exit the script and when nothing is select a pop warning to select something before proceding.

if len(xref_list) > 1:
    output = multchoicebox(text, title, xref_list, preselect=None)
else:
    output = xref_list

# sair se cancel ou nada for selecionado
if output is None:
    sys.exit()


问:
How can I open virtual keyboard
How can I open the virtual keyboard when I click spesific QlineEdit area ?

I am using below codes but I've error how can I do this correctly:

```<code>self.phoneUi.phoneNumber.focusInEvent = self.show_keyboard
def show_keyboard(self, event):
    input_method = QInputMethod.queryFocusObject()
    input_method.show()
</code>```

But I get this error:

```<code>, line 323, in show_keyboard
    input_method = QInputMethod.queryFocusObject()
TypeError: queryFocusObject(Qt.InputMethodQuery, Any): not enough arguments
</code>```

What is the correct argument I am using pyqt5

EDIT

When I try with below codes:

```<code>   def show_keyboard(self, event):
        self.phoneUi.phoneNumber.setFocus()
        input_method = QInputMethod.queryFocusObject(Qt.InputMethodQuery.ImHints, None)

        input_method.show()
</code>```

I get

```<code>input_method.show()
AttributeError: 'int' object has no attribute 'show'
</code>```

How can I solve please help

EDIT 2

```<code>   self.phoneUi.phoneNumber.focusInEvent  = self.show_keyboard
    def show_keyboard(self, event):
        print("hey")
        input_method = QApplication.inputMethod()
        input_method.show()
</code>```

I also try with above code I can see hey print but virtual key does not open

```<code>pip show pyqt5
Name: PyQt5
Version: 5.15.7
</code>```

Title: How can I open virtual keyboard

Body:
How can I open the virtual keyboard when I click spesific QlineEdit area ?

I am using below codes but I've error how can I do this correctly:

self.phoneUi.phoneNumber.focusInEvent = self.show_keyboard
def show_keyboard(self, event):
    input_method = QInputMethod.queryFocusObject()
    input_method.show()

But I get this error:

, line 323, in show_keyboard
    input_method = QInputMethod.queryFocusObject()
TypeError: queryFocusObject(Qt.InputMethodQuery, Any): not enough arguments

What is the correct argument I am using pyqt5

EDIT

When I try with below codes:

   def show_keyboard(self, event):
        self.phoneUi.phoneNumber.setFocus()
        input_method = QInputMethod.queryFocusObject(Qt.InputMethodQuery.ImHints, None)

        input_method.show()

I get

input_method.show()
AttributeError: 'int' object has no attribute 'show'

How can I solve please help

EDIT 2

   self.phoneUi.phoneNumber.focusInEvent  = self.show_keyboard
    def show_keyboard(self, event):
        print("hey")
        input_method = QApplication.inputMethod()
        input_method.show()

I also try with above code I can see hey print but virtual key does not open

pip show pyqt5
Name: PyQt5
Version: 5.15.7


问:
Micorsoft report builder - filter data graph by selecting serie from another graph
i'm a newbie .

I'm trying to understand if Microsoft report builder suits for my scope.

My aim is to have two "linked" graphs on a same report .

In other words: given graph 1 and graph 2 on the same report. i would like data displayed on graph 2 to be filtered by the selected serie on graph 1 (e.g. a sector of a pie , or a column etc..).

i'm not sure if this feature exists neither how its called.

If it does exists,  how it is called?  and could you give me any hints about how to implement it?

Thank you in advance for your kind reply. sorry for my bad english and eventual lack of specifics:)!

i'm not sure this feature it is possibile. In min 3:13 of the following video is explained the feature that i would like to obtain  :
(https://www.youtube.com/watch?v=1xdrxzSZhM4)


问:
Is the 'input' event always queued before knowing whether its handler will actually be called?
I have some code to be run:

immediately after the input event handler if it's called

when this handler would usually be called if it's not.

I noticed that queuing a message with setTimeout in the keydown handler works well.

In this demo, the logged sequence is the one we expect:

With a regular input : keydown | input | end

When an input is prevented in the keydown handler (try entering the letter 'b') : keydown | end

When hitting a key that doesn't trigger an input ('Escape') : keydown | end

So it  seems to me that the input event is queued before the keydown event is processed, when we don't really know yet whether there will actually be an input.  It's just what I need, but how can I be sure things are actually supposed to be implemented this way?


问:
Can't block special characters from Input
I have a component, AddEditTextModal, to enter data relevant to project creation in another modal, AddProjectsModal.

Problem: I need to user not to be able to enter special characters, but it's not working. I tried replacing the special characters with empty string onChange(), and also tried running preventDefault() when detecting those characters.

Here's my initial attempt: the text component,

```<code>import { FC } from "react"
import MaterialIcon from "../MaterialIcon"

interface AddEditTextModalProps {
  label: string
  text?: string
  ref?: string
  inputType?: string
  textValue?: string
  setText?: (text: string) => void
  editIconVisible?: boolean
}

const AddEditTextModal: FC<AddEditTextModalProps> = ({
  label,
  ref,
  inputType,
  textValue,
  setText,
  editIconVisible,
}) => {
  return (
    <div className="flex row-auto w-100 h-fit py-1.5 gap-2">
      <h1 className="w-1/5 font-semibold">{label}</h1>
      <input
        type={inputType ? "text" : inputType}
        defaultValue={textValue ? "" : textValue}
        ref={ref}
        onChange={(event) => {
          const result = event.target.value.replace(/[^a-z]/gi, "")
          setText?.(result)
        }}
        className="form-control block w-4/5 px-3 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded m-0 focus:text-gray-700 focus:bg-white focus:border-blue-300 focus:outline-none"
        aria-describedby="TextInput"
      />
      {editIconVisible && (
        <MaterialIcon className="cursor-pointer w-fit h-fit" icon={"edit"} />
      )}
    </div>
  )
}

export default AddEditTextModal

</code>```

and the parent modal that utilizes it.

```<code>import { randomString } from "../../utils/utils"
import projectService from "../../services/projectService"
import { FC, useState } from "react"
import AddEditTextModal from "./AddEditTextModal"

interface AddProjectsModalProps {
  setOpenModal: (v: boolean) => void
  refreshList?: () => void
}

const AddProjectsModal: FC<AddProjectsModalProps> = ({
  setOpenModal,
  refreshList,
}) => {
  const franchiseIdTemp = randomString(20)
  const image = ""
  const [projectName, setProjectName] = useState("")
  const [description, setDescription] = useState("")
  const [houseHoldCount, setHouseHoldCount] = useState(0)
  const createNewProject = () => {
    const newProject = {
       //project property values
    }
    projectService.updateCreateProject(newProject.docId, newProject)
    setOpenModal(false)
    refreshList?.()
  }

  return (
    <>
      <div className="form-group mb-6">
        <AddEditTextModal
          label={"Project Name"}
          inputType="text"
          setText={setProjectName}
        />
      </div>
      <div className="form-group mb-6">
        <AddEditTextModal
          label={"Project Description"}
          inputType="text"
          setText={setDescription}
        />
      </div>
      <div className="form-group mb-6">
        <input
          type="number"
          onChange={(event) => {
            setHouseHoldCount(parseInt(event.target.value))
          }}
          className="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded m-0 focus:text-gray-700 focus:bg-white focus:border-blue-300 focus:outline-none"
          aria-describedby="manageId"
          placeholder="Household Number"
        />
        <small id="help" className="block mt-1 text-xs text-gray-600">
          * Number of households included by the project
        </small>
      </div>
      <button
        onClick={createNewProject}
        className=" px-6 py-2.5 bg-gray-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-flowius-blue hover:shadow-lg focus:bg-blue-500 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-cyan-700 active:shadow-lg transition duration-150 ease-in-out"
      >
        Submit
      </button>
    </>
  )
}

export default AddProjectsModal

</code>```

Body:
I have a component, AddEditTextModal, to enter data relevant to project creation in another modal, AddProjectsModal.

Problem: I need to user not to be able to enter special characters, but it's not working. I tried replacing the special characters with empty string onChange(), and also tried running preventDefault() when detecting those characters.

Here's my initial attempt: the text component,

import { FC } from "react"
import MaterialIcon from "../MaterialIcon"

interface AddEditTextModalProps {
  label: string
  text?: string
  ref?: string
  inputType?: string
  textValue?: string
  setText?: (text: string) => void
  editIconVisible?: boolean
}

const AddEditTextModal: FC<AddEditTextModalProps> = ({
  label,
  ref,
  inputType,
  textValue,
  setText,
  editIconVisible,
}) => {
  return (

{label}

      <input
        type={inputType ? "text" : inputType}
        defaultValue={textValue ? "" : textValue}
        ref={ref}
        onChange={(event) => {
          const result = event.target.value.replace(/[^a-z]/gi, "")
          setText?.(result)
        }}
        className="form-control block w-4/5 px-3 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded m-0 focus:text-gray-700 focus:bg-white focus:border-blue-300 focus:outline-none"
        aria-describedby="TextInput"
      />
      {editIconVisible && (
        <MaterialIcon className="cursor-pointer w-fit h-fit" icon={"edit"} />
      )}

  )
}

export default AddEditTextModal

and the parent modal that utilizes it.

import { randomString } from "../../utils/utils"
import projectService from "../../services/projectService"
import { FC, useState } from "react"
import AddEditTextModal from "./AddEditTextModal"

interface AddProjectsModalProps {
  setOpenModal: (v: boolean) => void
  refreshList?: () => void
}

const AddProjectsModal: FC<AddProjectsModalProps> = ({
  setOpenModal,
  refreshList,
}) => {
  const franchiseIdTemp = randomString(20)
  const image = ""
  const [projectName, setProjectName] = useState("")
  const [description, setDescription] = useState("")
  const [houseHoldCount, setHouseHoldCount] = useState(0)
  const createNewProject = () => {
    const newProject = {
       //project property values
    }
    projectService.updateCreateProject(newProject.docId, newProject)
    setOpenModal(false)
    refreshList?.()
  }

  return (
    <>

        <AddEditTextModal
          label={"Project Name"}
          inputType="text"
          setText={setProjectName}
        />

        <AddEditTextModal
          label={"Project Description"}
          inputType="text"
          setText={setDescription}
        />

        <input
          type="number"
          onChange={(event) => {
            setHouseHoldCount(parseInt(event.target.value))
          }}
          className="form-control block w-full px-3 py-1.5 text-base font-normal text-gray-700 bg-white bg-clip-padding border border-solid border-gray-300 rounded m-0 focus:text-gray-700 focus:bg-white focus:border-blue-300 focus:outline-none"
          aria-describedby="manageId"
          placeholder="Household Number"
        />

          * Number of households included by the project

      <button
        onClick={createNewProject}
        className=" px-6 py-2.5 bg-gray-600 text-white font-medium text-xs leading-tight uppercase rounded shadow-md hover:bg-flowius-blue hover:shadow-lg focus:bg-blue-500 focus:shadow-lg focus:outline-none focus:ring-0 active:bg-cyan-700 active:shadow-lg transition duration-150 ease-in-out"
      >
        Submit
      </button>
    </>
  )
}

export default AddProjectsModal


问:
What is the Region Code for Zebra RFID reader MC33?
I am looking for a definition for the region code. I have two different models of Zebra RFID reader MC33 on one device (model: MC333U with Android 10) the region code 11 sets the region to Germany. On the other device (older MC333R with Android 8.1.0) this sets the region to Denmark.

Somehow it is very difficult for me to find good documentation on programming for Zebra in C#. Most of them are for Java or not well described.

What I have found is that you can set the region like this:

try
    {
        RegulatoryConfig regulatoryConfig =
        RfidReader.Config.RegulatoryConfig;
        RegionInfo regionInfo =
        RfidReader.ReaderCapabilities.SupportedRegions.GetRegionInfo(11);
        regulatoryConfig.Region = regionInfo.RegionCode;
        regulatoryConfig.SetIsHoppingOn(true);
        string[] supportedChannels = new[] { "865700", "866300", "866900", "867500" };
        regulatoryConfig.SetEnabledChannels(supportedChannels);
        RfidReader.Config.RegulatoryConfig = regulatoryConfig;
    }
        catch (Exception error)
    {
        ...
    }

```

And I read that the 11 should stand for Germany.

Body:
I am looking for a definition for the region code. I have two different models of Zebra RFID reader MC33 on one device (model: MC333U with Android 10) the region code 11 sets the region to Germany. On the other device (older MC333R with Android 8.1.0) this sets the region to Denmark.

Somehow it is very difficult for me to find good documentation on programming for Zebra in C#. Most of them are for Java or not well described.

What I have found is that you can set the region like this:

try
    {
        RegulatoryConfig regulatoryConfig =
        RfidReader.Config.RegulatoryConfig;
        RegionInfo regionInfo =
        RfidReader.ReaderCapabilities.SupportedRegions.GetRegionInfo(11);
        regulatoryConfig.Region = regionInfo.RegionCode;
        regulatoryConfig.SetIsHoppingOn(true);
        string[] supportedChannels = new[] { "865700", "866300", "866900", "867500" };
        regulatoryConfig.SetEnabledChannels(supportedChannels);
        RfidReader.Config.RegulatoryConfig = regulatoryConfig;
    }
        catch (Exception error)
    {
        ...
    }

And I read that the 11 should stand for Germany.


问:
msnbot create new guest customer instead to use as SearchEngine customer
I am using nopCommerce 4.1 version.
I have looked at the customer table and I have found lots of guest customer created with msnbot.  I have search that customer IP as below

```<code>Decimal: 3475901895
Hostname: msnbot-207-46-13-199.search.msn.com
ASN: 8075
ISP: Microsoft Corporation
Services: None detected
Assignment: Likely Static IP
Country: United States
State/Region: Washington
City: Quincy
</code>```

I have found below bot that continue coming

```<code>Hostname: msnbot-207-46-13-60.search.msn.com
Hostname: ec2-54-185-68-243.us-west-2.compute.amazonaws.com
</code>```

How to prevent this bot to create new guest customer?

Body:
I am using nopCommerce 4.1 version.
I have looked at the customer table and I have found lots of guest customer created with msnbot.  I have search that customer IP as below

Decimal: 3475901895
Hostname: msnbot-207-46-13-199.search.msn.com
ASN: 8075
ISP: Microsoft Corporation
Services: None detected
Assignment: Likely Static IP
Country: United States
State/Region: Washington
City: Quincy

I have found below bot that continue coming

Hostname: msnbot-207-46-13-60.search.msn.com
Hostname: ec2-54-185-68-243.us-west-2.compute.amazonaws.com

How to prevent this bot to create new guest customer?


问:
Should you normalizing a dataset per label, or across the range of entire dataset at once?
So I'm looking to train a CNN model in Keras. The labels (Y) in my dataset are of shape (1080, 1920, 2). The values themselves however are quite large. Ranging from floating point numbers up to 80,000.

To smooth out the training process I want to normalize each label (array) using the following code where y is the array in question:

```<code>y/np.linalg.norm(y)
</code>```

In order to denormalize my array I would simply do the opposite:

```<code>y * np.linalg.norm(y)
</code>```

Should I normalize each label individually, or should I normalize across the entire Y dataset at once? I ask because, when it comes to denormalizing my models output, I won't be sure which normalization rate to use (np.linalg.norm(y) output) if I normalize each label individually.

Am I thinking of this the right way?

I did read this post here: Denormalization of output from neural network

It appears to address denormalization per label. Which, I don't understand how that would denormalize a models output correctly, if each label has it's own range and the model was trained on all labels.

Body:
So I'm looking to train a CNN model in Keras. The labels (Y) in my dataset are of shape (1080, 1920, 2). The values themselves however are quite large. Ranging from floating point numbers up to 80,000.

To smooth out the training process I want to normalize each label (array) using the following code where y is the array in question:

y/np.linalg.norm(y)

In order to denormalize my array I would simply do the opposite:

y * np.linalg.norm(y)

Should I normalize each label individually, or should I normalize across the entire Y dataset at once? I ask because, when it comes to denormalizing my models output, I won't be sure which normalization rate to use (np.linalg.norm(y) output) if I normalize each label individually.

Am I thinking of this the right way?

I did read this post here: Denormalization of output from neural network

It appears to address denormalization per label. Which, I don't understand how that would denormalize a models output correctly, if each label has it's own range and the model was trained on all labels.


问:
Issue with Grafana not displaying with JSON API
I have downloaded a plugin JSON API by Marcus olsson and it all went well and the data sources was connected successfully. But the issue is to get the data from the API. When I tried to use the field as seen in the screen shot is not working :

The purpose in the dashboard to know the status for each key for example TEJD  is up and TECJ is down. But the issue is the fields in the JSON API plugin.  I have no success also in using telegraf metrics http

The sample of the JSON :

```<code>>     { "status": "UP",  "TEJD": {"status":"UP", "count":"0", "minDateTime":"", "description":"Workbasket Jdmin"},  "TECJ":
> {"status":"DOWN", "count":"0", "minDateTime":"",
> "description":"Workbasket CreateJppWait"},  "TEDE": {"status":"UP",
> "count":"0", "minDateTime":"", "description":"Workbasket default"},
> "TEEW": {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Workbasket eFormWriteFailure"},  "TEFB":
> {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Workbasket BackgroundProcessing"},  "TEIC":
> {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Workbasket IncompleteConnections"},  "TELB":
> {"status":"UP", "count":"18", "minDateTime":"20/12/2022 10:37",
> "description":"Workbasket LRBackgroundProcess"},   "JETE":
> {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Jssignment errors for Jssign-WorkBasket"},  "JEWL":
> {"status":"DOWN", "count":"0", "minDateTime":"",
> "description":"Jssignment errors for Jssign-Worklist"},   "FETE":
> {"status":"UP", "count":"0", "minDateTime":"", "description":"Flow
> errors for Jssign-WorkBasket"},  "FEWL": {"status":"UP", "count":"0",
> "minDateTime":"", "description":"Flow errors for Jssign-Worklist"},
> "BQBP": {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Broken queue System-Queue-BackgroundProcess"},  "BQDE":
> {"status":"UP", "count":"0", "minDateTime":"", "description":"Broken
> queue System-Queue-DefaultEntry"},   "CQCJ": {"status":"UP",
> "count":"0", "minDateTime":"", "description":"Custom query Create Jpp
> Requests"},   "JS02": {"status":"UP", "description":"Job Scheduler
> CaseDocumentDeletion (Jny one associated node:BackgroundProcessing)"},
> "JS21": {"status":"UP", "description":"Job Scheduler
> PurgeOldSIDExchangeRecords (Jll associated
> nodes:BackgroundProcessing)"},  "JS01": {"status":"UP",
> "description":"Job Scheduler UpdateReferenceData (Jny one associated
> node:BackgroundProcessing)"},   "package": { "name": "Pega Cluster",
> "elapsedTime": "819.0", "lastUpdated": "20/12/2022 10:52" } }
</code>```

Body:
I have downloaded a plugin JSON API by Marcus olsson and it all went well and the data sources was connected successfully. But the issue is to get the data from the API. When I tried to use the field as seen in the screen shot is not working :

The purpose in the dashboard to know the status for each key for example TEJD  is up and TECJ is down. But the issue is the fields in the JSON API plugin.  I have no success also in using telegraf metrics http

The sample of the JSON :

>     { "status": "UP",  "TEJD": {"status":"UP", "count":"0", "minDateTime":"", "description":"Workbasket Jdmin"},  "TECJ":
> {"status":"DOWN", "count":"0", "minDateTime":"",
> "description":"Workbasket CreateJppWait"},  "TEDE": {"status":"UP",
> "count":"0", "minDateTime":"", "description":"Workbasket default"},
> "TEEW": {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Workbasket eFormWriteFailure"},  "TEFB":
> {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Workbasket BackgroundProcessing"},  "TEIC":
> {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Workbasket IncompleteConnections"},  "TELB":
> {"status":"UP", "count":"18", "minDateTime":"20/12/2022 10:37",
> "description":"Workbasket LRBackgroundProcess"},   "JETE":
> {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Jssignment errors for Jssign-WorkBasket"},  "JEWL":
> {"status":"DOWN", "count":"0", "minDateTime":"",
> "description":"Jssignment errors for Jssign-Worklist"},   "FETE":
> {"status":"UP", "count":"0", "minDateTime":"", "description":"Flow
> errors for Jssign-WorkBasket"},  "FEWL": {"status":"UP", "count":"0",
> "minDateTime":"", "description":"Flow errors for Jssign-Worklist"},
> "BQBP": {"status":"UP", "count":"0", "minDateTime":"",
> "description":"Broken queue System-Queue-BackgroundProcess"},  "BQDE":
> {"status":"UP", "count":"0", "minDateTime":"", "description":"Broken
> queue System-Queue-DefaultEntry"},   "CQCJ": {"status":"UP",
> "count":"0", "minDateTime":"", "description":"Custom query Create Jpp
> Requests"},   "JS02": {"status":"UP", "description":"Job Scheduler
> CaseDocumentDeletion (Jny one associated node:BackgroundProcessing)"},
> "JS21": {"status":"UP", "description":"Job Scheduler
> PurgeOldSIDExchangeRecords (Jll associated
> nodes:BackgroundProcessing)"},  "JS01": {"status":"UP",
> "description":"Job Scheduler UpdateReferenceData (Jny one associated
> node:BackgroundProcessing)"},   "package": { "name": "Pega Cluster",
> "elapsedTime": "819.0", "lastUpdated": "20/12/2022 10:52" } }


问:
Android Studio Dolphin - can't get built-in camera image in emulator
Simple question here: I have Android Studio Dolphin | 2021.3.1 Patch 1 running on Lenovo ThinkPad L14 Gen 2. I'm trying to test a simple add that reads barcodes via camera. I set up the emulated device to use 'Webcam0' as Front camera, I make sure that the camera is on and that the app has camera permission on the emulated device, yet my surfaceView keeps showing a blank black square. The onCreate code is below, is there anything wrong with it?</p>
```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
        surfaceView = findViewById(R.id.surface_view);
        barcodeText = findViewById(R.id.barcode_text);
        initialiseDetectorsAndSources();
    }

    private void initialiseDetectorsAndSources() {

        Toast.makeText(getApplicationContext(), "Barcode scanner started", Toast.LENGTH_SHORT).show();

        barcodeDetector = new BarcodeDetector.Builder(this)
                .setBarcodeFormats(Barcode.ALL_FORMATS)
                .build();

        cameraSource = new CameraSource.Builder(this, barcodeDetector)
                .setRequestedPreviewSize(1920, 1080)
                .setAutoFocusEnabled(true) //you should add this feature
                .build();

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        cameraSource.start(surfaceView.getHolder());
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this, new
                                String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
</code>```

Body:
Simple question here: I have Android Studio Dolphin | 2021.3.1 Patch 1 running on Lenovo ThinkPad L14 Gen 2. I'm trying to test a simple add that reads barcodes via camera. I set up the emulated device to use 'Webcam0' as Front camera, I make sure that the camera is on and that the app has camera permission on the emulated device, yet my surfaceView keeps showing a blank black square. The onCreate code is below, is there anything wrong with it?

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toneGen1 = new ToneGenerator(AudioManager.STREAM_MUSIC, 100);
        surfaceView = findViewById(R.id.surface_view);
        barcodeText = findViewById(R.id.barcode_text);
        initialiseDetectorsAndSources();
    }

    private void initialiseDetectorsAndSources() {

        Toast.makeText(getApplicationContext(), "Barcode scanner started", Toast.LENGTH_SHORT).show();

        barcodeDetector = new BarcodeDetector.Builder(this)
                .setBarcodeFormats(Barcode.ALL_FORMATS)
                .build();

        cameraSource = new CameraSource.Builder(this, barcodeDetector)
                .setRequestedPreviewSize(1920, 1080)
                .setAutoFocusEnabled(true) //you should add this feature
                .build();

        surfaceView.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder holder) {
                try {
                    if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
                        cameraSource.start(surfaceView.getHolder());
                    } else {
                        ActivityCompat.requestPermissions(MainActivity.this, new
                                String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }


问:
Border at cronjob watermark cronjob
how can i gat a watermark frame around my "blablabla text inside the photo". this cronjob pick up the last dated photo from the server and watermark it. but i want a frame around the text. can´t find a way how. Tried various but could not get any frame around the text.</p>
```<code>

// Fester Dateiname des Bildes
$image_name = 'test.jpg';

// Wasserzeichentext
$watermarktext = 'blablabla text inside the photo';

// Wasserzeichen Schriftart
$watermarkfont = 'Helvetica.ttf';

// Wasserzeichen Schriftgröße
$watermarkfontsize = '35';

// Ordnerpfad ermitteln
$pattern = __DIR__ . '/*';

// Dateien in Array einlesen
$images = array();
search_images($pattern);

// sortieren, jüngstes Datum zuerst
rsort($images);

// jüngstes Bild kopieren falls vorhanden, sonst abbruch
if ( !isset($images[0]) ) {
       echo 'Noch kein Bild vorhanden.';
       exit;
}else{
    $watermarkimage = imagecreatefromjpeg($images[0]);
    list($width, $height) = getimagesize($images[0]);
    $white = imagecolorallocate($watermarkimage, 51, 51, 51);
    $border = imagecolorallocate($watermarkimage, 255, 255, 255);
    $x = $width - ($watermarkfontsize * (strlen($watermarktext) - 4));
    $y = $height - $watermarkfontsize;
    imagettftext($watermarkimage, $watermarkfontsize, 0, 402, 1010, $border, realpath($watermarkfont), $watermarktext);
    imagettftext($watermarkimage, $watermarkfontsize, 0, 400, 1012, $white, realpath($watermarkfont), $watermarktext);
    imagejpeg($watermarkimage, $image_name);
    imagedestroy($watermarkimage);
}

$dirs = array();
$last_dir = '';
delete_images($pattern);

foreach (array_reverse($dirs) as $dir => $total_images) {
    rmdir($dir);
    echo 'in Verzeichnis ' . $dir . ', ' . $total_images . ' Dateien gelöscht' . '<br>';
}

</code>```

Title: Border at cronjob watermark cronjob

Body:
how can i gat a watermark frame around my "blablabla text inside the photo". this cronjob pick up the last dated photo from the server and watermark it. but i want a frame around the text. can´t find a way how. Tried various but could not get any frame around the text.

// Fester Dateiname des Bildes
$image_name = 'test.jpg';

// Wasserzeichentext
$watermarktext = 'blablabla text inside the photo';

// Wasserzeichen Schriftart
$watermarkfont = 'Helvetica.ttf';

// Wasserzeichen Schriftgröße
$watermarkfontsize = '35';

// Ordnerpfad ermitteln
$pattern = __DIR__ . '/*';

// Dateien in Array einlesen
$images = array();
search_images($pattern);

// sortieren, jüngstes Datum zuerst
rsort($images);

// jüngstes Bild kopieren falls vorhanden, sonst abbruch
if ( !isset($images[0]) ) {
       echo 'Noch kein Bild vorhanden.';
       exit;
}else{
    $watermarkimage = imagecreatefromjpeg($images[0]);
    list($width, $height) = getimagesize($images[0]);
    $white = imagecolorallocate($watermarkimage, 51, 51, 51);
    $border = imagecolorallocate($watermarkimage, 255, 255, 255);
    $x = $width - ($watermarkfontsize * (strlen($watermarktext) - 4));
    $y = $height - $watermarkfontsize;
    imagettftext($watermarkimage, $watermarkfontsize, 0, 402, 1010, $border, realpath($watermarkfont), $watermarktext);
    imagettftext($watermarkimage, $watermarkfontsize, 0, 400, 1012, $white, realpath($watermarkfont), $watermarktext);
    imagejpeg($watermarkimage, $image_name);
    imagedestroy($watermarkimage);
}

$dirs = array();
$last_dir = '';
delete_images($pattern);

foreach (array_reverse($dirs) as $dir => $total_images) {
    rmdir($dir);
    echo 'in Verzeichnis ' . $dir . ', ' . $total_images . ' Dateien gelöscht' . '
';
}


问:
I want to save object instead of array in reactjs with laravel api
When I save a multi-select, I experted the transLanguage to be an true form object, or anything else like
["ak", "an", "lu", "am", "as"]
(Save as Ditto mark form)

But I can just save the transLanguage as an array like: ['ak', 'an', 'lu', 'am', 'as']
(As Apostrophe form)

So what should I change? This is my Reactjs code:

```<code>import '../../css/style.css';
import { useEffect } from "react";
import { useState, useSelector } from "react";
import { ajaxCallGetUrlDemo, ajaxCallPost } from "../libs/base";
import Select from 'react-select'
import { Const_Libs } from "../libs/Const_Libs";
import languagesList from "./languageList/country";
import { get } from 'jquery';

const ModalAddNgonNgu = (props) => {
const { handleGetLanguage } = props;
const [langName, setLangName] = useState("");
const [mainLang, setMainLang] = useState("");
const [titleLang, setTitleLang] = useState("");
const [describeLang, setDescribeLang] = useState("");
const [authorLang, setAuthorLang] = useState("");
const [rateLang, setRateLang] = useState("");
const [reviewsLang, setReviewsLang] = useState("");
const [translateList, setTranslateList] = useState();

const mainLangOptions = [
    { value: 'vi', label: 'Vietnamese' },
    { value: 'en', label: 'English' },
    { value: 'zh', label: 'Chinese' },
    { value: 'ja', label: 'Japanese' },
    { value: 'de', label: 'German' },
];
const handleMainLang=(e)=>{
    setMainLang(e.value);
}

const handleTransList=(e)=>{
    setTranslateList(Array.isArray(e)?e.map(x=>x.value):[]);
}

const handleSubmit = () => {
    let arr = [{
        nameLanguage: langName,
        mainLanguage: mainLang,
        titleLanguage: titleLang,
        descriptionLanguage: describeLang,
        authorLanguage: authorLang,
        rateLanguage: rateLang,
        reviewsLanguage: reviewsLang,
        transLanguage: translateList
    }]
    console.log(arr);
    resetData();
    props.saveLang(arr);
}

const resetData = () => {
    setLangName("");
    setMainLang("");
    setTitleLang("");
    setDescribeLang("");
    setAuthorLang("");
    setRateLang("");
    setReviewsLang("");
    setTranslateList();
}

return (
    <>
        <button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModalAddNgonNgu" style={{ fontSize: '14px' }}>
            Thêm
        </button>
        <div>
            <div className="modal fade" id="myModalAddNgonNgu">
                <div className="modal-dialog modal-dialog-centered" style={{ minWidth: '700px' }}>
                    <div className="modal-content">
                        <div className="modal-header">
                            <h4 className="modal-title">Thêm ngôn ngữ</h4>
                            <button type="button" className="btn-close" data-bs-dismiss="modal" />
                        </div>
                        <div className="modal-body">
                            <form>
                                <div className="col">
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tên ngôn ngữ</label>
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập tên ngôn ngữ...."
                                            // value={langName}
                                            onChange={(e) => setLangName(e.target.value)}
                                        />
                                    </div>
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tiêu đề</label>
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập tiêu đề...."
                                            // value={titleLang}
                                            onChange={(e) => setTitleLang(e.target.value)}
                                        />
                                    </div>
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Mô tả</label>
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập mô tả...."
                                            // value={describeLang}
                                            onChange={(e) => setDescribeLang(e.target.value)}
                                        />
                                    </div>
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Tác giả</label>
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập tác giả (VD: Author)"
                                            // value={authorLang}
                                            onChange={(e) => setAuthorLang(e.target.value)}
                                        />
                                    </div>
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Đánh giá</label>
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập đánh giá (VD: Rate)"
                                            // value={rateLang}
                                            onChange={(e) => setRateLang(e.target.value)}
                                        />
                                    </div>
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Lượt đánh giá</label>
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập lượt đánh giá (VD: reviews)"
                                            // value={reviewsLang}
                                            onChange={(e) => setReviewsLang(e.target.value)}
                                        />
                                    </div>
                                </div>
                                <div className="col">
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Ngôn ngữ chính</label>
                                        {/* <select placeholder='Select' className={`col-12 o-languages`} onChange={(e)=>handleMainLang(e)}>
                                            {
                                                mainLangOptions.map((ml) => (
                                                    <option value={ml.value}>{ml.label}</option>
                                                )
                                                )
                                            }
                                        </select> */}
                                         <Select
                                            onChange={handleMainLang}
                                            options={mainLangOptions}
                                        />
                                    </div>
                                    <div className="row-2">
                                        <label htmlFor="name-campaign" className="form-label fs-6 fw-bolder">Những ngôn ngữ dịch</label>
                                        {/* <select multiple className={`col-12 o-languages`} onChange={(e) =>handleTransList(e)}>
                                            {
                                                languagesList.map((lgl) => (
                                                    <option value={lgl.value}>{lgl.label}</option>
                                                )
                                                )
                                            }
                                        </select> */}
                                        <Select
                                            onChange={handleTransList}
                                            isMulti
                                            isSearchable={true}
                                            options={languagesList}
                                        />
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div className="modal-footer">
                            <button type="button" className="btn btn-success" data-bs-dismiss="modal" onClick={handleSubmit}>Submit</button>
                            <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </>
);
}

export default ModalAddNgonNgu;
</code>```

Body:
When I save a multi-select, I experted the transLanguage to be an true form object, or anything else like
["ak", "an", "lu", "am", "as"]
(Save as Ditto mark form)

But I can just save the transLanguage as an array like: ['ak', 'an', 'lu', 'am', 'as']
(As Apostrophe form)

So what should I change? This is my Reactjs code:

import '../../css/style.css';
import { useEffect } from "react";
import { useState, useSelector } from "react";
import { ajaxCallGetUrlDemo, ajaxCallPost } from "../libs/base";
import Select from 'react-select'
import { Const_Libs } from "../libs/Const_Libs";
import languagesList from "./languageList/country";
import { get } from 'jquery';

const ModalAddNgonNgu = (props) => {
const { handleGetLanguage } = props;
const [langName, setLangName] = useState("");
const [mainLang, setMainLang] = useState("");
const [titleLang, setTitleLang] = useState("");
const [describeLang, setDescribeLang] = useState("");
const [authorLang, setAuthorLang] = useState("");
const [rateLang, setRateLang] = useState("");
const [reviewsLang, setReviewsLang] = useState("");
const [translateList, setTranslateList] = useState();

const mainLangOptions = [
    { value: 'vi', label: 'Vietnamese' },
    { value: 'en', label: 'English' },
    { value: 'zh', label: 'Chinese' },
    { value: 'ja', label: 'Japanese' },
    { value: 'de', label: 'German' },
];
const handleMainLang=(e)=>{
    setMainLang(e.value);
}

const handleTransList=(e)=>{
    setTranslateList(Array.isArray(e)?e.map(x=>x.value):[]);
}

const handleSubmit = () => {
    let arr = [{
        nameLanguage: langName,
        mainLanguage: mainLang,
        titleLanguage: titleLang,
        descriptionLanguage: describeLang,
        authorLanguage: authorLang,
        rateLanguage: rateLang,
        reviewsLanguage: reviewsLang,
        transLanguage: translateList
    }]
    console.log(arr);
    resetData();
    props.saveLang(arr);
}

const resetData = () => {
    setLangName("");
    setMainLang("");
    setTitleLang("");
    setDescribeLang("");
    setAuthorLang("");
    setRateLang("");
    setReviewsLang("");
    setTranslateList();
}

return (
    <>
        <button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#myModalAddNgonNgu" style={{ fontSize: '14px' }}>
            Thêm
        </button>

Thêm ngôn ngữ

                            <button type="button" className="btn-close" data-bs-dismiss="modal" />

                            <form>

                                        Tên ngôn ngữ
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập tên ngôn ngữ...."
                                            // value={langName}
                                            onChange={(e) => setLangName(e.target.value)}
                                        />

                                        Tiêu đề
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập tiêu đề...."
                                            // value={titleLang}
                                            onChange={(e) => setTitleLang(e.target.value)}
                                        />

                                        Mô tả
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập mô tả...."
                                            // value={describeLang}
                                            onChange={(e) => setDescribeLang(e.target.value)}
                                        />

                                        Tác giả
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập tác giả (VD: Author)"
                                            // value={authorLang}
                                            onChange={(e) => setAuthorLang(e.target.value)}
                                        />

                                        Đánh giá
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập đánh giá (VD: Rate)"
                                            // value={rateLang}
                                            onChange={(e) => setRateLang(e.target.value)}
                                        />

                                        Lượt đánh giá
                                        <input type="text"
                                            className="form-control" id="name-campaign"
                                            placeholder="Nhập lượt đánh giá (VD: reviews)"
                                            // value={reviewsLang}
                                            onChange={(e) => setReviewsLang(e.target.value)}
                                        />

                                        Ngôn ngữ chính
                                        {/* <select placeholder='Select' className={`col-12 o-languages`} onChange={(e)=>handleMainLang(e)}>
                                            {
                                                mainLangOptions.map((ml) => (
                                                    <option value={ml.value}>{ml.label}</option>
                                                )
                                                )
                                            }
                                        </select> */}
                                         <Select
                                            onChange={handleMainLang}
                                            options={mainLangOptions}
                                        />

                                        Những ngôn ngữ dịch
                                        {/* <select multiple className={`col-12 o-languages`} onChange={(e) =>handleTransList(e)}>
                                            {
                                                languagesList.map((lgl) => (
                                                    <option value={lgl.value}>{lgl.label}</option>
                                                )
                                                )
                                            }
                                        </select> */}
                                        <Select
                                            onChange={handleTransList}
                                            isMulti
                                            isSearchable={true}
                                            options={languagesList}
                                        />

                            </form>

                            <button type="button" className="btn btn-success" data-bs-dismiss="modal" onClick={handleSubmit}>Submit</button>
                            <button type="button" className="btn btn-danger" data-bs-dismiss="modal">Close</button>

    </>
);
}

export default ModalAddNgonNgu;


问:
Datadog - Alert if a value reached a threshold for x amount of consecutive days
I've found this article from DD: https://docs.datadoghq.com/monitors/guide/alert-on-no-change-in-value/ but it seems to be the more simple case of no diff over a period of time.

But, how is it possible to add a condition?
More specifically:
Trigger an alert if a value exceeds x each day for 3 consecutive days.

I imagine this to be a combination? E.g.

check if value exceeded x over a period of a day
AND

no diff in the past 3 days


问:
PHP Amazon S3 - Error 'The request signature we calculated does not match the signature' error?
I'm trying to get all buckets from a S3 host but I'm having problems with the AWS Signature

I followed every step on https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html.

My code is inspired from https://github.com/avi-wish/aws4-signature-php/blob/master/aws_secure_request.php

Do I miss something? what am I doing wrong. I made a working version of it in Postman where I can GET & CREATE buckets. Thanks in advance for the reply.

```<code>"Code": "SignatureDoesNotMatch",
"Message": "The request signature we calculated does not match the signature you provided. Check your Secret Access Key and signing method. For more information, see REST Authentication and SOAP Authentication for details.",
</code>```
```<code> public function signature($secretAccessKey, $region, $service, $date, $timeStamp, $httpRequestMethod, $host, $uri, $payload): array
    {
        $debugCanonicalRequest = [];
        $debugStringToSign = [];

        $canonicalRequest = [];
        $canonicalHeaders = [];
        $stringToSign = [];

        $phpAlgorithm = 'sha256';
        $aws4_request = 'aws4_request';
        $algorithm = 'AWS4-HMAC-SHA256';
        $canonicalQueryString = '';
        $signedHeaders = 'content-type;host;x-amz-date';

        $canonicalHeaders[] = 'content-type:application/x-www-form-urlencoded';
        $canonicalHeaders[] = 'host:' . $host;
        $canonicalHeaders[] = 'x-amz-date:' . $timeStamp;
        $canonicalHeadersStr = implode("\n", $canonicalHeaders);

        $canonicalRequest[] = $debugCanonicalRequest["HTTP verb"] = $httpRequestMethod;
        $canonicalRequest[] = $debugCanonicalRequest["canonical URI"] = $uri;
        $canonicalRequest[] = $debugCanonicalRequest["canonical query string"] = $canonicalQueryString;
        $canonicalRequest[] = $debugCanonicalRequest["canonical headers"] = $canonicalHeadersStr . "\n";
        $canonicalRequest[] = $debugCanonicalRequest["Signed headers"] = $signedHeaders;
        $canonicalRequest[] = hash($phpAlgorithm, $payload);
        $debugCanonicalRequest["hashed payload"] = hash($phpAlgorithm, $payload);

        $requestCanonicalRequest = implode("\n", $canonicalRequest);
        $debugCanonicalRequest["full canonical request"] = implode("\n", $canonicalRequest);

        $stringToSign[] = $debugStringToSign["algorithm"] = $algorithm;
        $stringToSign[] = $debugStringToSign["timestamp"] = $timeStamp;
        $stringToSign[] = $debugStringToSign["scope"] = implode('/', [$date, $region, $service, $aws4_request]);
        $stringToSign[] = hash($phpAlgorithm, utf8_encode($requestCanonicalRequest));

        $stringToSignStr = $debugStringToSign["full string to sign"] = implode("\n", $stringToSign);

        $dateKey = hash_hmac($phpAlgorithm, $date, 'AWS4' . $secretAccessKey, true);
        $dateRegionKey = hash_hmac($phpAlgorithm, $region, $dateKey, true);
        $dateRegionServiceKey = hash_hmac($phpAlgorithm, $service, $dateRegionKey, true);
        $signingKey = hash_hmac($phpAlgorithm, $aws4_request, $dateRegionServiceKey, true);
        return ["signature" => hash_hmac($phpAlgorithm, $stringToSignStr, $signingKey), "debug" => ["CanonicalRequest" => $debugCanonicalRequest, "StringToSign" => $debugStringToSign]];
    }

    public function s3Request(): bool|string
    {
        $accessKey = [[accessKey]];
        $secretKey = [[secretKey]];
        $region = "us-east-1";
        $service = "s3";
        $httpRequestMethod = "GET";
        $uri = '/';
        $host = [[host]];
        $payload = "";

        $currentDateTime = new DateTime('UTC');
        $date = $currentDateTime->format('Ymd');
        $timeStamp = $currentDateTime->format('Ymd\THis\Z');
        $signature = $this->signature($secretKey, $region, $service, $date, $timeStamp, $httpRequestMethod, $host, $uri, $payload);
        $content = hash("sha256", $payload);

        $headers = [
            'X-Amz-Content-Sha256: ' . $content,
            'X-Amz-Date: ' . $timeStamp,
            'Authorization: AWS4-HMAC-SHA256 Credential=' . $accessKey . '/' . $date . '/' . $region . '/' . $service . '/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=' . $signature["signature"]
        ];

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://192.168.1.18:9020/",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $httpRequestMethod,
            CURLOPT_HTTPHEADER => $headers,
        ));

        $response = curl_exec($curl);
        curl_close($curl);

        return json_encode([$signature["debug"], "headers" => $headers, "response" => $this->utility->responseConverter($response, "xmlBody")]);
    }
</code>```

Body:
I'm trying to get all buckets from a S3 host but I'm having problems with the AWS Signature

I followed every step on https://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-authenticating-requests.html.

My code is inspired from https://github.com/avi-wish/aws4-signature-php/blob/master/aws_secure_request.php

Do I miss something? what am I doing wrong. I made a working version of it in Postman where I can GET & CREATE buckets. Thanks in advance for the reply.

"Code": "SignatureDoesNotMatch",
"Message": "The request signature we calculated does not match the signature you provided. Check your Secret Access Key and signing method. For more information, see REST Authentication and SOAP Authentication for details.",

 public function signature($secretAccessKey, $region, $service, $date, $timeStamp, $httpRequestMethod, $host, $uri, $payload): array
    {
        $debugCanonicalRequest = [];
        $debugStringToSign = [];

        $canonicalRequest = [];
        $canonicalHeaders = [];
        $stringToSign = [];

        $phpAlgorithm = 'sha256';
        $aws4_request = 'aws4_request';
        $algorithm = 'AWS4-HMAC-SHA256';
        $canonicalQueryString = '';
        $signedHeaders = 'content-type;host;x-amz-date';

        $canonicalHeaders[] = 'content-type:application/x-www-form-urlencoded';
        $canonicalHeaders[] = 'host:' . $host;
        $canonicalHeaders[] = 'x-amz-date:' . $timeStamp;
        $canonicalHeadersStr = implode("\n", $canonicalHeaders);

        $canonicalRequest[] = $debugCanonicalRequest["HTTP verb"] = $httpRequestMethod;
        $canonicalRequest[] = $debugCanonicalRequest["canonical URI"] = $uri;
        $canonicalRequest[] = $debugCanonicalRequest["canonical query string"] = $canonicalQueryString;
        $canonicalRequest[] = $debugCanonicalRequest["canonical headers"] = $canonicalHeadersStr . "\n";
        $canonicalRequest[] = $debugCanonicalRequest["Signed headers"] = $signedHeaders;
        $canonicalRequest[] = hash($phpAlgorithm, $payload);
        $debugCanonicalRequest["hashed payload"] = hash($phpAlgorithm, $payload);

        $requestCanonicalRequest = implode("\n", $canonicalRequest);
        $debugCanonicalRequest["full canonical request"] = implode("\n", $canonicalRequest);

        $stringToSign[] = $debugStringToSign["algorithm"] = $algorithm;
        $stringToSign[] = $debugStringToSign["timestamp"] = $timeStamp;
        $stringToSign[] = $debugStringToSign["scope"] = implode('/', [$date, $region, $service, $aws4_request]);
        $stringToSign[] = hash($phpAlgorithm, utf8_encode($requestCanonicalRequest));

        $stringToSignStr = $debugStringToSign["full string to sign"] = implode("\n", $stringToSign);

        $dateKey = hash_hmac($phpAlgorithm, $date, 'AWS4' . $secretAccessKey, true);
        $dateRegionKey = hash_hmac($phpAlgorithm, $region, $dateKey, true);
        $dateRegionServiceKey = hash_hmac($phpAlgorithm, $service, $dateRegionKey, true);
        $signingKey = hash_hmac($phpAlgorithm, $aws4_request, $dateRegionServiceKey, true);
        return ["signature" => hash_hmac($phpAlgorithm, $stringToSignStr, $signingKey), "debug" => ["CanonicalRequest" => $debugCanonicalRequest, "StringToSign" => $debugStringToSign]];
    }

    public function s3Request(): bool|string
    {
        $accessKey = [[accessKey]];
        $secretKey = [[secretKey]];
        $region = "us-east-1";
        $service = "s3";
        $httpRequestMethod = "GET";
        $uri = '/';
        $host = [[host]];
        $payload = "";

        $currentDateTime = new DateTime('UTC');
        $date = $currentDateTime->format('Ymd');
        $timeStamp = $currentDateTime->format('Ymd\THis\Z');
        $signature = $this->signature($secretKey, $region, $service, $date, $timeStamp, $httpRequestMethod, $host, $uri, $payload);
        $content = hash("sha256", $payload);

        $headers = [
            'X-Amz-Content-Sha256: ' . $content,
            'X-Amz-Date: ' . $timeStamp,
            'Authorization: AWS4-HMAC-SHA256 Credential=' . $accessKey . '/' . $date . '/' . $region . '/' . $service . '/aws4_request, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=' . $signature["signature"]
        ];

        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "http://192.168.1.18:9020/",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => $httpRequestMethod,
            CURLOPT_HTTPHEADER => $headers,
        ));

        $response = curl_exec($curl);
        curl_close($curl);

        return json_encode([$signature["debug"], "headers" => $headers, "response" => $this->utility->responseConverter($response, "xmlBody")]);
    }


问:
How do I create a file in a already created directory?
I managed to create a directory with:

```<code>FileWriter writer = new FileWriter(Arrays.toString(getApplicationContext().getExternalFilesDirs("test")));
</code>```

I want to write data in that directory with this method:

```<code>public void writeToFile (String fileName, String content){

    File path = getApplicationContext().getFilesDir();
    //File path = new File(Arrays.toString(getApplicationContext().getExternalFilesDirs("test")));
    try{
        FileOutputStream writer1 = new FileOutputStream(new File(path, fileName));
        writer1.write(content.getBytes());
        writer1.close();
        Toast.makeText(getApplicationContext(), "Wrote to file " + fileName, Toast.LENGTH_SHORT).show();
    } catch (Exception e){
        e.printStackTrace();
    }

}
</code>```

In the main-method I declared that I want the file "file.txt" created in that very directory

```<code>String content = titleEditText.getText().toString();
writeToFile("file.txt", content);
</code>```

I expected to get a file named "file.txt" but I just got an Exception:

java.io.FileNotFoundException: [/storage/emulated/0/Android/data/com.example.testtest123/files/test, /storage/14F4-2011/Android/data/com.example.testtest123/files/test]: open failed: ENOENT (No such file or directory)
and
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
```

Body:
I managed to create a directory with:

FileWriter writer = new FileWriter(Arrays.toString(getApplicationContext().getExternalFilesDirs("test")));

I want to write data in that directory with this method:

public void writeToFile (String fileName, String content){

    File path = getApplicationContext().getFilesDir();
    //File path = new File(Arrays.toString(getApplicationContext().getExternalFilesDirs("test")));
    try{
        FileOutputStream writer1 = new FileOutputStream(new File(path, fileName));
        writer1.write(content.getBytes());
        writer1.close();
        Toast.makeText(getApplicationContext(), "Wrote to file " + fileName, Toast.LENGTH_SHORT).show();
    } catch (Exception e){
        e.printStackTrace();
    }

}

In the main-method I declared that I want the file "file.txt" created in that very directory

String content = titleEditText.getText().toString();
writeToFile("file.txt", content);

I expected to get a file named "file.txt" but I just got an Exception:

java.io.FileNotFoundException: [/storage/emulated/0/Android/data/com.example.testtest123/files/test, /storage/14F4-2011/Android/data/com.example.testtest123/files/test]: open failed: ENOENT (No such file or directory)
and
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)


问:
Tensorflow weightNorm with variable length input
```<code>in_dim, out_dim = 10, 7
bias = False
activation = None

layer = tfp.layers.weight_norm.WeightNorm(
               tf.keras.layers.Dense(out_dim, input_shape=(None, in_dim, ),
                                     use_bias = bias, activation = activation),
               input_shape = (None, None, in_dim))
</code>```

I would like to give a input with variable length in the second dimension.
Suppose I run the below code first.

```<code>input = tf.random.normal(shape = (2, 3, 10))
output = layer(input)
output.shape
# [2, 3, 7]
</code>```

After running the above code, I give another input to network

```<code>input2 = tf.random.normal(shape = (2, 4, 10))
output2 = layer(input2)
</code>```

However, it causes error

Input 0 of layer "weight_norm_3" is incompatible with the layer:
expected shape=(None, 3, 10), found shape=(2, 4, 10)

I would like to give a variable length of second dimension. How can I do it?

Body:
in_dim, out_dim = 10, 7
bias = False
activation = None

layer = tfp.layers.weight_norm.WeightNorm(
               tf.keras.layers.Dense(out_dim, input_shape=(None, in_dim, ),
                                     use_bias = bias, activation = activation),
               input_shape = (None, None, in_dim))

I would like to give a input with variable length in the second dimension.
Suppose I run the below code first.

input = tf.random.normal(shape = (2, 3, 10))
output = layer(input)
output.shape
# [2, 3, 7]

After running the above code, I give another input to network

input2 = tf.random.normal(shape = (2, 4, 10))
output2 = layer(input2)

However, it causes error

Input 0 of layer "weight_norm_3" is incompatible with the layer:
expected shape=(None, 3, 10), found shape=(2, 4, 10)

I would like to give a variable length of second dimension. How can I do it?


问:
How can I configure multiple databases with springboot one being JPA and the other 5 plain jdbc?
For a project with a springboot backend, I have to use 1 database in Postgresql to save information and to add a history feature to the application and 5 other databases in Oracle on which I only have readonly access on views. For those 5 I only have to get ponctual values and the databases are huge so it doesn't make sense to have repositories and entities. But I can't find any information on how to configure multiple databases if one uses ORM and the others don't.

application.properties

```<code>#informations for the history database
spring.datasource.url = jdbc:postgresql://localhost:5432/NA_db
spring.datasource.username = userNA
spring.datasource.password = userNApwd
spring.datasource.driver-class-name=org.postgresql.Driver
spring.session.jdbc.initialize-schema: always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
</code>```

DataSourceConfiguration.java

```<code>import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "historyEntityManagerFactory", transactionManagerRef = "historyTransactionManager", basePackages = "mypackage.history.dao")
@EntityScan("mypackage.history.model.entities")
public class DataSourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSourceProperties SourceProperties() {
        return new DataSourceProperties();
    }

    @Primary
    @Bean(name = "historyDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.configuration")
    public DataSource dataSource() {
        return SourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();

    }

    @Primary
    @Bean(name = "historyEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("historyDatasource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("mypackage.history.model.entities")
                .persistenceUnit("historyPU").build();
    }

    @Primary
    @Bean(name = "historyTransactionManager")
    public PlatformTransactionManager barTransactionManager(
            @Qualifier("historyEntityManagerFactory") EntityManagerFactory barEntityManagerFactory) {
        return new JpaTransactionManager(barEntityManagerFactory);
    }
}

</code>```

Connection and Statement creation for the other databases

```<code>
    Class.forName("oracle.jdbc.OracleDriver");
            connectionYG = DriverManager.getConnection(urlYG, user, password);
            stmtYG = connectionYG.createStatement();
            connectionZA = DriverManager.getConnection(urlZA, user, password);
            stmtZA = connectionZA.createStatement();
            connectionZB = DriverManager.getConnection(urlZB, user, password);
            stmtZB = connectionZB.createStatement();
            connectionZC = DriverManager.getConnection(urlZC, user, password);
            stmtZC = connectionZC.createStatement();
            connectionZD = DriverManager.getConnection(urlZD, user, password);
            stmtZD = connectionZD.createStatement();

</code>```

Here is what I tried with a configuration class for the history database and instantiation of the connections directly where I need them in my service class.

Here is what I get :

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

</code>```

I am pretty sure I just don't configurate my databases the correct way but I can't find the correct informations. Have you any ideas on how am I supposed to do ?

Body:
For a project with a springboot backend, I have to use 1 database in Postgresql to save information and to add a history feature to the application and 5 other databases in Oracle on which I only have readonly access on views. For those 5 I only have to get ponctual values and the databases are huge so it doesn't make sense to have repositories and entities. But I can't find any information on how to configure multiple databases if one uses ORM and the others don't.

application.properties

#informations for the history database
spring.datasource.url = jdbc:postgresql://localhost:5432/NA_db
spring.datasource.username = userNA
spring.datasource.password = userNApwd
spring.datasource.driver-class-name=org.postgresql.Driver
spring.session.jdbc.initialize-schema: always
spring.jpa.hibernate.ddl-auto=update
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect

DataSourceConfiguration.java

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.zaxxer.hikari.HikariDataSource;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "historyEntityManagerFactory", transactionManagerRef = "historyTransactionManager", basePackages = "mypackage.history.dao")
@EntityScan("mypackage.history.model.entities")
public class DataSourceConfig {

    @Primary
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSourceProperties SourceProperties() {
        return new DataSourceProperties();
    }

    @Primary
    @Bean(name = "historyDatasource")
    @ConfigurationProperties(prefix = "spring.datasource.configuration")
    public DataSource dataSource() {
        return SourceProperties().initializeDataSourceBuilder().type(HikariDataSource.class).build();

    }

    @Primary
    @Bean(name = "historyEntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean barEntityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("historyDatasource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("mypackage.history.model.entities")
                .persistenceUnit("historyPU").build();
    }

    @Primary
    @Bean(name = "historyTransactionManager")
    public PlatformTransactionManager barTransactionManager(
            @Qualifier("historyEntityManagerFactory") EntityManagerFactory barEntityManagerFactory) {
        return new JpaTransactionManager(barEntityManagerFactory);
    }
}

Connection and Statement creation for the other databases

    Class.forName("oracle.jdbc.OracleDriver");
            connectionYG = DriverManager.getConnection(urlYG, user, password);
            stmtYG = connectionYG.createStatement();
            connectionZA = DriverManager.getConnection(urlZA, user, password);
            stmtZA = connectionZA.createStatement();
            connectionZB = DriverManager.getConnection(urlZB, user, password);
            stmtZB = connectionZB.createStatement();
            connectionZC = DriverManager.getConnection(urlZC, user, password);
            stmtZC = connectionZC.createStatement();
            connectionZD = DriverManager.getConnection(urlZD, user, password);
            stmtZD = connectionZD.createStatement();

Here is what I tried with a configuration class for the history database and instantiation of the connections directly where I need them in my service class.

Here is what I get :

***************************
APPLICATION FAILED TO START
***************************

Description:

Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.

Reason: Failed to determine a suitable driver class

Action:

Consider the following:
    If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
    If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).

I am pretty sure I just don't configurate my databases the correct way but I can't find the correct informations. Have you any ideas on how am I supposed to do ?


问:
The GET method is not supported for this route. Supported methods: HEAD. (happen on dreamhost deploy laravel project)
enter image description hereSymfony \ Component\ HttpKernel\ Exception\ MethodNotAllowedHttpException

The GET method is not supported for this route. Supported methods: HEAD

Symfony \ Component\ HttpKernel\ Exception\ MethodNotAllowedHttpException

The GET method is not supported for this route. Supported methods: HEAD


问:
EF Core - RowVersion with EF Core - InvalidCastException
I have added to my Entity an RowVersion in Code

```<code>[Timestamp]
public byte[] Version { get; set; }
</code>```

and applied to to my Table. In the table it is a "Raw" Type.

My problem is now, that when I call the Entity await context.Orders.... , the System will throw an Error:

```<code>InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.
</code>```

There is no mention of the Column that makes problems, but since I have no other byte[] and this is the only change I made, I guess that the Version is the problem.

I have now checked and apparently there is no RowVersion for Oralce?  What should I do here? Is there something that can mimic this or  should I just add an Date Row and always update it?

Body:
I have added to my Entity an RowVersion in Code

[Timestamp]
public byte[] Version { get; set; }

and applied to to my Table. In the table it is a "Raw" Type.

My problem is now, that when I call the Entity await context.Orders.... , the System will throw an Error:

InvalidCastException: Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'.

There is no mention of the Column that makes problems, but since I have no other byte[] and this is the only change I made, I guess that the Version is the problem.

I have now checked and apparently there is no RowVersion for Oralce?  What should I do here? Is there something that can mimic this or  should I just add an Date Row and always update it?


问:
Incompatible Type Warning when changing an entry in list of tuples
I have a small piece of code where Pycharm gives me a warning I don't understand how to get rid of:

```<code>movement_dict = {'R': (0, 1), 'L': (0, -1), 'U': (-1, 0), 'D': (1, 0), 'RU': (-1, 1), 'LU': (-1, -1), 'LD': (1, -1),
                 'RD': (1, 1)}

def move_in_dir(position, dir):
    return tuple(i + j for i, j in zip(position, movement_dict[dir]))

if __name__ == '__main__':
    rope = [(0, 0) for _ in range(10)]

    rope[0] = move_in_dir(rope[0], 'LD')

    print(rope[0])
</code>```

The warning is:

Unexpected type(s): (int, tuple[Any, ...]) Possible type(s): (SupportsIndex, tuple[int, int]) (slice, Iterable[tuple[int, int]])

and it is located at the first 0 in rope[0] = move_in_dir(rope[0], 'LD').

The code works perfectly fine and as expected, it just bugs me that i don't understand the warning. Somehow the tuples are of a different type, but is there a way to change that?

My python version is 3.10.6

Body:
I have a small piece of code where Pycharm gives me a warning I don't understand how to get rid of:

movement_dict = {'R': (0, 1), 'L': (0, -1), 'U': (-1, 0), 'D': (1, 0), 'RU': (-1, 1), 'LU': (-1, -1), 'LD': (1, -1),
                 'RD': (1, 1)}

def move_in_dir(position, dir):
    return tuple(i + j for i, j in zip(position, movement_dict[dir]))

if __name__ == '__main__':
    rope = [(0, 0) for _ in range(10)]

    rope[0] = move_in_dir(rope[0], 'LD')

    print(rope[0])

The warning is:

Unexpected type(s): (int, tuple[Any, ...]) Possible type(s): (SupportsIndex, tuple[int, int]) (slice, Iterable[tuple[int, int]])

and it is located at the first 0 in rope[0] = move_in_dir(rope[0], 'LD').

The code works perfectly fine and as expected, it just bugs me that i don't understand the warning. Somehow the tuples are of a different type, but is there a way to change that?

My python version is 3.10.6


问:
Importing npm scripts into authored jQuery-plugin
I'm trying to import a library into my authored jQuery-plugin and am getting stuck with what i believe it's babel's default importing behaviour.

Whenever i try

```<code>import * as autosize from 'autosize';
// or
import autosize from 'autosize';
// or
const autosize = require('autosize');

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
... rest of the fucking owl...

</code>```

My console gives me an importing error, stating that require is not defined (since it's a browser environment) and going into the script only shows me that the importing statement has been transformed into an _interopRequireDefault call.

How can i get around this? Is it even possible to use external libraries in an jQuery plugin?

Thanks in advance!

Body:
I'm trying to import a library into my authored jQuery-plugin and am getting stuck with what i believe it's babel's default importing behaviour.

Whenever i try

import * as autosize from 'autosize';
// or
import autosize from 'autosize';
// or
const autosize = require('autosize');

(function (factory) {
  if (typeof define === 'function' && define.amd) {
    // AMD. Register as an anonymous module.
    define(['jquery'], factory);
... rest of the fucking owl...

My console gives me an importing error, stating that require is not defined (since it's a browser environment) and going into the script only shows me that the importing statement has been transformed into an _interopRequireDefault call.

How can i get around this? Is it even possible to use external libraries in an jQuery plugin?

Thanks in advance!


问:
form validation is not working in JavaScript multistep form
Validation is not working here , I am stuck here please help


问:
Sonar Qube: Checkmarx vulnerability Reflected_XSS_All_Clients for Spring boot application
We are getting CheckMarx Vulnerability: Reflected_XSS_All_Clients issue for our spring boot application in Service class although:

We are validating the particular parameter using java validation pattern

We remove xss component from all our input parameter in one filter class.

Above two step ensures protection from Reflected XSS issue, still sonar qube is raising this critical issue.

How can I overcome this issue?


问:
DrawGeometry / Arc Segment single Center Point
Considering current code that takes a single center point.

```<code>     using (DrawingContext drawingContext = this.RenderOpen())
                {
drawingContext.DrawEllipse(highlightBrush, _isSelected ? SelectedPen : DeselectedPen, originPoint, radius, radius);
                }
</code>```

Is there a way to draw the shown image possibly with DrawGeometry?

Body:
Considering current code that takes a single center point.

     using (DrawingContext drawingContext = this.RenderOpen())
                {
drawingContext.DrawEllipse(highlightBrush, _isSelected ? SelectedPen : DeselectedPen, originPoint, radius, radius);
                }

Is there a way to draw the shown image possibly with DrawGeometry?


问:
CORS policy not workign Laravel 9, Angular 14, Plesk Centos, Php 8.1
My application keeps returning the CORS error. I've followed every solution on the internet but havent found the right answer yet.

Console Errors:
Access to XMLHttpRequest at 'https://api.domain/api/v1/status' from origin 'https://domain.nl' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

main.js console error:
"Http failure response for https://api.domain/api/v1/status: 0 Unknown Error"

Strange thing: the data is loaded and shown in the app. So it looks like OPTIONS is failing but the actual xhr request is working.

My server is Plesk based with Centos. Here I run php 8.1 on a Dedicated FPM application served by nginx.

pm.max_children is set to 20

I've tried the following solutions:

Add headers via Plesk > Apache & Nginx settings in Additional directives for HTTPS:

```<code>Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "*"
Header set Access-Control-Allow-Headers "*"
</code>```

Add headers via Plesk > Apache & Nginx settings in Additional nginx directives:

```<code>add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' '*';
add_header 'Access-Control-Allow-Headers' '*';
</code>```

In Laravel added the cors middleware by adding cors to all routes

```<code>Turn:
->middleware('api','auth:sanctum')
Into:
->middleware('cors','api','auth:sanctum')
</code>```

in Laravel downloaded the fruitcake/laravel-cors package

Added the header to all response() returns

```<code>return response()
    ->json(['Count'=>$result['count'], 'Result'=>$collection])
    ->withCallback($request->input('callback'))
    ->header("Access-Control-Allow-Origin",  "*");
</code>```

Changed the config of cors.php

```<code>This:
'allowed_origins_patterns' => [],
Into:
'allowed_origins_patterns' => ['*'],

And this:
'supports_credentials' => false,
Into:
'supports_credentials' => true,
</code>```

NONE of these solutions work! please help me

p.s. need to mention that a developemnt setup works fine. This is a locally run angular (localhost:4200) connected to a domain run on the SAME server as the test application is running also in Plesk > Centos > Php8.1 FPM served by nginx.

p.p.s. yes i've run composer dump-autoload, artisan optimize and artisan cache:clear many times in between

After consulting phpnl slack ive added the following solution

added the laravel Cors Middleware in Kernel.php

```<code>\App\Http\Middleware\Cors::class,
</code>```

In the server Logs I see the following error keeps comming up:

2785#0: *3791483 peer closed connection in SSL handshake (104: Connection reset by peer) while SSL handshaking to upstream

I've added a Let's Encrypt free certificate. and reissued it. This did not help. And the same error keeps showing.

Response for JubOps:
This is the code making the request

```<code>  getRequest(url: string, requestParams: any = {}): Observable<any> {
    const headerDict = {
      'Authorization': 'Bearer ' + environment.authData.plainTextToken,
      'X-UserId': environment.authData.curUser['UserId'].toString()
    };

    const requestOptions = {
      headers: new HttpHeaders(headerDict),
      params: requestParams
    };

    return this.http.get(environment.apiUrl + url, requestOptions);
  }
</code>```

this is a screenshot of the console:

And here a screenshot of the logs in Plesk:

Here a screenshot of the network tab

Body:
My application keeps returning the CORS error. I've followed every solution on the internet but havent found the right answer yet.

Console Errors:
Access to XMLHttpRequest at 'https://api.domain/api/v1/status' from origin 'https://domain.nl' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

main.js console error:
"Http failure response for https://api.domain/api/v1/status: 0 Unknown Error"

Strange thing: the data is loaded and shown in the app. So it looks like OPTIONS is failing but the actual xhr request is working.

My server is Plesk based with Centos. Here I run php 8.1 on a Dedicated FPM application served by nginx.

pm.max_children is set to 20

I've tried the following solutions:

Add headers via Plesk > Apache & Nginx settings in Additional directives for HTTPS:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "*"
Header set Access-Control-Allow-Headers "*"

Add headers via Plesk > Apache & Nginx settings in Additional nginx directives:

add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Methods' '*';
add_header 'Access-Control-Allow-Headers' '*';

In Laravel added the cors middleware by adding cors to all routes

Turn:
->middleware('api','auth:sanctum')
Into:
->middleware('cors','api','auth:sanctum')

in Laravel downloaded the fruitcake/laravel-cors package

Added the header to all response() returns

return response()
    ->json(['Count'=>$result['count'], 'Result'=>$collection])
    ->withCallback($request->input('callback'))
    ->header("Access-Control-Allow-Origin",  "*");

Changed the config of cors.php

This:
'allowed_origins_patterns' => [],
Into:
'allowed_origins_patterns' => ['*'],

And this:
'supports_credentials' => false,
Into:
'supports_credentials' => true,

NONE of these solutions work! please help me

p.s. need to mention that a developemnt setup works fine. This is a locally run angular (localhost:4200) connected to a domain run on the SAME server as the test application is running also in Plesk > Centos > Php8.1 FPM served by nginx.

p.p.s. yes i've run composer dump-autoload, artisan optimize and artisan cache:clear many times in between

After consulting phpnl slack ive added the following solution

added the laravel Cors Middleware in Kernel.php

\App\Http\Middleware\Cors::class,

In the server Logs I see the following error keeps comming up:

2785#0: *3791483 peer closed connection in SSL handshake (104: Connection reset by peer) while SSL handshaking to upstream

I've added a Let's Encrypt free certificate. and reissued it. This did not help. And the same error keeps showing.

Response for JubOps:
This is the code making the request

  getRequest(url: string, requestParams: any = {}): Observable<any> {
    const headerDict = {
      'Authorization': 'Bearer ' + environment.authData.plainTextToken,
      'X-UserId': environment.authData.curUser['UserId'].toString()
    };

    const requestOptions = {
      headers: new HttpHeaders(headerDict),
      params: requestParams
    };

    return this.http.get(environment.apiUrl + url, requestOptions);
  }

this is a screenshot of the console:

And here a screenshot of the logs in Plesk:

Here a screenshot of the network tab


问:
Methods called on jest mocked response fails with error
I have the below line in my service.

```<code>  const timeline = await buildClient.getBuildTimeline(project.id, buildId);
</code>```

The above code is successfully mocked by jest as below using the __mocks__ approach.

jest.mock('azure-devops-extension-api', () => {
  return { getClient: (client: any) => new GitRestClient() };
});

export const mockGetItems = jest
  .fn()
  .mockReturnValue({ records: [{ state: 2, type: 'TASK', task: { id: TASK_IDS[0] } }] });

class GitRestClient {
  public getBuildTimeline(projectId: string, buildId: string): Promise<Timeline[]> {
    return new Promise((resolve) => resolve(mockGetItems()));
  }
}
```
<p>But when I get error during jest test in the below <code>find</code> method which acts upon the mocked response.</p>
```  const record = timeline.records.find((rec) => {
    return rec.type === 'Task';
  });
```

How should I update so that the above code snippet is mocked perfectly to return the record value using the find method.

Body:
I have the below line in my service.

  const timeline = await buildClient.getBuildTimeline(project.id, buildId);

The above code is successfully mocked by jest as below using the __mocks__ approach.

jest.mock('azure-devops-extension-api', () => {
  return { getClient: (client: any) => new GitRestClient() };
});

export const mockGetItems = jest
  .fn()
  .mockReturnValue({ records: [{ state: 2, type: 'TASK', task: { id: TASK_IDS[0] } }] });

class GitRestClient {
  public getBuildTimeline(projectId: string, buildId: string): Promise<Timeline[]> {
    return new Promise((resolve) => resolve(mockGetItems()));
  }
}

But when I get error during jest test in the below find method which acts upon the mocked response.

  const record = timeline.records.find((rec) => {
    return rec.type === 'Task';
  });

How should I update so that the above code snippet is mocked perfectly to return the record value using the find method.


问:
The Serverless Function exceeds the maximum size limit of 50mb
I am trying to deploy my Django project on Vercel and when I am deplying my project it is giving the error -

"The Serverless Function "StockChart/wsgi.py" is 128.14mb which exceeds the maximum size limit of 50mb."

I have attached the GitHub repository of my project below -

GitHub

I have tried to minimise the modules in requirements.txt and only kept the essential modules but then also it is giving the same error.