问:
How to include types of my private repo in the public repo bundle of monorepo?
I currently use yarn pnp & workspace for my monorepo.

And, I made a @types repository to share the types in my repositories.

However, this @types repository is private, i wanna publish them with my public repository.

For example, I exported @types in my public library repo.

```<code>// @types/index.ts
export enum BUTTON_TAG {
  BUTTON = "button",
  ANCHOR = "a",
}
export type ButtonTag = `${BUTTON_TAG}`;
</code>```
```<code>// my-public-library/index.ts
export * from "@types";
</code>```

But my bundle does not includes @types. I'm worried that users won't be able import these types when my library is published.

Body:
I currently use yarn pnp & workspace for my monorepo.

And, I made a @types repository to share the types in my repositories.

However, this @types repository is private, i wanna publish them with my public repository.

For example, I exported @types in my public library repo.

// @types/index.ts
export enum BUTTON_TAG {
  BUTTON = "button",
  ANCHOR = "a",
}
export type ButtonTag = `${BUTTON_TAG}`;

// my-public-library/index.ts
export * from "@types";

But my bundle does not includes @types. I'm worried that users won't be able import these types when my library is published.


来源: stackexchange

问:
My coding in flayer container disabled when I set flayer section default why?
Actually I am new here, and finding solution about this..
I have create a design on a wordpress page through elementor. for some creative design I have set flayer container as active. Now I have to create a simple design and need to use inner section in  a section.

For that I have set flayer container as default or inactive. In both setup my earliest design missing which I have created in flayer container....

ContentLicense: CC BY-SA 4.0


问:
Updating PromQL to query on all volumes in one namespace
I'm looking to reduce the number of Grafana alerts by making the existing PromQL slightly more DRY. How can I alert on all persistentvolumeclaim's within the same namespace? The ideal scenario is that I have one PromQL query targeting one namespace and the alerts can indicate something like "Volume 95% Utilized", etc.

Example PromQL queries that I would like to reduce to one:

```<code>sum without(instance, node) (topk(1, (kubelet_volume_stats_available_bytes{cluster="", job="kubelet", metrics_path="/metrics", namespace="develop", persistentvolumeclaim="chserver-logs"})))

sum without(instance, node) (topk(1, (kubelet_volume_stats_available_bytes{cluster="", job="kubelet", metrics_path="/metrics", namespace="develop", persistentvolumeclaim="chserver-vol2"})))
</code>```

Body:
I'm looking to reduce the number of Grafana alerts by making the existing PromQL slightly more DRY. How can I alert on all persistentvolumeclaim's within the same namespace? The ideal scenario is that I have one PromQL query targeting one namespace and the alerts can indicate something like "Volume 95% Utilized", etc.

Example PromQL queries that I would like to reduce to one:

sum without(instance, node) (topk(1, (kubelet_volume_stats_available_bytes{cluster="", job="kubelet", metrics_path="/metrics", namespace="develop", persistentvolumeclaim="chserver-logs"})))

sum without(instance, node) (topk(1, (kubelet_volume_stats_available_bytes{cluster="", job="kubelet", metrics_path="/metrics", namespace="develop", persistentvolumeclaim="chserver-vol2"})))


问:
Getting This Error: FileNotFoundError: [Errno 2] No such file or directory: './upload_images/Image_1.jpg'
Please help me I am Getting This error:
Please Check the Screenshot

I am trying to upload a picture to fetch calaroies of that image. I am getting this error while uploading the image

The below is my complete code please help me

```<code>
def run():
    st.title("Fruits-Vegetable Classification")
    img_file = st.file_uploader("Choose an Image", type=["jpg", "png"])
    if img_file is not None:
        img = Image.open(img_file).resize((250, 250))
        st.image(img, use_column_width=False)
        save_image_path = './upload_images/' + img_file.name
        with open(save_image_path, "wb") as f:
            f.write(img_file.getbuffer())

        # if st.button("Predict"):
        if img_file is not None:
            result = processed_img(save_image_path)
            print(result)
            if result in vegetables:
                st.info('**Category : Vegetables**')
            else:
                st.info('**Category : Fruit**')
            st.success("**Predicted : " + result + '**')
            cal = fetch_calories(result)
            if cal:
                st.warning('**' + cal + '(100 grams)**')

run()
</code>```

While uploading the Image I am getting error File not Found

Body:
Please help me I am Getting This error:
Please Check the Screenshot

I am trying to upload a picture to fetch calaroies of that image. I am getting this error while uploading the image

The below is my complete code please help me

def run():
    st.title("Fruits-Vegetable Classification")
    img_file = st.file_uploader("Choose an Image", type=["jpg", "png"])
    if img_file is not None:
        img = Image.open(img_file).resize((250, 250))
        st.image(img, use_column_width=False)
        save_image_path = './upload_images/' + img_file.name
        with open(save_image_path, "wb") as f:
            f.write(img_file.getbuffer())

        # if st.button("Predict"):
        if img_file is not None:
            result = processed_img(save_image_path)
            print(result)
            if result in vegetables:
                st.info('**Category : Vegetables**')
            else:
                st.info('**Category : Fruit**')
            st.success("**Predicted : " + result + '**')
            cal = fetch_calories(result)
            if cal:
                st.warning('**' + cal + '(100 grams)**')

run()

While uploading the Image I am getting error File not Found


问:
HTML tags and elements difference
what is the difference between HTML tags and HTML elements?

I tried to ask HTML question with some mentors and some websites, but its finding difficulty in getting the accurate difference between HTML tags and HTML elements.

Title: HTML tags and elements difference


问:
How to separate two different sliders with breakpoints in swiper.js
I'm trying to implement two different sliders with swiper.js.
Above 768px and below.
But I can't successfully reset and regenerate.
Based on the screen width of 768px, I would like the two sliders to switch seamlessly.
I would appreciate it if you could teach me.

Here is the actual js code.

```<code>// ***** Swiper@8.4.5 *****
'use strict';

let destroyed = true;

document.addEventListener('DOMContentLoaded', function () {

   if (destroyed == false) {
      this.mySwiper.destroy(false, true);
      destroyed = true;
   }

    const mediaQuery = window.matchMedia('(max-width: 768px)');

    const checkBreakpoint = (e) => {

        if (e.matches) {
            const mySwiper = new Swiper('.swiper-main', {

                init: true,

                loop: true,

                spaceBetween: 20,

                speed: 300,

                thresholdDelta: 100,

                allowTouchMove: true,

                centeredSlides: true,

                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                    type: 'bullets'
                },
            });
          destroyed = false;
        }
        else {
            const thumb = document.querySelectorAll('.thumb-media');

            const switchThumb = (index) => {
                document.querySelector('.thumb-media-active').classList.remove('thumb-media-active');
                thumb[index].classList.add('thumb-media-active');
            };

            const mySwiper = new Swiper('.swiper-main', {

                init: true,

                loop: false,

                spaceBetween: 20,

                speed: 800,

                allowTouchMove: false,

                centeredSlides: true,

                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },

                on: {
                    afterInit: (swiper) => {
                        thumb[swiper.realIndex].classList.add('thumb-media-active');
                        for (let i = 0; i < thumb.length; i++) {
                            thumb[i].onclick = () => {
                                swiper.slideTo(i);
                            };
                        }
                    },

                    slideChange: (swiper) => {
                        switchThumb(swiper.realIndex);
                    },
                },
            });
          destroyed = false;
        };
    }
    mediaQuery.addEventListener("change", checkBreakpoint);
    checkBreakpoint(mediaQuery);
})

</code>```

swiper.js destroy doesn't work.

Body:
I'm trying to implement two different sliders with swiper.js.
Above 768px and below.
But I can't successfully reset and regenerate.
Based on the screen width of 768px, I would like the two sliders to switch seamlessly.
I would appreciate it if you could teach me.

Here is the actual js code.

// ***** Swiper@8.4.5 *****
'use strict';

let destroyed = true;

document.addEventListener('DOMContentLoaded', function () {

   if (destroyed == false) {
      this.mySwiper.destroy(false, true);
      destroyed = true;
   }

    const mediaQuery = window.matchMedia('(max-width: 768px)');

    const checkBreakpoint = (e) => {

        if (e.matches) {
            const mySwiper = new Swiper('.swiper-main', {

                init: true,

                loop: true,

                spaceBetween: 20,

                speed: 300,

                thresholdDelta: 100,

                allowTouchMove: true,

                centeredSlides: true,

                pagination: {
                    el: '.swiper-pagination',
                    clickable: true,
                    type: 'bullets'
                },
            });
          destroyed = false;
        }
        else {
            const thumb = document.querySelectorAll('.thumb-media');

            const switchThumb = (index) => {
                document.querySelector('.thumb-media-active').classList.remove('thumb-media-active');
                thumb[index].classList.add('thumb-media-active');
            };

            const mySwiper = new Swiper('.swiper-main', {

                init: true,

                loop: false,

                spaceBetween: 20,

                speed: 800,

                allowTouchMove: false,

                centeredSlides: true,

                navigation: {
                    nextEl: '.swiper-button-next',
                    prevEl: '.swiper-button-prev',
                },

                on: {
                    afterInit: (swiper) => {
                        thumb[swiper.realIndex].classList.add('thumb-media-active');
                        for (let i = 0; i < thumb.length; i++) {
                            thumb[i].onclick = () => {
                                swiper.slideTo(i);
                            };
                        }
                    },

                    slideChange: (swiper) => {
                        switchThumb(swiper.realIndex);
                    },
                },
            });
          destroyed = false;
        };
    }
    mediaQuery.addEventListener("change", checkBreakpoint);
    checkBreakpoint(mediaQuery);
})

swiper.js destroy doesn't work.


问:
Talend Cannot satisfy dependency
Good day,

I am new to Talend Studio and today I am hitting the following error when I am trying to udpate by click on the "Feature Manager" button:

```<code>Update check failed
  Cannot complete the install because of a conflicting dependency.
    Software being installed: Generic 8.0.1.20220714_0754 (org.talend.rcp.branding.generic 8.0.1.20220714_0754)
    Software currently installed: All branding features included 8.0.1.20211109_1130 (org.talend.rcp.branding.all.feature.feature.group 8.0.1.20211109_1130)
    Only one of the following can be installed at once:
      Generic 8.0.1.20220714_0754 (org.talend.rcp.branding.generic 8.0.1.20220714_0754)
      Generic 8.0.1.20211109_1130 (org.talend.rcp.branding.generic 8.0.1.20211109_1130)
    Cannot satisfy dependency:
      From: Feature 8.0.1.20211109_1130 (org.talend.commandline.light.feature.feature.group 8.0.1.20211109_1130)
      To: org.eclipse.equinox.p2.iu; org.talend.rcp.branding.generic [8.0.1.20211109_1130,8.0.1.20211109_1130]
    Cannot satisfy dependency:
      From: All branding features included 8.0.1.20211109_1130 (org.talend.rcp.branding.all.feature.feature.group 8.0.1.20211109_1130)
      To: org.eclipse.equinox.p2.iu; org.talend.commandline.light.feature.feature.group 0.0.0
</code>```

looks like it complain about 2 version hitting conflict? 8.0.1.20220714_0754 and 8.0.1.20211109_1130.

May I know how is this happen and how should I fix this?

Title: Talend Cannot satisfy dependency

Body:
Good day,

I am new to Talend Studio and today I am hitting the following error when I am trying to udpate by click on the "Feature Manager" button:

Update check failed
  Cannot complete the install because of a conflicting dependency.
    Software being installed: Generic 8.0.1.20220714_0754 (org.talend.rcp.branding.generic 8.0.1.20220714_0754)
    Software currently installed: All branding features included 8.0.1.20211109_1130 (org.talend.rcp.branding.all.feature.feature.group 8.0.1.20211109_1130)
    Only one of the following can be installed at once:
      Generic 8.0.1.20220714_0754 (org.talend.rcp.branding.generic 8.0.1.20220714_0754)
      Generic 8.0.1.20211109_1130 (org.talend.rcp.branding.generic 8.0.1.20211109_1130)
    Cannot satisfy dependency:
      From: Feature 8.0.1.20211109_1130 (org.talend.commandline.light.feature.feature.group 8.0.1.20211109_1130)
      To: org.eclipse.equinox.p2.iu; org.talend.rcp.branding.generic [8.0.1.20211109_1130,8.0.1.20211109_1130]
    Cannot satisfy dependency:
      From: All branding features included 8.0.1.20211109_1130 (org.talend.rcp.branding.all.feature.feature.group 8.0.1.20211109_1130)
      To: org.eclipse.equinox.p2.iu; org.talend.commandline.light.feature.feature.group 0.0.0

looks like it complain about 2 version hitting conflict? 8.0.1.20220714_0754 and 8.0.1.20211109_1130.

May I know how is this happen and how should I fix this?


问:
RuntimeError: value cannot be converted to type int without overflow
I want to reproduce DVGO on my platform. It seems the environment is already set up.

(the torch version is 1.12.1+cu113, the gcc version is 7.5.0, and the nvcc version is 11.0.194)

However, when I ran the command "python run.py --config configs/nerf/hotdog.py --render_test", the overflow issue occurred.

Following is the Traceback code.

```<code>Traceback (most recent call last):
  File "run.py", line 630, in <module>
    train(args, cfg, data_dict)
  File "run.py", line 545, in train
    data_dict=data_dict, stage='coarse')
  File "run.py", line 449, in scene_rep_reconstruction
    **render_kwargs)
  File "/opt/pyenv/versions/mlhw/lib/python3.7/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/DirectVoxGO/lib/dvgo.py", line 309, in forward
    rays_o=rays_o, rays_d=rays_d, **render_kwargs)
  File "/home/user/DirectVoxGO/lib/dvgo.py", line 288, in sample_ray
    ray_pts, mask_outbbox, ray_id, step_id, N_steps, t_min, t_max = render_utils_cuda.sample_pts_on_rays(
RuntimeError: value cannot be converted to type int without overflow
</code>```

Does anyone know how to deal with the problem?

I have tried to trace the source code in the above GitHub page, but I am not familiar with the gcc source code.

Body:
I want to reproduce DVGO on my platform. It seems the environment is already set up.

(the torch version is 1.12.1+cu113, the gcc version is 7.5.0, and the nvcc version is 11.0.194)

However, when I ran the command "python run.py --config configs/nerf/hotdog.py --render_test", the overflow issue occurred.

Following is the Traceback code.

Traceback (most recent call last):
  File "run.py", line 630, in <module>
    train(args, cfg, data_dict)
  File "run.py", line 545, in train
    data_dict=data_dict, stage='coarse')
  File "run.py", line 449, in scene_rep_reconstruction
    **render_kwargs)
  File "/opt/pyenv/versions/mlhw/lib/python3.7/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "/home/user/DirectVoxGO/lib/dvgo.py", line 309, in forward
    rays_o=rays_o, rays_d=rays_d, **render_kwargs)
  File "/home/user/DirectVoxGO/lib/dvgo.py", line 288, in sample_ray
    ray_pts, mask_outbbox, ray_id, step_id, N_steps, t_min, t_max = render_utils_cuda.sample_pts_on_rays(
RuntimeError: value cannot be converted to type int without overflow

Does anyone know how to deal with the problem?

I have tried to trace the source code in the above GitHub page, but I am not familiar with the gcc source code.


问:
In a HTML code a image is not showing in background . and
An error is showing while I entered to the website and also in java transactions not working properly

An unexpected error
image not showing

Title: In a HTML code a image is not showing in background . and <img src="">


问:
Is it possible to prevent file from being copied? Or atleast know that the file has been duplicated/copied/moved?
In this case, i have image file like picture/video that contain sensitive content (my home cctv video). is it possible to prevent my file from being duplicated? Or atleast know that file has been duplicated/copied/moved. Example : i share the file to 2 different people and told them to not share it but it got leaked and no one wanna admit it, what can i do to prevent it?

ps: Sorry for the bad english, its not my first language

I tried search about hashfile but haven't found what I'm looking for


问:
gitlab backup fails at one repo
problem is that during backing up of repos, everytime i get the same error, that you can see below

my gitlab settings are 8 cpu, 16gb ram and 1.5tb space (if you need more data, let me know)
this one repo is about 50gb and it stops my whole process... i have other ones that are bigger and everything goes smoothly.

assuming that hardware is ok, what can i do to complete backup?
ps. those repos contains dvd images, but i dont have access to check what exactly

ive increased disk space and ram, tried to reconfigure, but it didnt help.
i didnt try yet to increase swap and ram even higher, although it doesnt seem like its going out of memory, ill try to increase it, just to eliminate hardware for 100%

Title: gitlab backup fails at one repo


问:
How to extract data from the dataset with a certain condition and how to combine data from two columns into one in R
This is my dataset example for one person:
dataset example for one person

I have made this table :

deathYear
diagYear
fcediags
pid

2013
NA
I21
1

2011
NA
I63
2

2033
NA
I21
4

2029
NA
I25
5

2020
NA
I21
18

2012
NA
I63
19

I have the problem with the data for the diagYear above. The results are NA.

And also:
The table T2 should only show the rows for persons that have at least one of these Diags: "I20","I21","I22","I25" or "I63" in the document data (no matter document$fces$alive=TRUE or FALSE), but (and only for these persons with this condition) it should also show the year of death (extracted from the date like in the code above - deathYear code) no matter the pearson died from some other diagnoses.

I also need to make one column Year instead of these two (deathYear and diagYear) which would contain the data for the year (extracted from the date - document$FCEs$date (pls see the picture) depending on the next conditions: 1. if document$fces$alive is TRUE, the Year column should have the data for the year only if there's at least one Diag1 in the person's document set that is either "I20", "I21", "I22", "I25" or "I63"
2. if document$fces$alive is FALSE (but only for these persons from the condition 1.), then the column Year should have a deathYear data from the code above no matter the Diag value for the case of death (in this case Diag1, doesn't have to be "I20", "I21", "I22", "I25" or "I63").

I have tried these codes:

```<code>getDiags <- function(x) {
  document<-fromJSON(x)
  fcediags <- document$FCEs$Diag1
  fcedage <- document$FCEs$pAge
  fcealive <- document$FCEs$alive

  deathYear<-2030
  if(length(strsplit(document$FCEs[document$FCEs$alive==FALSE,]$date, "/"))>0)
    deathYear<-as.numeric(strsplit(document$FCEs[document$FCEs$alive==FALSE,]$date, "/")[[1]][1])

  diagYear<-0
  v1 = c("I20","I21","I22","I25","I63")
  for (i in 1:length(document$FCEs$Diag1)){
    if (document$FCEs$Diag1[i] %in% v1){
      diagYear<-as.numeric(strsplit(document$FCEs[document$FCEs$Diag1[i],]$date, "/")[[1]][1])
    }
  }  #this block of code doesn't work, it shows NA in the table

  return (data.frame(fcedage,fcediags,fcealive,sex,ldl,pid=document$ID,deathYear,diagYear))
}

for (i in 1:length(fces$fcediags)){
  T2 <- subset(fces,fces$fcediags == "I20" | fces$fcediags == "I21" | fces$fcediags == "I22" | fces$fcediags == "I25" | fces$fcediags == "I63", select = c(deathYear,diagYear,fcediags,pid))
}

#I've obviously made this table wrong because it shows rows for only these "I20","I21",...,"I63" Diag1s, but for  these persons (with these mentioned Diag1s), it should show the year of death (document$fces$alive=FALSE) no matter the Diag1 value for the case of death.
</code>```

(pid is pearson's ID), but they are not good enough. Results in the column diagYear shouldn't be NA and the two columns should be merged in one.

Can someone please help me? Thank you in advance!

Body:
This is my dataset example for one person:
dataset example for one person

I have made this table :

deathYear
diagYear
fcediags
pid

2013
NA
I21
1

2011
NA
I63
2

2033
NA
I21
4

2029
NA
I25
5

2020
NA
I21
18

2012
NA
I63
19

I have the problem with the data for the diagYear above. The results are NA.

And also:
The table T2 should only show the rows for persons that have at least one of these Diags: "I20","I21","I22","I25" or "I63" in the document data (no matter document$fces$alive=TRUE or FALSE), but (and only for these persons with this condition) it should also show the year of death (extracted from the date like in the code above - deathYear code) no matter the pearson died from some other diagnoses.

I also need to make one column Year instead of these two (deathYear and diagYear) which would contain the data for the year (extracted from the date - document$FCEs$date (pls see the picture) depending on the next conditions: 1. if document$fces$alive is TRUE, the Year column should have the data for the year only if there's at least one Diag1 in the person's document set that is either "I20", "I21", "I22", "I25" or "I63"
2. if document$fces$alive is FALSE (but only for these persons from the condition 1.), then the column Year should have a deathYear data from the code above no matter the Diag value for the case of death (in this case Diag1, doesn't have to be "I20", "I21", "I22", "I25" or "I63").

I have tried these codes:

getDiags <- function(x) {
  document<-fromJSON(x)
  fcediags <- document$FCEs$Diag1
  fcedage <- document$FCEs$pAge
  fcealive <- document$FCEs$alive

  deathYear<-2030
  if(length(strsplit(document$FCEs[document$FCEs$alive==FALSE,]$date, "/"))>0)
    deathYear<-as.numeric(strsplit(document$FCEs[document$FCEs$alive==FALSE,]$date, "/")[[1]][1])

  diagYear<-0
  v1 = c("I20","I21","I22","I25","I63")
  for (i in 1:length(document$FCEs$Diag1)){
    if (document$FCEs$Diag1[i] %in% v1){
      diagYear<-as.numeric(strsplit(document$FCEs[document$FCEs$Diag1[i],]$date, "/")[[1]][1])
    }
  }  #this block of code doesn't work, it shows NA in the table

  return (data.frame(fcedage,fcediags,fcealive,sex,ldl,pid=document$ID,deathYear,diagYear))
}

for (i in 1:length(fces$fcediags)){
  T2 <- subset(fces,fces$fcediags == "I20" | fces$fcediags == "I21" | fces$fcediags == "I22" | fces$fcediags == "I25" | fces$fcediags == "I63", select = c(deathYear,diagYear,fcediags,pid))
}

#I've obviously made this table wrong because it shows rows for only these "I20","I21",...,"I63" Diag1s, but for  these persons (with these mentioned Diag1s), it should show the year of death (document$fces$alive=FALSE) no matter the Diag1 value for the case of death.

(pid is pearson's ID), but they are not good enough. Results in the column diagYear shouldn't be NA and the two columns should be merged in one.

Can someone please help me? Thank you in advance!


问:
How to use an Iconfiguration service as Idisposable in .net core as Coverity shows a resource leak?
I am using IconfigurationRoot service using Build() function.

```<code>IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"));
var configservice = builder.Build();
</code>```

Now this works, but the problem is since Configuration service cannot be treated as IDisposable, how do I prevent the resource leak happening in Static Analysis Security Test? How to dispose of configservice?

I tried 'using' method or using Dispose() but it can't be used as such methods can only be used with Idisposable or IdisposableAsync.

Body:
I am using IconfigurationRoot service using Build() function.

IConfigurationBuilder builder = new ConfigurationBuilder();
builder.AddJsonFile(Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json"));
var configservice = builder.Build();

Now this works, but the problem is since Configuration service cannot be treated as IDisposable, how do I prevent the resource leak happening in Static Analysis Security Test? How to dispose of configservice?

I tried 'using' method or using Dispose() but it can't be used as such methods can only be used with Idisposable or IdisposableAsync.


问:
how to use multiple filter on php list with javascript
this is my list and i want to filter words ,  i want to use multiple select box to filter data

i dont know how this is possible

i dont know i can handle it with php or javascript

because im new in programming

function filterCategory(varSelect, IdSelect, varCat, clCat) {
  this.varSelect = document.getElementById(IdSelect)
  this.varCat = document.querySelectorAll("." + clCat)
  this.varSelect.addEventListener("change", () => {
    this.varCat.forEach((item) => {
      let text = item.innerText;
      const targetStyle = item.parentElement.parentElement.style;
      if (this.varSelect.value == "all") {
        targetStyle.display = ""
      } else if (text.includes(this.varSelect.value)) {
        targetStyle.display = "revert"
      } else {
        targetStyle.display = "none"
      } else if (targetStyle.display !== "none") {
        if (this.varSelect.value == "all") {
          targetStyle.display = ""
        } else if (text.includes(this.varSelect.value)) {
          targetStyle.display = "revert"
        } else {
          targetStyle.display = "none"
        }
      }
    })
  })
}
```


问:
Nuxt.js show window is not defined when load to production
I have an application with nuxt.js as a framework and it's running well in development mode. However, when I deployed to the server for production, it's show "window is not defined".

I think it's because highcharts-vue.min.js module not loaded in components so shows this error but I'm not sure about that. I attach some code and screen shoot results after deploying on the server

<template>
  <highcharts class="hc" :options="chartOptions" ref="chart">
  </highcharts>
</template>

```


问:
FlatFileFooterCallback Exception not coming in Skip Listener
Issue :- Error throwing from FlatFileFooterCallback is not skippable and Job is getting stopped
What we tried

Job Configuration below

```<code>    @Bean
public Step mmsSlaveStep() throws Exception {
    return stepBuilderFactory.get("mmsSlaveStep").<BaseDTO, BaseDTO>chunk(chunkSize).reader(mmsReader(null))
            .processor(mmsProcessor()).writer(mmsItemWriter(null)).faultTolerant().skipLimit(skipErrorCount)
            .skip(Exception.class).listener(itemSkipListener()).build();
}
</code>```

ItemWriter that have Footer Call Back

```<code>@Bean
@StepScope
public FlatFileItemWriter<BaseDTO> mmsItemWriter(@Value("#{stepExecutionContext['fileName']}") String filePath)
        throws Exception {
    BeanWrapperFieldExtractor<BaseDTO> fieldExtractor = new BeanWrapperFieldExtractor<>();
    fieldExtractor.setNames(mmsWriterFields);
    fieldExtractor.afterPropertiesSet();
    FormatterLineAggregator<BaseDTO> lineAggregator = new FormatterLineAggregator<>();
    lineAggregator.setFormat(mmsWriterFieldsFormat);
    lineAggregator.setFieldExtractor(fieldExtractor);
    String fileName = FilenameUtils.getName(filePath);
    Resource outputResource = new FileSystemResource(new File(sucessPath + fileName + inputDataSource));
    return new FlatFileItemWriterBuilder<BaseDTO>().name("mmsWriter").resource(outputResource)
            .lineAggregator(lineAggregator).shouldDeleteIfEmpty(true).footerCallback(mmsSummaryItemWriter()).build();
}
</code>```

FooterCall Back Writer that have writeFooter that aggregates data to a DB table. This exception is not coming to SkipListener

public class MMSSummaryWriter implements FlatFileFooterCallback {

```<code>@Autowired
private MMSMasterService mmsMasterService;
@Value("#{stepExecution}")
private StepExecution stepExecution;

@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;

@Override
    public void writeFooter(Writer writer) throws IOException{
        ExecutionContext  executionContext =stepExecution.getExecutionContext();
    HashMap<String,MMSDto> summaryMap = (HashMap<String, MMSDto>) executionContext.get("Summary");

    List<MMSDto> summaryValues = new ArrayList<>(summaryMap.values());

    int[] updateCounts =  jdbcTemplate.batchUpdate(InterConnectUtils.SUMMARY_EVENT_INSERT, new BatchPreparedStatementSetter() {
              @Override
              public void setValues(PreparedStatement ps, int i) throws SQLException   {
                  int counter =0;
                  MMSDto mmsDto = summaryValues.get(i);
                  ps.setString(1,mmsDto.getBatchNumber());
                  ps.setString(2,mmsDto.getEntityCode());
                  ps.setString(3,mmsDto.getInputFileType());
                  ps.setInt(4, mmsDto.getTotalType());
                  ps.setString(5,mmsDto.getServiceType());
                  ps.setString(6, mmsDto.getCallInd());
                  ps.setString(7,mmsDto.getCallDateTime());
                  ps.setString(8,mmsDto.getEventDirection());
                  ps.setString(9,mmsDto.getProductID());
                  ps.setInt(10,mmsDto.getTargetInd());
                  ps.setInt(11,mmsDto.getNoRecords());
                  ps.setLong(26,mmsDto.getTotalDuration());
                System.out.println("InsertValues : "+mmsDto.getBatchNumber()+"#"+mmsDto.getTotalType()+"#"+mmsDto.getCallInd()+"#"+mmsDto.getServiceType()+"#"+
                        mmsDto.getProductID()+"#"+mmsDto.getCallDateTime()+"#"+mmsDto.getTotalType());
              }
              @Override
              public int getBatchSize() {
                  System.out.println("summaryMap.size()"+summaryMap.size());
                return summaryMap.size();
              }

            });

}
</code>```

}

SkipListner Class that handles errors and log to table and allow the job to continue

```<code>public class PreProcSkipListener implements SkipListener<BaseDTO, BaseDTO> {

private static final Logger logger = LoggerFactory.getLogger(PreProcSkipListener.class);

@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void onSkipInWrite(BaseDTO item, Throwable t) {
    Exception ex = new Exception(t);
    jdbcTemplate.update(InterConnectUtils.BATCH_ERROR_INSERT, new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            MMSDto mmsDto = (MMSDto) item;
            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            ps.setDate(1, new java.sql.Date(new Date().getTime()));
            ps.setString(2, mmsDto.getBatchNumber());
            ps.setString(3, "WRITER");
            Reader reader = new StringReader(exceptionAsString + "--" + ex.getMessage());
            ps.setClob(4, reader);
        }

    });

    }
   }}
</code>```

There is an open issue mentioned in github to consider. Let us know any workaround
github defect

Body:
Issue :- Error throwing from FlatFileFooterCallback is not skippable and Job is getting stopped
What we tried

Job Configuration below

    @Bean
public Step mmsSlaveStep() throws Exception {
    return stepBuilderFactory.get("mmsSlaveStep").<BaseDTO, BaseDTO>chunk(chunkSize).reader(mmsReader(null))
            .processor(mmsProcessor()).writer(mmsItemWriter(null)).faultTolerant().skipLimit(skipErrorCount)
            .skip(Exception.class).listener(itemSkipListener()).build();
}

ItemWriter that have Footer Call Back

@Bean
@StepScope
public FlatFileItemWriter<BaseDTO> mmsItemWriter(@Value("#{stepExecutionContext['fileName']}") String filePath)
        throws Exception {
    BeanWrapperFieldExtractor<BaseDTO> fieldExtractor = new BeanWrapperFieldExtractor<>();
    fieldExtractor.setNames(mmsWriterFields);
    fieldExtractor.afterPropertiesSet();
    FormatterLineAggregator<BaseDTO> lineAggregator = new FormatterLineAggregator<>();
    lineAggregator.setFormat(mmsWriterFieldsFormat);
    lineAggregator.setFieldExtractor(fieldExtractor);
    String fileName = FilenameUtils.getName(filePath);
    Resource outputResource = new FileSystemResource(new File(sucessPath + fileName + inputDataSource));
    return new FlatFileItemWriterBuilder<BaseDTO>().name("mmsWriter").resource(outputResource)
            .lineAggregator(lineAggregator).shouldDeleteIfEmpty(true).footerCallback(mmsSummaryItemWriter()).build();
}

FooterCall Back Writer that have writeFooter that aggregates data to a DB table. This exception is not coming to SkipListener

public class MMSSummaryWriter implements FlatFileFooterCallback {

@Autowired
private MMSMasterService mmsMasterService;
@Value("#{stepExecution}")
private StepExecution stepExecution;

@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;

@Override
    public void writeFooter(Writer writer) throws IOException{
        ExecutionContext  executionContext =stepExecution.getExecutionContext();
    HashMap<String,MMSDto> summaryMap = (HashMap<String, MMSDto>) executionContext.get("Summary");

    List<MMSDto> summaryValues = new ArrayList<>(summaryMap.values());

    int[] updateCounts =  jdbcTemplate.batchUpdate(InterConnectUtils.SUMMARY_EVENT_INSERT, new BatchPreparedStatementSetter() {
              @Override
              public void setValues(PreparedStatement ps, int i) throws SQLException   {
                  int counter =0;
                  MMSDto mmsDto = summaryValues.get(i);
                  ps.setString(1,mmsDto.getBatchNumber());
                  ps.setString(2,mmsDto.getEntityCode());
                  ps.setString(3,mmsDto.getInputFileType());
                  ps.setInt(4, mmsDto.getTotalType());
                  ps.setString(5,mmsDto.getServiceType());
                  ps.setString(6, mmsDto.getCallInd());
                  ps.setString(7,mmsDto.getCallDateTime());
                  ps.setString(8,mmsDto.getEventDirection());
                  ps.setString(9,mmsDto.getProductID());
                  ps.setInt(10,mmsDto.getTargetInd());
                  ps.setInt(11,mmsDto.getNoRecords());
                  ps.setLong(26,mmsDto.getTotalDuration());
                System.out.println("InsertValues : "+mmsDto.getBatchNumber()+"#"+mmsDto.getTotalType()+"#"+mmsDto.getCallInd()+"#"+mmsDto.getServiceType()+"#"+
                        mmsDto.getProductID()+"#"+mmsDto.getCallDateTime()+"#"+mmsDto.getTotalType());
              }
              @Override
              public int getBatchSize() {
                  System.out.println("summaryMap.size()"+summaryMap.size());
                return summaryMap.size();
              }

            });

}

}

SkipListner Class that handles errors and log to table and allow the job to continue

public class PreProcSkipListener implements SkipListener<BaseDTO, BaseDTO> {

private static final Logger logger = LoggerFactory.getLogger(PreProcSkipListener.class);

@Autowired
@Qualifier("jdbcTemplate")
private JdbcTemplate jdbcTemplate;
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void onSkipInWrite(BaseDTO item, Throwable t) {
    Exception ex = new Exception(t);
    jdbcTemplate.update(InterConnectUtils.BATCH_ERROR_INSERT, new PreparedStatementSetter() {
        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            MMSDto mmsDto = (MMSDto) item;
            StringWriter sw = new StringWriter();
            ex.printStackTrace(new PrintWriter(sw));
            String exceptionAsString = sw.toString();
            ps.setDate(1, new java.sql.Date(new Date().getTime()));
            ps.setString(2, mmsDto.getBatchNumber());
            ps.setString(3, "WRITER");
            Reader reader = new StringReader(exceptionAsString + "--" + ex.getMessage());
            ps.setClob(4, reader);
        }

    });

    }
   }}

There is an open issue mentioned in github to consider. Let us know any workaround
github defect


问:
how can I run commands in VSCode in VSCode tasks with password prompt?
I have this .vscode/tasks.json file:

```<code>{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Run mysql on startup",
            "type":"shell",
            "command": "sudo mysql.server start",
            "presentation": {
                "reveal": "always",
                "panel": "new"
            },
            "runOptions": { "runOn": "folderOpen" },
            "options": {

            }
        }
    ]
}

</code>```

when I run sudo mysql.server start in the terminal, I have to add my password in a separate command.

I want:

combine the command with the password in one command.

get the password in a secure way (like using .env or from a secure file, etc).

by the way, I am using a mac OS.

Body:
I have this .vscode/tasks.json file:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Run mysql on startup",
            "type":"shell",
            "command": "sudo mysql.server start",
            "presentation": {
                "reveal": "always",
                "panel": "new"
            },
            "runOptions": { "runOn": "folderOpen" },
            "options": {

            }
        }
    ]
}

when I run sudo mysql.server start in the terminal, I have to add my password in a separate command.

I want:

combine the command with the password in one command.

get the password in a secure way (like using .env or from a secure file, etc).

by the way, I am using a mac OS.


问:
Handling QEventloop and QThread
Can we create our own event loop inside QThread inherited class ? Is it a good approach as QThread itself have its own event loop. I am looing for a good approach to implement thread which exists life time of the application which should be also capable of emitting signals to another thread. I am little confused on the usage of QEventloop. This is my current implementation. Can someone suggest is this a good approach ?</p>
```<code>class MyWorker: public QThread
{
    public :
      void run() {
        while (notExit)
        {
            evLoop->processEvents(QEventLoop::AllEvents, 10);
        }
      }
      void post(int eventMsg){
        QMetaObject::invokeMethod(this, [this, eventMsg] {
            onMessage(int eventMsg);
        }, Qt::QueuedConnection);
      }

      void onMessage(int eventMsg)
      {
          if(eventMsg == 1) { evLoop->quit(); }
      }
};
</code>```

Title: Handling QEventloop and QThread

Body:
Can we create our own event loop inside QThread inherited class ? Is it a good approach as QThread itself have its own event loop. I am looing for a good approach to implement thread which exists life time of the application which should be also capable of emitting signals to another thread. I am little confused on the usage of QEventloop. This is my current implementation. Can someone suggest is this a good approach ?

class MyWorker: public QThread
{
    public :
      void run() {
        while (notExit)
        {
            evLoop->processEvents(QEventLoop::AllEvents, 10);
        }
      }
      void post(int eventMsg){
        QMetaObject::invokeMethod(this, [this, eventMsg] {
            onMessage(int eventMsg);
        }, Qt::QueuedConnection);
      }

      void onMessage(int eventMsg)
      {
          if(eventMsg == 1) { evLoop->quit(); }
      }
};


问:
Android- How to read meta data from Custom chrome tab?
I am building an Android application in which I would like to launch the privacy policy web URL using Custom chrome tab.

As the privacy policy might be changing in the future, we would like to maintain the document version in <metadata> tag of HTML page.

Is it possible to read the meta data while using Custom chrome tab?


问:
How can I deploy a graphql server in lambda linking with a websocket apigateway in go
I am trying to deploy a graphql server in AWS over websocket connection. I have deployed a websocket apigateway which has two routes, $connect and $default. Each route points to a lambda implemented in golang. I am using LAMBDA_PROXY.

I am using github.com/graph-gophers/graphql-go library to support resolvers in the lambda side. Since the apigateway provides websocket connection, I don't need any websocket transport inside my lambda.

What I am trying to do is to receive the subscribe request from clients and parse the request body and save the connection and subscribed topic in a database.

But I can't figure out how to make it work without a real ws grahpql transport in the lambda.

Below is the code in lambda for $connect route,

```<code>func (h *Handler) GraphqlSubscriptionHandler(ctx context.Context, event events.APIGatewayWebsocketProxyRequest) (events.APIGatewayProxyResponse, error) {
    log.Println("event.RequestContext ConnectionID:", event.RequestContext.ConnectionID)
    log.Println("body", event.Body)
    log.Println("PathParameters", event.PathParameters)
    log.Println("QueryStringParameters", event.QueryStringParameters)
    return events.APIGatewayProxyResponse{Body: "", StatusCode: 200}, nil
}

func main() {
   lambda.Start(GraphqlSubscriptionHandler)
}
</code>```

when the client sends a subscription request like below:

```<code>subscription event {
    event(on:"xxxx") {
      message
    }
  }
</code>```

I can see below logs in $connect lambda but the $default route lambda is not triggered.

```<code>event.RequestContext ConnectionID: dbmemc7FywMCEpQ=
body
PathParameters map[]
QueryStringParameters map[]
</code>```

In above log, I can only get connectionId from the client but the body is empty. I think it is correct because this is $connect route which only handle connection.

The problem is more about why $default route doesn't receive any requests. Below is the client side which is using apollo client:

```<code>const { ApolloClient } = require('apollo-client');
const { InMemoryCache } = require('apollo-cache-inmemory');
const { WebSocketLink } = require('apollo-link-ws');
const { SubscriptionClient } = require('subscriptions-transport-ws');
const ws = require('ws');
const gql = require('graphql-tag');

const wsLink = new WebSocketLink(
  new SubscriptionClient(
    'wss://xxxx.execute-api.ap-southeast-2.amazonaws.com/dev',
    {
      reconnect: true,
    },
    ws
  )
);

const client = new ApolloClient({
  link: wsLink,
  cache: new InMemoryCache(),
});

const s = client.subscribe({
  query: gql`
  subscription event {
    event(on:"xxxx") {
      message
    }
  }
  `,
});

s.subscribe({
  next: ({ data }) => console.log(data),
  error: (err) => console.error(err),
});

</code>```

Body:
I am trying to deploy a graphql server in AWS over websocket connection. I have deployed a websocket apigateway which has two routes, $connect and $default. Each route points to a lambda implemented in golang. I am using LAMBDA_PROXY.

I am using github.com/graph-gophers/graphql-go library to support resolvers in the lambda side. Since the apigateway provides websocket connection, I don't need any websocket transport inside my lambda.

What I am trying to do is to receive the subscribe request from clients and parse the request body and save the connection and subscribed topic in a database.

But I can't figure out how to make it work without a real ws grahpql transport in the lambda.

Below is the code in lambda for $connect route,

func (h *Handler) GraphqlSubscriptionHandler(ctx context.Context, event events.APIGatewayWebsocketProxyRequest) (events.APIGatewayProxyResponse, error) {
    log.Println("event.RequestContext ConnectionID:", event.RequestContext.ConnectionID)
    log.Println("body", event.Body)
    log.Println("PathParameters", event.PathParameters)
    log.Println("QueryStringParameters", event.QueryStringParameters)
    return events.APIGatewayProxyResponse{Body: "", StatusCode: 200}, nil
}

func main() {
   lambda.Start(GraphqlSubscriptionHandler)
}

when the client sends a subscription request like below:

subscription event {
    event(on:"xxxx") {
      message
    }
  }

I can see below logs in $connect lambda but the $default route lambda is not triggered.

event.RequestContext ConnectionID: dbmemc7FywMCEpQ=
body
PathParameters map[]
QueryStringParameters map[]

In above log, I can only get connectionId from the client but the body is empty. I think it is correct because this is $connect route which only handle connection.

The problem is more about why $default route doesn't receive any requests. Below is the client side which is using apollo client:

const { ApolloClient } = require('apollo-client');
const { InMemoryCache } = require('apollo-cache-inmemory');
const { WebSocketLink } = require('apollo-link-ws');
const { SubscriptionClient } = require('subscriptions-transport-ws');
const ws = require('ws');
const gql = require('graphql-tag');

const wsLink = new WebSocketLink(
  new SubscriptionClient(
    'wss://xxxx.execute-api.ap-southeast-2.amazonaws.com/dev',
    {
      reconnect: true,
    },
    ws
  )
);

const client = new ApolloClient({
  link: wsLink,
  cache: new InMemoryCache(),
});

const s = client.subscribe({
  query: gql`
  subscription event {
    event(on:"xxxx") {
      message
    }
  }
  `,
});

s.subscribe({
  next: ({ data }) => console.log(data),
  error: (err) => console.error(err),
});


问:
Access command line arguments in jsf web application backing bean
I'm building a web app with jsf 2.3 (Java 8, GlassFish application server). Obviously I dont have access to the main function, so my questions are

Can I have access to the command line arguments inside my beans?

How can I pass command line arguments to my application through GlassFish?

```<code>@Named(value = 'myBean')
@ApplicationScope
public class MyBean {

    String argc[] args = ConsoleLineArguments();

    ...
}
</code>```

Body:
I'm building a web app with jsf 2.3 (Java 8, GlassFish application server). Obviously I dont have access to the main function, so my questions are

Can I have access to the command line arguments inside my beans?

How can I pass command line arguments to my application through GlassFish?

@Named(value = 'myBean')
@ApplicationScope
public class MyBean {

    String argc[] args = ConsoleLineArguments();

    ...
}


问:
Images Conversion into video
If I select multiple images from gallery  then how I can convert them into video in flutter?

There is no package for this to work.

Title: Images Conversion into video


问:
Creating security for web application issue in the code for logging into the page
I was building spring security web application using "https://spring.io/guides/gs/securing-web/" but im getting error as " Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Tue Dec 20 11:47:42 IST 2022
There was an unexpected error (type=Internal Server Error, status=500). "pls help!!

i tried to add some jsp dependencies / to use @ configuration but still same error and i am expecting the message to be displayed


问:
How to make tkinter frame scrollable. I want to make a scrollable frame with various frame containing text
I put the text inside a frame and make those frames scrollable inside the parent frame. I have done a lot of afforts but cannot achieve this the error says.
"AttributeError: 'Frame' object has no attribute 'yview'" Is there any way to resolve this?</p>
```<code>from tkinter import *
def main():
    window = Tk()
    window.title("TexComp")
    window.geometry("500x500")
    window.resizable(height=FALSE,width=FALSE)
    windowBackground = '#E3DCA8'
    window.configure(bg=windowBackground)
    frameinfo1 = Frame(window, bd=2, bg="white")
    frameinfo1.grid(row=0, column=0, sticky=E + W + N + S)
    instruction = Label(frameinfo1,text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.", bg=windowBackground)
    instruction.grid(row=0,column=0)
    frameinfo2 = Frame(window, bd=2, bg="white")
    frameinfo2.grid(row=1, column=0, sticky=E + W + N + S)
    instruction = Label(frameinfo2,
                        text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.",
                        bg=windowBackground)
    instruction.grid(row=0, column=0)
    frameinfo3 = Frame(window, bd=2, bg="white")
    frameinfo3.grid(row=2, column=0, sticky=E + W + N + S)
    instruction = Label(frameinfo3,
                        text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.",
                        bg=windowBackground)
    instruction.grid(row=0, column=0)
    scroll1y=Scrollbar(window, command=frameinfo1.yview)
    scroll1y.grid(row=0,column=1,rowspan=5)
    mainloop()
if __name__ == '__main__':
    main()
</code>```

Body:
I put the text inside a frame and make those frames scrollable inside the parent frame. I have done a lot of afforts but cannot achieve this the error says.
"AttributeError: 'Frame' object has no attribute 'yview'" Is there any way to resolve this?

from tkinter import *
def main():
    window = Tk()
    window.title("TexComp")
    window.geometry("500x500")
    window.resizable(height=FALSE,width=FALSE)
    windowBackground = '#E3DCA8'
    window.configure(bg=windowBackground)
    frameinfo1 = Frame(window, bd=2, bg="white")
    frameinfo1.grid(row=0, column=0, sticky=E + W + N + S)
    instruction = Label(frameinfo1,text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.", bg=windowBackground)
    instruction.grid(row=0,column=0)
    frameinfo2 = Frame(window, bd=2, bg="white")
    frameinfo2.grid(row=1, column=0, sticky=E + W + N + S)
    instruction = Label(frameinfo2,
                        text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.",
                        bg=windowBackground)
    instruction.grid(row=0, column=0)
    frameinfo3 = Frame(window, bd=2, bg="white")
    frameinfo3.grid(row=2, column=0, sticky=E + W + N + S)
    instruction = Label(frameinfo3,
                        text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.",
                        bg=windowBackground)
    instruction.grid(row=0, column=0)
    scroll1y=Scrollbar(window, command=frameinfo1.yview)
    scroll1y.grid(row=0,column=1,rowspan=5)
    mainloop()
if __name__ == '__main__':
    main()


问:
prisma query change add custom column in select and update field
Below is the snippet with comments that, we are planning to achieve with Prisma orm query, which is quite possible in raw SQL.

```<code>class User {
  id: number;
  type: 'custom' | 'default' | 'legacy';
  name: string;
  email: string;
  dep?: string;
  createdAt: Date;
  updatedAt: Date

}

prisma.users.findMany({
        where: {
          type: {in : ['custom', 'legacy']},
        },
        select:{
          type: // constant as 'custom'
          dep: true // want to alert it to department
        }
        // add new property, not part of schema
        createdBy: 'System'
      })
</code>```

Not able to find anything in the doc related to requirements here.

set a constant value for a field here e.g. type to custom

change filed/column name e.g. dep -> department

add new filed/column which is not part of table schema

Body:
Below is the snippet with comments that, we are planning to achieve with Prisma orm query, which is quite possible in raw SQL.

class User {
  id: number;
  type: 'custom' | 'default' | 'legacy';
  name: string;
  email: string;
  dep?: string;
  createdAt: Date;
  updatedAt: Date

}

prisma.users.findMany({
        where: {
          type: {in : ['custom', 'legacy']},
        },
        select:{
          type: // constant as 'custom'
          dep: true // want to alert it to department
        }
        // add new property, not part of schema
        createdBy: 'System'
      })

Not able to find anything in the doc related to requirements here.

set a constant value for a field here e.g. type to custom

change filed/column name e.g. dep -> department

add new filed/column which is not part of table schema


问:
IVR twilio programmable SMS and Email alert stopped working after twilio reset
Please I have an IVR solution build with php on asterisk issabel. I am currently using twilio programmable api for SMS and Email otp verification. Eveything was working fine until yesterday when my account was reset by twilio team. Now I cannot receive SMS and Email otp and message. Please help me what should I do.
Thanks

I have checked all the message sid from my source code and everything look fine.


问:
How to fix Fancybox called multiple times after opened?
My web page work fine, but when I check Network it showed the fancybox do multiple request.
Here is my situtation open_bp_wip_detail runs 3 times
F12 Network
Here my codes

```<code><div>
<%= link_to 'Detail',{:action => :open_bp_wip_detail, :device => 'device_01'}, {:class => "fancy"} %>
</div>

<script>
$(document).ready(function() {
    $('.fancy').addClass('fancybox.ajax');
});
</script>

</code>```

Let fancybox only request once.

Body:
My web page work fine, but when I check Network it showed the fancybox do multiple request.
Here is my situtation open_bp_wip_detail runs 3 times
F12 Network
Here my codes

<%= link_to 'Detail',{:action => :open_bp_wip_detail, :device => 'device_01'}, {:class => "fancy"} %>

Let fancybox only request once.


问:
Play console not showing statics for managed app
The Play console is not showing the statistics of the app installed on the client side as they are using the SOTI Mobility Control as EMM for managing their device. The statics are showing only the count of device that we installed in our dev environment. As we are not getting any statistics of the client side installation counts.

We want to get the statistics of the app usage in the client side in the Google play console.


问:
Copy the values from the next row using Pandas
I have a data frame. There are multiple rows with the same email id. I wanted to copy the values from the next row (second/consecutive) , only for the columns in the first row is empty, for the same email id.

Lets say i have a data frame.

input df

So, now i tried to check if the email id of two consecutive rows are same, and then copy the values from the second row if the first row of the columns are empty.

```<code>if df['EMAIL'][i]==df['EMAIL'][j+1]:
            #df.loc[big_df['NAME'][i].isnull(), 'Y'] = big_df['NAME'][j+1]
            df['NAME'][i].fillna(method='bfill', inplace=True)
            j=j+1
else:
            print('noting to do')
</code>```

I tried the above code and got an error as follows.

```<code>Attributerror: 'float' object has no attribut 'fillna'

</code>```

I am looking for the output as given below:
output df

Body:
I have a data frame. There are multiple rows with the same email id. I wanted to copy the values from the next row (second/consecutive) , only for the columns in the first row is empty, for the same email id.

Lets say i have a data frame.

input df

So, now i tried to check if the email id of two consecutive rows are same, and then copy the values from the second row if the first row of the columns are empty.

if df['EMAIL'][i]==df['EMAIL'][j+1]:
            #df.loc[big_df['NAME'][i].isnull(), 'Y'] = big_df['NAME'][j+1]
            df['NAME'][i].fillna(method='bfill', inplace=True)
            j=j+1
else:
            print('noting to do')

I tried the above code and got an error as follows.

Attributerror: 'float' object has no attribut 'fillna'

I am looking for the output as given below:
output df


问:
Creating a simple multiple user types in Django
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here.

Here's what I have so far.

models.py

```<code>class CustomUser(AbstractUser):
    ACCOUNT_TYPE_CHOICES = (
        ('admin', 'Admin'),
        ('developer', 'Developer'),
        ('project_manager', 'Project Manager')
    )
    account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES)
</code>```

login and signupviews

```<code>class LoginView(View):
    def get(self, request):
        # Render the login form
        form = LoginForm()
        return render(request, 'users/login.html', {'form': form})

    def post(self, request):
        # Get the form data from the request
        form = LoginForm(request.POST)

        # Validate the form data
        if form.is_valid():
            # Get the username and password from the form
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            # Authenticate the user
            user = authenticate(request, username=username, password=password)

            # If the user is authenticated, log them in and redirect to the homepage
            if user is not None:
                login(request, user)
                if user.account_type == 'admin':
                    return redirect('admin_home')
                elif user.account_type == 'developer':
                    return redirect('developer_home')
                elif user.account_type == 'project_manager':
                    return redirect('projectmanager_home')
                return redirect('home')

            # If the user is not authenticated, render the login form again with an error message
            else:
                form.add_error(None, 'Invalid username or password')
                return render(request, 'users/login.html', {'form': form})
        else:
            return render(request, 'users/login.html', {'form': form})

class LogoutView(View):
    def get(self, request):
        # Log out the user and redirect to the login page
        logout(request)
        return redirect('home')

class AdminSignUpView(CreateView):
    form_class = AdminSignUpForm
    template_name = 'users/admin_signup.html'
    success_url = '/admin_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class DeveloperSignUpView(CreateView):
    form_class = DeveloperSignUpForm
    template_name = 'users/developer_signup.html'
    success_url = '/developer_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class ProjectManagerSignUpView(CreateView):
    form_class = ProjectManagerSignUpForm
    template_name = 'users/projectmanager_signup.html'
    success_url = '/projectmanager_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

</code>```

forms.py

```<code>class AdminSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='admin')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class DeveloperSignUpForm(forms.ModelForm):
    # Define the form fields for the developer sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='developer')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class ProjectManagerSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='admin')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class LoginForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'password']
        widgets = {
            'password': forms.PasswordInput(),
        }
</code>```

Let me know if you need any more information.

Body:
So I've created 3 different users: admins, developers, and project managers. When I use the individual signup forms for each of these users and log out, it works, but then I when try to use the login form, it seems to me that it's acting like the signup form. Because when I input the same user details as the one I just created into the login form, it throws up the built-in error message, 'A user with that user name already exists' I'm not sure how to proceed from here.

Here's what I have so far.

models.py

class CustomUser(AbstractUser):
    ACCOUNT_TYPE_CHOICES = (
        ('admin', 'Admin'),
        ('developer', 'Developer'),
        ('project_manager', 'Project Manager')
    )
    account_type = models.CharField(max_length=20, choices=ACCOUNT_TYPE_CHOICES)

login and signupviews

class LoginView(View):
    def get(self, request):
        # Render the login form
        form = LoginForm()
        return render(request, 'users/login.html', {'form': form})

    def post(self, request):
        # Get the form data from the request
        form = LoginForm(request.POST)

        # Validate the form data
        if form.is_valid():
            # Get the username and password from the form
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']

            # Authenticate the user
            user = authenticate(request, username=username, password=password)

            # If the user is authenticated, log them in and redirect to the homepage
            if user is not None:
                login(request, user)
                if user.account_type == 'admin':
                    return redirect('admin_home')
                elif user.account_type == 'developer':
                    return redirect('developer_home')
                elif user.account_type == 'project_manager':
                    return redirect('projectmanager_home')
                return redirect('home')

            # If the user is not authenticated, render the login form again with an error message
            else:
                form.add_error(None, 'Invalid username or password')
                return render(request, 'users/login.html', {'form': form})
        else:
            return render(request, 'users/login.html', {'form': form})

class LogoutView(View):
    def get(self, request):
        # Log out the user and redirect to the login page
        logout(request)
        return redirect('home')

class AdminSignUpView(CreateView):
    form_class = AdminSignUpForm
    template_name = 'users/admin_signup.html'
    success_url = '/admin_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class DeveloperSignUpView(CreateView):
    form_class = DeveloperSignUpForm
    template_name = 'users/developer_signup.html'
    success_url = '/developer_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

class ProjectManagerSignUpView(CreateView):
    form_class = ProjectManagerSignUpForm
    template_name = 'users/projectmanager_signup.html'
    success_url = '/projectmanager_home/'

    def form_valid(self, form):
        # Create the user and log them in
        user = form.save()
        login(self.request, user)
        return redirect(self.success_url)

forms.py

class AdminSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='admin')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class DeveloperSignUpForm(forms.ModelForm):
    # Define the form fields for the developer sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='developer')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class ProjectManagerSignUpForm(forms.ModelForm):
    # Define the form fields for the admin sign-up form
    account_type = forms.CharField(max_length=20, widget=forms.HiddenInput(), initial='admin')
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    email = forms.EmailField()
    username = forms.CharField(max_length=150)
    password = forms.CharField(max_length=128, widget=forms.PasswordInput())

    class Meta:
        model = CustomUser
        fields = ['first_name', 'last_name', 'email', 'username', 'password']

class LoginForm(forms.ModelForm):
    class Meta:
        model = CustomUser
        fields = ['username', 'password']
        widgets = {
            'password': forms.PasswordInput(),
        }

Let me know if you need any more information.


问:
After adding Content security policy , i have encountered issues in console
I am adding csp by eliminating * and adding respective rules.Now I am facing issues like
1.Error retrieving icon: Wale! Svg tag not found
2.Cannot read properties of undefined(reading 'cols').

But if we add * the error is not thrown.


问:
Elastic Beanstalk running Docker stops and doesn't restart
I have a simple single-instance Elastic Beanstalk application that runs Node.js. About 6 hours ago, I had gotten an alarm email from EB that the environment status had turned to Degraded. Once I logged in the AWS console, I saw this message:

Following services are not running: eb-docker-compose-log.

Once I logged in with SSH on the instance, I could see that Docker is indeed not running quite right:

```<code>$ ps aux | grep -i docker
root      1262  0.0  6.7 1447872 65116 ?       Ssl  Dec11   4:56 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --default-ulimit nofile=32768:65536
root      1418  0.0  2.6 1125944 25636 ?       Ssl  Dec11   0:36 docker events
root      1864  0.0  5.8 178520 56568 ?        Ss   Dec11   0:00 /bin/python3 /usr/local/bin/docker-compose events
ec2-user 21525  0.0  0.0 112896   512 pts/0    S+   06:23   0:00 grep --color=auto -i docker
</code>```

Before this error, I remember that I could see a node index.js process in this output.

One important thing to note is that I'm using spot instances, but there wasn't anything peculiar happening lately. The current instance has been running for over 7 days straight. It's not like it was replaced by another one.

I guess I could just restart the instance and fix this, but my question is why doesn't Elastic Beanstalk do that itself? It obviously detects that something is wrong, yet does nothing about it. I searched most log files, but found nothing useful. Is there anything else I could check to see what went wrong?

Body:
I have a simple single-instance Elastic Beanstalk application that runs Node.js. About 6 hours ago, I had gotten an alarm email from EB that the environment status had turned to Degraded. Once I logged in the AWS console, I saw this message:

Following services are not running: eb-docker-compose-log.

Once I logged in with SSH on the instance, I could see that Docker is indeed not running quite right:

$ ps aux | grep -i docker
root      1262  0.0  6.7 1447872 65116 ?       Ssl  Dec11   4:56 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --default-ulimit nofile=32768:65536
root      1418  0.0  2.6 1125944 25636 ?       Ssl  Dec11   0:36 docker events
root      1864  0.0  5.8 178520 56568 ?        Ss   Dec11   0:00 /bin/python3 /usr/local/bin/docker-compose events
ec2-user 21525  0.0  0.0 112896   512 pts/0    S+   06:23   0:00 grep --color=auto -i docker

Before this error, I remember that I could see a node index.js process in this output.

One important thing to note is that I'm using spot instances, but there wasn't anything peculiar happening lately. The current instance has been running for over 7 days straight. It's not like it was replaced by another one.

I guess I could just restart the instance and fix this, but my question is why doesn't Elastic Beanstalk do that itself? It obviously detects that something is wrong, yet does nothing about it. I searched most log files, but found nothing useful. Is there anything else I could check to see what went wrong?


问:
Export Zonal Stat CSV for a multipolygon shp csv to an individual polygon csv
I want to compute daily surface temperature over district level of india for last 5 year. but for this large feature collection it is not possible to compute it in one csv. because it sown an error as "User memory limit exceed" . So i am computing this one by one for each state and a single year...and this process took so much time...as there are 37 state an ut....SO is there any way to compute it once for all....here is my code sample.

```<code>var filter = table.filter(ee.Filter.eq("State_Name", 'ARUNACHAL PRADESH'))

var collection = ee.ImageCollection("ECMWF/ERA5_LAND/HOURLY")
                  .filterDate(startDate, endDate)
                  .filterBounds(filter)
                  .select('skin_temperature');
//Map.addLayer(collection,{},'collection')

var numberOfDays1 = endDate.difference(startDate, 'days');

var daily1 = ee.ImageCollection(
  ee.List.sequence(0, numberOfDays1.subtract(1))
    .map(function (dayOffset) {
      var start = startDate.advance(dayOffset, 'days');
      var end = start.advance(1, 'days');
      return collection
        .filterDate(start, end)
        .mean()
        .set('system:time_start', start.millis());
    })
);

function maskimg(img){
  return img.clip(filter)
  .subtract(273.15)
  .copyProperties(img, img.propertyNames());
}
var temp = ee.ImageCollection(daily1)
.filter(ee.Filter.date(startDate, endDate))
.select('skin_temperature').filterBounds(filter).map(maskimg);
//print ("skin_temperature", temp);
var bands = temp.toBands();
var zonal = bands.reduceRegions({
  collection: filter,
  reducer: ee.Reducer.mean(),
  scale: 11132,
  // tileScale: 8,
});
//Map.addLayer(temp,{},'temp')

Export.table.toDrive({

  description:'ARUNACHAL_PRADESH',
  collection: zonal,
  folder : 'TEMP_DAILY_2022',
  fileFormat: 'CSV',
  fileName: 'ARUNACHAL_PRADESH'

 });

</code>```

i tried to do it one by one...changing the state name from feature collection....I just want to know that is there any way to do this process in a short way...
like...looping the feature collection for each state and export csv for all state one by all.

Body:
I want to compute daily surface temperature over district level of india for last 5 year. but for this large feature collection it is not possible to compute it in one csv. because it sown an error as "User memory limit exceed" . So i am computing this one by one for each state and a single year...and this process took so much time...as there are 37 state an ut....SO is there any way to compute it once for all....here is my code sample.

var filter = table.filter(ee.Filter.eq("State_Name", 'ARUNACHAL PRADESH'))

var collection = ee.ImageCollection("ECMWF/ERA5_LAND/HOURLY")
                  .filterDate(startDate, endDate)
                  .filterBounds(filter)
                  .select('skin_temperature');
//Map.addLayer(collection,{},'collection')

var numberOfDays1 = endDate.difference(startDate, 'days');

var daily1 = ee.ImageCollection(
  ee.List.sequence(0, numberOfDays1.subtract(1))
    .map(function (dayOffset) {
      var start = startDate.advance(dayOffset, 'days');
      var end = start.advance(1, 'days');
      return collection
        .filterDate(start, end)
        .mean()
        .set('system:time_start', start.millis());
    })
);

function maskimg(img){
  return img.clip(filter)
  .subtract(273.15)
  .copyProperties(img, img.propertyNames());
}
var temp = ee.ImageCollection(daily1)
.filter(ee.Filter.date(startDate, endDate))
.select('skin_temperature').filterBounds(filter).map(maskimg);
//print ("skin_temperature", temp);
var bands = temp.toBands();
var zonal = bands.reduceRegions({
  collection: filter,
  reducer: ee.Reducer.mean(),
  scale: 11132,
  // tileScale: 8,
});
//Map.addLayer(temp,{},'temp')

Export.table.toDrive({

  description:'ARUNACHAL_PRADESH',
  collection: zonal,
  folder : 'TEMP_DAILY_2022',
  fileFormat: 'CSV',
  fileName: 'ARUNACHAL_PRADESH'

 });

i tried to do it one by one...changing the state name from feature collection....I just want to know that is there any way to do this process in a short way...
like...looping the feature collection for each state and export csv for all state one by all.


问:
Printing letters in a group of fours from a string
I am trying to print the letters from this string in groups of four.

For example:

string sequence = "GnatBatsFish"

I am trying to get the letters to print out like this:

Gnat
Bats
Fish

I've tried to attempt this with the code below but it just ends up printing the first letter of each word in the string:

```<code> string sequences = "GnatBatsFish";

            int test = 4;
            int j;
            for (j = 0; j < test; j++)
            {
                Console.WriteLine(sequences[j]);
                j += 3;
                test += 3;

            }
</code>```

Outputs:

G
B
F

Body:
I am trying to print the letters from this string in groups of four.

For example:

string sequence = "GnatBatsFish"

I am trying to get the letters to print out like this:

Gnat
Bats
Fish

I've tried to attempt this with the code below but it just ends up printing the first letter of each word in the string:

 string sequences = "GnatBatsFish";

            int test = 4;
            int j;
            for (j = 0; j < test; j++)
            {
                Console.WriteLine(sequences[j]);
                j += 3;
                test += 3;

            }

Outputs:

G
B
F


问:
Suggestion container of react-google-autocomplete package
enter image description hereHow can I show the suggestion container in top of the input field using react-google-autocomplete package?</p>
```<code>import React from "react";
import Autocomplete from "react-google-autocomplete";

const AddressSearch = (props) => {
  const onClickPlace = (place) => {
    console.log(place);
  };

  return (
    <Autocomplete
      className="w-full px-4 py-2 rounded-lg bg-[#343A40] focus:outline-none focus:border-btnBlue focus:btnBlue focus:ring-2"
      apiKey="api_key"
      onPlaceSelected={(place) => onClickPlace(place)}
      placeholder="Address Search..."
    />
  );
};

export default AddressSearch;

</code>```

Body:
enter image description hereHow can I show the suggestion container in top of the input field using react-google-autocomplete package?

import React from "react";
import Autocomplete from "react-google-autocomplete";

const AddressSearch = (props) => {
  const onClickPlace = (place) => {
    console.log(place);
  };

  return (
    <Autocomplete
      className="w-full px-4 py-2 rounded-lg bg-[#343A40] focus:outline-none focus:border-btnBlue focus:btnBlue focus:ring-2"
      apiKey="api_key"
      onPlaceSelected={(place) => onClickPlace(place)}
      placeholder="Address Search..."
    />
  );
};

export default AddressSearch;


问:
How do I use aggregate functions in the conditional of an Altair condition statement?
I rarely use Altair conditions (basically Vega-Lite expressions) but whenever I do they seem to cause me a challenge. I'm working on a dataset where I want to slightly obfuscate small values e.g. if a value is less than 5, I want the label to display as "< 5" rather than "3".

Let's say my working histogram looks something like this:

```<code>bars_cl6_labels = bars_cl6.mark_text(
  color = '#ff6100',
  dy = -10,
  fontSize = 12
).encode(
  text = 'count():Q',
)
</code>```

I need to update the value of the text label in the encode step, so I've been trying variations of:

```<code>bars_cl6_labels = bars_cl6.mark_text(
  color = '#ff6100',
  dy = -10,
  fontSize = 12
).encode(
  text = alt.condition(+'count():Q' < 5, 'count():Q', alt.value('< 5'))
)
</code>```

...but the initial +'count():Q' < 5 is invalid.

Is there a different way of writing the conditional part of the condition expression?

Body:
I rarely use Altair conditions (basically Vega-Lite expressions) but whenever I do they seem to cause me a challenge. I'm working on a dataset where I want to slightly obfuscate small values e.g. if a value is less than 5, I want the label to display as "< 5" rather than "3".

Let's say my working histogram looks something like this:

bars_cl6_labels = bars_cl6.mark_text(
  color = '#ff6100',
  dy = -10,
  fontSize = 12
).encode(
  text = 'count():Q',
)

I need to update the value of the text label in the encode step, so I've been trying variations of:

bars_cl6_labels = bars_cl6.mark_text(
  color = '#ff6100',
  dy = -10,
  fontSize = 12
).encode(
  text = alt.condition(+'count():Q' < 5, 'count():Q', alt.value('< 5'))
)

...but the initial +'count():Q' < 5 is invalid.

Is there a different way of writing the conditional part of the condition expression?


问:
JPA Error when using CriteriaBuilder.diff for calculation number of days between a date and now?
I calculate number of days between a date and now using this expression:

```<code>Expression<Integer> diffInDays = cb.function("date_part", Integer.class, cb.literal("day"), cb.diff(cb.currentDate(), contractJoin.get("endDate")) );
</code>```

But the VS Code complain that "The method diff(Expression<? extends N>, Expression<? extends N>) in the type CriteriaBuilder is not applicable for the arguments (Expression, Path)"

How can i solve this?

Thank you

Body:
I calculate number of days between a date and now using this expression:

Expression<Integer> diffInDays = cb.function("date_part", Integer.class, cb.literal("day"), cb.diff(cb.currentDate(), contractJoin.get("endDate")) );

But the VS Code complain that "The method diff(Expression<? extends N>, Expression<? extends N>) in the type CriteriaBuilder is not applicable for the arguments (Expression, Path)"

How can i solve this?

Thank you


问:
Unity to Microsoft SQL Server
I am trying to link my Unity project and SQL Server together with PHP. Currently, I am trying to setup the login credentials alongside user registration. However, Unity doesn't read the num_row function as shown below. Are there any other ways?

```<code>$loginID = $_POST["loginID"];
$loginName = $_POST["loginName"];
$loginEmail = $_POST["loginEmail"];

$sql = "SELECT id FROM testing WHERE id = '" . $loginID . "'";
$result = sqlsrv_query($conn,$sql);

if($result->num_rows > 0)
{
  echo "Staff ID exists";
}
else
{
  echo "Creating user...";
  $sql2 = "INSERT INTO testing (id,name,email) VALUES ('" . $loginID . "','" . $loginName . "', '" . $loginEmail . "')";
  $result1 = sqlsrv_query($conn,$sql2);

  if($result1 == TRUE)
  {
    echo " New user has been created successfully";
  }
  else
  {
    echo "Error: " . $sql2 . "<br>" . $conn->error;
  }

}
</code>```

Thanks guys!

I want to pull and push data between Unity and SSMS.

```<code>IEnumerator Register(string id, string name, string email)
    {
        WWWForm form = new WWWForm();
        form.AddField("loginID",id);
        form.AddField("loginName",name);
        form.AddField("loginEmail",email);
        using (UnityWebRequest www = UnityWebRequest.Post("http://localhost/UnityBackendTest/Register.php", form))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
            }
        }
    }
</code>```

Title: Unity to Microsoft SQL Server

Body:
I am trying to link my Unity project and SQL Server together with PHP. Currently, I am trying to setup the login credentials alongside user registration. However, Unity doesn't read the num_row function as shown below. Are there any other ways?

$loginID = $_POST["loginID"];
$loginName = $_POST["loginName"];
$loginEmail = $_POST["loginEmail"];

$sql = "SELECT id FROM testing WHERE id = '" . $loginID . "'";
$result = sqlsrv_query($conn,$sql);

if($result->num_rows > 0)
{
  echo "Staff ID exists";
}
else
{
  echo "Creating user...";
  $sql2 = "INSERT INTO testing (id,name,email) VALUES ('" . $loginID . "','" . $loginName . "', '" . $loginEmail . "')";
  $result1 = sqlsrv_query($conn,$sql2);

  if($result1 == TRUE)
  {
    echo " New user has been created successfully";
  }
  else
  {
    echo "Error: " . $sql2 . "
" . $conn->error;
  }

}

Thanks guys!

I want to pull and push data between Unity and SSMS.

IEnumerator Register(string id, string name, string email)
    {
        WWWForm form = new WWWForm();
        form.AddField("loginID",id);
        form.AddField("loginName",name);
        form.AddField("loginEmail",email);
        using (UnityWebRequest www = UnityWebRequest.Post("http://localhost/UnityBackendTest/Register.php", form))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
            }
            else
            {
                Debug.Log(www.downloadHandler.text);
            }
        }
    }


问:
Can we change the hostname of Docker Container running in VM?
I am creating an elasticsearch image and want to run the container on some remote machine.

Suppose the machine hostname is "abc.com", so I am accessing the URL as "abc.com:9200" to access elasticsearch. After testing successfully, this container will be deployed to Kubernetes.
But to access elasticsearch (for filebeat, kibana and logstash) I need some static hostname so that while accessing it from different applications will be easy.
I am trying to make the hostname "elasticsearch" and want it to access as "http://elasticsearch:9200".

PS: I am new to Docker, and want to clear my doubts by asking silly questions

I have tried adding "--hostname" and "--add-host", both didnt worked.
docker run -d --name=elasticsearch \ --network=elk \ -p=9200:9200 -p 9300:9300 \ --hostname "elasticsearch" \ elasticsearch:7.17.6

Expecting to get the response by accessing "http://elsaticsearch:9200"


问:
Rust, what decides a function name is a fn pointer to fn item?
Here is the code that works.

use core::future::Future;

async fn haha(ctx: u8) -> u8 {
    return 2u8;
}

fn set_func<T>(path: &'static str, f: fn(u8) -> T) -> u8
where
    T: Future<Output = u8> + Send + 'static,
{
    return 8u8;
}

fn main() {
  set_func("haha", haha);
}

```
<p>but when I change the haha function to</p>
<pre class="lang-rust prettyprint-override"><code>use core::future::Future;

async fn haha(ctx: &mut u8) -> u8 {
    return 2u8;
}

fn set_func<T>(path: &'static str, f: fn(&mut u8) -> T) -> u8
where
    T: Future<Output = u8> + Send + 'static,
{
    return 8u8;
}

fn main() {
  set_func("haha", haha);
}

</code>```

Then error will shows like this:

```<code>   |
13 |     set_func("haha", haha);
   |     --------         ^^^^ one type is more general than the other
   |     |
   |     arguments to this function are incorrect
   |
   = note: expected fn pointer `for<'a> fn(&'a mut u8) -> _`
                 found fn item `for<'a> fn(&'a mut u8) -> impl Future<Output = u8> {haha}`
</code>```

I am so confusing that changing a argument from u8 to &mut u8 will change the fn pointer to fn item. why this happen?

and the &mut u8 is a requirement, do you have anyway can keep the &mut u8 and make it pass the type check?

Body:
Here is the code that works.

use core::future::Future;

async fn haha(ctx: u8) -> u8 {
    return 2u8;
}

fn set_func<T>(path: &'static str, f: fn(u8) -> T) -> u8
where
    T: Future<Output = u8> + Send + 'static,
{
    return 8u8;
}

fn main() {
  set_func("haha", haha);
}

but when I change the haha function to

use core::future::Future;

async fn haha(ctx: &mut u8) -> u8 {
    return 2u8;
}

fn set_func<T>(path: &'static str, f: fn(&mut u8) -> T) -> u8
where
    T: Future<Output = u8> + Send + 'static,
{
    return 8u8;
}

fn main() {
  set_func("haha", haha);
}

Then error will shows like this:

   |
13 |     set_func("haha", haha);
   |     --------         ^^^^ one type is more general than the other
   |     |
   |     arguments to this function are incorrect
   |
   = note: expected fn pointer `for<'a> fn(&'a mut u8) -> _`
                 found fn item `for<'a> fn(&'a mut u8) -> impl Future<Output = u8> {haha}`

I am so confusing that changing a argument from u8 to &mut u8 will change the fn pointer to fn item. why this happen?

and the &mut u8 is a requirement, do you have anyway can keep the &mut u8 and make it pass the type check?


问:
Import module that contain relative path importing in Python
I have a project tree as follow:

```<code>C:.
│   infer.py
│
└───models
    │   __init__.py
    │
    ├───cnn
    │       cnn.py
    │
    └───yolo
        │   yolo.py
        │
        └───model
                exp.py
                __init__.py
</code>```

In models/yolo/yolo.py, I've import a module by relative path like this:

```<code>from model.exp import Hello2

def Hello3():
    Hello2()
    print("Hello 3")
</code>```

And in infer.py:

```<code>from models.yolo.yolo import Hello3

Hello3()
</code>```

So when I execute code in infer.py, It's turn out like this:

```<code>Traceback (most recent call last):
  File "c:\Users\hoang\OneDrive\Desktop\test_module_py\tempCodeRunnerFile.py", line 1, in <module>
    from models.yolo.yolo import Hello3
  File "c:\Users\hoang\OneDrive\Desktop\test_module_py\models\yolo\yolo.py", line 1, in <module>
    from model.exp import Hello2
ModuleNotFoundError: No module named 'model'
</code>```

SO how can i deal with this problem

Please help me! Thanks a lot

Body:
I have a project tree as follow:

C:.
│   infer.py
│
└───models
    │   __init__.py
    │
    ├───cnn
    │       cnn.py
    │
    └───yolo
        │   yolo.py
        │
        └───model
                exp.py
                __init__.py

In models/yolo/yolo.py, I've import a module by relative path like this:

from model.exp import Hello2

def Hello3():
    Hello2()
    print("Hello 3")

And in infer.py:

from models.yolo.yolo import Hello3

Hello3()

So when I execute code in infer.py, It's turn out like this:

Traceback (most recent call last):
  File "c:\Users\hoang\OneDrive\Desktop\test_module_py\tempCodeRunnerFile.py", line 1, in <module>
    from models.yolo.yolo import Hello3
  File "c:\Users\hoang\OneDrive\Desktop\test_module_py\models\yolo\yolo.py", line 1, in <module>
    from model.exp import Hello2
ModuleNotFoundError: No module named 'model'

SO how can i deal with this problem

Please help me! Thanks a lot


问:
Flutter app crashes with "Invalid, null, or malformed redirect_uri supplied" error when using MSAL in release mode
I am using MSAL (Microsoft Authentication Library) in a Flutter app and when I try to run the app in release mode, it crashes with the following error:

```<code>Fatal Exception: java.lang.IllegalArgumentException: Invalid, null, or malformed redirect_uri supplied
       at com.microsoft.identity.client.PublicClientApplicationConfiguration.validateRedirectUri(:45)
       at com.microsoft.identity.client.PublicClientApplicationConfiguration.validateConfiguration(:2)
       at com.microsoft.identity.client.PublicClientApplicationConfigurationFactory.initializeConfigurationInternal(:14)
       at com.microsoft.identity.client.PublicClientApplicationConfigurationFactory.initializeConfiguration(:9)
       at com.microsoft.identity.client.PublicClientApplication$7.run(:4)
       at java.lang.Thread.run(Thread.java:764)
</code>```

I am using native code in my Flutter app and I have properly configured the redirect URI for my app, but I am still seeing this error.

I am creating a JSON file in native android and passing

```<code>client_id, resource_id, redirect_ui, tenant_id
</code>```

From flutter to native android because we have different users with different credentials like client_id, redirect_ui etc. And that JSON file we're using native android.

```<code>PublicClientApplication.createSingleAccountPublicClientApplication(context,   File("/data/data/" + context.getPackageName().toString() + "/" +"config.json"),
                object : ISingleAccountApplicationCreatedListener {
                    override fun onCreated(application: ISingleAccountPublicClientApplication) {

                        mSingleAccountApp = application
                        callBack(LoginModel(error = false,message = "initialized data",token = null))
                        loadAccount()
                    }

                    override fun onError(exception: MsalException) {
                        callBack(LoginModel(error = true,message = exception.message,token = null))

                    }
                })
</code>```

The is the method for initializing object of ISingleAccountPublicClientApplication and it was working fine in debug mode.

I have tried double-checking the redirect URI configuration, checking for typos or other mistakes in the URI, and checking for issues with the authorization request, but I am still having trouble resolving this issue.

Any help or suggestions on how to troubleshoot this error would be greatly appreciated.

Body:
I am using MSAL (Microsoft Authentication Library) in a Flutter app and when I try to run the app in release mode, it crashes with the following error:

Fatal Exception: java.lang.IllegalArgumentException: Invalid, null, or malformed redirect_uri supplied
       at com.microsoft.identity.client.PublicClientApplicationConfiguration.validateRedirectUri(:45)
       at com.microsoft.identity.client.PublicClientApplicationConfiguration.validateConfiguration(:2)
       at com.microsoft.identity.client.PublicClientApplicationConfigurationFactory.initializeConfigurationInternal(:14)
       at com.microsoft.identity.client.PublicClientApplicationConfigurationFactory.initializeConfiguration(:9)
       at com.microsoft.identity.client.PublicClientApplication$7.run(:4)
       at java.lang.Thread.run(Thread.java:764)

I am using native code in my Flutter app and I have properly configured the redirect URI for my app, but I am still seeing this error.

I am creating a JSON file in native android and passing

client_id, resource_id, redirect_ui, tenant_id

From flutter to native android because we have different users with different credentials like client_id, redirect_ui etc. And that JSON file we're using native android.

PublicClientApplication.createSingleAccountPublicClientApplication(context,   File("/data/data/" + context.getPackageName().toString() + "/" +"config.json"),
                object : ISingleAccountApplicationCreatedListener {
                    override fun onCreated(application: ISingleAccountPublicClientApplication) {

                        mSingleAccountApp = application
                        callBack(LoginModel(error = false,message = "initialized data",token = null))
                        loadAccount()
                    }

                    override fun onError(exception: MsalException) {
                        callBack(LoginModel(error = true,message = exception.message,token = null))

                    }
                })

The is the method for initializing object of ISingleAccountPublicClientApplication and it was working fine in debug mode.

I have tried double-checking the redirect URI configuration, checking for typos or other mistakes in the URI, and checking for issues with the authorization request, but I am still having trouble resolving this issue.

Any help or suggestions on how to troubleshoot this error would be greatly appreciated.


问:
How to change google places autocomplete URL form data
I have configured the Google places autocomplete and after selecting search I am getting URL form data like so:
http://127.0.0.1:8000/location/?term=1+York+Street%2C+Sydney+NSW%2C+Australia.
I would like to get it configured so that it returns multiple name/value pairs like so:
http://127.0.0.1:8000/location/?inputNumber=1&inputStreet=York+Street&inputCity=Sydney&inputState=NSW&inputZip=2000

This is required as I am using a Django and would like to use the name/value pairs to help with retrieving data from the model.

This what I have configured in my script tags:

```<code><script>
    function initMap() {
      var input = document.getElementById('search_term');
      const options = { types: ["address"], };
      var autocomplete = new google.maps.places.Autocomplete(input);
      autocomplete.setComponentRestrictions({ country: ["au"], });
    }
  </script>
  <script async
    src="https://maps.googleapis.com/maps/api/js?key=xxxxxx&libraries=places&callback=initMap">
  </script>

</code>```

Any help would be appreciated?

Body:
I have configured the Google places autocomplete and after selecting search I am getting URL form data like so:
http://127.0.0.1:8000/location/?term=1+York+Street%2C+Sydney+NSW%2C+Australia.
I would like to get it configured so that it returns multiple name/value pairs like so:
http://127.0.0.1:8000/location/?inputNumber=1&inputStreet=York+Street&inputCity=Sydney&inputState=NSW&inputZip=2000

This is required as I am using a Django and would like to use the name/value pairs to help with retrieving data from the model.

This what I have configured in my script tags:

Any help would be appreciated?


问:
Autosar bootloader
I have done partioning for boot loader and application. My application is less in size it have some unused address, so I fill that unused address with some known value with the help of Hexmate in Mplab. I got error while flashing. Does anyone help me out.

Microcontroller used microchip ATSEMC21G18A
Application partition 0x00006000 - 0x0003FFFF
Application actual size 0x00006000 - 0x0001ACC0
After 0x0001ACC0 - 0x0003FFF0 have some unknown value. After 0x0003FFF0 stored "End marker value" for application validation.

I tried Hexmate utility provided in MPlab(XC32) but my newly generated Hex file is having some problem while flashing

Title: Autosar bootloader


问:
How to mock Intent.class functions in Junit3 & Mockito?
I'm trying to write unit test for the following function in Android code,

```<code>public ClassA {

    int a = 0
    String b = null;

    @Override
    protected void fun(Bundle savedInstanceState) {
        setContentView(R.layout.a_activity_xml);
        new ClassC(context:this);
        a = getIntent().getIntExtra(ClassB.VAL1, ClassB.VAL2);
        b = getIntent().getIntExtra(ClassB.VAL3, ClassB.VAL4);
    }
}

</code>```

Following is the @Test function I'm writing to test it, (it's showing errors)

```<code>
@Test
public void funTest() {

    Whitebox.setInternalState(a_obj, "a",
        Intent.getIntent().getIntExtra(ClassB.VAL1, ClassB.VAL2));

    Whitebox.setInternalState(a_obj, "b",
        Intent.getIntent().getIntExtra(ClassB.VAL3, ClassB.VAL4));

}
</code>```

Body:
I'm trying to write unit test for the following function in Android code,

public ClassA {

    int a = 0
    String b = null;

    @Override
    protected void fun(Bundle savedInstanceState) {
        setContentView(R.layout.a_activity_xml);
        new ClassC(context:this);
        a = getIntent().getIntExtra(ClassB.VAL1, ClassB.VAL2);
        b = getIntent().getIntExtra(ClassB.VAL3, ClassB.VAL4);
    }
}

Following is the @Test function I'm writing to test it, (it's showing errors)

@Test
public void funTest() {

    Whitebox.setInternalState(a_obj, "a",
        Intent.getIntent().getIntExtra(ClassB.VAL1, ClassB.VAL2));

    Whitebox.setInternalState(a_obj, "b",
        Intent.getIntent().getIntExtra(ClassB.VAL3, ClassB.VAL4));

}