问:
NgbModal not being mocked correctly
having an issue trying to mock NgbModal. Whatever I do I can't properly mock NgbModal, so when this.modalService.open is called in the delete modal component, it doesn't return what I want it to. Also the test "Modal Opened" fails due to modalService.open not being called at all. Am new to jasmine & angular so hoping someone has some insight.

Thanks for any help.

```<code>describe('DeleteModalComponent', () => {

  let component: DeleteModalComponent;
  let fixture: ComponentFixture<DeleteModalComponent>;
  let modalService: NgbModal;
  let modalRef: NgbModalRef;

  beforeEach(async () => {
    const toastSpy = jasmine.createSpyObj('ToastrService', ['error']);
    await TestBed.configureTestingModule({
      declarations: [
        DeleteModalComponent,
        GroupDeleteModalComponent,
      ],
      imports: [
        BrowserModule,
        HttpClientTestingModule,
        RouterTestingModule.withRoutes([]),
        NgbModule,
      ],
      providers: [
        NgbActiveModal,
        { provide: ToastrService, useValue: toastSpy },
      ],
    }).overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [GroupDeleteModalComponent],
      },
    }).compileComponents();
  });
  beforeEach(() => {
    modalService = TestBed.inject(NgbModal) as jasmine.SpyObj<NgbModal>;
    modalRef = modalService.open(GroupDeleteModalComponent);
    spyOn(modalService, 'open').and.returnValue(modalRef);
    spyOn(console, 'log').and.callThrough();
    fixture = TestBed.createComponent(DeleteModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

    it('Modal Opened', () => {
      component.open();
      fixture.detectChanges();
      expect(modalService.open).toHaveBeenCalled();
    });

});

@Component({
  selector: 'app-delete-modal',
  templateUrl: './delete-modal.component.html',
  styleUrls: ['./delete-modal.component.css'],
  providers: [NgbModalConfig, NgbModal],
})
export class DeleteModalComponent {
  @Output()
  readonly notify: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor(private modalService: NgbModal, private toastr: ToastrService) { }

  open() {
    const modalRef: NgbModalRef = this.modalService.open(GroupDeleteModalComponent);
    modalRef.result.then((value) => {
      this.notify.emit(value);
    }).catch((error) => {
      console.error(error);
      this.toastr.error('Delete failed.');
    });
  }
}
</code>```

Title: NgbModal not being mocked correctly

Body:
having an issue trying to mock NgbModal. Whatever I do I can't properly mock NgbModal, so when this.modalService.open is called in the delete modal component, it doesn't return what I want it to. Also the test "Modal Opened" fails due to modalService.open not being called at all. Am new to jasmine & angular so hoping someone has some insight.

Thanks for any help.

describe('DeleteModalComponent', () => {

  let component: DeleteModalComponent;
  let fixture: ComponentFixture<DeleteModalComponent>;
  let modalService: NgbModal;
  let modalRef: NgbModalRef;

  beforeEach(async () => {
    const toastSpy = jasmine.createSpyObj('ToastrService', ['error']);
    await TestBed.configureTestingModule({
      declarations: [
        DeleteModalComponent,
        GroupDeleteModalComponent,
      ],
      imports: [
        BrowserModule,
        HttpClientTestingModule,
        RouterTestingModule.withRoutes([]),
        NgbModule,
      ],
      providers: [
        NgbActiveModal,
        { provide: ToastrService, useValue: toastSpy },
      ],
    }).overrideModule(BrowserDynamicTestingModule, {
      set: {
        entryComponents: [GroupDeleteModalComponent],
      },
    }).compileComponents();
  });
  beforeEach(() => {
    modalService = TestBed.inject(NgbModal) as jasmine.SpyObj<NgbModal>;
    modalRef = modalService.open(GroupDeleteModalComponent);
    spyOn(modalService, 'open').and.returnValue(modalRef);
    spyOn(console, 'log').and.callThrough();
    fixture = TestBed.createComponent(DeleteModalComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

    it('Modal Opened', () => {
      component.open();
      fixture.detectChanges();
      expect(modalService.open).toHaveBeenCalled();
    });

});

@Component({
  selector: 'app-delete-modal',
  templateUrl: './delete-modal.component.html',
  styleUrls: ['./delete-modal.component.css'],
  providers: [NgbModalConfig, NgbModal],
})
export class DeleteModalComponent {
  @Output()
  readonly notify: EventEmitter<boolean> = new EventEmitter<boolean>();

  constructor(private modalService: NgbModal, private toastr: ToastrService) { }

  open() {
    const modalRef: NgbModalRef = this.modalService.open(GroupDeleteModalComponent);
    modalRef.result.then((value) => {
      this.notify.emit(value);
    }).catch((error) => {
      console.error(error);
      this.toastr.error('Delete failed.');
    });
  }
}


来源: stackexchange

问:
VS Code: Custome natvis doesn't work when template parameter is size_t
Here is the natvis:

Works with int:

Doesn't work with size_t:

Softwares:

g++: 11.3.0

vscode:

size_t is actualy long unsigned int, and I think the reason is 3 keywords,
because when you remove one of them it works.

ContentLicense: CC BY-SA 4.0


问:
In the below code I am getting an error of only size-1 arrays can be converted to Python scalars in the last line of Pd[i[]
```<code># Input of signal bandwidth
# Here we are taking M = 14 snapshots at a time
#Import the random library
# Here we need input if random values, in reality we have taken values from horn antena, but for reproducing research paper I have considered

import numpy as np
sigma_s = np.random.randint(0,4,(1,14))
sigma_w = np.random.randint(0,3,(1,14))
sigma_x = np.random.randint(0,2,(1,14))
sigma_g = np.random.randint(0,5,(1,14))
sigma_h = np.random.randint(0,9,(1,14))

Pd = np.zeros((1,14))

# The random array generate is in db so converting it into linear values
snr_db = np.random.randint(-30,0,(1,14))
snr_linear = (10\*\*(np.random.randint(-30,0,(1,14)) \* (-1/10)))

# y = threshold value
y = 1.1
u =np.random.rand(1,14)# u here is a small step size
h = np.random.rand(1,14)
M = 14
N = 4
a = 3

import numpy as np
import sympy as sy
import math
import numpy as np

np.seterr(divide='ignore', invalid='ignore')
for i in range(14):
  rho_one_sqaure = h[i]* ((snr_linear[i] / sigma_h[i])** 2 ) * ((snr_linear[i]+1) ** 1/2)

  rho = h[i]*(((((sigma_s[i])**2)/(sigma_w[i])**2))**(1/2))
  z = (sigma_x[i])**2/sigma_g[i]**2
  sigma_zero_sqaure = (1-(rho)**2)*(rho**2)*(u**2)*(2-2*N*M*u/(1+(2*z)**(N*M)))/(1+z)**(N*M)/2
  u_one  = M * ((rho_one_sqaure)**2) *u[i]*((1+2*M*N*z)**(N*M/2))
  sigma_one_square = (sigma_x **2) * (1-rho_one_sqaure)*rho_one_sqaure*(u**2)*(2-2*N*M*u/(1+(2*N*M*z))**(N*M/2))/(1+(2*N*M*z))**(N*M/2)
   # T(wave function) is the sufficient statistics and it is determined as given below

  def sufficient_statistics(wave_function):
     return ((wave_function - u_one * (sigma_zero_sqaure)/sigma_one_square - sigma_zero_sqaure)**2)

  t_wave_function = sufficient_statistics(4)

  Pd[i]= np.int(((math.sqrt(a*a*a*snr_linear[i]))**((N/2)-1)) * sy.integrate(x**(N/2-1))*math.exp(-(x**2+a*a*a*snr_linear[i]))*1/3.14 * (sy.integrate(math.exp(a*x)*math.cos(a*theta), (theta,0,math.pi()))) ,(x,math.sqrt(y),2))
</code>```

I was trying to calculate the value of Pd[i] at the end of every loop for 14 times.
And the wanted to have graph of Pd.
BUt the error comes

Body:
# Input of signal bandwidth
# Here we are taking M = 14 snapshots at a time
#Import the random library
# Here we need input if random values, in reality we have taken values from horn antena, but for reproducing research paper I have considered

import numpy as np
sigma_s = np.random.randint(0,4,(1,14))
sigma_w = np.random.randint(0,3,(1,14))
sigma_x = np.random.randint(0,2,(1,14))
sigma_g = np.random.randint(0,5,(1,14))
sigma_h = np.random.randint(0,9,(1,14))

Pd = np.zeros((1,14))

# The random array generate is in db so converting it into linear values
snr_db = np.random.randint(-30,0,(1,14))
snr_linear = (10\*\*(np.random.randint(-30,0,(1,14)) \* (-1/10)))

# y = threshold value
y = 1.1
u =np.random.rand(1,14)# u here is a small step size
h = np.random.rand(1,14)
M = 14
N = 4
a = 3

import numpy as np
import sympy as sy
import math
import numpy as np

np.seterr(divide='ignore', invalid='ignore')
for i in range(14):
  rho_one_sqaure = h[i]* ((snr_linear[i] / sigma_h[i])** 2 ) * ((snr_linear[i]+1) ** 1/2)

  rho = h[i]*(((((sigma_s[i])**2)/(sigma_w[i])**2))**(1/2))
  z = (sigma_x[i])**2/sigma_g[i]**2
  sigma_zero_sqaure = (1-(rho)**2)*(rho**2)*(u**2)*(2-2*N*M*u/(1+(2*z)**(N*M)))/(1+z)**(N*M)/2
  u_one  = M * ((rho_one_sqaure)**2) *u[i]*((1+2*M*N*z)**(N*M/2))
  sigma_one_square = (sigma_x **2) * (1-rho_one_sqaure)*rho_one_sqaure*(u**2)*(2-2*N*M*u/(1+(2*N*M*z))**(N*M/2))/(1+(2*N*M*z))**(N*M/2)
   # T(wave function) is the sufficient statistics and it is determined as given below

  def sufficient_statistics(wave_function):
     return ((wave_function - u_one * (sigma_zero_sqaure)/sigma_one_square - sigma_zero_sqaure)**2)

  t_wave_function = sufficient_statistics(4)

  Pd[i]= np.int(((math.sqrt(a*a*a*snr_linear[i]))**((N/2)-1)) * sy.integrate(x**(N/2-1))*math.exp(-(x**2+a*a*a*snr_linear[i]))*1/3.14 * (sy.integrate(math.exp(a*x)*math.cos(a*theta), (theta,0,math.pi()))) ,(x,math.sqrt(y),2))

I was trying to calculate the value of Pd[i] at the end of every loop for 14 times.
And the wanted to have graph of Pd.
BUt the error comes


问:
How can I pass values from JS to JSCRIPT dynamicly (it drives me nuts)
My home automation system only allows communication through JSCRIPT that runs on the SPS embedded IIS as ASP code. The old web interface was just on HTML and JSCRIPT. I need to move to HTML, CSS and JS with Bootstrap, but for data access I need to stick with JSCRIPT (ASP).
Reading data from asp variables is working easy, set it with a static value as well, **but to set asp variables through JS DYNAMICLY is where I struggle. **

I'd like something likd WritetoASP(A_Var, J_Var) where A_Var has the name of the ASP var and J_Var the value to be passed.

I'm sure that all the experts here do have a solution for me.

Here is a sample Code that shows the challenge.

```<code><% @LANGUAGE="JSCRIPT"%>
<%
  var A_Var=88;
 %>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>ASP JS HTML Test</title>
<script runat="server" type="text/javascript">
  var J_Var, Par="A_Var";
  /* use the real asp variable name, returns the right ASP value */
  J_Var = <%=A_Var %>;
  document.write ('J_Var = '+J_Var+'<br>');
  /* write a static value to the asp variable, writes the right value to ASP  */
  <%A_Var = 66;%>;
  document.write ('A_Var = '+<%=A_Var%>+'<br>');
  /* try to store and use the asp variable name in a JS variable, fails */
  J_Var = <%="Par"%>;
  document.write ('J_Var = '+J_Var+'<br>');
  /* using eval to execute the asp command, fails */
  J_Var = eval('<%="Par" %>');
  document.write ('J_Var = '+J_Var+'<br>');
  /* eval execute string generated in a variable, fails */
  /* the replace is needed, otherwise JS interpretes the ASP tag */
  Par="'Ü%="+Par+"%>'";
  document.write ('Par = '+Par+'<br>');
  J_Var = eval(Par.replace(/Ü/g,"<"));
  document.write ('J_Var = '+J_Var+'<br>');
</script>
</head>
<body>
</body>
</html>

This is the result:
J_Var = 88
A_Var = 66
J_Var = A_Var
J_Var = A_Var
Par = 'Ü%=A_Var%>'
J_Var = <%=A_Var%>
</code>```

Body:
My home automation system only allows communication through JSCRIPT that runs on the SPS embedded IIS as ASP code. The old web interface was just on HTML and JSCRIPT. I need to move to HTML, CSS and JS with Bootstrap, but for data access I need to stick with JSCRIPT (ASP).
Reading data from asp variables is working easy, set it with a static value as well, **but to set asp variables through JS DYNAMICLY is where I struggle. **

I'd like something likd WritetoASP(A_Var, J_Var) where A_Var has the name of the ASP var and J_Var the value to be passed.

I'm sure that all the experts here do have a solution for me.

Here is a sample Code that shows the challenge.

<% @LANGUAGE="JSCRIPT"%>
<%
  var A_Var=88;
 %>

<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>ASP JS HTML Test</title>

This is the result:
J_Var = 88
A_Var = 66
J_Var = A_Var
J_Var = A_Var
Par = 'Ü%=A_Var%>'
J_Var = <%=A_Var%>


问:
Cannot capture webcam on chrome or safari on ios
For some reason I can’t seem to capture media from the web cam of my iPhone. This worked fine on older versions. I was on 16.1 and now 16.2 - same results.

I’m testing using: https://webcamtests.com/

It’s says:

This happens in chrome and safari. After the permission prompt.

Any ideas?


问:
Check for indentical rows in a numpy arrays
I have 2 numpy arrays: points = np.array([[253, 1472], [301 1956], [796, 1011], [3, 2179], [759, 844], [485, 1053], [312, 1536], [485, 1505], [313, 1304], [357, 1434]]) and coords which basically contains all of the coordinates from [0, 0] to [2000, 2000]. I want to return indices of the coords array which contain exactly the values from points. I tried the solution from here: check for identical rows in different numpy arrays, so using this function: res = (coords[:, None] == points).all(-1).any(-1). However in this case this does not match the value [485, 1505]. I suppose it is because there is another value with the same x coordinate. This is suprising for me that there is no ready numpy function for exactly that purpose. I tried everything but I don't achieve the wanted result.


问:
How do I make the IL Viewer work with Unity projects in JetBrains Rider?
In Rider, when I open the IL Viewer I get a message "Build your project to view IL". However, Unity is in charge of the entire build process, so build through Rider is not possible. Is there a way making the IL Viewer work with Unity projects ?

Perhaps by telling Rider to read the built project from Library/ScriptAssemblies ?

I've looked around in the IDE settings but could not find anything related to this.


问:
Modelling language to represent folder structure
Is there a modelling language that can represent file structures?

I've seen examples like the one below, does it have a name? Is there a standardized format?

```<code>+-- file.txt
+-- folder
|   +-- image.jpg
|   +-- nested
|       +-- program.exe
+-- index.html
</code>```

Body:
Is there a modelling language that can represent file structures?

I've seen examples like the one below, does it have a name? Is there a standardized format?

+-- file.txt
+-- folder
|   +-- image.jpg
|   +-- nested
|       +-- program.exe
+-- index.html


问:
GeoJSON: Add Timestamp to LineString from a Pandas DataFrame
Kepler.gl requires a special format for the trip layer to animate a path (https://docs.kepler.gl/docs/user-guides/c-types-of-layers/k-trip):

"In order to animate the path, the geoJSON data needs to contain LineString in its features' geometry, and the coordinates in the LineString need to have 4 elements in the format of [longitude, latitude, altitude, timestamp], with the last element being a timestamp"

However I do not find a way to get the timestamp into the LineString.

Assuming the following DataFrame df

Geometry
Timestamp

POINT (548522.717 7353166.639)
1564184363

POINT (548435.456 7353365.835)
1564184363

I can get the Geometry data into a LineString using

line = LineString(df.geometry)

However I found no hint at how to add the timestamp...


问:
Why is the array empty on get allFiles with Laravel storage
I have an Laravel application witch works with an ftp server. Till now, I used the ftp service from hostpoint.ch. Everything works well.
Now, the customer like to use his own ftp server. So I created a new disk for the new ftp.

```<code>        'ftp_customer' => [
            'driver' => 'ftp',
            'host' => 'xxx.xxx.xx.x',
            'username' => 'xxx',
            'password' => 'xxx',
            'port' => 21,
            'passive' => true,
            'root'=> '/',
        ],
</code>```

To test the server, I created the following script:

```<code>        Storage::disk('ftp_customer')->put('file1.txt', 'Contents');
        $files = Storage::disk('ftp_customer')->allFiles();

        dd($files);
</code>```

On the server, the file1.txt exists:

-rw-rw-rw- 1 ftp ftp               8 Dec 20 13:43 file1.txt

Therefore, I know, that the put method works.

But the get allFiles returns always an empty array.

I tried to create first a folder and use it. Also, I tried to change the config.

I'm not sure if it creates problems, because it's a Windows server.

Does anyone have an idea how to solve it?

Body:
I have an Laravel application witch works with an ftp server. Till now, I used the ftp service from hostpoint.ch. Everything works well.
Now, the customer like to use his own ftp server. So I created a new disk for the new ftp.

        'ftp_customer' => [
            'driver' => 'ftp',
            'host' => 'xxx.xxx.xx.x',
            'username' => 'xxx',
            'password' => 'xxx',
            'port' => 21,
            'passive' => true,
            'root'=> '/',
        ],

To test the server, I created the following script:

        Storage::disk('ftp_customer')->put('file1.txt', 'Contents');
        $files = Storage::disk('ftp_customer')->allFiles();

        dd($files);

On the server, the file1.txt exists:

-rw-rw-rw- 1 ftp ftp               8 Dec 20 13:43 file1.txt

Therefore, I know, that the put method works.

But the get allFiles returns always an empty array.

I tried to create first a folder and use it. Also, I tried to change the config.

I'm not sure if it creates problems, because it's a Windows server.

Does anyone have an idea how to solve it?


问:
Error in if (.) else { : the condition has length > 1 - without 'else' in R
This is my code: I want to delete the row containing Fa when there in already a row with FA in this run and this block.

```<code>SDTT%>%
  group_by(Run, Block)%>%
  if (SDTT$SDT=="FA"){
    SDTT[!(SDT=="Fa"),]
  }
</code>```

But I get the following error:

```<code>Error in if (.) else { : the condition has length > 1
</code>```

Similar questions are already asked, but to my knowledge, they all use the else condition which I don't.

Thank you in advance for any help!!

Body:
This is my code: I want to delete the row containing Fa when there in already a row with FA in this run and this block.

SDTT%>%
  group_by(Run, Block)%>%
  if (SDTT$SDT=="FA"){
    SDTT[!(SDT=="Fa"),]
  }

But I get the following error:

Error in if (.) else { : the condition has length > 1

Similar questions are already asked, but to my knowledge, they all use the else condition which I don't.

Thank you in advance for any help!!


问:
Apollo link how to decorate response data to have error inside data
Bit new to front-end stack, from Apollo documentation I can't figure out myself how to do below.

I am trying to wrap errors also into the response data. So then I will have data.data and data.error as response.

export const wrapDataLink = new ApolloLink((operation, forward) => {
  // not sure how I access data and erorrs both here
  return forward(operation);
});
```
<p>Btw I already has an onError link to handle errors.</p>
<pre class="lang-js prettyprint-override"><code>const errorLink = onError(({ graphQLErrors, operation, forward }) => {
    if (graphQLErrors) {
      for (const err of graphQLErrors) {
        // some logic here for auth errors, rest just forward(operation);
      }
    }
  });
</code>```

I am using "@apollo/client": "3.7.1" and "apollo-link-rest": "0.9.0-rc.2",

Body:
Bit new to front-end stack, from Apollo documentation I can't figure out myself how to do below.

I am trying to wrap errors also into the response data. So then I will have data.data and data.error as response.

export const wrapDataLink = new ApolloLink((operation, forward) => {
  // not sure how I access data and erorrs both here
  return forward(operation);
});

Btw I already has an onError link to handle errors.

const errorLink = onError(({ graphQLErrors, operation, forward }) => {
    if (graphQLErrors) {
      for (const err of graphQLErrors) {
        // some logic here for auth errors, rest just forward(operation);
      }
    }
  });

I am using "@apollo/client": "3.7.1" and "apollo-link-rest": "0.9.0-rc.2",


问:
Nginx status code is 200 but I want to send it as 404
The config content is as follows;

```<code>location / {
   rewrite ^([^.\?]*[^/])$ https://$domain_prefix$domain_name$1/ permanent;
   try_files /page-cache/$uri/pc__index__pc.html /page-cache/404/$uri/pc__index__pc.html /page-cache/404/$uri/$uri.html $uri $uri/ /index.php$is_args$args;
}
</code>```

It finds and opens the files in page-cache/ or page-cache/404/ folders, but it returns 200 status code. If it is under the page-cache/404/ folder, I want 404 status code to be returned.

I tried creating a directive and using if.

Body:
The config content is as follows;

location / {
   rewrite ^([^.\?]*[^/])$ https://$domain_prefix$domain_name$1/ permanent;
   try_files /page-cache/$uri/pc__index__pc.html /page-cache/404/$uri/pc__index__pc.html /page-cache/404/$uri/$uri.html $uri $uri/ /index.php$is_args$args;
}

It finds and opens the files in page-cache/ or page-cache/404/ folders, but it returns 200 status code. If it is under the page-cache/404/ folder, I want 404 status code to be returned.

I tried creating a directive and using if.


问:
Upate parts of hovertemplate for plotly express
I would like to update parts of the hovertemplate within a plotly express plot, and keep the rest as is. At the moment the default hovertemplate is used . In the end I would like to display "MY-new_fancy_name" instead of "lables" and a different string than "parents" and "id".

the printed hovertemplate shows something like this:

```<code>labels=%{label}<br>'some_column_values_which_changed_interactively_in_a_streamlit_app'=%{value}<br>parent=%{parent}<br>id=%{id}<br>'some_other_column_values_which_changed_interactively_in_a_streamlit_app'=%{color}<extra></extra>
</code>```

while the 'some_column_values_which_changed_interactively_in_a_streamlit_app' should stay as is and  change with the selection in the streamlit app – labels, parent and id outside the {} should be set to other strings. so "'my_choosen_name_for_labels'=%{label}" for example.

Ideally 'my_choosen_name_for_labels' etc could also be configurable.

Is this possible within plotly express?

I was able to hardcode all "keys" within the hovertemplate but not a mix or simply update certain keys.

Body:
I would like to update parts of the hovertemplate within a plotly express plot, and keep the rest as is. At the moment the default hovertemplate is used . In the end I would like to display "MY-new_fancy_name" instead of "lables" and a different string than "parents" and "id".

the printed hovertemplate shows something like this:

labels=%{label}
'some_column_values_which_changed_interactively_in_a_streamlit_app'=%{value}
parent=%{parent}
id=%{id}
'some_other_column_values_which_changed_interactively_in_a_streamlit_app'=%{color}<extra></extra>

while the 'some_column_values_which_changed_interactively_in_a_streamlit_app' should stay as is and  change with the selection in the streamlit app – labels, parent and id outside the {} should be set to other strings. so "'my_choosen_name_for_labels'=%{label}" for example.

Ideally 'my_choosen_name_for_labels' etc could also be configurable.

Is this possible within plotly express?

I was able to hardcode all "keys" within the hovertemplate but not a mix or simply update certain keys.


问:
How to use bind mount in docker with angular application?
I am dockerizing an angular application. But I want to use bind mount for code sharing purpose. I am running following command which makes container up and running and entire application works completely fine. But when I make changes in my local repository, it doesn`t get reflected on a webpage.

This is how I run the container

```<code>docker run -d -p 4200:80 --rm --name frontend -v E:\dir1\dir2\subdirectory:/app image_name:image_tag
</code>```
```<code>#Dockerfile
FROM node:14-alpine as node

WORKDIR /app

COPY ./package.json .

RUN npm install

COPY . .

RUN npm run build --prod

FROM nginx:alpine

COPY --from=node app/dist/angular-frontend usr/share/nginx/html

EXPOSE 80

</code>```

Body:
I am dockerizing an angular application. But I want to use bind mount for code sharing purpose. I am running following command which makes container up and running and entire application works completely fine. But when I make changes in my local repository, it doesn`t get reflected on a webpage.

This is how I run the container

docker run -d -p 4200:80 --rm --name frontend -v E:\dir1\dir2\subdirectory:/app image_name:image_tag

#Dockerfile
FROM node:14-alpine as node

WORKDIR /app

COPY ./package.json .

RUN npm install

COPY . .

RUN npm run build --prod

FROM nginx:alpine

COPY --from=node app/dist/angular-frontend usr/share/nginx/html

EXPOSE 80


问:
How to add Pie Chart percentage on Chart Area in react-chartjs-2
I have a pie chart from react-chartjs-2 package, I want the percentage of each segment to be displayed in each area of the pie chart.

Below is my code and the chart I have so far, the desired chart image is also below.

Thank you.

import React from "react";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Pie } from "react-chartjs-2";

ChartJS.register(ArcElement, Tooltip, Legend);

export default function PieChart() {
  return (
    <>
      <Pie
        options={{
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { display: false },
            tooltip: false,
          },
          onHover: function (e) {
            e.native.target.style.cursor = "pointer";
          },
          rotation: 270,
          events: ["click"],
          onClick: function (event, element) {
            console.log(element[0].index);
          },
        }}
        data={{
          labels: ["Above 60%", "Below 60%"],
          datasets: [
            {
              data: [20, 10],
              backgroundColor: ["#3A925D", "#FD7E14"],
              borderWidth: 0,
            },
          ],
        }}
      />
    </>
  );
```

current chart.

desired chart.

Body:
I have a pie chart from react-chartjs-2 package, I want the percentage of each segment to be displayed in each area of the pie chart.

Below is my code and the chart I have so far, the desired chart image is also below.

Thank you.

import React from "react";
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Pie } from "react-chartjs-2";

ChartJS.register(ArcElement, Tooltip, Legend);

export default function PieChart() {
  return (
    <>
      <Pie
        options={{
          responsive: true,
          maintainAspectRatio: false,
          plugins: {
            legend: { display: false },
            tooltip: false,
          },
          onHover: function (e) {
            e.native.target.style.cursor = "pointer";
          },
          rotation: 270,
          events: ["click"],
          onClick: function (event, element) {
            console.log(element[0].index);
          },
        }}
        data={{
          labels: ["Above 60%", "Below 60%"],
          datasets: [
            {
              data: [20, 10],
              backgroundColor: ["#3A925D", "#FD7E14"],
              borderWidth: 0,
            },
          ],
        }}
      />
    </>
  );

current chart.

desired chart.


问:
How to send a CAN-message in CANoe 10 in one network to an another network?
I want to send a message from one network to trigger an event on an another network in CANoe. They have different dbcs.

I've tried it with output(CAN.MessageName). Unfortunately it didn't work.
"'CAN' does not contain this member variable.  " is the error CANoe gave me.

Kind regards for helping me.


问:
How to make a dropdown unclickable until a value from another dropdown is chosen, and use that value to filter the dropdown in Excel and Pandas
So I have an excel file that I generated with pandas that has a sheet with two columns A and B that are dropdowns (The values of those dropdowns are coming from another sheet in the same excel file), I want B to be unclickable for any row until A has been filled for any row. And after that, I want the value in A to be used to filter the dropdown in B. Does anyone have an idea how to go about it? This help will be greatly appreciated


问:
Tkinter withdraw function inside button hides window from beginning
My target is to create two windows. Window1 is opening at the beginning including a button and window2 is hidden. If I press the button I would like to hide window1 and show window2.

To do so I've created a small function and want to execute this function by pressing the button.

```<code>from tkinter import *

window1 = Tk()
window2 = Tk()
window2.withdraw()

def change_windows():
    window2.deiconify()
    window1.withdraw()

Btn1 = Button(window1, text="Show window2", command=change_windows())
Btn1.grid(row=0, column=0)

window1.mainloop()
window2.mainloop()
</code>```

Problem is that the only thing that opens when I run the program is window2. It looks like the function is already executed without activating the button.

When I  delete the command function inside the button like this:

```<code>from tkinter import *

window1 = Tk()
window2 = Tk()
window2.withdraw()

def change_windows():
    window2.deiconify()
    window1.withdraw()

Btn1 = Button(window1, text="Show window2")
Btn1.grid(row=0, column=0)

window1.mainloop()
window2.mainloop()
</code>```

..then window1 is opening and window2 is hidden. I am a beginner but I don't get what is the issue here.

Body:
My target is to create two windows. Window1 is opening at the beginning including a button and window2 is hidden. If I press the button I would like to hide window1 and show window2.

To do so I've created a small function and want to execute this function by pressing the button.

from tkinter import *

window1 = Tk()
window2 = Tk()
window2.withdraw()

def change_windows():
    window2.deiconify()
    window1.withdraw()

Btn1 = Button(window1, text="Show window2", command=change_windows())
Btn1.grid(row=0, column=0)

window1.mainloop()
window2.mainloop()

Problem is that the only thing that opens when I run the program is window2. It looks like the function is already executed without activating the button.

When I  delete the command function inside the button like this:

from tkinter import *

window1 = Tk()
window2 = Tk()
window2.withdraw()

def change_windows():
    window2.deiconify()
    window1.withdraw()

Btn1 = Button(window1, text="Show window2")
Btn1.grid(row=0, column=0)

window1.mainloop()
window2.mainloop()

..then window1 is opening and window2 is hidden. I am a beginner but I don't get what is the issue here.


问:
Python-C API can't reach member through return type
I'm trying to create a python wrapper for my C++ code using python's header file.

I want one of my types methods to return another type, and on python level I want to access one of it's members.

Here is how I want it to look like on python level:

import my_module

obj = my_module.MyType()

ret = obj.process() # returns custom_type
print(ret.my_var)

```
<p>And here is the C++ code I have written:
py_types.hpp:</p>
<pre class="lang-cpp prettyprint-override"><code>    typedef struct custom_type_s
    {
        PyObject_HEAD
        std::unordered_multimap<std::string, int> um;
        float my_var;
    } custom_type;

    PyObject* get_custom_type_success_rate(PyObject* self, PyObject* args);

    static PyMemberDef custom_type_members[] = {
        {"my_var", T_FLOAT, offsetof(custom_type, my_var), 0,
         "The success rate."},
        {NULL}  /* Sentinel */
    };

    static PyTypeObject custom_typeType = {
        PyVarObject_HEAD_INIT(NULL, 0)
        .tp_name = "type.custom_type",
        .tp_basicsize = sizeof(custom_type),
        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
        .tp_members = custom_type_members,
    };

    typedef struct mytype_s
    {
        PyObject_HEAD

    } MyType;

    void MyType_dealloc(MyType *self);

    PyObject* MyType_new(PyTypeObject *type, PyObject *args, PyObject *kwds);

    int MyType_init(MyType *self, PyObject *args, PyObject *kwds);

    PyObject* processing(MyType *self, PyObject *args);

   static PyMethodDef MyTypeMethods[] = {
        {"process", (PyCFunction) processing, METH_VARARGS,
        "Return the name, combining the first and last name"
        },
        {NULL}  /* Sentinel */
    };

    static PyTypeObject MyTypeType = {
        PyVarObject_HEAD_INIT(NULL, 0)
        .tp_name = "type.MyType",
        .tp_basicsize = sizeof(MyType),
        .tp_dealloc = (destructor) MyType_dealloc,
        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
        .tp_methods = MyTypeMethods,
        .tp_init = (initproc) MyType_init,
        .tp_new = MyType_new,
    };
</code>```

And on my cpp file return an instance of my_var in process:

PyObject* wrapper::processing(MyType *self, PyObject* args)
{
    PyObject* arg;
    if (!PyArg_ParseTuple(args, "O", &arg))
        return NULL;

    ...

    process_out_t ret = from_my_cpp_code();

    custom_type* ret_process = PyObject_New(custom_type, &custom_typeType);
    PyObject* as_obj = PyObject_Init((PyObject*)ret_process, &custom_typeType);
    ret_process->my_var = ret.my_var;

    Py_INCREF(ret_process);
    return as_obj;
}
```
<p>When I run the above python script I get this error:</p>
```Traceback (most recent call last):
  File "/home/user/Desktop/python/test.py", line 18, in <module>
    print(ret.my_var)
AttributeError: 'type.custom_type' object has no attribute 'my_var'
```
<p>I've tried adding a getter/setter, adding init/new to <code>custom_type</code> to no avail.</p>
<p>When I add an init and a new to <code>custom_type</code> I can do <code>ret = type.custom_type()</code> and <code>print(ret.my_val)</code> just fine. But even then doing the first python script gives me an error. How do I access it's members? (I've registered both types in PyInit.)</p>
<p>Update:
For some reason, when I add this to my code it magically works:</p>
<pre class="lang-py prettyprint-override"><code>import my_module

obj = my_module.MyType()

ret = obj.process() # returns custom_type
print(dir(ret))
print(ret.my_var)
</code>```

But the moment I remove dir it gives the error again...

Body:
I'm trying to create a python wrapper for my C++ code using python's header file.

I want one of my types methods to return another type, and on python level I want to access one of it's members.

Here is how I want it to look like on python level:

import my_module

obj = my_module.MyType()

ret = obj.process() # returns custom_type
print(ret.my_var)

And here is the C++ code I have written:
py_types.hpp:

    typedef struct custom_type_s
    {
        PyObject_HEAD
        std::unordered_multimap<std::string, int> um;
        float my_var;
    } custom_type;

    PyObject* get_custom_type_success_rate(PyObject* self, PyObject* args);

    static PyMemberDef custom_type_members[] = {
        {"my_var", T_FLOAT, offsetof(custom_type, my_var), 0,
         "The success rate."},
        {NULL}  /* Sentinel */
    };

    static PyTypeObject custom_typeType = {
        PyVarObject_HEAD_INIT(NULL, 0)
        .tp_name = "type.custom_type",
        .tp_basicsize = sizeof(custom_type),
        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
        .tp_members = custom_type_members,
    };

    typedef struct mytype_s
    {
        PyObject_HEAD

    } MyType;

    void MyType_dealloc(MyType *self);

    PyObject* MyType_new(PyTypeObject *type, PyObject *args, PyObject *kwds);

    int MyType_init(MyType *self, PyObject *args, PyObject *kwds);

    PyObject* processing(MyType *self, PyObject *args);

   static PyMethodDef MyTypeMethods[] = {
        {"process", (PyCFunction) processing, METH_VARARGS,
        "Return the name, combining the first and last name"
        },
        {NULL}  /* Sentinel */
    };

    static PyTypeObject MyTypeType = {
        PyVarObject_HEAD_INIT(NULL, 0)
        .tp_name = "type.MyType",
        .tp_basicsize = sizeof(MyType),
        .tp_dealloc = (destructor) MyType_dealloc,
        .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
        .tp_methods = MyTypeMethods,
        .tp_init = (initproc) MyType_init,
        .tp_new = MyType_new,
    };

And on my cpp file return an instance of my_var in process:

PyObject* wrapper::processing(MyType *self, PyObject* args)
{
    PyObject* arg;
    if (!PyArg_ParseTuple(args, "O", &arg))
        return NULL;

    ...

    process_out_t ret = from_my_cpp_code();

    custom_type* ret_process = PyObject_New(custom_type, &custom_typeType);
    PyObject* as_obj = PyObject_Init((PyObject*)ret_process, &custom_typeType);
    ret_process->my_var = ret.my_var;

    Py_INCREF(ret_process);
    return as_obj;
}

When I run the above python script I get this error:

Traceback (most recent call last):
  File "/home/user/Desktop/python/test.py", line 18, in <module>
    print(ret.my_var)
AttributeError: 'type.custom_type' object has no attribute 'my_var'

I've tried adding a getter/setter, adding init/new to custom_type to no avail.

When I add an init and a new to custom_type I can do ret = type.custom_type() and print(ret.my_val) just fine. But even then doing the first python script gives me an error. How do I access it's members? (I've registered both types in PyInit.)

Update:
For some reason, when I add this to my code it magically works:

import my_module

obj = my_module.MyType()

ret = obj.process() # returns custom_type
print(dir(ret))
print(ret.my_var)

But the moment I remove dir it gives the error again...


问:
TLS 1.2 HttpClient With Certificate Error
I have this very code on Java, node, but .. in c# i cant make this work.

```<code>
var certFile = @"path..certificate.nokey.pem";
var certKey = @"path..certificate.key";
X509Certificate2 clientCertificate = X509Certificate2.CreateFromPemFile(certFile, certKey);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

var handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCertificate);

var httpClient = new HttpClient(handler);

httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri= new Uri("https://url"),
Content = new FormUrlEncodedContent(new Dictionary\<string, string\> {
{ "grant_type", "client_credentials" },
{ "client_id", "client_id" },
{ "client_secret", "client_secret" }
})
};

Console.WriteLine("Request:");
Console.WriteLine(request.ToString());
if (request.Content != null)
{
Console.WriteLine(await request.Content.ReadAsStringAsync());
}
var response = await httpClient.SendAsync(request);

string resultContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);

</code>```

Got this error :

Unhandled exception. System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.

System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.

System.ComponentModel.Win32Exception (0x80090326): Mensagem recebida inesperada ou formatada incorretamente.

Body:
I have this very code on Java, node, but .. in c# i cant make this work.

var certFile = @"path..certificate.nokey.pem";
var certKey = @"path..certificate.key";
X509Certificate2 clientCertificate = X509Certificate2.CreateFromPemFile(certFile, certKey);
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

var handler = new HttpClientHandler();
handler.ClientCertificates.Add(clientCertificate);

var httpClient = new HttpClient(handler);

httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");

var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri= new Uri("https://url"),
Content = new FormUrlEncodedContent(new Dictionary\<string, string\> {
{ "grant_type", "client_credentials" },
{ "client_id", "client_id" },
{ "client_secret", "client_secret" }
})
};

Console.WriteLine("Request:");
Console.WriteLine(request.ToString());
if (request.Content != null)
{
Console.WriteLine(await request.Content.ReadAsStringAsync());
}
var response = await httpClient.SendAsync(request);

string resultContent = await response.Content.ReadAsStringAsync();
Console.WriteLine(resultContent);

Got this error :

Unhandled exception. System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.

System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.

System.ComponentModel.Win32Exception (0x80090326): Mensagem recebida inesperada ou formatada incorretamente.


问:
What happenes with relationships if I copy all node properties using Cypher?
If I use SET to copy the properties of one node/relationship to another, all the properties of the latter will be removed and replaced with new ones. But what happens with relationships? Are they also copied?

Here is the code:

```<code>CREATE (p1:Person {name: 'Harry'}), (p2:Person {name: 'Anna'})
SET p1 = p2
RETURN p1, p2;
</code>```

Are the relationships that Harry has copied to Anna?

Body:
If I use SET to copy the properties of one node/relationship to another, all the properties of the latter will be removed and replaced with new ones. But what happens with relationships? Are they also copied?

Here is the code:

CREATE (p1:Person {name: 'Harry'}), (p2:Person {name: 'Anna'})
SET p1 = p2
RETURN p1, p2;

Are the relationships that Harry has copied to Anna?


问:
View Pdf From Realtime Database Flutter Firebase?
```<code>import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:my_project/hello/Courses.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:advance_pdf_viewer/advance_pdf_viewer.dart';

class ViewCourses extends StatefulWidget {
  const ViewCourses({super.key});

  @override
  State<ViewCourses> createState() => _ViewCoursesState();
}

class _ViewCoursesState extends State<ViewCourses> {
 Query dbRef = FirebaseDatabase.instance.ref().child('Students');
  DatabaseReference reference = FirebaseDatabase.instance.ref().child('Students');

  Widget listItem({required Map student}) {
    if (!mounted) return Container();
    return SingleChildScrollView(
      child: GestureDetector(
        onTap: () {

        },
        child: Container(
          margin: const EdgeInsets.all(10),
          padding: const EdgeInsets.all(10),
          height: 300,
          color: Color.fromARGB(255, 255, 200, 0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                (student['Course'] ?? "").toString(),
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
              ),
              const SizedBox(
                height: 5,
              ),
              Text(
                (student['Title'] ?? "").toString(),
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
              ),
              const SizedBox(
                height: 5,
              ),
              Text(
                (student['CreatedBy'] ?? "").toString(),
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
              ),
              Text(
              (student['file'] ?? "").toString(),
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
            ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () {

                    },
                    child: Row(
                      children: [
                        Icon(
                          Icons.edit,
                          color: Theme.of(context).primaryColor,
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(
                    width: 6,
                  ),
                  GestureDetector(
                    onTap: () {
                      reference.child(student['key']).remove();
                    },
                    child: Row(
                      children: [
                        Icon(
                          Icons.delete,
                          color: Colors.red[700],
                        ),
                      ],
                    ),
                  ),
                  ElevatedButton(
                  onPressed: () async {
                    // Launch the URL in the default browser
                    await PDFDocument.fromURL(student['file']);
                  },
                  child: Text('Open URL'),

                ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetching data'),
      ),
      body: Container(
        height: double.infinity,
        child: FirebaseAnimatedList(
          query: dbRef,
          itemBuilder: (BuildContext context, DataSnapshot snapshot, Animation<double> animation, int index) {

            Map student = snapshot.value as Map;
            student['key'] = snapshot.key;

            return listItem(student: student);

          },
        ),
      )
    );
  }
}
</code>```

Hey developers i have trying to view the file url which is in realtime database in firebase to view it on the app i am going to upload pdf on the realtime database and i have currently did this to let the user launch the url when they click on open url but i dont want the user to launch the url but i want the user to view the pdf through the link can you help me to solve this much thanks

```<code>ElevatedButton(
                  onPressed: () async {
                    // Launch the URL in the default browser
                    await PDFDocument.fromURL(student['file']);
                  },
                  child: Text('Open URL'),

</code>```

Body:
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';
import 'package:my_project/hello/Courses.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:advance_pdf_viewer/advance_pdf_viewer.dart';

class ViewCourses extends StatefulWidget {
  const ViewCourses({super.key});

  @override
  State<ViewCourses> createState() => _ViewCoursesState();
}

class _ViewCoursesState extends State<ViewCourses> {
 Query dbRef = FirebaseDatabase.instance.ref().child('Students');
  DatabaseReference reference = FirebaseDatabase.instance.ref().child('Students');

  Widget listItem({required Map student}) {
    if (!mounted) return Container();
    return SingleChildScrollView(
      child: GestureDetector(
        onTap: () {

        },
        child: Container(
          margin: const EdgeInsets.all(10),
          padding: const EdgeInsets.all(10),
          height: 300,
          color: Color.fromARGB(255, 255, 200, 0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                (student['Course'] ?? "").toString(),
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
              ),
              const SizedBox(
                height: 5,
              ),
              Text(
                (student['Title'] ?? "").toString(),
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
              ),
              const SizedBox(
                height: 5,
              ),
              Text(
                (student['CreatedBy'] ?? "").toString(),
                style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
              ),
              Text(
              (student['file'] ?? "").toString(),
              style: TextStyle(fontSize: 16, fontWeight: FontWeight.w400),
            ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  GestureDetector(
                    onTap: () {

                    },
                    child: Row(
                      children: [
                        Icon(
                          Icons.edit,
                          color: Theme.of(context).primaryColor,
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(
                    width: 6,
                  ),
                  GestureDetector(
                    onTap: () {
                      reference.child(student['key']).remove();
                    },
                    child: Row(
                      children: [
                        Icon(
                          Icons.delete,
                          color: Colors.red[700],
                        ),
                      ],
                    ),
                  ),
                  ElevatedButton(
                  onPressed: () async {
                    // Launch the URL in the default browser
                    await PDFDocument.fromURL(student['file']);
                  },
                  child: Text('Open URL'),

                ),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Fetching data'),
      ),
      body: Container(
        height: double.infinity,
        child: FirebaseAnimatedList(
          query: dbRef,
          itemBuilder: (BuildContext context, DataSnapshot snapshot, Animation<double> animation, int index) {

            Map student = snapshot.value as Map;
            student['key'] = snapshot.key;

            return listItem(student: student);

          },
        ),
      )
    );
  }
}

Hey developers i have trying to view the file url which is in realtime database in firebase to view it on the app i am going to upload pdf on the realtime database and i have currently did this to let the user launch the url when they click on open url but i dont want the user to launch the url but i want the user to view the pdf through the link can you help me to solve this much thanks

ElevatedButton(
                  onPressed: () async {
                    // Launch the URL in the default browser
                    await PDFDocument.fromURL(student['file']);
                  },
                  child: Text('Open URL'),


问:
Purpose of enableVertexAttribArray, bindBuffer, and vertexAttribPointer in render function
Looking through this example at learnwebgl.brown37.net, I can't understand the purpose of lines 182-189 in simple_model_render_03.js, or lines 4-7 in the following snippet:

gl.uniformMatrix4fv(u_Transform_location, false, transform);
gl.bindBuffer(gl.ARRAY_BUFFER, triangles_vertex_buffer_id);
gl.vertexAttribPointer(a_Vertex_location, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Vertex_location); // this
gl.bindBuffer(gl.ARRAY_BUFFER, triangles_color_buffer_id); // this
gl.vertexAttribPointer(a_Color_location, 3, gl.FLOAT, false, 0, 0); // this
gl.enableVertexAttribArray(a_Color_location); // and this
gl.drawArrays(gl.TRIANGLES, 0, number_triangles * 3);
```

When I comment out these lines and click "Re-start", the output is exactly the same. If the output is the same, then what is the purpose of these lines?

Body:
Looking through this example at learnwebgl.brown37.net, I can't understand the purpose of lines 182-189 in simple_model_render_03.js, or lines 4-7 in the following snippet:

gl.uniformMatrix4fv(u_Transform_location, false, transform);
gl.bindBuffer(gl.ARRAY_BUFFER, triangles_vertex_buffer_id);
gl.vertexAttribPointer(a_Vertex_location, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Vertex_location); // this
gl.bindBuffer(gl.ARRAY_BUFFER, triangles_color_buffer_id); // this
gl.vertexAttribPointer(a_Color_location, 3, gl.FLOAT, false, 0, 0); // this
gl.enableVertexAttribArray(a_Color_location); // and this
gl.drawArrays(gl.TRIANGLES, 0, number_triangles * 3);

When I comment out these lines and click "Re-start", the output is exactly the same. If the output is the same, then what is the purpose of these lines?


问:
Remove Line Item From Order By API
I want to remove line item from order and add new variant in the order when order is placed. but there is no api for deleting line item from order

I have tried with below article

https://shopify.dev/apps/fulfillment/order-management-apps/order-editing#add-a-new-variant

Title: Remove Line Item From Order By API


问:
Facing errors in running the application of Ruby on Rails
Im new to ruby and when try run a application, Im facing the below error

Gemfile:

```<code>source 'https://rubygems.org'
gem 'rails'
gem 'mysql2'
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'haml'
gem 'nifty-utils'
gem 'nilify_blanks'
gem 'authie'
gem 'kaminari'
gem 'chronic'
gem 'dynamic_form'
gem 'activevalidators'
gem 'bcrypt', '3.1.7'
gem 'rails_env_config'
gem 'chronic_duration'
gem 'datey'
gem 'nifty-attachments'
gem 'puma'
gem 'moonrope'
gem 'florrick'
gem 'delayed_job_active_record'
gem 'foreman'
gem 'redcarpet', '3.5.1'
gem 'premailer'

group :development, :test do
  gem 'byebug'
  gem 'web-console'
  gem 'annotate'
  gem 'pry-rails'
end
</code>```

Error:

```<code>Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Development/status/vendor/bundle/ruby/2.6.0/gems/racc-1.6.1/ext/racc/cparse
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby -I /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0 -r
./siteconf20221220-32692-ivgdf1.rb extconf.rb
checking for rb_block_call()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.
</code>```

while running the below command

```<code>bundle --full-index
</code>```

Body:
Im new to ruby and when try run a application, Im facing the below error

Gemfile:

source 'https://rubygems.org'
gem 'rails'
gem 'mysql2'
gem 'sass-rails'
gem 'uglifier'
gem 'coffee-rails'
gem 'jquery-rails'
gem 'haml'
gem 'nifty-utils'
gem 'nilify_blanks'
gem 'authie'
gem 'kaminari'
gem 'chronic'
gem 'dynamic_form'
gem 'activevalidators'
gem 'bcrypt', '3.1.7'
gem 'rails_env_config'
gem 'chronic_duration'
gem 'datey'
gem 'nifty-attachments'
gem 'puma'
gem 'moonrope'
gem 'florrick'
gem 'delayed_job_active_record'
gem 'foreman'
gem 'redcarpet', '3.5.1'
gem 'premailer'

group :development, :test do
  gem 'byebug'
  gem 'web-console'
  gem 'annotate'
  gem 'pry-rails'
end

Error:

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    current directory: /Development/status/vendor/bundle/ruby/2.6.0/gems/racc-1.6.1/ext/racc/cparse
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/bin/ruby -I /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0 -r
./siteconf20221220-32692-ivgdf1.rb extconf.rb
checking for rb_block_call()... *** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

while running the below command

bundle --full-index


问:
Creating a component library to NPM from existing CRA
I want to export some of my CRA components to an external NPM package.
I created a package.json file inside my Components and set the main to index.ts.
The index.ts file contains an import and export of the wanted components.

I then run npm publish on the components folder and install it in another project.

The other project is able to identify the components with the correct needed type (props) but it won't compile.

I get the following error:

```<code>Module parse failed: Unexpected token (8:23)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| import './style.scss';
|
> const Footer = ({links}: FooterProps) => {
</code>```

Body:
I want to export some of my CRA components to an external NPM package.
I created a package.json file inside my Components and set the main to index.ts.
The index.ts file contains an import and export of the wanted components.

I then run npm publish on the components folder and install it in another project.

The other project is able to identify the components with the correct needed type (props) but it won't compile.

I get the following error:

Module parse failed: Unexpected token (8:23)
File was processed with these loaders:
 * ./node_modules/@pmmmwh/react-refresh-webpack-plugin/loader/index.js
 * ./node_modules/source-map-loader/dist/cjs.js
You may need an additional loader to handle the result of these loaders.
| import './style.scss';
|
> const Footer = ({links}: FooterProps) => {


问:
How to put a space between two strings c++
```<code>#include <iostream>
#include <string>
using namespace std;

int main() {
    string x  ;
    string y ;
    string sum;
    string z = " " ;

  cout << "Write your name:" ;
  cin >> x ;
cout  << "Write your second name:" ;
cin >>  y ;
  sum = (x+z+y) ;
  cout << "your name is:" << sum ;

  return 0 ;
}
</code>```

Is there another way to add a space between this two names other than string z = " "
to be like that your name is first name( space)second name

Body:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string x  ;
    string y ;
    string sum;
    string z = " " ;

  cout << "Write your name:" ;
  cin >> x ;
cout  << "Write your second name:" ;
cin >>  y ;
  sum = (x+z+y) ;
  cout << "your name is:" << sum ;

  return 0 ;
}

Is there another way to add a space between this two names other than string z = " "
to be like that your name is first name( space)second name


问:
Next URL param changes to undefined
I am clicking on a Link tag in Next, at first the url loads correctly and then it changes to undefined causing the app to crash.

```<code>{filteredCourses.map((course) => (
                      <Link href={`/technologies/${course.name}`}>
                        <Combobox.Option
                          key={course.id}
                          value={course}
                          className={({ active }) =>
                            classNames(
                              'cursor-pointer select-none px-4 py-2',
                              active && 'bg-[#ec6372] text-white'
                            )
                          }
                        >
                          {course.tech}
                        </Combobox.Option>
                      </Link>
                    ))}
</code>```

Sample of data:

```<code>{
    id: 2,
    price: '322',
    img: 'https://cdn-icons-png.flaticon.com/512/226/226777.png',
    type: 'One-Time',
    tech: 'Java',
    time: '7 Hours',
    des: 'Complete Java Tutorial',
    name: 'java',
  },
</code>```

Why does it turn to undefined after loading at first?

Title: Next URL param changes to undefined

Body:
I am clicking on a Link tag in Next, at first the url loads correctly and then it changes to undefined causing the app to crash.

{filteredCourses.map((course) => (
                      <Link href={`/technologies/${course.name}`}>
                        <Combobox.Option
                          key={course.id}
                          value={course}
                          className={({ active }) =>
                            classNames(
                              'cursor-pointer select-none px-4 py-2',
                              active && 'bg-[#ec6372] text-white'
                            )
                          }
                        >
                          {course.tech}
                        </Combobox.Option>
                      </Link>
                    ))}

Sample of data:

{
    id: 2,
    price: '322',
    img: 'https://cdn-icons-png.flaticon.com/512/226/226777.png',
    type: 'One-Time',
    tech: 'Java',
    time: '7 Hours',
    des: 'Complete Java Tutorial',
    name: 'java',
  },

Why does it turn to undefined after loading at first?


问:
How to make a React form that would submit data as shown in example
How can I get the submitted data to look like this.

{
'banana': {
price: 2,
available: 5
}
};

Right now I just get an object. I want the name to act like the banana.

```<code>const [valueData, setValueData] = useState({
        name: "",
        des: "",
        alergens: "",
});

const handleChange = (event) => {
    setValueData({ ...valueData, [event.target.name]: event.target.value });
};

const handleSubmit = (event) => {
    event.preventDefault();
};

return (
    <form onSubmit={handleSubmit}>
        <div>
            <label>Product name </label>
            <input
                type="text"
                placeholder="Product name"
                name="name"
                value={valueData.name}
                onChange={handleChange}
            />
        </div>
        <div>
            <label>Product description </label>
            <input
                type="text"
                placeholder="Product description"
                name="des"
                value={valueData.des}
                onChange={handleChange}
            />
        </div>
        <div>
            <button onClick={handleClick}>Submit</button>
        </div>
    </form>
)
</code>```

I don't know what's the correct syntax for this problem.

Body:
How can I get the submitted data to look like this.

{
'banana': {
price: 2,
available: 5
}
};

Right now I just get an object. I want the name to act like the banana.

const [valueData, setValueData] = useState({
        name: "",
        des: "",
        alergens: "",
});

const handleChange = (event) => {
    setValueData({ ...valueData, [event.target.name]: event.target.value });
};

const handleSubmit = (event) => {
    event.preventDefault();
};

return (
    <form onSubmit={handleSubmit}>

            Product name
            <input
                type="text"
                placeholder="Product name"
                name="name"
                value={valueData.name}
                onChange={handleChange}
            />

            Product description
            <input
                type="text"
                placeholder="Product description"
                name="des"
                value={valueData.des}
                onChange={handleChange}
            />

            <button onClick={handleClick}>Submit</button>

    </form>
)

I don't know what's the correct syntax for this problem.


问:
Expo App rejected by Apple due to using "public APIs with Notification Center"
I got an app (build with Expo/ReactNative) in the Apple AppStore (and Google PlayStore) that has been rejected a whole year after it has been published and being accepted by Apple.

Apple's message is the following:

Guideline 2.5.1 - Performance - Software Requirements

We still found that your app uses public APIs with Notification Center in a manner not prescribed by Apple, which is not in compliance with the Apple Developer Program License Agreement, as required by the App Store Review Guidelines.

In particular, section 3.3.1 of the Apple Developer Program License Agreement specifies:

"Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs."

While your app may use public APIs such as local notifications to display content in Notification Center, the content displayed is not consistent with the purpose of Notification Center.

Problem is: The app isn't using Notification Center at all.

I already search the whole code for something related to Notification Center or something similar, but even a fulltext search for notif returns no result.

Those are the dependencies:

```<code>  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.15.11",
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/native-stack": "^6.2.5",
    "expo": "~43.0.2",
    "expo-av": "^10.1.3",
    "expo-brightness": "^10.0.3",
    "expo-keep-awake": "^10.0.0",
    "expo-localization": "~11.0.0",
    "expo-status-bar": "~1.1.0",
    "expo-web-browser": "~10.0.3",
    "i18n-js": "^3.8.0",
    "lodash": "^4.17.21",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.9.0",
    "react-native-web": "0.17.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },
</code>```

Do you guys see any package that could possibly contain something or do you know anything that would make Apple giue the statement written above? I have no clue what to do to bring the app back into the AppStore.

The only packages coming remotely near to the Notification Center are expo-brightness and expo-keep-awake, but I didn't find any hint in the web that those two packages have been rejected before. And both packages are kinda crucial for the app.

Maybe you can help.

Thanks a lot!

Body:
I got an app (build with Expo/ReactNative) in the Apple AppStore (and Google PlayStore) that has been rejected a whole year after it has been published and being accepted by Apple.

Apple's message is the following:

Guideline 2.5.1 - Performance - Software Requirements

We still found that your app uses public APIs with Notification Center in a manner not prescribed by Apple, which is not in compliance with the Apple Developer Program License Agreement, as required by the App Store Review Guidelines.

In particular, section 3.3.1 of the Apple Developer Program License Agreement specifies:

"Applications may only use Documented APIs in the manner prescribed by Apple and must not use or call any private APIs."

While your app may use public APIs such as local notifications to display content in Notification Center, the content displayed is not consistent with the purpose of Notification Center.

Problem is: The app isn't using Notification Center at all.

I already search the whole code for something related to Notification Center or something similar, but even a fulltext search for notif returns no result.

Those are the dependencies:

  "dependencies": {
    "@react-native-async-storage/async-storage": "^1.15.11",
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/native-stack": "^6.2.5",
    "expo": "~43.0.2",
    "expo-av": "^10.1.3",
    "expo-brightness": "^10.0.3",
    "expo-keep-awake": "^10.0.0",
    "expo-localization": "~11.0.0",
    "expo-status-bar": "~1.1.0",
    "expo-web-browser": "~10.0.3",
    "i18n-js": "^3.8.0",
    "lodash": "^4.17.21",
    "react": "17.0.1",
    "react-dom": "17.0.1",
    "react-native": "0.64.3",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.9.0",
    "react-native-web": "0.17.1"
  },
  "devDependencies": {
    "@babel/core": "^7.12.9"
  },

Do you guys see any package that could possibly contain something or do you know anything that would make Apple giue the statement written above? I have no clue what to do to bring the app back into the AppStore.

The only packages coming remotely near to the Notification Center are expo-brightness and expo-keep-awake, but I didn't find any hint in the web that those two packages have been rejected before. And both packages are kinda crucial for the app.

Maybe you can help.

Thanks a lot!


问:
How to extract trained embedding dimensions from a keras recommender system?
Following the tutorial link

How do you extract the trained embeddings of a trained model?

I know you can use model.get_layer(‘sequential_##’).get_weights()[0] to output the embeddings. Also, that  a StringLookup layer was implemented to map the string to integers? How do you index this back to unique_user_ids/unique_movie_titles, also taking into account the +1 padding on the user_model and movie_model?

Thanks.

Have tried:

model.get_layer(‘sequential_##’).get_weights()[0] - to retrieve the trained embeddings

decoder = tf.keras.layers.StringLookup(vocabulary=vocab, output_mode="int", invert=True) - created decoder but unable to extract the mapped integers


问:
How do I select the first value of of a parameter to be the default value?
I want to show a default value in the dropdown for my parameters. The thing is, my parameter doesn't reference a Dataset but it references another parameter. So I want the default value of parameter 2 to be the selected value of parameter 1.

I can't seem to get it to work. I my specific case I want "DisplayMonat" to default to the selected value from "Monat" and not .

Thanks in advance


问:
Can two intent filters in the same activity provide this behaviour?
I have an activity with two intent filters:

```<code><activity
    android:name=".MainActivity"
    android:exported="true">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="https" />

        <data android:host="www.my-domain.com" />
    </intent-filter>
</activity>
</code>```

The second intent filter is used for deep links. This means that when I click on a particular link, I want my app to open. The file from https://www.my-domain.com/.well-known/ is verified.

If I test the URL in "App Links Assitant" I get:

```<code>This URL maps to .MainActivity (MyAwsomeApp.app)
</code>```

If I run:

```<code>adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://www.my-domain.com"
</code>```

The app is opened successfully on my device. However, when I click on a URL in the email, the browser directly opens the URL instead of redirecting to app. How to overcome this situation? I'm using Jetpack Compose for navigation and not activities. Any help would be greatly appreciated.

Body:
I have an activity with two intent filters:

<activity
    android:name=".MainActivity"
    android:exported="true">
    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

    <intent-filter android:autoVerify="true">
        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data android:scheme="https" />

        <data android:host="www.my-domain.com" />
    </intent-filter>
</activity>

The second intent filter is used for deep links. This means that when I click on a particular link, I want my app to open. The file from https://www.my-domain.com/.well-known/ is verified.

If I test the URL in "App Links Assitant" I get:

This URL maps to .MainActivity (MyAwsomeApp.app)

If I run:

adb shell am start -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://www.my-domain.com"

The app is opened successfully on my device. However, when I click on a URL in the email, the browser directly opens the URL instead of redirecting to app. How to overcome this situation? I'm using Jetpack Compose for navigation and not activities. Any help would be greatly appreciated.


问:
Unset field for the required field in Open API Specification README
I have recently started working on README to document the APIs using Open API Specification document.

For the required fields which takes enum as the input values, it is showing the first enum value however the value is not populated in backend. This results in manually toggling the fields to select the right value.

And also I do not want to give the default value for the field, as this supposed to be filled by the user.

Could you please help me in finding the right solution fox this fix.


问:
Running Parse server with SSL on WHM/CPANEL
i have a Parse API server running on port 1337 on my WHM/CPANEL server. This instance is protected usign AutoSSL features on cpanel an the certificate is correctly running on port 483. When i hit http://myip.com:1337 the server is working correctly, but i need that is running on https.
I read that i need to reverse proxy usign Passenger feature on WHM and i have created the config file like this, but unfortunately this is not working and i got 503 error.</p>
```<code>`ProxyRequests On
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>
   ProxyPass / http://localhost:1337/
   ProxyPassReverse / http://localhost:1337/
<Location "/">
    <IfModule mod_passenger.c>
        PassengerAppEnv "production"

        PassengerEnabled on
        PassengerBaseURI "/"
        PassengerAppRoot "/home/oltrepop/api"
        PassengerAppGroupName "oltrepop - oltrepop"
        PassengerRuby /usr/bin/ruby
        PassengerPython /usr/bin/python3.6m
        PassengerNodejs /opt/cpanel/ea-nodejs16/bin/node
    </IfModule>
</Location>
<Directory "/home/oltrepop/api">
    Allow from all
    Options -MultiViews
    Options -Indexes
    Require all granted
</Directory>
`
</code>```

Body:
i have a Parse API server running on port 1337 on my WHM/CPANEL server. This instance is protected usign AutoSSL features on cpanel an the certificate is correctly running on port 483. When i hit http://myip.com:1337 the server is working correctly, but i need that is running on https.
I read that i need to reverse proxy usign Passenger feature on WHM and i have created the config file like this, but unfortunately this is not working and i got 503 error.

`ProxyRequests On
  <Proxy *>
    Order deny,allow
    Allow from all
  </Proxy>
   ProxyPass / http://localhost:1337/
   ProxyPassReverse / http://localhost:1337/
<Location "/">
    <IfModule mod_passenger.c>
        PassengerAppEnv "production"

        PassengerEnabled on
        PassengerBaseURI "/"
        PassengerAppRoot "/home/oltrepop/api"
        PassengerAppGroupName "oltrepop - oltrepop"
        PassengerRuby /usr/bin/ruby
        PassengerPython /usr/bin/python3.6m
        PassengerNodejs /opt/cpanel/ea-nodejs16/bin/node
    </IfModule>
</Location>
<Directory "/home/oltrepop/api">
    Allow from all
    Options -MultiViews
    Options -Indexes
    Require all granted
</Directory>
`


问:
FireStore draws Charts overlapping display
I want to draw a chart, fill the chart with data from firestore, but it overlaps as shown in the picture
I use the library https://github.com/danielgindi/Charts to create charts, using swift.. Sorry for the unclear description

What I want is to populate the Charts in chronological order, this is my FireStore

I am just new at this so if anyone can help me with this it would be great.

```<code>func LiveChart() {
        db.collection("Admin").document("AiSmartRobot").collection("AiDailyProfit").addSnapshotListener({ [self] (querySnapShot, error) in

            for document in querySnapShot!.documents{

                if let quantity = document.data()["quantity"] as? Double{
                    if let datetime = document.data()["date"] as? String{

                        let barChartView = BarChartView(frame: live.bounds)
                        barChartView.delegate = self
                        barChartView.xAxis.labelPosition = .bottom

                        let xValues = [datetime]
                        barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xValues)
                        self.live.addSubview(barChartView)
                        var values = [BarChartDataEntry]()
                        let numbers : [Double] = [quantity]
                        for i in 0..<numbers.count {
                            let value = BarChartDataEntry(x: Double(i), y: numbers[i])
                            values.append(value)
                        }
                        let ds = BarChartDataSet(values: values, label: "")
                        let data = BarChartData(dataSets: [ds])
                        ds.valueColors = [UIColor(red: 57.0/255.0, green: 176.0/255.0, blue: 158.0/255.0, alpha: 1)]
                        barChartView.data = data
                        barChartView.chartDescription?.text = ""
                        barChartView.animate(yAxisDuration: 2)
                        barChartView.notifyDataSetChanged()

                    }

                }

            }
        })
    }
}

</code>```

Body:
I want to draw a chart, fill the chart with data from firestore, but it overlaps as shown in the picture
I use the library https://github.com/danielgindi/Charts to create charts, using swift.. Sorry for the unclear description

What I want is to populate the Charts in chronological order, this is my FireStore

I am just new at this so if anyone can help me with this it would be great.

func LiveChart() {
        db.collection("Admin").document("AiSmartRobot").collection("AiDailyProfit").addSnapshotListener({ [self] (querySnapShot, error) in

            for document in querySnapShot!.documents{

                if let quantity = document.data()["quantity"] as? Double{
                    if let datetime = document.data()["date"] as? String{

                        let barChartView = BarChartView(frame: live.bounds)
                        barChartView.delegate = self
                        barChartView.xAxis.labelPosition = .bottom

                        let xValues = [datetime]
                        barChartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xValues)
                        self.live.addSubview(barChartView)
                        var values = [BarChartDataEntry]()
                        let numbers : [Double] = [quantity]
                        for i in 0..<numbers.count {
                            let value = BarChartDataEntry(x: Double(i), y: numbers[i])
                            values.append(value)
                        }
                        let ds = BarChartDataSet(values: values, label: "")
                        let data = BarChartData(dataSets: [ds])
                        ds.valueColors = [UIColor(red: 57.0/255.0, green: 176.0/255.0, blue: 158.0/255.0, alpha: 1)]
                        barChartView.data = data
                        barChartView.chartDescription?.text = ""
                        barChartView.animate(yAxisDuration: 2)
                        barChartView.notifyDataSetChanged()

                    }

                }

            }
        })
    }
}


问:
How to add learning capability for TextPredictionGenerator?
How to make TextPredictionGenerator support learning from user input?

https://learn.microsoft.com/en-us/uwp/api/windows.data.text.textpredictiongenerator?view=winrt-22621


问:
Create Desktop Application(Window Form .net 6) With Identity
I am working on desktop application( window form .net 6.0).
I want to implement Microsoft identity for user management.

when i call it

await _signInManager.PasswordSignInAsync(user.UserName, Password, true, lockoutOnFailure: false)
```
<p>It will return HttpContext must not be null</p>
<p>Here is My <strong>Program.cs</strong> file  where i register identity service</p>
<pre class="lang-cs prettyprint-override"><code>[STAThread]
static void Main()
{
    {

        Application.SetHighDpiMode(HighDpiMode.SystemAware);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var services = new ServiceCollection();
        services.AddLogging(option =>
        {
            option.SetMinimumLevel(LogLevel.Information);
            //option.AddNLog("nlog.config");
        });
        services.AddAutoMapper(typeof(AutoMapperProfile).GetTypeInfo().Assembly);
        services.AddPersistence();
        services.AddApplication();
        services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
        services.AddHttpContextAccessor();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient<IUserHttpContextProvider, UserHttpContextProvider>();

        //services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>()?.HttpContext?.User);
        services.AddIdentityCore<ApplicationUser>();
        // GetService<IHttpContextAccessor>().HttpContext.User

        services.AddScoped<Form1>();
        // ConfigurationService.ConfigureServices(services);
        using (ServiceProvider serviceProvider = services.BuildServiceProvider())
        {

            var Form1 = serviceProvider.GetRequiredService<Form1>();
            Application.Run(Form1);
        }
    }
}
</code>```

Here is my class where i call SignInManager

namespace Desktop
{
    public class DummyAccount
    {
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly UrlEncoder _utEncoder;
        private readonly IApplicationDbContext _context;

        public DummyAccount(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager,
           IApplicationDbContext context, UrlEncoder utEncoder)
        {
            _signInManager = signInManager;
            _utEncoder = utEncoder;
            _context = context;
            _userManager = userManager;
        }

        public async Task UserLogin(string Email, string Password)
        {
            SignInResult result = new SignInResult();

            //var user = await _userManager.FindByEmailAsync(Input.Email);
            ApplicationUser user;
            using (var conn = new SqlConnection("Server=DESKTOP-DMB5OIT;Database=Noble;Trusted_Connection=True;MultipleActiveResultSets=true"))
            {
                user =
                    conn.Query<ApplicationUser>("select * from AspNetUsers where Email='" +
                                                Email.ToLower() + "'").FirstOrDefault();

                conn.Close();
            }
            if (user != null)
                result = await _signInManager.PasswordSignInAsync(user.UserName, Password, true, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                //var user = await _userManager.FindByEmailAsync(Input.Email);
                ApplicationUser user;
                using (var conn = new SqlConnection("Server=DESKTOP-DMB5OIT;Database=Noble;Trusted_Connection=True;MultipleActiveResultSets=true"))
                {
                    user = conn.Query<ApplicationUser>("select top 1 * from AspNetUsers where Email='" +
                                                    Email.ToLower() + "'").FirstOrDefault();

                    conn.Close();
                }
            }
        }
    }
}
```

Here the error i got
enter image description here

Body:
I am working on desktop application( window form .net 6.0).
I want to implement Microsoft identity for user management.

when i call it

await _signInManager.PasswordSignInAsync(user.UserName, Password, true, lockoutOnFailure: false)

It will return HttpContext must not be null

Here is My Program.cs file  where i register identity service

[STAThread]
static void Main()
{
    {

        Application.SetHighDpiMode(HighDpiMode.SystemAware);
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var services = new ServiceCollection();
        services.AddLogging(option =>
        {
            option.SetMinimumLevel(LogLevel.Information);
            //option.AddNLog("nlog.config");
        });
        services.AddAutoMapper(typeof(AutoMapperProfile).GetTypeInfo().Assembly);
        services.AddPersistence();
        services.AddApplication();
        services.AddIdentity<ApplicationUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
        services.AddHttpContextAccessor();
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        services.AddTransient<IUserHttpContextProvider, UserHttpContextProvider>();

        //services.AddTransient<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>()?.HttpContext?.User);
        services.AddIdentityCore<ApplicationUser>();
        // GetService<IHttpContextAccessor>().HttpContext.User

        services.AddScoped<Form1>();
        // ConfigurationService.ConfigureServices(services);
        using (ServiceProvider serviceProvider = services.BuildServiceProvider())
        {

            var Form1 = serviceProvider.GetRequiredService<Form1>();
            Application.Run(Form1);
        }
    }
}

Here is my class where i call SignInManager

namespace Desktop
{
    public class DummyAccount
    {
        private readonly SignInManager<ApplicationUser> _signInManager;
        private readonly UserManager<ApplicationUser> _userManager;
        private readonly UrlEncoder _utEncoder;
        private readonly IApplicationDbContext _context;

        public DummyAccount(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager,
           IApplicationDbContext context, UrlEncoder utEncoder)
        {
            _signInManager = signInManager;
            _utEncoder = utEncoder;
            _context = context;
            _userManager = userManager;
        }

        public async Task UserLogin(string Email, string Password)
        {
            SignInResult result = new SignInResult();

            //var user = await _userManager.FindByEmailAsync(Input.Email);
            ApplicationUser user;
            using (var conn = new SqlConnection("Server=DESKTOP-DMB5OIT;Database=Noble;Trusted_Connection=True;MultipleActiveResultSets=true"))
            {
                user =
                    conn.Query<ApplicationUser>("select * from AspNetUsers where Email='" +
                                                Email.ToLower() + "'").FirstOrDefault();

                conn.Close();
            }
            if (user != null)
                result = await _signInManager.PasswordSignInAsync(user.UserName, Password, true, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                //var user = await _userManager.FindByEmailAsync(Input.Email);
                ApplicationUser user;
                using (var conn = new SqlConnection("Server=DESKTOP-DMB5OIT;Database=Noble;Trusted_Connection=True;MultipleActiveResultSets=true"))
                {
                    user = conn.Query<ApplicationUser>("select top 1 * from AspNetUsers where Email='" +
                                                    Email.ToLower() + "'").FirstOrDefault();

                    conn.Close();
                }
            }
        }
    }
}

Here the error i got
enter image description here


问:
reversing an image gradient transformation in matlab
I have this function in matlab where a grayscaled image is converted to an image gradient. What i'm wondering is if there is a way to take the image I got here (gradient) and convert it back to the grayscale image (im_gray) such that input_grayscale == output_grayscale</p>
```<code>function gradient = gradient_conv(im_gray)

wx=[1, -1];
wy=[1, -1]';

image=im2double(im_gray);

image_gradx=imfilter(double(image),wx,'conv','replicate');
image_grady=imfilter(double(image),wy,'conv','replicate');
G1=sqrt(image_gradx.^2+image_grady.^2);
G1=double(G1*255);

A=max(max(G1));
G1=G1/A;
gradient=uint8(G1*255);
end
</code>```

Body:
I have this function in matlab where a grayscaled image is converted to an image gradient. What i'm wondering is if there is a way to take the image I got here (gradient) and convert it back to the grayscale image (im_gray) such that input_grayscale == output_grayscale

function gradient = gradient_conv(im_gray)

wx=[1, -1];
wy=[1, -1]';

image=im2double(im_gray);

image_gradx=imfilter(double(image),wx,'conv','replicate');
image_grady=imfilter(double(image),wy,'conv','replicate');
G1=sqrt(image_gradx.^2+image_grady.^2);
G1=double(G1*255);

A=max(max(G1));
G1=G1/A;
gradient=uint8(G1*255);
end


问:
I can not receive sms in twilio?? "twilio" "sms"
I cannot receive SMS in twilio in order to receive activation codes. I tried to send a code to twilio but the message did not arrive and I tried again via my mobile phone number to send to twilio number but it did not arrive??
I don't know if the problem is with Webhook to POST or MESSAGING SERVICE.
A note is shown to me
Routing
United States (US1) Region inbound message routing is: Active

I have a twilio GB number.     "twilio" "sms"

I cannot receive SMS in twilio in order to receive activation codes. I tried to send a code to twilio but the message did not arrive and I tried again via my mobile phone number to send to twilio number but it did not arrive??
I don't know if the problem is with Webhook to POST or MESSAGING SERVICE.
A note is shown to me
Routing
United States (US1) Region inbound message routing is: Active

I have a twilio GB number.


问:
CSV writing data in columns but not at the top
'''
I can get the output to CSV and put it in three columns as I want to. But the second and third column of the .csv file don't populate from the top.
'''
'''
The output to the .csv is successful.

'''
import csv
import random

```<code>tieList = []
youWinList = []
computerWinsList = []
myList = [tieList, youWinList, computerWinsList]

tie = 0
youWin = 0
computerWins = 0
for i in range(1000):
    choices = ['rock', 'paper', 'scissors']
    player_choice = random.choice(choices)
    computer_choice = random.choice(choices)
    print(f"You chose {player_choice} and the computer chose {computer_choice}.")

    if player_choice == computer_choice:
        tie =tie + 1
        tieList.append(1)
        print("It's a tie!")
    elif player_choice == 'rock' and computer_choice == 'scissors':
        print("You win!")
        youWin +=1
        youWinList.append(1)
    elif player_choice == 'paper' and computer_choice == 'rock':
        print("You win!")
        youWin +=1
        youWinList.append(1)
    elif player_choice == 'scissors' and computer_choice == 'paper':
        print("You win!")
        youWin +=1
        youWinList.append(1)
    else:
        print("The computer wins!")
        computerWins +=1
        computerWinsList.append(1)
print(f'You Win: {youWin}  Computer Wins: {computerWins}  Tie: {tie}')
print(f'TieList.....:{tieList}')

with open('data.csv', 'w', newline='') as csv_file:
  writer = csv.writer(csv_file)

  for i in range(len(tieList)):
    writer.writerow([tieList[i]])
  for i in range(len(youWinList)):
    writer.writerow(['',youWinList[i]])
  for i in range(len(computerWinsList)):
    writer.writerow(['', '',computerWinsList[i]])
</code>```

Body:
'''
I can get the output to CSV and put it in three columns as I want to. But the second and third column of the .csv file don't populate from the top.
'''
'''
The output to the .csv is successful.

'''
import csv
import random

tieList = []
youWinList = []
computerWinsList = []
myList = [tieList, youWinList, computerWinsList]

tie = 0
youWin = 0
computerWins = 0
for i in range(1000):
    choices = ['rock', 'paper', 'scissors']
    player_choice = random.choice(choices)
    computer_choice = random.choice(choices)
    print(f"You chose {player_choice} and the computer chose {computer_choice}.")

    if player_choice == computer_choice:
        tie =tie + 1
        tieList.append(1)
        print("It's a tie!")
    elif player_choice == 'rock' and computer_choice == 'scissors':
        print("You win!")
        youWin +=1
        youWinList.append(1)
    elif player_choice == 'paper' and computer_choice == 'rock':
        print("You win!")
        youWin +=1
        youWinList.append(1)
    elif player_choice == 'scissors' and computer_choice == 'paper':
        print("You win!")
        youWin +=1
        youWinList.append(1)
    else:
        print("The computer wins!")
        computerWins +=1
        computerWinsList.append(1)
print(f'You Win: {youWin}  Computer Wins: {computerWins}  Tie: {tie}')
print(f'TieList.....:{tieList}')

with open('data.csv', 'w', newline='') as csv_file:
  writer = csv.writer(csv_file)

  for i in range(len(tieList)):
    writer.writerow([tieList[i]])
  for i in range(len(youWinList)):
    writer.writerow(['',youWinList[i]])
  for i in range(len(computerWinsList)):
    writer.writerow(['', '',computerWinsList[i]])


问:
can we implement sha512 encryption,decryption logic in node.js?
We have one Java logic for checksum generation and sha512 encryption,decryption.
The same logic has to be implemented in node

Encryption:
var m = 'naveen';
o/p :
637a752d6442dac06d1f7880b0cef6f10af8afc9f45c03d22588f8f49d1fbc25038dc911304960e320569e422c31a32e826c684d1a698c3f481e169d34712f17

When am trying to decrypting the o/p not getting the original value.


问:
how to write a proper post endpoint in openAPI (formerly swagger) in a openapi.yaml file?
I don't know why but when I try to fire the login endpoint I got error saying that my credential are wrong.
How can I do proper post request in openapi.yaml file?
Here is the code I wrote:

```<code>login:
  post:
    description: login member, it returns access_token
    operationId: login
    tags:
      - login
    parameters:
      - name: tc_no
        in: body
        required: true
      - name: password
        in: body
        required: true
      - name: session_id
        in: body
        required: true
    responses:
      '403':
        description: 'Wrong credentials!'
      '200':
        description: Successful operation
        content:
          application/json:
            schema:
              title: loginResponse
              type: object
</code>```

Here is how it is displayed on gitlab

Body:
I don't know why but when I try to fire the login endpoint I got error saying that my credential are wrong.
How can I do proper post request in openapi.yaml file?
Here is the code I wrote:

login:
  post:
    description: login member, it returns access_token
    operationId: login
    tags:
      - login
    parameters:
      - name: tc_no
        in: body
        required: true
      - name: password
        in: body
        required: true
      - name: session_id
        in: body
        required: true
    responses:
      '403':
        description: 'Wrong credentials!'
      '200':
        description: Successful operation
        content:
          application/json:
            schema:
              title: loginResponse
              type: object

Here is how it is displayed on gitlab


问:
AG Grid gridApi not being set in Cypress e2e test
I am writing a suite of Cypress tests that want to test gridApi functionality. The grid renders properly, but the gridApi is not set during the test. It sets properly during dev. Does anyone have a working example of a test where they render a grid and perform an action that is driven by a gridApi method call directly?

Here is how I instantiate the gridApi for reference:

```<code>const onGridReady = useCallback(({ api, columnApi }: GridReadyEvent): void => {
    if (!api || !columnApi) {
      return;
    }
    setGridApi(api);
    setColumnApi(columnApi);
  }, []);
</code>```

I tried to navigate to the page, check that the grid was rendered, then perform an action that invokes the gridApi. That action failed as the gridApi is not instantiated.

Body:
I am writing a suite of Cypress tests that want to test gridApi functionality. The grid renders properly, but the gridApi is not set during the test. It sets properly during dev. Does anyone have a working example of a test where they render a grid and perform an action that is driven by a gridApi method call directly?

Here is how I instantiate the gridApi for reference:

const onGridReady = useCallback(({ api, columnApi }: GridReadyEvent): void => {
    if (!api || !columnApi) {
      return;
    }
    setGridApi(api);
    setColumnApi(columnApi);
  }, []);

I tried to navigate to the page, check that the grid was rendered, then perform an action that invokes the gridApi. That action failed as the gridApi is not instantiated.