问:
PermissionBasedRouting VueJS
I am trying to give access to the teams with multiple users. Unfortunatly other users are also able to view the VueComponents. The Vue code runs perfectly but other users, who are not in team 'admins' are able to see the components. Also, the console prints teamName as 'admins' even the current logged user is not part of the team. For example the current user is 'test' user which is not part of admin teams but the console prints 'admins'. please see the image console output, contains teamsList with users.

Vue file

```<code>this.loadTeams()
      .then((response) => {
        this.teamsList = response.data;
        console.log("teams list after loadteams", this.teamsList);
        this.teamsList.forEach((item) => {
          if (item.teamName === "admins") {
            this.haveAccess = true;
            console.log("teamName is :", item.teamName);
          }
        });
      })
</code>```

router file

```<code>router.beforeEach((to, from, next) => {

  // condition for teams to access administration page

  if (to.meta.haveAccess && store.getters("administration/teams", ["teamsList"])) {
    this.teamsList.forEach((item) => {
      if (item.teamName === "admins") {
        next({
          name:'Administration',
       params: {
      desiredRoute: to.fullPath
    }})
      }
      else {
        router.push({
          name:'NotFound'
        })
      }
    });

  }
});
</code>```

Title: PermissionBasedRouting VueJS

Body:
I am trying to give access to the teams with multiple users. Unfortunatly other users are also able to view the VueComponents. The Vue code runs perfectly but other users, who are not in team 'admins' are able to see the components. Also, the console prints teamName as 'admins' even the current logged user is not part of the team. For example the current user is 'test' user which is not part of admin teams but the console prints 'admins'. please see the image console output, contains teamsList with users.

Vue file

this.loadTeams()
      .then((response) => {
        this.teamsList = response.data;
        console.log("teams list after loadteams", this.teamsList);
        this.teamsList.forEach((item) => {
          if (item.teamName === "admins") {
            this.haveAccess = true;
            console.log("teamName is :", item.teamName);
          }
        });
      })

router file

router.beforeEach((to, from, next) => {

  // condition for teams to access administration page

  if (to.meta.haveAccess && store.getters("administration/teams", ["teamsList"])) {
    this.teamsList.forEach((item) => {
      if (item.teamName === "admins") {
        next({
          name:'Administration',
       params: {
      desiredRoute: to.fullPath
    }})
      }
      else {
        router.push({
          name:'NotFound'
        })
      }
    });

  }
});


来源: stackexchange

问:
Parsing *.scn files from Bio Rad Image Lab in python
Im using Bio-Rad Image Lab software (https://www.bio-rad.com/en-il/product/image-lab-software?ID=KRE6P5E8Z) to scan biochemical reactions slides.
The software can save mutiple-images  in one action as *.scn files.

I want to convert the *.scn files to *.tiff by myself using Python.
ImageJ can open these *.scn files.
Yet, I could not open these files using either slideio or tifffile (python packages) and of course opencv also failes.

For example, when using tifffile:

```<code>import tifffile

path = 'img.scn'
img = tifffile.imread(path)
</code>```

I get the following error:

```<code>Exception has occurred: TiffFileError
not a TIFF file b'MIME'
KeyError: b'MI'

During handling of the above exception, another exception occurred:

  File "/mnt/c/analysis/dev_analysis/2022_12_12_scn_extract/scn2tiff.py", line 9, in <module>
    img = tifffile.imread(path)
tifffile.tifffile.TiffFileError: not a TIFF file b'MIME'
</code>```

When using slideio:

```<code>import slideio

path = 'img.scn'
slide = slideio.open_slide(path, "SCN")
</code>```

I get the following error:

```<code>Exception has occurred: RuntimeError
SCNImageDriver: Cannot open file:img.scn
  File "/mnt/c/analysis/dev_analysis/2022_12_12_scn_extract/scn2tiff.py", line 6, in <module>
    slide = slideio.open_slide(path, "SCN")
RuntimeError: SCNImageDriver: Cannot open file:img.scn
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im using Bio-Rad Image Lab software (https://www.bio-rad.com/en-il/product/image-lab-software?ID=KRE6P5E8Z) to scan biochemical reactions slides.
The software can save mutiple-images  in one action as *.scn files.

I want to convert the *.scn files to *.tiff by myself using Python.
ImageJ can open these *.scn files.
Yet, I could not open these files using either slideio or tifffile (python packages) and of course opencv also failes.

For example, when using tifffile:

import tifffile

path = 'img.scn'
img = tifffile.imread(path)

I get the following error:

Exception has occurred: TiffFileError
not a TIFF file b'MIME'
KeyError: b'MI'

During handling of the above exception, another exception occurred:

  File "/mnt/c/analysis/dev_analysis/2022_12_12_scn_extract/scn2tiff.py", line 9, in <module>
    img = tifffile.imread(path)
tifffile.tifffile.TiffFileError: not a TIFF file b'MIME'

When using slideio:

import slideio

path = 'img.scn'
slide = slideio.open_slide(path, "SCN")

I get the following error:

Exception has occurred: RuntimeError
SCNImageDriver: Cannot open file:img.scn
  File "/mnt/c/analysis/dev_analysis/2022_12_12_scn_extract/scn2tiff.py", line 6, in <module>
    slide = slideio.open_slide(path, "SCN")
RuntimeError: SCNImageDriver: Cannot open file:img.scn


问:
Load test Oracle Apex applications
I have various Oracle apex apps which are session encrypted, protected and on friendly URLs. My objective is to load test the apps. My team is using NeoLoad but it is causing so many issues because of session encryption and protection as HTTP request gets changed.

Is there any tool which is optimized for Load testing apex apps?

Title: Load test Oracle Apex applications


问:
Codeigniter 3 | intervention-image
I use library intervention-image

```<code>https://image.intervention.io/v2
</code>```

I fallowing to documentation and write function:

```<code>//product default image upload
    public function product_default_image_upload($path, $folder)
    {
        $new_name = 'img_x500_' . generate_unique_id() . '.' . pathinfo($path, PATHINFO_EXTENSION);
        $new_path = 'uploads/' . $folder . '/' . $new_name;
        if ($folder == 'images') {
            $directory = $this->create_upload_directory('images');
            $new_name = $directory . $new_name;
            $new_path = 'uploads/images/' . $new_name;
        }
        $img = Image::make($path)->orientate();
        $img = Image::canvas(32, 32, '#ff0000');
        $img->resize(null, 500, function ($constraint) {
            $constraint->aspectRatio();
        });
        $img->save(FCPATH . $new_path, $this->quality);
        //add watermark
        if ($this->general_settings->watermark_product_images == 1) {
            $this->add_watermark(FCPATH . $new_path, 'mid');
        }
        return $new_name;
    }
</code>```

I need add background color image under product image during upload.

```<code>$img = Image::canvas(32, 32, '#ff0000');
</code>```

Example I upload photo with watch on white background and I need change this white background to RED.

The problem is with this function when I upload image then this code fill full background red. But I need bg only under product.

Title: Codeigniter 3 | intervention-image

Body:
I use library intervention-image

https://image.intervention.io/v2

I fallowing to documentation and write function:

//product default image upload
    public function product_default_image_upload($path, $folder)
    {
        $new_name = 'img_x500_' . generate_unique_id() . '.' . pathinfo($path, PATHINFO_EXTENSION);
        $new_path = 'uploads/' . $folder . '/' . $new_name;
        if ($folder == 'images') {
            $directory = $this->create_upload_directory('images');
            $new_name = $directory . $new_name;
            $new_path = 'uploads/images/' . $new_name;
        }
        $img = Image::make($path)->orientate();
        $img = Image::canvas(32, 32, '#ff0000');
        $img->resize(null, 500, function ($constraint) {
            $constraint->aspectRatio();
        });
        $img->save(FCPATH . $new_path, $this->quality);
        //add watermark
        if ($this->general_settings->watermark_product_images == 1) {
            $this->add_watermark(FCPATH . $new_path, 'mid');
        }
        return $new_name;
    }

I need add background color image under product image during upload.

$img = Image::canvas(32, 32, '#ff0000');

Example I upload photo with watch on white background and I need change this white background to RED.

The problem is with this function when I upload image then this code fill full background red. But I need bg only under product.


问:
how to override the background when using float element
I have a website footer, this is the code looks like:

```<code><div className="App-footer-float">
  <div id="footer" className="App-footer">
    <Divider></Divider>
    <div>
      <Row justify="center" align="middle">
        <Col>
          <div>© 2022 Apple</div>
          <div>ICP 1700232-6</div>
        </Col>
      </Row>
    </div>
  </div>
</div>
</code>```

this is the css looks like:

```<code>.App-footer-float{
  margin: 0 auto;
  width: 100%;
}

.App-footer{
  font-size: 0.3rem;
  position: fixed;
  bottom: 0;
  text-align: "center";
  width: 100%;
}
</code>```

this footer element are transparent, now I want to using the float element to override the background element. I have tried to set the background color in App-footer-float:

```<code>.App-footer-float{
  margin: 0 auto;
  width: 100%;
  background-color:red;
}
</code>```

also tried to set the opacity and transparent, seems could not work. what should I do to make the footer element override the background and make it non-transparent?

Body:
I have a website footer, this is the code looks like:

    <Divider></Divider>

      <Row justify="center" align="middle">
        <Col>

© 2022 Apple

ICP 1700232-6

        </Col>
      </Row>

this is the css looks like:

.App-footer-float{
  margin: 0 auto;
  width: 100%;
}

.App-footer{
  font-size: 0.3rem;
  position: fixed;
  bottom: 0;
  text-align: "center";
  width: 100%;
}

this footer element are transparent, now I want to using the float element to override the background element. I have tried to set the background color in App-footer-float:

.App-footer-float{
  margin: 0 auto;
  width: 100%;
  background-color:red;
}

also tried to set the opacity and transparent, seems could not work. what should I do to make the footer element override the background and make it non-transparent?


问:
How to post a csv file using useForm from 'react-hook-form?
I got a query using RTK, and a component where I attach the file and submit - after I attach the file and submit as shown in the image below I get the file in a weird format such as: file: "[object FileList]" after console log it.

How was wondering how to post a csv file in the correct format, such as file.csv. My component looks like as follow:

```<code>import { FC, FormEventHandler, RefObject, useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';

import {
  Dialog,
  DialogPortal,
  DialogOverlay,
  DialogContent,
  DialogTitle,
  DialogClose
} from '@radix-ui/react-dialog';

import { DownloadIcon, XIcon } from '@heroicons/react/outline';
import { setFormErrors } from 'utils/formHelpers';
import InputField from 'components/ui/atoms/InputField';
import { useUploadBatchMutation } from 'redux/api/uploadBatchApi';

const schema = yup
  .object({
    description: yup.string().optional(),
    file: yup.string().label('file').required()
  })
  .required();

interface Inputs extends yup.InferType<typeof schema> {
  base: null;
}

interface Props {
  open: boolean;
  onClose: (value: boolean) => void;
  triggerRef: RefObject<HTMLAnchorElement>;
}

const UploadBatchDialog: FC<Props> = ({ open, onClose, triggerRef }) => {
  const [showLoading, setShowLoading] = useState<boolean>(false);

  const {
    handleSubmit,
    register,
    setError,
    formState,
    setValue,
    reset: resetForm
  } = useForm<Inputs>({
    mode: 'onSubmit',
    resolver: yupResolver(schema)
  });
  const [uploadBatch] = useUploadBatchMutation();

  const onSubmit: FormEventHandler<HTMLFormElement> = async (event) => {
    console.log('test');
    event.preventDefault();
    try {
      await handleSubmit(async (data) => {
        console.log(data);
        const formData = new FormData();
        formData.append('file', data.file);
        if (data.description) {
          formData.append('name', data.description);
        }
        uploadBatch(formData);
      })(event);
    } catch (error: any) {
      setTimeout(
        () =>
          setFormErrors({
            error,
            setError,
            fields: Object.keys(schema.fields)
          }),
        50
      );
    }
  };
  const formFailed = () => Object.keys(formState.errors).length > 0;

  const onDialogClose = (value: boolean) => {
    resetForm();
    onClose(value);
  };

  const onCloseAutoFocus = () => triggerRef.current?.focus();

  const [file, setFile] = useState<any>();

  return (
    <Dialog open={open} onOpenChange={onDialogClose}>
      <DialogPortal>
        <DialogOverlay className="bg-opacity/90 fixed inset-0 z-50 bg-inpay-green-700">
          <DialogContent
            onCloseAutoFocus={onCloseAutoFocus}
            onInteractOutside={(e) => e.preventDefault()}
            className="fixed top-[50%] left-[50%] translate-y-[-50%] translate-x-[-50%] rounded-lg shadow-[0_0_6px_#B7BCBA]"
          >
            <DialogTitle className="flex h-12 items-center justify-between rounded-t-lg border-b border-b-inpay-pumice bg-white px-6">
              <DownloadIcon className="w-8 stroke-1 group-hover:stroke-1.5" />
              <span className="pr-20">Upload batch file</span>
              <DialogClose
                aria-label="Close"
                className="outline-none focus:outline-none"
              >
                <XIcon className="-m-1 h-8 w-8 outline-none focus:outline-none" />
              </DialogClose>
            </DialogTitle>
            <div className="flex justify-center rounded-b-lg bg-inpay-black-haze-100 p-6">
              <div className="w-72">
                <form onSubmit={onSubmit} autoComplete="off">
                  <InputField
                    {...register('description')}
                    className="mb-4"
                    label="Name (if left blank the file name will be used)"
                    name="description"
                  />

                  <div className="mb-4 flex flex-col">
                    <label className="mb-0.5 pl-2 text-xs">
                      Attach payout request batch file
                    </label>
                    <div className="relative flex h-12 w-full rounded-lg bg-white p-1 shadow-plain focus:shadow-plain-lg group-hover:shadow-plain-lg">
                      <input
                        className="absolute opacity-0"
                        type="file"
                        accept="text/csv"
                        {...register('file')}
                        onChange={(e) => {
                          if (e.target.files) {
                            setFile(e.target.files[0]);
                          } else {
                            setFile(null);
                          }
                        }}
                      />
                      <span className="flex w-full items-center justify-between pl-2">
                        {file ? file.name : 'Please attach your file'}
                        <button className="inpay-button h-10">
                          Attach file
                        </button>
                      </span>
                    </div>
                    {/* <div>Create batch template</div> */}
                  </div>
                  <button
                    type="submit"
                    className="inpay-button w-full"
                    // disabled={
                    //   formState.isSubmitSuccessful || !formState.isValid
                    // }
                  >
                    Upload batch
                  </button>
                  {formState.errors.base && (
                    <div
                      role="alert"
                      className="mt-2 rounded-2xl bg-rose-200 p-3 text-sm text-inpay-red-600"
                      style={{
                        filter: 'drop-shadow(0 0 1px rgb(0 0 0 / 0.16))'
                      }}
                    >
                      {formState.errors.base.message}
                    </div>
                  )}
                </form>
              </div>
            </div>
          </DialogContent>
        </DialogOverlay>
      </DialogPortal>
    </Dialog>
  );
};

export default UploadBatchDialog;
</code>```

while my post request looks like this:

```<code>import { customerApi } from './customerApi';
interface UploadedFile {
  file: any;
  name: string;
}
export const uploadBatchApi = customerApi.injectEndpoints({
  endpoints: (builder) => ({
    uploadBatch: builder.mutation<any, any>({
      query(form) {
        return {
          url: 'payouts/payout_request_csv_batches',
          method: 'POST',
          credentials: 'include',
          body: form
        };
      }
    })
  })
});
export const { useUploadBatchMutation } = uploadBatchApi;
</code>```

I am wondering what I did wrong and why react hook passes that strange string. Any clues would be much appreciated.

Body:
I got a query using RTK, and a component where I attach the file and submit - after I attach the file and submit as shown in the image below I get the file in a weird format such as: file: "[object FileList]" after console log it.

How was wondering how to post a csv file in the correct format, such as file.csv. My component looks like as follow:

import { FC, FormEventHandler, RefObject, useState } from 'react';
import { useForm } from 'react-hook-form';
import { yupResolver } from '@hookform/resolvers/yup';
import * as yup from 'yup';

import {
  Dialog,
  DialogPortal,
  DialogOverlay,
  DialogContent,
  DialogTitle,
  DialogClose
} from '@radix-ui/react-dialog';

import { DownloadIcon, XIcon } from '@heroicons/react/outline';
import { setFormErrors } from 'utils/formHelpers';
import InputField from 'components/ui/atoms/InputField';
import { useUploadBatchMutation } from 'redux/api/uploadBatchApi';

const schema = yup
  .object({
    description: yup.string().optional(),
    file: yup.string().label('file').required()
  })
  .required();

interface Inputs extends yup.InferType<typeof schema> {
  base: null;
}

interface Props {
  open: boolean;
  onClose: (value: boolean) => void;
  triggerRef: RefObject<HTMLAnchorElement>;
}

const UploadBatchDialog: FC<Props> = ({ open, onClose, triggerRef }) => {
  const [showLoading, setShowLoading] = useState<boolean>(false);

  const {
    handleSubmit,
    register,
    setError,
    formState,
    setValue,
    reset: resetForm
  } = useForm<Inputs>({
    mode: 'onSubmit',
    resolver: yupResolver(schema)
  });
  const [uploadBatch] = useUploadBatchMutation();

  const onSubmit: FormEventHandler<HTMLFormElement> = async (event) => {
    console.log('test');
    event.preventDefault();
    try {
      await handleSubmit(async (data) => {
        console.log(data);
        const formData = new FormData();
        formData.append('file', data.file);
        if (data.description) {
          formData.append('name', data.description);
        }
        uploadBatch(formData);
      })(event);
    } catch (error: any) {
      setTimeout(
        () =>
          setFormErrors({
            error,
            setError,
            fields: Object.keys(schema.fields)
          }),
        50
      );
    }
  };
  const formFailed = () => Object.keys(formState.errors).length > 0;

  const onDialogClose = (value: boolean) => {
    resetForm();
    onClose(value);
  };

  const onCloseAutoFocus = () => triggerRef.current?.focus();

  const [file, setFile] = useState<any>();

  return (
    <Dialog open={open} onOpenChange={onDialogClose}>
      <DialogPortal>
        <DialogOverlay className="bg-opacity/90 fixed inset-0 z-50 bg-inpay-green-700">
          <DialogContent
            onCloseAutoFocus={onCloseAutoFocus}
            onInteractOutside={(e) => e.preventDefault()}
            className="fixed top-[50%] left-[50%] translate-y-[-50%] translate-x-[-50%] rounded-lg shadow-[0_0_6px_#B7BCBA]"
          >
            <DialogTitle className="flex h-12 items-center justify-between rounded-t-lg border-b border-b-inpay-pumice bg-white px-6">
              <DownloadIcon className="w-8 stroke-1 group-hover:stroke-1.5" />
              Upload batch file
              <DialogClose
                aria-label="Close"
                className="outline-none focus:outline-none"
              >
                <XIcon className="-m-1 h-8 w-8 outline-none focus:outline-none" />
              </DialogClose>
            </DialogTitle>

                <form onSubmit={onSubmit} autoComplete="off">
                  <InputField
                    {...register('description')}
                    className="mb-4"
                    label="Name (if left blank the file name will be used)"
                    name="description"
                  />

                      Attach payout request batch file

                      <input
                        className="absolute opacity-0"
                        type="file"
                        accept="text/csv"
                        {...register('file')}
                        onChange={(e) => {
                          if (e.target.files) {
                            setFile(e.target.files[0]);
                          } else {
                            setFile(null);
                          }
                        }}
                      />

                        {file ? file.name : 'Please attach your file'}
                        <button className="inpay-button h-10">
                          Attach file
                        </button>

                    {/*
Create batch template
 */}

                  <button
                    type="submit"
                    className="inpay-button w-full"
                    // disabled={
                    //   formState.isSubmitSuccessful || !formState.isValid
                    // }
                  >
                    Upload batch
                  </button>
                  {formState.errors.base && (

                      {formState.errors.base.message}

                  )}
                </form>

          </DialogContent>
        </DialogOverlay>
      </DialogPortal>
    </Dialog>
  );
};

export default UploadBatchDialog;

while my post request looks like this:

import { customerApi } from './customerApi';
interface UploadedFile {
  file: any;
  name: string;
}
export const uploadBatchApi = customerApi.injectEndpoints({
  endpoints: (builder) => ({
    uploadBatch: builder.mutation<any, any>({
      query(form) {
        return {
          url: 'payouts/payout_request_csv_batches',
          method: 'POST',
          credentials: 'include',
          body: form
        };
      }
    })
  })
});
export const { useUploadBatchMutation } = uploadBatchApi;

I am wondering what I did wrong and why react hook passes that strange string. Any clues would be much appreciated.


问:
JSTree - why is it not reading from my JSON Array correctly but renders properly when returned a single JSON string?
I've been working on this for days and can't see to crack it! Deadlines are very close and I am full of covid. Please please help me crack it asap. I feel like i've tried every option of square brackets, curly brackets but I just can't get JSTree to interpret it correctly from my Array. When I return a 1 line string using the exact same format, JSTree correctly renders it as a folder with the correct name but when I return the Array, JSTree shows a list of folders but they have the whole string as the name:

https://i.imgur.com/A0U9gGi.png

I've checked the JSON Array using this checker: https://jsonformatter.curiousconcept.com/

and it checks properly:

Returned Array:

[{"id":"New Lib","parent":"#","text":"New Lib","data":"0"},{"id":"40","parent":"New Lib","text":"Text TXT","data":"1"},{"id":"39","parent":"New Lib","text":"new 5","data":"2"},{"id":"34","parent":"New Lib","text":"Hi","data":"3"},{"id":"41","parent":"34","text":"Test URL Facebook","data":"4"},{"id":"37","parent":"34","text":"Hi 2","data":"5"}]

Output from the checker:

```<code>[
   {
      "id":"New Lib",
      "parent":"#",
      "text":"New Lib",
      "data":"0"
   },
   {
      "id":"40",
      "parent":"New Lib",
      "text":"Text TXT",
      "data":"1"
   },
   {
      "id":"39",
      "parent":"New Lib",
      "text":"new 5",
      "data":"2"
   },
   {
      "id":"34",
      "parent":"New Lib",
      "text":"Hi",
      "data":"3"
   },
   {
      "id":"41",
      "parent":"34",
      "text":"Test URL Facebook",
      "data":"4"
   },
   {
      "id":"37",
      "parent":"34",
      "text":"Hi 2",
      "data":"5"
   }
]
</code>```

Maybe I need to parse it somehow? I've found this thread: Loading Json as variable into jsTree

But I don't understand how to implement this into mine fully

C# Code:

```<code>[WebMethod]
public static Array getChildren(string libraryID)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    con.Open();

    //Get the library name
    string getUserInfo = "select LibraryName from Document_Library_Names where Id =" + libraryID;
    SqlCommand getUserInfocmd = new SqlCommand(getUserInfo, con);
    string libraryName = Convert.ToString(getUserInfocmd.ExecuteScalar()).Trim();

    //Getting documents
    string strGetDocuments = "Select * from Documents where LID =" + libraryID + "  order by DisplayOrder ASC";
    SqlCommand getDocumentsCMD = new SqlCommand(strGetDocuments, con);
    getDocumentsCMD.ExecuteNonQuery();

    DataTable dt = new DataTable();
    SqlDataReader sqlDR = getDocumentsCMD.ExecuteReader();
    dt.Load(sqlDR);
    sqlDR.Close();

    if (dt != null)
    {
        if (dt.Rows.Count > 0)
        {
            int arrayCount = dt.Rows.Count;
            int rowCount = 1;
            string arrayEnd = "";

            string[] documentArray = new string[arrayCount+1];

            //List<string> documentList = new List<string>();
            documentArray[0] = "[{\"id\":\"" + libraryName + "\",\"parent\":\"#\",\"text\":\"" + libraryName + "\",\"data\":\"0\"}]";

            //Build the string
            foreach (DataRow row in dt.Rows)
            {
                //Getting the data
                string ID = row[0].ToString().Trim();
                string type = row[2].ToString().Trim();
                string name = row[3].ToString().Trim();
                string parentFolder = row[4].ToString().Trim();
                string displayOrder = row[5].ToString().Trim();
                string extension = row[8].ToString().Trim();

                //Get parentFolder ID
                string parentFolderID = "0";
                if (parentFolder != "")
                {
                    string strParentFolderID = "Select ID from Documents where Name=@Name and Type=0";
                    SqlCommand strParentFolderIDcmd = new SqlCommand(strParentFolderID, con);
                    strParentFolderIDcmd.Parameters.AddWithValue("@Name", parentFolder);
                    parentFolderID = Convert.ToString(strParentFolderIDcmd.ExecuteScalar());
                }
                else
                {
                    parentFolderID = libraryName;
                }

                documentArray[rowCount] = "[{\"id\":\"" + ID + "\",\"parent\":\"" + parentFolderID + "\",\"text\":\"" + name + "\",\"data\":\"" + displayOrder + "\"}]";
                rowCount = rowCount + 1;
        }
        con.Close();
            return documentArray;
        }
        else
        {
            con.Close();
            return null;
        }
    }
    else
    {
        con.Close();
        return null;
    }
}
</code>```

Javascript:

```<code><script type="text/javascript">

    const queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    const libraryID = urlParams.get('ID');

    $('#libraryTreeview').jstree({
        "core": {
            "data": {
                    type: "POST",
                    url: "LibraryFiles.aspx/getChildren",
                    data: '{"libraryID":"' + libraryID + '"}',
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert(data.d);
                        data.d;
                        $(data).each(function () {
                           return { "id": this.id };
                        });
                    }
            },
            "themes": {
                dots: false,
                //"variant": "large",
                //"responsive": true
            },
            "types": {
                "FDR": {
                    "icon": "WebsiteImages/LibraryIcons/Folder48.png"
                },
                "IMG": {
                    "icon": "WebsiteImages/LibraryIcons/Image48.png"
                }
            },
            "plugins": ["types", "themes"]
        }
    });
</script>
</code>```

Body:
I've been working on this for days and can't see to crack it! Deadlines are very close and I am full of covid. Please please help me crack it asap. I feel like i've tried every option of square brackets, curly brackets but I just can't get JSTree to interpret it correctly from my Array. When I return a 1 line string using the exact same format, JSTree correctly renders it as a folder with the correct name but when I return the Array, JSTree shows a list of folders but they have the whole string as the name:

https://i.imgur.com/A0U9gGi.png

I've checked the JSON Array using this checker: https://jsonformatter.curiousconcept.com/

and it checks properly:

Returned Array:

[{"id":"New Lib","parent":"#","text":"New Lib","data":"0"},{"id":"40","parent":"New Lib","text":"Text TXT","data":"1"},{"id":"39","parent":"New Lib","text":"new 5","data":"2"},{"id":"34","parent":"New Lib","text":"Hi","data":"3"},{"id":"41","parent":"34","text":"Test URL Facebook","data":"4"},{"id":"37","parent":"34","text":"Hi 2","data":"5"}]

Output from the checker:

[
   {
      "id":"New Lib",
      "parent":"#",
      "text":"New Lib",
      "data":"0"
   },
   {
      "id":"40",
      "parent":"New Lib",
      "text":"Text TXT",
      "data":"1"
   },
   {
      "id":"39",
      "parent":"New Lib",
      "text":"new 5",
      "data":"2"
   },
   {
      "id":"34",
      "parent":"New Lib",
      "text":"Hi",
      "data":"3"
   },
   {
      "id":"41",
      "parent":"34",
      "text":"Test URL Facebook",
      "data":"4"
   },
   {
      "id":"37",
      "parent":"34",
      "text":"Hi 2",
      "data":"5"
   }
]

Maybe I need to parse it somehow? I've found this thread: Loading Json as variable into jsTree

But I don't understand how to implement this into mine fully

C# Code:

[WebMethod]
public static Array getChildren(string libraryID)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    con.Open();

    //Get the library name
    string getUserInfo = "select LibraryName from Document_Library_Names where Id =" + libraryID;
    SqlCommand getUserInfocmd = new SqlCommand(getUserInfo, con);
    string libraryName = Convert.ToString(getUserInfocmd.ExecuteScalar()).Trim();

    //Getting documents
    string strGetDocuments = "Select * from Documents where LID =" + libraryID + "  order by DisplayOrder ASC";
    SqlCommand getDocumentsCMD = new SqlCommand(strGetDocuments, con);
    getDocumentsCMD.ExecuteNonQuery();

    DataTable dt = new DataTable();
    SqlDataReader sqlDR = getDocumentsCMD.ExecuteReader();
    dt.Load(sqlDR);
    sqlDR.Close();

    if (dt != null)
    {
        if (dt.Rows.Count > 0)
        {
            int arrayCount = dt.Rows.Count;
            int rowCount = 1;
            string arrayEnd = "";

            string[] documentArray = new string[arrayCount+1];

            //List<string> documentList = new List<string>();
            documentArray[0] = "[{\"id\":\"" + libraryName + "\",\"parent\":\"#\",\"text\":\"" + libraryName + "\",\"data\":\"0\"}]";

            //Build the string
            foreach (DataRow row in dt.Rows)
            {
                //Getting the data
                string ID = row[0].ToString().Trim();
                string type = row[2].ToString().Trim();
                string name = row[3].ToString().Trim();
                string parentFolder = row[4].ToString().Trim();
                string displayOrder = row[5].ToString().Trim();
                string extension = row[8].ToString().Trim();

                //Get parentFolder ID
                string parentFolderID = "0";
                if (parentFolder != "")
                {
                    string strParentFolderID = "Select ID from Documents where Name=@Name and Type=0";
                    SqlCommand strParentFolderIDcmd = new SqlCommand(strParentFolderID, con);
                    strParentFolderIDcmd.Parameters.AddWithValue("@Name", parentFolder);
                    parentFolderID = Convert.ToString(strParentFolderIDcmd.ExecuteScalar());
                }
                else
                {
                    parentFolderID = libraryName;
                }

                documentArray[rowCount] = "[{\"id\":\"" + ID + "\",\"parent\":\"" + parentFolderID + "\",\"text\":\"" + name + "\",\"data\":\"" + displayOrder + "\"}]";
                rowCount = rowCount + 1;
        }
        con.Close();
            return documentArray;
        }
        else
        {
            con.Close();
            return null;
        }
    }
    else
    {
        con.Close();
        return null;
    }
}

Javascript:


问:
How can i show a list in a jsp file
This may seem like a simple question but I am 100% confused.

All I want to do is to be able to display a list of objects generated via a servlet into a JSP file.

Here is my servlet

```<code>    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    ProductLoader p1 = new ProductLoader();
    List<Product> products = p1.getProducts();
    System.out.print(products);
    request.setAttribute("products", products);
    request.getRequestDispatcher("/product.jsp").forward(request, response);
}
</code>```

the result of     System.out.print(products); is [Product [name=CHECK PRINT SHIRT, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/M63H24W7JF0-L302-ALTGHOST?wid=1500&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=110.0], Product [name=GLORIA HIGH LOGO SNEAKER, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/FLGLO4FAL12-BEIBR?wid=700&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=91.0], Product [name=CATE RIGID BAG, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/HWVG6216060-TAN?wid=700&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=94.5], Product [name=GUESS CONNECT WATCH, imgUrl=http://guesseu.scene7.com/is/image/GuessEU/WC0001FMSWC-G5?wid=520&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=438.9], Product [name='70s RETRO GLAM KEFIAH, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/AW6308VIS03-SAP?wid=700&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=20.0]

But how do I show this as a JSP?

Title: How can i show a list in a jsp file

Body:
This may seem like a simple question but I am 100% confused.

All I want to do is to be able to display a list of objects generated via a servlet into a JSP file.

Here is my servlet

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    ProductLoader p1 = new ProductLoader();
    List<Product> products = p1.getProducts();
    System.out.print(products);
    request.setAttribute("products", products);
    request.getRequestDispatcher("/product.jsp").forward(request, response);
}

the result of     System.out.print(products); is [Product [name=CHECK PRINT SHIRT, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/M63H24W7JF0-L302-ALTGHOST?wid=1500&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=110.0], Product [name=GLORIA HIGH LOGO SNEAKER, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/FLGLO4FAL12-BEIBR?wid=700&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=91.0], Product [name=CATE RIGID BAG, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/HWVG6216060-TAN?wid=700&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=94.5], Product [name=GUESS CONNECT WATCH, imgUrl=http://guesseu.scene7.com/is/image/GuessEU/WC0001FMSWC-G5?wid=520&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=438.9], Product [name='70s RETRO GLAM KEFIAH, imgUrl=https://guesseu.scene7.com/is/image/GuessEU/AW6308VIS03-SAP?wid=700&fmt=jpeg&qlt=80&op_sharpen=0&op_usm=1.0,1.0,5,0&iccEmbed=0, price=20.0]

But how do I show this as a JSP?


问:
Wordpress – post_per_page ignored on custom post type
following code is returning arbitrary 5 posts:

```<code>$args = array(
            'post_type'  => 'convenzioni',
            'post_per_page' => 10,
            'orderby' => 'post_title',
            'order' => 'ASC',
            'meta_query' => array(
                array(
                    'key'     => 'pinned',
                    'value'   => 1,
                    'compare' => '=',
                ),
            ),
        );
        $the_query = get_posts( $args );
</code>```

while it should return an higher number:

following code, confirms there are more and infact returns all the custom posts

```<code>$args = array(
            'post_type'  => 'convenzioni',
            'post_per_page' => -1,
            'orderby' => 'post_title',
            'order' => 'ASC',
            'nopaging' => true, //THANKS TO THIS!
            'meta_query' => array(
                array(
                    'key'     => 'pinned',
                    'value'   => 1,
                    'compare' => '=',
                ),
            ),
        );
        $the_query = get_posts( $args );
</code>```

what am I missing?

ty

Body:
following code is returning arbitrary 5 posts:

$args = array(
            'post_type'  => 'convenzioni',
            'post_per_page' => 10,
            'orderby' => 'post_title',
            'order' => 'ASC',
            'meta_query' => array(
                array(
                    'key'     => 'pinned',
                    'value'   => 1,
                    'compare' => '=',
                ),
            ),
        );
        $the_query = get_posts( $args );

while it should return an higher number:

following code, confirms there are more and infact returns all the custom posts

$args = array(
            'post_type'  => 'convenzioni',
            'post_per_page' => -1,
            'orderby' => 'post_title',
            'order' => 'ASC',
            'nopaging' => true, //THANKS TO THIS!
            'meta_query' => array(
                array(
                    'key'     => 'pinned',
                    'value'   => 1,
                    'compare' => '=',
                ),
            ),
        );
        $the_query = get_posts( $args );

what am I missing?

ty


问:
Chart JS invert axes and change line color
I am using Chart.js(1.0.2) to draw a double line-chart in AngularJS.
I have used the example from https://jtblin.github.io/angular-chart.js/
The chart is generated but I want to invert the Y and X-axis. I want the months on Y-axis and the numbers on X-axis. How can this be done?

I have also specified chart-colors="colors" but the default colors are still being used. How can I customize the line colors please? Thanks.

```<code><canvas id="line" class="chart chart-line" chart-data="data"
     chart-labels="labels" chart-series="series" chart-options="options"
     chart-colors="colors"
     chart-dataset-override="datasetOverride" chart-click="onClick">
</canvas>
</code>```
```<code>$scope.labels = ["January", "February", "March", "April", "May", "June", "July","August","September","October","November","December"];
$scope.series = ['Current Year', 'Previous Year'];
$scope.data = [
   [65, 59, 80, 81, 56, 55, 40, 28, 48, 40, 19, 86],
   [28, 48, 40, 19, 86, 27, 90, 22, 38, 43, 27, 120.5]
];
$scope.colors = ['#16347E', '#FEF27E'];

$scope.onClick = function (points, evt) {
   console.log(points, evt);
};
$scope.datasetOverride = [{ yAxisID: 'y-axis-1' }, { yAxisID: 'y-axis-2' }];
$scope.options = {
  scales: {
     yAxes: [
        {
          id: 'y-axis-1',
          type: 'linear',
          display: true,
          position: 'left'
         },
         {
          id: 'y-axis-2',
          type: 'linear',
          display: true,
          position: 'right'
         }
                ]
            }
        };
</code>```

Body:
I am using Chart.js(1.0.2) to draw a double line-chart in AngularJS.
I have used the example from https://jtblin.github.io/angular-chart.js/
The chart is generated but I want to invert the Y and X-axis. I want the months on Y-axis and the numbers on X-axis. How can this be done?

I have also specified chart-colors="colors" but the default colors are still being used. How can I customize the line colors please? Thanks.

<canvas id="line" class="chart chart-line" chart-data="data"
     chart-labels="labels" chart-series="series" chart-options="options"
     chart-colors="colors"
     chart-dataset-override="datasetOverride" chart-click="onClick">
</canvas>

$scope.labels = ["January", "February", "March", "April", "May", "June", "July","August","September","October","November","December"];
$scope.series = ['Current Year', 'Previous Year'];
$scope.data = [
   [65, 59, 80, 81, 56, 55, 40, 28, 48, 40, 19, 86],
   [28, 48, 40, 19, 86, 27, 90, 22, 38, 43, 27, 120.5]
];
$scope.colors = ['#16347E', '#FEF27E'];

$scope.onClick = function (points, evt) {
   console.log(points, evt);
};
$scope.datasetOverride = [{ yAxisID: 'y-axis-1' }, { yAxisID: 'y-axis-2' }];
$scope.options = {
  scales: {
     yAxes: [
        {
          id: 'y-axis-1',
          type: 'linear',
          display: true,
          position: 'left'
         },
         {
          id: 'y-axis-2',
          type: 'linear',
          display: true,
          position: 'right'
         }
                ]
            }
        };


问:
How to run a python function/file completely independent to the main process
Hi I am using Python version 2.7
OS - Windows
Libraries used (preferably solutions involving these if there are any),
Sys, os, subprocess, multiprocessing, threading

At the beginning of file one.py I need to start/create a new separate process and run the function observerLogFunc() (which is most likely from a different file i.e. file two.py).
I want that function to run Independently while file one.py and other python code continues to run.

For some background observerLogFunc() takes in the argument pid (pid= os.getpid()) and every 5 seconds checks if file one.py’s pid still exists, if it doesn't exist it returns and saves the calculated runtime of file one.py and its related processes.

The function will need to still be running after the main process has completed in order for it to record the processes and time and return the total time… how do I go about doing that?

Context - File one.py is used by 10 or so different files. For example (not going to go into too much detail) basically sometimes file one.py will run file a.py and other times it will run b.py etc, i need to measure the time of the process without having to edit all the a.py, b.py files and so on.
Ive ages experimenting trying and testing different things, spent hours and hours reading through documentation, previously asked questions, and many tutorials. Any help is highly appreciated thanks.

Here is a image describing the process I am after, hope that helps...

I have tried threading, subprocess module and daemon threads etc, problem with them is they all reply off the parent thread so they are not able to detect when that thread has ended because it terminates their process as well.'

I also tried a few command prompt solutions (using os.popen) to try and open up a new process through that but that didn't work either.

Like i said i spent lots and lots of time googling everything i could think of and reading through lots of tutorials and questions but none have seemed to work so far.


问:
dealing with Hibernate second level cache
I'm working on Java Spring project where we use Hibernate second level cache, Redisson is our cache region provider, by accessing a cache values by the following:

```<code>Collection<Object> mylist=redissonClient.getMapCache("regionName").readAllValues();
</code>```

and the output is something like this:

```<code>[read-write Item(CacheEntry(com.example.test.entities.myEntity))]
</code>```

How can I change the fully qualified class name "com.example.test.entities.myEntity" to be just captured as myEntity.

I need to unify the name because I have different sub-projects accessing the same cache and same classes and the fully qualified name for the same class differs from sub-project to another.

Body:
I'm working on Java Spring project where we use Hibernate second level cache, Redisson is our cache region provider, by accessing a cache values by the following:

Collection<Object> mylist=redissonClient.getMapCache("regionName").readAllValues();

and the output is something like this:

[read-write Item(CacheEntry(com.example.test.entities.myEntity))]

How can I change the fully qualified class name "com.example.test.entities.myEntity" to be just captured as myEntity.

I need to unify the name because I have different sub-projects accessing the same cache and same classes and the fully qualified name for the same class differs from sub-project to another.


问:
C# How to properly call/use .NET Framework 4.8 Windows Form
so i try to use a Windows Form (.NET Framework 4.8) RichTextBox as kind of Logger.
It is a fun project where i just want to have some inputs into it.

So, when i go into my Class (Also .NET Framework 4.8) and call the Class, i simply cannot edit or have inputs into the RichTextBox.

My other Class starts a Game Server for a Game. Whenever it started up, it should output something.

Example:

```<code>Console.WriteLine("[START] The Gaya Game Server has been started");
Console.WriteLine($"Time: {DateTime.Now}");
Form1 form = new Form1();
form.richTextBox1.Text = "[LOG] GAME SERVER HAS BEEN STARTED";
</code>```

i also tried

```<code>using (Form1 main = new Form1())
{
     main.richTextBox1.Text += "[LOG] GAME SERVER HAS BEEN STARTED";
}
</code>```

I always start the Windows Form first before starting my Game Server Console, so there'S no issue.
How do i make sure to call it and make an entry?

Thank you very much!

```<code>Console.WriteLine("[START] The Gaya Game Server has been started");
Console.WriteLine($"Time: {DateTime.Now}");
Form1 form = new Form1();
form.richTextBox1.Text = "[LOG] GAME SERVER HAS BEEN STARTED";
</code>```

Body:
so i try to use a Windows Form (.NET Framework 4.8) RichTextBox as kind of Logger.
It is a fun project where i just want to have some inputs into it.

So, when i go into my Class (Also .NET Framework 4.8) and call the Class, i simply cannot edit or have inputs into the RichTextBox.

My other Class starts a Game Server for a Game. Whenever it started up, it should output something.

Example:

Console.WriteLine("[START] The Gaya Game Server has been started");
Console.WriteLine($"Time: {DateTime.Now}");
Form1 form = new Form1();
form.richTextBox1.Text = "[LOG] GAME SERVER HAS BEEN STARTED";

i also tried

using (Form1 main = new Form1())
{
     main.richTextBox1.Text += "[LOG] GAME SERVER HAS BEEN STARTED";
}

I always start the Windows Form first before starting my Game Server Console, so there'S no issue.
How do i make sure to call it and make an entry?

Thank you very much!

Console.WriteLine("[START] The Gaya Game Server has been started");
Console.WriteLine($"Time: {DateTime.Now}");
Form1 form = new Form1();
form.richTextBox1.Text = "[LOG] GAME SERVER HAS BEEN STARTED";


问:
Flutter Browser App - set default startup page
I have the Flutter Browser App up and running and I'm trying to change the startup url.

https://github.com/pichillilorenzo/flutter_browser_app

Can someone point me in the right direction?


问:
mock psycopg2 fetchone and fetchall to return different dataset doesn't work
I'm trying to mock fetchone/fetchall to return different data set for different cases within a suite but it seems the first mock is global and can't be overwritten. All I get for the subsequent tests is the same value.

The first test case which sets up the mock:

```<code>def test_rejected_scenario():
    with mock.patch('psycopg2.connect') as mock_connect:
        mock_con = mock_connect.return_value
        mock_cursor = mock_con.cursor.return_value
        mock_cursor.fetchall.return_value = REQUESTS
        mock_cursor.fetchone.return_value = REQUESTS[0]
        response = handler()
        assert response["statusCode"] == 200
</code>```

All the subsequent tests will get REQUESTS for fetchall() and REQUESTS[0] for fetchone() no matter how the mock is set up.

This question is about setting different return data set between test cases. Setting mock for individual case works for me.

Body:
I'm trying to mock fetchone/fetchall to return different data set for different cases within a suite but it seems the first mock is global and can't be overwritten. All I get for the subsequent tests is the same value.

The first test case which sets up the mock:

def test_rejected_scenario():
    with mock.patch('psycopg2.connect') as mock_connect:
        mock_con = mock_connect.return_value
        mock_cursor = mock_con.cursor.return_value
        mock_cursor.fetchall.return_value = REQUESTS
        mock_cursor.fetchone.return_value = REQUESTS[0]
        response = handler()
        assert response["statusCode"] == 200

All the subsequent tests will get REQUESTS for fetchall() and REQUESTS[0] for fetchone() no matter how the mock is set up.

This question is about setting different return data set between test cases. Setting mock for individual case works for me.


问:
Python - Dynamic Buttons + Run rest of Shell based on outcome
I have a df which is very dynamic.

```<code>df

Col1    Col2
AAAA    1000000
BBBB    500000
CCCC    250000
DDDD    125000
</code>```

What I am trying to achieve is to

Run the Python Shell,

A separate Window comes up, with the df information.

User chooses/selects one or multiple information from COL1.

Based on selection the shell runs the rest of the code.

I looked into PySimpleGui and tkinter, but cant find a solution.

Hope this helps.

Body:
I have a df which is very dynamic.

df

Col1    Col2
AAAA    1000000
BBBB    500000
CCCC    250000
DDDD    125000

What I am trying to achieve is to

Run the Python Shell,

A separate Window comes up, with the df information.

User chooses/selects one or multiple information from COL1.

Based on selection the shell runs the rest of the code.

I looked into PySimpleGui and tkinter, but cant find a solution.

Hope this helps.


问:
Developing a music live stream site using reactjs and drf
when a song (div) is clicked on and currently playing, i add a "play" to the class list. when the user clicks on another song i want to remove that play from the initial div (song) that was clicked on and add it to the current div that was click ASAP. Also when the song is been played i'm having a delay in response, like i'd have to click twice first click will fetch the song then the second click will then play it. how can i rectify it so when i click once everything fetches and plays asap. i have used the fetch function and applied a call back yet still having same issues.</p>
```<code> const audio=document.querySelector('#audio')
const music_container=document.querySelector('#music_container')

const [image, setImage]=useState('')
const [posts, setPosts]=useState([])
const [icon,setIcon]=useState(faPlay)
const[playing,setPlaying]=useState(false)
const[music,setMusic]=useState('')
const[audioUrl,setAudioUrl]=useState('')

// const progress=useRef()
const[progress,SetCurrentProgress]=useState(0)

    function getAllPosts(){
        fetch(`http://127.0.0.1:8000/`)
        .then(response=>response.json())
        .then(data=>{
            // console.log(data)
            setPosts(data)
        })

    }
    // console.log(posts.artist_name)

// LOAD ALL POSTS
        // function soundrimage(){
        //     // setImage(music_img)

        // }

        useEffect(()=>{
            getAllPosts()
            // console.log(this)
        },[])

// LOAD AND CONTROL MUSIC
            function playSong(e){
                // music_audio=music.`http://127.0.0.1:8000${audio}`

                e.target.classList.add('play')
                setIcon(faPause)
                setPlaying(true)
                audio.play()

            }

            function pauseSong(e){

                e.target.classList.remove('play')
                setIcon(faPlay)
                setPlaying(true)
                console.log(music.audio)
                audio.pause()

            }

        function playPause(e){

            let isplaying=e.target.classList.contains('play')

                if(isplaying){
                    pauseSong(e)
                }else{
                    playSong(e)
                }

        }

        const UpdateProgress=(e)=>{
            // console.log(e.target.duration)
            const {duration,currentTime}=e.target

            const ProgressPercent=(currentTime/duration)*100

            SetCurrentProgress(`${ProgressPercent}`)

        }

    const setAudioSrc=(e)=>{
        // setAudioUrl(`http://127.0.0.1:8000/${e.target.id}/`)

        fetch(`http://127.0.0.1:8000/${e.target.id}/`).then(
            response=>response.json()
            ).then(data=>{
            // console.log(data)
            setMusic(data)

            // if(e.target === e.currentTarget){
            e.target.nextSibling.id='audio'

            // }else{
            //     e.target.nextSibling.id=' '
            // }

            playPause(e)
            })

        // console.log(e.target.nextSibling.id)

    }
        // console.log(progress.current)

        const setProgress=(e)=>{
            const width=e.target.clientWidth
            // console.log(e)
            const clickX=e.nativeEvent.offsetX
            // console.log(clickX)
            const duration=audio.duration
            // console.log(duration)

            audio.currentTime=(clickX/width)*duration

        }

    // MUSIC INFO
    // const music_image= document.querySelector("#music_image")

return(
    <body>

        <Navbar/>
        <main className="landing">

    {posts.map((post,i)=>(

        <div className="music_holder" key={i}>

                <div className="music_container" >

                    <img  className="music_image"

                    // onMouseEnter={e=>setAudioSrc(e)}
                    // onMouseLeave={()=>{
                    //     setAudioUrl('')
                    // }}
                    onClick={(e)=>{playPause(e)}}
                    src={'http://127.0.0.1:8000'+post.image} />

                    {/* <button >
                        <FontAwesomeIcon icon={icon} onClick={(e)=>{playPause(e)}}   id="playBtn"  />
                    </button> */}

                    <div className="music_overlay"
                    id={post.id}

                    // onMouseEnter={e=>setAudioSrc(e)}
                    // onMouseLeave={(e)=>{
                    //     // setAudioUrl('')
                    //     e.target.nextSibling.id=' '
                    // }}
                    onClick={e=>setAudioSrc(e)}
                    ></div>

                    <audio src={music.audio} id="" onTimeUpdate={e=>UpdateProgress(e)}/>

                    </div>

                <div className="caption_holder">
                    <p className="caption">{post.title}</p>
                </div>

            </div>

                )

            )}
</code>```

Body:
when a song (div) is clicked on and currently playing, i add a "play" to the class list. when the user clicks on another song i want to remove that play from the initial div (song) that was clicked on and add it to the current div that was click ASAP. Also when the song is been played i'm having a delay in response, like i'd have to click twice first click will fetch the song then the second click will then play it. how can i rectify it so when i click once everything fetches and plays asap. i have used the fetch function and applied a call back yet still having same issues.

 const audio=document.querySelector('#audio')
const music_container=document.querySelector('#music_container')

const [image, setImage]=useState('')
const [posts, setPosts]=useState([])
const [icon,setIcon]=useState(faPlay)
const[playing,setPlaying]=useState(false)
const[music,setMusic]=useState('')
const[audioUrl,setAudioUrl]=useState('')

// const progress=useRef()
const[progress,SetCurrentProgress]=useState(0)

    function getAllPosts(){
        fetch(`http://127.0.0.1:8000/`)
        .then(response=>response.json())
        .then(data=>{
            // console.log(data)
            setPosts(data)
        })

    }
    // console.log(posts.artist_name)

// LOAD ALL POSTS
        // function soundrimage(){
        //     // setImage(music_img)

        // }

        useEffect(()=>{
            getAllPosts()
            // console.log(this)
        },[])

// LOAD AND CONTROL MUSIC
            function playSong(e){
                // music_audio=music.`http://127.0.0.1:8000${audio}`

                e.target.classList.add('play')
                setIcon(faPause)
                setPlaying(true)
                audio.play()

            }

            function pauseSong(e){

                e.target.classList.remove('play')
                setIcon(faPlay)
                setPlaying(true)
                console.log(music.audio)
                audio.pause()

            }

        function playPause(e){

            let isplaying=e.target.classList.contains('play')

                if(isplaying){
                    pauseSong(e)
                }else{
                    playSong(e)
                }

        }

        const UpdateProgress=(e)=>{
            // console.log(e.target.duration)
            const {duration,currentTime}=e.target

            const ProgressPercent=(currentTime/duration)*100

            SetCurrentProgress(`${ProgressPercent}`)

        }

    const setAudioSrc=(e)=>{
        // setAudioUrl(`http://127.0.0.1:8000/${e.target.id}/`)

        fetch(`http://127.0.0.1:8000/${e.target.id}/`).then(
            response=>response.json()
            ).then(data=>{
            // console.log(data)
            setMusic(data)

            // if(e.target === e.currentTarget){
            e.target.nextSibling.id='audio'

            // }else{
            //     e.target.nextSibling.id=' '
            // }

            playPause(e)
            })

        // console.log(e.target.nextSibling.id)

    }
        // console.log(progress.current)

        const setProgress=(e)=>{
            const width=e.target.clientWidth
            // console.log(e)
            const clickX=e.nativeEvent.offsetX
            // console.log(clickX)
            const duration=audio.duration
            // console.log(duration)

            audio.currentTime=(clickX/width)*duration

        }

    // MUSIC INFO
    // const music_image= document.querySelector("#music_image")

return(

        <Navbar/>

    {posts.map((post,i)=>(

                    setAudioSrc(e)}
                    // onMouseLeave={()=>{
                    //     setAudioUrl('')
                    // }}
                    onClick={(e)=>{playPause(e)}}
                    src={'http://127.0.0.1:8000'+post.image} />

                    {/* <button >
                        <FontAwesomeIcon icon={icon} onClick={(e)=>{playPause(e)}}   id="playBtn"  />
                    </button> */}

setAudioSrc(e)}
                    // onMouseLeave={(e)=>{
                    //     // setAudioUrl('')
                    //     e.target.nextSibling.id=' '
                    // }}
                    onClick={e=>setAudioSrc(e)}
                    >

                    <audio src={music.audio} id="" onTimeUpdate={e=>UpdateProgress(e)}/>

{post.title}

                )

            )}


问:
CloudBuild - GitHub - Expected — Waiting for status to be reported
GitHub settingsPR status check

Hello everyone, I started getting an error getting status from CloudBuild, although some PRs  still work fine. What could be wrong? I have already checked all the settings and can't find the problem

Check all GCP settings
Changed Status check in GitHub


问:
Issue while Customer tries to place order because of 3D Secure
We are using Opayo Sagepay on our website for payment. It works fine for most orders, but some customers face issues related to 3D security. Customers complain that when they try to place an order using the Opayo Sagepay Credit/Debit card method, they are not redirected to the 3D secure page and the cart is empty. We have seen that a large number of customers are facing this issue but not all.

Has anyone of you faced this kind of issue? Please let me know.


问:
How to make few routes use app.register(require("fastify-multipart"), { addToBody: true }); and other use app.register(require("fastify-multipart"))
I am trying to send image in multipart form data for few routes because I wish to use
request.multipart  function.

I have used app.register(require("fastify-multipart") ), { addToBody: true }) for all routes but for routes having image (starting like /image/*) I want to get multipart data not in body.

please guide me to get the solution for this, I am trying this for quite some time now but didn't find any solution.

```<code>//creating fastify server and add below plugin
app.register(require("fastify-multipart"), { addToBody: true });
</code>```
```<code>app.get("/health", (_, reply) => reply.send("Congratulations! reverse proxy is working....."));

app.route({
  method: ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"],
  url: "*",
  handler: handler,
})

</code>```

handler for /image/upload is

```<code>handler : async (request) => {
 const formData = new FormData();
    const multipart = request.multipart(async (field, stream, filename, encoding, mimetype) => {
      formData.append('image', stream);

  try {

        const data = await axios.post(`http:127.0.0.1:80/downstream`, formData, config )
        console.log("upload success with url", data)
      }
      catch(e) {
          console.log(`An error occurred during upload: ${e.message}`)
           reply.code(500).send()
      }
  }, (error) => {

      if(error) {
          console.log(`Error uploading file: ${error.message}`)
           reply.code(500).send()
      }
  })
}
</code>```

this above handler work when I remove { addToBody: true } from app.register(require("fastify-multipart"), { addToBody: true }) plugin i.e app.register(require("fastify-multipart")) because req.multipart handler only works on stream that's why adding image to body doesn't work.

Body:
I am trying to send image in multipart form data for few routes because I wish to use
request.multipart  function.

I have used app.register(require("fastify-multipart") ), { addToBody: true }) for all routes but for routes having image (starting like /image/*) I want to get multipart data not in body.

please guide me to get the solution for this, I am trying this for quite some time now but didn't find any solution.

//creating fastify server and add below plugin
app.register(require("fastify-multipart"), { addToBody: true });

app.get("/health", (_, reply) => reply.send("Congratulations! reverse proxy is working....."));

app.route({
  method: ["DELETE", "GET", "HEAD", "PATCH", "POST", "PUT"],
  url: "*",
  handler: handler,
})

handler for /image/upload is

handler : async (request) => {
 const formData = new FormData();
    const multipart = request.multipart(async (field, stream, filename, encoding, mimetype) => {
      formData.append('image', stream);

  try {

        const data = await axios.post(`http:127.0.0.1:80/downstream`, formData, config )
        console.log("upload success with url", data)
      }
      catch(e) {
          console.log(`An error occurred during upload: ${e.message}`)
           reply.code(500).send()
      }
  }, (error) => {

      if(error) {
          console.log(`Error uploading file: ${error.message}`)
           reply.code(500).send()
      }
  })
}

this above handler work when I remove { addToBody: true } from app.register(require("fastify-multipart"), { addToBody: true }) plugin i.e app.register(require("fastify-multipart")) because req.multipart handler only works on stream that's why adding image to body doesn't work.


问:
Chrome Extension WebRequest API OnBeforeRequest not capturing PATCH method body
Chrome extension, chrome.webRequest.onBeforeRequest captures only POST and PUT method body.
is there any way to capture body of PATCH method?

I am expecting to capture PATCH and DELETE request body using chrome webrequest API, or do I have to use debugger api?


问:
WebSocket's in OpenAPI documentation
Based on the following https://swagger.io/docs/specification/api-host-and-base-path/ it seems that we can use wss:// and ws:// schemas in OpenAPI documentation.

So, I am just wondering how to represent requests and responses and the source of request because I don't find answers for below points.

There is nothing like GET, POST in websocket right? Should I assume all as POST?

Source of request should be represented, if it is server or client who is making request to who.

Not able to find any examples too for the websocket in Open API format or any other format that I am aware of.

Title: WebSocket's in OpenAPI documentation


问:
React typescript getting a number not found error, when adding points?
I am trying to add points to an points in an object in my array. I have a league table where I declare here in App.tsx and I also add teams to the league table which seems to be fine:

```<code>interface Team {

  id: number;
  label:string;
  points:number;
  wins:number;
  draws:number;
  lost:number;

}
const teams: Team[] = [
  { id: 1, label: "team1", points: 0, wins: 0, draws: 0, lost: 0 },
  { id: 2, label: "team2", points: 0, wins: 0, draws: 0, lost: 0 },
  { id: 3, label: "team3", points: 0, wins: 0, draws: 0, lost: 0 },
  { id: 4, label: "team4", points: 0, wins: 0, draws: 0, lost: 0 },
];

function App() {
  const [points, setPoints] = useState(teams);

  const addPointsHandler = (id: number) => {
    setPoints(
      points.map((point) => {
        //first I will get the point object
        if (point.id === id) {
          //copy everything in the point object, add a new property of points to update the object
          return {
            ...point,
            points: point.points,
            wins: point.wins,
            lost: point.lost,
            draw: point.draws,
          };
        } else {
          return point;
        }
      })
    );
  };

  const insertTeam = (team: any) => {
    setPoints((prevTeams) => {
      return [team, ...prevTeams];
    });
  };
</code>```

In Newscore.tsx, if the number of goals team1 scores is greater than team2 then I add 3 points to the team, with wins and losses etc. My issue is that when I try to add 3 points with team1.points += 3, it gives an error under the word points as,' property 'points' does not exist under number', the same with wins and lost as well. Even though when I debug to return team I can see points as a property.This was working when I had it as a jsx file before

```<code> const NewScore = (props:any) => {
      const [goalsTeam1, setGoalsTeam1] = useState(0);
      const [goalsTeam2, setGoalsTeam2] = useState(0);
      const [team1, setTeam1] = useState(0);
      const [team2, setTeam2] = useState(0);

      const submitScore = (event:any) => {
        event.preventDefault();

        if (Number(goalsTeam1) > Number(goalsTeam2)) {
        //getting a number not found
        **team1.points+=3**
        team1.wins[0] += 1;
        team2.lost[0] += 1;

        props.addPoints();
      };
</code>```

Body:
I am trying to add points to an points in an object in my array. I have a league table where I declare here in App.tsx and I also add teams to the league table which seems to be fine:

interface Team {

  id: number;
  label:string;
  points:number;
  wins:number;
  draws:number;
  lost:number;

}
const teams: Team[] = [
  { id: 1, label: "team1", points: 0, wins: 0, draws: 0, lost: 0 },
  { id: 2, label: "team2", points: 0, wins: 0, draws: 0, lost: 0 },
  { id: 3, label: "team3", points: 0, wins: 0, draws: 0, lost: 0 },
  { id: 4, label: "team4", points: 0, wins: 0, draws: 0, lost: 0 },
];

function App() {
  const [points, setPoints] = useState(teams);

  const addPointsHandler = (id: number) => {
    setPoints(
      points.map((point) => {
        //first I will get the point object
        if (point.id === id) {
          //copy everything in the point object, add a new property of points to update the object
          return {
            ...point,
            points: point.points,
            wins: point.wins,
            lost: point.lost,
            draw: point.draws,
          };
        } else {
          return point;
        }
      })
    );
  };

  const insertTeam = (team: any) => {
    setPoints((prevTeams) => {
      return [team, ...prevTeams];
    });
  };

In Newscore.tsx, if the number of goals team1 scores is greater than team2 then I add 3 points to the team, with wins and losses etc. My issue is that when I try to add 3 points with team1.points += 3, it gives an error under the word points as,' property 'points' does not exist under number', the same with wins and lost as well. Even though when I debug to return team I can see points as a property.This was working when I had it as a jsx file before

 const NewScore = (props:any) => {
      const [goalsTeam1, setGoalsTeam1] = useState(0);
      const [goalsTeam2, setGoalsTeam2] = useState(0);
      const [team1, setTeam1] = useState(0);
      const [team2, setTeam2] = useState(0);

      const submitScore = (event:any) => {
        event.preventDefault();

        if (Number(goalsTeam1) > Number(goalsTeam2)) {
        //getting a number not found
        **team1.points+=3**
        team1.wins[0] += 1;
        team2.lost[0] += 1;

        props.addPoints();
      };


问:
apache 2.4 rewriterule redirect regex matching letters, but not matching dot
I have a nodejs application that uses django application as a websocket and REST API server. Since I developed using node-http-proxy, I am trying to deploy using the same setup.

if /api is in REQUEST_URI, it should be proxied to rest server's /api.

If /api/ws is in REQUEST_URI, it should be proxied to websockets server's /api/ws.

If we are reading a deployed file, it should be served directly.

If we are going to any URI other than /api that is not a file it should just redirect to /

This last statement is needed because refreshing a react route generated URI causes 404.

I wrote the following virtual host, but the rewrite rule doesn't capture /dashboard

```<code>Listen 0.0.0.0:3001

<VirtualHost *:3001>
        ServerName site.example.com
        DocumentRoot /var/www/site.example.com
        ProxyRequests on
        ProxyPass /api/ws ws://127.0.0.1:8081/api/ws
        ProxyPassReverse /api/ws ws://127.0.0.1:8081/api/ws
        ProxyPass /api http://127.0.0.1:8081/api
        ProxyPassReverse /api http://127.0.0.1:8081/api

        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-l
        RewriteCond %{REQUEST_URI} !^/api.*$
        RewriteRule ^/(.+)$ / [L,R]
</VirtualHost>
</code>```

But somehow the redirect rule fails to match non-API urls

If I replace

```<code>  RewriteRule ^/(.+)$ / [L,R]
</code>```

with

```<code>  RewriteRule ^/([a-z]+)$ / [L,R]
</code>```

then it captures /dashboard and redirects to / correctly.

The question is: why doesn't /dashboard match .+ while it matches [a-z]+ ?

Body:
I have a nodejs application that uses django application as a websocket and REST API server. Since I developed using node-http-proxy, I am trying to deploy using the same setup.

if /api is in REQUEST_URI, it should be proxied to rest server's /api.

If /api/ws is in REQUEST_URI, it should be proxied to websockets server's /api/ws.

If we are reading a deployed file, it should be served directly.

If we are going to any URI other than /api that is not a file it should just redirect to /

This last statement is needed because refreshing a react route generated URI causes 404.

I wrote the following virtual host, but the rewrite rule doesn't capture /dashboard

Listen 0.0.0.0:3001

<VirtualHost *:3001>
        ServerName site.example.com
        DocumentRoot /var/www/site.example.com
        ProxyRequests on
        ProxyPass /api/ws ws://127.0.0.1:8081/api/ws
        ProxyPassReverse /api/ws ws://127.0.0.1:8081/api/ws
        ProxyPass /api http://127.0.0.1:8081/api
        ProxyPassReverse /api http://127.0.0.1:8081/api

        RewriteEngine on
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteCond %{REQUEST_FILENAME} !-l
        RewriteCond %{REQUEST_URI} !^/api.*$
        RewriteRule ^/(.+)$ / [L,R]
</VirtualHost>

But somehow the redirect rule fails to match non-API urls

If I replace

  RewriteRule ^/(.+)$ / [L,R]

with

  RewriteRule ^/([a-z]+)$ / [L,R]

then it captures /dashboard and redirects to / correctly.

The question is: why doesn't /dashboard match .+ while it matches [a-z]+ ?


问:
.NET6 - Integration test with Entity Framework Core gives tracking error
I've created an AppFactory class which is used by all test classes through IClassFixture to setup a consistent startpoint for all the test classes. Every test class gets it's own docker database, through the use of the TestContainer package.

```<code>private readonly TestcontainerDatabase _dbContainer =
    new TestcontainersBuilder<PostgreSqlTestcontainer>()
        .WithDatabase(new PostgreSqlTestcontainerConfiguration
        {
            Database = "integration_test",
            Username = "integration_test",
            Password = "integration_test"
        })
        .Build();
</code>```
```<code>builder.ConfigureTestServices(services =>
{
    services.RemoveAll(typeof(IHostedService));

    services.RemoveDbContext<ApplicationDbContext>();
    services.RemoveAll<DbContext>();

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(_dbContainer.ConnectionString)
    );
</code>```

This Appfactory inherits from WebApplicationFactory<IAppMarker>, IAsyncLifetime. In the InitializeAsync of the AppFactory I seed the database. However when more then 1 class is testing in parallel I get issues with the tracking of Entityframework. Even though every test class has it's own database.

```<code>System.InvalidOperationException The instance of entity type 'Country' cannot be tracked because
another instance with the same key value for {'Id'} is already being tracked.
When attaching existing entities, ensure that only one entity instance with a given
key value is attached.
</code>```

I've tried adding context.ChangeTracker.Clear(); to the seeder, which decreases the chance of the error occuring, but it can still occur. I expect entity framework to create a different tracker for each test class/database, so that this error does not occur.

I've also tried to create a new context for each test with AddDbContextFactory however this also has had no effect.

Body:
I've created an AppFactory class which is used by all test classes through IClassFixture to setup a consistent startpoint for all the test classes. Every test class gets it's own docker database, through the use of the TestContainer package.

private readonly TestcontainerDatabase _dbContainer =
    new TestcontainersBuilder<PostgreSqlTestcontainer>()
        .WithDatabase(new PostgreSqlTestcontainerConfiguration
        {
            Database = "integration_test",
            Username = "integration_test",
            Password = "integration_test"
        })
        .Build();

builder.ConfigureTestServices(services =>
{
    services.RemoveAll(typeof(IHostedService));

    services.RemoveDbContext<ApplicationDbContext>();
    services.RemoveAll<DbContext>();

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseNpgsql(_dbContainer.ConnectionString)
    );

This Appfactory inherits from WebApplicationFactory<IAppMarker>, IAsyncLifetime. In the InitializeAsync of the AppFactory I seed the database. However when more then 1 class is testing in parallel I get issues with the tracking of Entityframework. Even though every test class has it's own database.

System.InvalidOperationException The instance of entity type 'Country' cannot be tracked because
another instance with the same key value for {'Id'} is already being tracked.
When attaching existing entities, ensure that only one entity instance with a given
key value is attached.

I've tried adding context.ChangeTracker.Clear(); to the seeder, which decreases the chance of the error occuring, but it can still occur. I expect entity framework to create a different tracker for each test class/database, so that this error does not occur.

I've also tried to create a new context for each test with AddDbContextFactory however this also has had no effect.


问:
Access update query formula- Minimum date from multiple criteria
I have created an Access update query and input the below formula in the field "Update to";

IIf(IsNull([Rule2 mapping]![MBO Hier]),"Check",IIf(IsNull([Final_Data]![Start Date]),"Check",IIf([Final_Data]![Start Date]>FixDate2(),IIf((GetReportingDate()-[Final_Data]![Start Date])>(36554),([Final_Data]![Start Date]+36555+4),IIf((GetReportingDate()-[Final_Data]![Start Date])>(36553),([Final_Data]![Start Date]+36554+4),IIf((GetReportingDate()-[Final_Data]![Start Date])>(36552),([Final_Data]![Start Date]+36553+4),IIf((GetReportingDate()-[Final_Data]![Start Date])>(3655),([Final_Data]![Start Date]+36552+4),IIf(([Final_Data]![Start Date]+3655)<[Final_Data]![Maturity Date],([Final_Data]![Start Date]+365*5+4),[Final_Data]![Maturity Date]))))),"Check")))

I would like to add a condition of minimum date as Maturity Date wherever the criteria condition is "True". Access is giving me erratic results. Please help me in adding minimum of Maturity date or [Final_Data]![Start Date]+3655xx

I tried to derive the minimum date using DMIN function but Access threw erratic results


问:
firebase function which uses google drive api will run locally but will not deploy
I have a firebase cloud function which calls the google drive api to obtain a list of the files in the drive (i want this to change so it accepts a folder id as a parameter), and returns the list of files. When i do npm run serve, the function works as expected and displays the list, but when i try to deploy to firebase functions i get an error saying "There was an error deploying functions" and I can not see any detail as to why it is not deploying.
code

Terminal output:

when deployed locally correct data is displayed, however will not deploy


问:
Remove "SELECT version();" query in Typeorm
I am using TypeORM in a AWS Lambda function and I am trying to optimise the performance of the Lambda function.

After enabling logging in TypeORM, I always see this query in the log:

```<code>INFO query: SELECT version();
</code>```

...that seems to be done by TypeORM to check if the version of PostgreSQL supports generated columns:

        const results = (await this.executeQuery(
            connection,
            "SELECT version();",
        )) as {
            rows: {
                version: string
            }[]
        }
        const versionString = results.rows[0].version.replace(
            /^PostgreSQL ([\d\.]+) .*$/,
            "$1",
        )
        this.version = versionString
        this.isGeneratedColumnsSupported = VersionUtils.isGreaterOrEqual(
            versionString,
            "12.0",
        )
```

https://github.com/typeorm/typeorm/blob/2473ff0a8eca2fafffdabd6fa4cc46b76347f0c2/src/driver/postgres/PostgresDriver.ts#L370

Now my question is: Is it possible to disable this check or cache the result or hardcode the value once for all to avoid this query every time we do run a DB query?

Thanks a lot.

Body:
I am using TypeORM in a AWS Lambda function and I am trying to optimise the performance of the Lambda function.

After enabling logging in TypeORM, I always see this query in the log:

INFO query: SELECT version();

...that seems to be done by TypeORM to check if the version of PostgreSQL supports generated columns:

        const results = (await this.executeQuery(
            connection,
            "SELECT version();",
        )) as {
            rows: {
                version: string
            }[]
        }
        const versionString = results.rows[0].version.replace(
            /^PostgreSQL ([\d\.]+) .*$/,
            "$1",
        )
        this.version = versionString
        this.isGeneratedColumnsSupported = VersionUtils.isGreaterOrEqual(
            versionString,
            "12.0",
        )

https://github.com/typeorm/typeorm/blob/2473ff0a8eca2fafffdabd6fa4cc46b76347f0c2/src/driver/postgres/PostgresDriver.ts#L370

Now my question is: Is it possible to disable this check or cache the result or hardcode the value once for all to avoid this query every time we do run a DB query?

Thanks a lot.


问:
Extra parameters to be updated in back propagation of Neural Network in Keras
I'm working on a MIDAS regression approach to Neural Networks. I use the exponential almon lag function to preprocess my high frequency data and use the processed data as input for my neural network using Keras. However, the exponential almon lag takes two parameters to determine the shape of the polynomial theta_1 and theta_2. However, I want to incorporate this function in the back propagation scheme of the Neural Network. Is there a way to update these parameters as the model is training? The function I use for the exponential almon lag looks as follows:

```<code>def exp_almon_lag(data, theta_1, theta_2):
    # Load the data
    df = data

    # Transform the data to 4 weekly sets
    data_transposed = []

    for i in range(int(len(df)/4)):
        array = [df.iloc[(i*4),0], df.iloc[(i*4+1),0], df.iloc[(i*4+2),0], df.iloc[(i*4+3),0]]
        data_transposed.append(array)

    # For k = 4 the exponential almon lag values are
    lag_1 = np.exp(theta_1 * 1 + theta_2 * 1 ** 2)
    lag_2 = np.exp(theta_1 * 2 + theta_2 * 2 ** 2)
    lag_3 = np.exp(theta_1 * 3 + theta_2 * 3 ** 2)
    lag_4 = np.exp(theta_1 * 4 + theta_2 * 4 ** 2)

    denominator = lag_1 + lag_2 + lag_3 + lag_4

    # Store lag operator values in an array
    almon_values = [(lag_1 / denominator), (lag_2 / denominator),
                    (lag_3 / denominator), (lag_4 / denominator)]

    processed_data = []

    for i in range(len(data_transposed)):
        processed_data.append(np.multiply(data_transposed[i], almon_values).sum())

    return processed_data
</code>```

At the moment I use this function to preprocess the data, but I want the theta values to be updated by the network as well.

Body:
I'm working on a MIDAS regression approach to Neural Networks. I use the exponential almon lag function to preprocess my high frequency data and use the processed data as input for my neural network using Keras. However, the exponential almon lag takes two parameters to determine the shape of the polynomial theta_1 and theta_2. However, I want to incorporate this function in the back propagation scheme of the Neural Network. Is there a way to update these parameters as the model is training? The function I use for the exponential almon lag looks as follows:

def exp_almon_lag(data, theta_1, theta_2):
    # Load the data
    df = data

    # Transform the data to 4 weekly sets
    data_transposed = []

    for i in range(int(len(df)/4)):
        array = [df.iloc[(i*4),0], df.iloc[(i*4+1),0], df.iloc[(i*4+2),0], df.iloc[(i*4+3),0]]
        data_transposed.append(array)

    # For k = 4 the exponential almon lag values are
    lag_1 = np.exp(theta_1 * 1 + theta_2 * 1 ** 2)
    lag_2 = np.exp(theta_1 * 2 + theta_2 * 2 ** 2)
    lag_3 = np.exp(theta_1 * 3 + theta_2 * 3 ** 2)
    lag_4 = np.exp(theta_1 * 4 + theta_2 * 4 ** 2)

    denominator = lag_1 + lag_2 + lag_3 + lag_4

    # Store lag operator values in an array
    almon_values = [(lag_1 / denominator), (lag_2 / denominator),
                    (lag_3 / denominator), (lag_4 / denominator)]

    processed_data = []

    for i in range(len(data_transposed)):
        processed_data.append(np.multiply(data_transposed[i], almon_values).sum())

    return processed_data

At the moment I use this function to preprocess the data, but I want the theta values to be updated by the network as well.


问:
Docker Compose build success on local but getting forbidden path outside the build context on Github Action
I hope you all are doing well.

In My project i'm using turborepo, my project structure is like this

```<code>- apps/service1/Dockerfile
- docker-compose.yaml
</code>```

In my docker file i did

```<code>COPY ../../ .
</code>```

in my docker comopse file i did

```<code>build:
  context: .
  dockerfile: apps/service1/Dockerfile
</code>```

when i build it in my local pc, there are no issue, but when i try to build it on github action thne i get this error

```<code>COPY failed: forbidden path outside the build context: ../../ ()
</code>```

I check both github action and my local docker version they are both in 20.

So what is the issue now ? what i'm missing ?

Body:
I hope you all are doing well.

In My project i'm using turborepo, my project structure is like this

- apps/service1/Dockerfile
- docker-compose.yaml

In my docker file i did

COPY ../../ .

in my docker comopse file i did

build:
  context: .
  dockerfile: apps/service1/Dockerfile

when i build it in my local pc, there are no issue, but when i try to build it on github action thne i get this error

COPY failed: forbidden path outside the build context: ../../ ()

I check both github action and my local docker version they are both in 20.

So what is the issue now ? what i'm missing ?


问:
Pull Data from Spreadsheet but only Display the Last Four Digits Using Apps Script
I use Apps Script to pull data from Google Spreadsheets and then Display the data on an HTML page in a table format.

I am trying to hide the data that is pulled from the spreadsheet and displayed on the table but make the last four digits of the data to be visible.

I tried the JS code below and it works fine on HTML pages but the JS code doesn't work when I tried to apply it to Apps Script probably because the HTML page has its table value typed as text in the cells while Apps Script needs to pull its table value from the spreadsheet before applying the rule from the JS code to the data to hide it and only display the last four digits of the data.

Any help to understand how to apply the script below to Apps Script to hide data but show the last four digits will be appreciated.

JS and HTML Code Below;

var id_number = document.getElementById('data2');
id_number.innerHTML = new Array(id_number.innerHTML.length-3).join('x') +
id_number.innerHTML.substr(id_number.innerHTML.length-4, 4);
console.log(id_number.innerHTML);

var phone = document.getElementById('data3');
phone.innerHTML = new Array(phone.innerHTML.length-3).join('x') +
phone.innerHTML.substr(phone.innerHTML.length-4, 4);
console.log(phone.innerHTML);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>

              <tr>
                    <td width = "120">ID NUMBER</td>
                    <td width = "15">:</td>
                    <td id="data2" class="hidetext">1234567890</td>
                  </tr>

                  <tr>
                    <td>PHONE</td>
                    <td>:</td>
                    <td id="data3" class="hidetext">0000000000</td>
                  </tr>

</table></code>```

My Code.gs Code in Apps Script Below;

```<code>function doGet(e) {
  return HtmlService.createTemplateFromFile("index").evaluate()
  .setTitle("HTML DATA PAGE")
  .addMetaTag('viewport', 'width=device-width, initial-scale=1')
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
};

let ss = SpreadsheetApp.getActiveSpreadsheet();
function getData(keyword){
  let sheet = ss.getSheetByName('Data');
  let data = sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).getDisplayValues();
  let index = data.map(d => d[2]).indexOf(keyword);
  console.log(data);
  console.log(data.map(d => d[2]));
  console.log(index);
  if(index > -1){
    return data[index];
  }else{
    return undefined;
  }

}

let url = ScriptApp.getService().getUrl();
</code>```

My Apps Script Table Code in Index.html

```<code> <table>

              <tr>
                    <td width = "120">ID NUMBER</td>
                    <td width = "15">:</td>
                    <td id="data2"></td>
                  </tr>
                  <tr>
                    <td>PHONE</td>
                    <td>:</td>
                    <td id="data3"></td>
                  </tr>
</table>
</code>```

Body:
I use Apps Script to pull data from Google Spreadsheets and then Display the data on an HTML page in a table format.

I am trying to hide the data that is pulled from the spreadsheet and displayed on the table but make the last four digits of the data to be visible.

I tried the JS code below and it works fine on HTML pages but the JS code doesn't work when I tried to apply it to Apps Script probably because the HTML page has its table value typed as text in the cells while Apps Script needs to pull its table value from the spreadsheet before applying the rule from the JS code to the data to hide it and only display the last four digits of the data.

Any help to understand how to apply the script below to Apps Script to hide data but show the last four digits will be appreciated.

JS and HTML Code Below;

var id_number = document.getElementById('data2');
id_number.innerHTML = new Array(id_number.innerHTML.length-3).join('x') +
id_number.innerHTML.substr(id_number.innerHTML.length-4, 4);
console.log(id_number.innerHTML);

var phone = document.getElementById('data3');
phone.innerHTML = new Array(phone.innerHTML.length-3).join('x') +
phone.innerHTML.substr(phone.innerHTML.length-4, 4);
console.log(phone.innerHTML);

                    ID NUMBER
                    :
                    1234567890

                    PHONE
                    :
                    0000000000

My Code.gs Code in Apps Script Below;

function doGet(e) {
  return HtmlService.createTemplateFromFile("index").evaluate()
  .setTitle("HTML DATA PAGE")
  .addMetaTag('viewport', 'width=device-width, initial-scale=1')
  .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
};

let ss = SpreadsheetApp.getActiveSpreadsheet();
function getData(keyword){
  let sheet = ss.getSheetByName('Data');
  let data = sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).getDisplayValues();
  let index = data.map(d => d[2]).indexOf(keyword);
  console.log(data);
  console.log(data.map(d => d[2]));
  console.log(index);
  if(index > -1){
    return data[index];
  }else{
    return undefined;
  }

}

let url = ScriptApp.getService().getUrl();

My Apps Script Table Code in Index.html

                    ID NUMBER
                    :

                    PHONE
                    :


问:
Getting error No qualifying bean of type 'com.cav.controllers.repository.UserRepository' SpringMVC
I am getting the following error running my application.
No qualifying bean of type 'com.cav.controllers.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate

I have a repository interface

```<code>package com.cav.controllers.repository;
import org.springframework.data.jpa.repository.JpaRepository;

import com.cav.models.User;

public interface UserRepository extends JpaRepository<User, String>{

}
</code>```

And a simple controller

```<code>@Controller
public class AddController {

    @Autowired
    UserRepository userRepository;

    @RequestMapping("/addUser")
    public ModelAndView addUser(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("Running method addUser");
        String param1 = req.getParameter("t1");
        String param2 = req.getParameter("t2");
        String param3 = req.getParameter("t3");

        ModelAndView mv = new ModelAndView();
        User user = new User(param1,param2,param3);
        userRepository.save(user);
        //userService.saveUser(user);
        mv.setViewName("displayUser.jsp");
        mv.addObject("userID", param1);
        mv.addObject("fname", param2);
        mv.addObject("sname", param3);
        return mv;
    }
}
</code>```

My main app

```<code>package com.cav;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
public class WebBankMvcApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebBankMvcApplication.class, args);
    }

}

</code>```

My controllers-servlet.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:ctx="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd ">

    <ctx:annotation-config></ctx:annotation-config>
    <ctx:component-scan base-package="com.cav.controllers"></ctx:component-scan>
</beans>
</code>```

I cant see what is wrong my repository is in the path

```<code>package com.cav.controllers.repository
</code>```

So it should be able to see the jparepository and autowire it.

Body:
I am getting the following error running my application.
No qualifying bean of type 'com.cav.controllers.repository.UserRepository' available: expected at least 1 bean which qualifies as autowire candidate

I have a repository interface

package com.cav.controllers.repository;
import org.springframework.data.jpa.repository.JpaRepository;

import com.cav.models.User;

public interface UserRepository extends JpaRepository<User, String>{

}

And a simple controller

@Controller
public class AddController {

    @Autowired
    UserRepository userRepository;

    @RequestMapping("/addUser")
    public ModelAndView addUser(HttpServletRequest req, HttpServletResponse resp) {
        System.out.println("Running method addUser");
        String param1 = req.getParameter("t1");
        String param2 = req.getParameter("t2");
        String param3 = req.getParameter("t3");

        ModelAndView mv = new ModelAndView();
        User user = new User(param1,param2,param3);
        userRepository.save(user);
        //userService.saveUser(user);
        mv.setViewName("displayUser.jsp");
        mv.addObject("userID", param1);
        mv.addObject("fname", param2);
        mv.addObject("sname", param3);
        return mv;
    }
}

My main app

package com.cav;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

@SpringBootApplication
public class WebBankMvcApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebBankMvcApplication.class, args);
    }

}

My controllers-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:ctx="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-2.5.xsd ">

    <ctx:annotation-config></ctx:annotation-config>
    <ctx:component-scan base-package="com.cav.controllers"></ctx:component-scan>
</beans>

I cant see what is wrong my repository is in the path

package com.cav.controllers.repository

So it should be able to see the jparepository and autowire it.


问:
click event not working on href in angular
I have below code in .ts file

```<code> columns: Array<GuiColumn> = [
    {
    {
      header: 'Company Guid',
      field: 'companyGuid',
      view: (value: string, obj: any) => { return `<a href="#" (click)="onClickDelegateAccess(${obj.companyGuid})">${obj.companyGuid}</a>`; },
      width: 330
    }];
</code>```

Now this function is in .ts file as per below

```<code>onClickDelegateAccess(companyGuid: string) {
    alert("hi");
  }
</code>```

But this function is not calling. Any idea on this..

Body:
I have below code in .ts file

 columns: Array<GuiColumn> = [
    {
    {
      header: 'Company Guid',
      field: 'companyGuid',
      view: (value: string, obj: any) => { return `<a href="#" (click)="onClickDelegateAccess(${obj.companyGuid})">${obj.companyGuid}</a>`; },
      width: 330
    }];

Now this function is in .ts file as per below

onClickDelegateAccess(companyGuid: string) {
    alert("hi");
  }

But this function is not calling. Any idea on this..