问:
Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)
When running 'kubectl top nodes' has error:

Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)

```<code>k8s version:
kubectl version
Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.1", GitCommit:"eec55b9ba98609a46fee712359c7b5b365bdd920", GitTreeState:"clean", BuildDate:"2018-12-13T10:39:04Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.1", GitCommit:"eec55b9ba98609a46fee712359c7b5b365bdd920", GitTreeState:"clean", BuildDate:"2018-12-13T10:31:33Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"linux/amd64"}

[root@manager ~]# kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
metrics.k8s.io/v1beta1
networking.k8s.io/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

[root@manager ~]# kubectl get po --all-namespaces

NAMESPACE     NAME                                    READY   STATUS    RESTARTS   AGE
kube-system   coredns-86c58d9df4-km7jc                1/1     Running   0          2d21h
kube-system   coredns-86c58d9df4-vltm9                1/1     Running   0          2d21h
kube-system   etcd-manager                            1/1     Running   0          2d23h
kube-system   kube-apiserver-manager                  1/1     Running   0          5h47m
kube-system   kube-controller-manager-manager         1/1     Running   1          2d23h
kube-system   kube-flannel-ds-amd64-5g8w8             1/1     Running   0          2d23h
kube-system   kube-flannel-ds-amd64-69lcm             1/1     Running   0          2d23h
kube-system   kube-flannel-ds-amd64-9hx2f             1/1     Running   0          2d23h
kube-system   kube-proxy-9s6zm                        1/1     Running   0          2d23h
kube-system   kube-proxy-k4qwz                        1/1     Running   0          2d23h
kube-system   kube-proxy-wnzgd                        1/1     Running   0          2d23h
kube-system   kube-scheduler-manager                  1/1     Running   1          2d23h
kube-system   kubernetes-dashboard-79ff88449c-7fpw6   1/1     Running   0          2d23h
kube-system   metrics-server-68d85f76bb-pj8bs         1/1     Running   0          111m
kube-system   tiller-deploy-5478b6c547-bf82v          1/1     Running   0          4h7m

[root@manager ~]# kubectl logs -f -n kube-system metrics-server-68d85f76bb-pj8bs

I1217 06:42:43.451782       1 serving.go:273] Generated self-signed cert (apiserver.local.config/certificates/apiserver.crt, apiserver.local.config/certificates/apiserver.key)
[restful] 2018/12/17 06:42:44 log.go:33: [restful/swagger] listing is available at https://:443/swaggerapi
[restful] 2018/12/17 06:42:44 log.go:33: [restful/swagger] https://:443/swaggerui/ is mapped to folder /swagger-ui/
I1217 06:42:44.099720       1 serve.go:96] Serving securely on [::]:443
</code>```

And has no system error log.
How can I resolve this problem?

OS is :CentOS Linux release 7.5.1804 (Core)

答:
i had solved this problem, add hostNetwork: true to metries-server.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    k8s-app: metrics-server
  name: metrics-server
  namespace: kube-system
spec:
  selector:
    matchLabels:
      k8s-app: metrics-server
  strategy:
    rollingUpdate:
      maxUnavailable: 0
  template:
    metadata:
      labels:
        k8s-app: metrics-server
    spec:
      hostNetwork: true ## add
```
<p>docs:</p>
<pre class="lang-sh prettyprint-override"><code>[root@xx yaml]# kubectl explain deployment.spec.template.spec.hostNetwork
KIND:     Deployment
VERSION:  apps/v1

FIELD:    hostNetwork <boolean>

DESCRIPTION:
     Host networking requested for this pod. Use the host's network namespace.
     If this option is set, the ports that will be used must be specified.
     Default to false.
</code>```

background:

successful running metries, but kubectl top nodes occuied: Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io).

Body:
When running 'kubectl top nodes' has error:

Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io)

k8s version:
kubectl version
Client Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.1", GitCommit:"eec55b9ba98609a46fee712359c7b5b365bdd920", GitTreeState:"clean", BuildDate:"2018-12-13T10:39:04Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"linux/amd64"}
Server Version: version.Info{Major:"1", Minor:"13", GitVersion:"v1.13.1", GitCommit:"eec55b9ba98609a46fee712359c7b5b365bdd920", GitTreeState:"clean", BuildDate:"2018-12-13T10:31:33Z", GoVersion:"go1.11.2", Compiler:"gc", Platform:"linux/amd64"}

[root@manager ~]# kubectl api-versions
admissionregistration.k8s.io/v1beta1
apiextensions.k8s.io/v1beta1
apiregistration.k8s.io/v1
apiregistration.k8s.io/v1beta1
apps/v1
apps/v1beta1
apps/v1beta2
authentication.k8s.io/v1
authentication.k8s.io/v1beta1
authorization.k8s.io/v1
authorization.k8s.io/v1beta1
autoscaling/v1
autoscaling/v2beta1
autoscaling/v2beta2
batch/v1
batch/v1beta1
certificates.k8s.io/v1beta1
coordination.k8s.io/v1beta1
events.k8s.io/v1beta1
extensions/v1beta1
metrics.k8s.io/v1beta1
networking.k8s.io/v1
policy/v1beta1
rbac.authorization.k8s.io/v1
rbac.authorization.k8s.io/v1beta1
scheduling.k8s.io/v1beta1
storage.k8s.io/v1
storage.k8s.io/v1beta1
v1

[root@manager ~]# kubectl get po --all-namespaces

NAMESPACE     NAME                                    READY   STATUS    RESTARTS   AGE
kube-system   coredns-86c58d9df4-km7jc                1/1     Running   0          2d21h
kube-system   coredns-86c58d9df4-vltm9                1/1     Running   0          2d21h
kube-system   etcd-manager                            1/1     Running   0          2d23h
kube-system   kube-apiserver-manager                  1/1     Running   0          5h47m
kube-system   kube-controller-manager-manager         1/1     Running   1          2d23h
kube-system   kube-flannel-ds-amd64-5g8w8             1/1     Running   0          2d23h
kube-system   kube-flannel-ds-amd64-69lcm             1/1     Running   0          2d23h
kube-system   kube-flannel-ds-amd64-9hx2f             1/1     Running   0          2d23h
kube-system   kube-proxy-9s6zm                        1/1     Running   0          2d23h
kube-system   kube-proxy-k4qwz                        1/1     Running   0          2d23h
kube-system   kube-proxy-wnzgd                        1/1     Running   0          2d23h
kube-system   kube-scheduler-manager                  1/1     Running   1          2d23h
kube-system   kubernetes-dashboard-79ff88449c-7fpw6   1/1     Running   0          2d23h
kube-system   metrics-server-68d85f76bb-pj8bs         1/1     Running   0          111m
kube-system   tiller-deploy-5478b6c547-bf82v          1/1     Running   0          4h7m

[root@manager ~]# kubectl logs -f -n kube-system metrics-server-68d85f76bb-pj8bs

I1217 06:42:43.451782       1 serving.go:273] Generated self-signed cert (apiserver.local.config/certificates/apiserver.crt, apiserver.local.config/certificates/apiserver.key)
[restful] 2018/12/17 06:42:44 log.go:33: [restful/swagger] listing is available at https://:443/swaggerapi
[restful] 2018/12/17 06:42:44 log.go:33: [restful/swagger] https://:443/swaggerui/ is mapped to folder /swagger-ui/
I1217 06:42:44.099720       1 serve.go:96] Serving securely on [::]:443

And has no system error log.
How can I resolve this problem?

OS is :CentOS Linux release 7.5.1804 (Core)

Body:
i had solved this problem, add hostNetwork: true to metries-server.yaml:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    k8s-app: metrics-server
  name: metrics-server
  namespace: kube-system
spec:
  selector:
    matchLabels:
      k8s-app: metrics-server
  strategy:
    rollingUpdate:
      maxUnavailable: 0
  template:
    metadata:
      labels:
        k8s-app: metrics-server
    spec:
      hostNetwork: true ## add

docs:

[root@xx yaml]# kubectl explain deployment.spec.template.spec.hostNetwork
KIND:     Deployment
VERSION:  apps/v1

FIELD:    hostNetwork <boolean>

DESCRIPTION:
     Host networking requested for this pod. Use the host's network namespace.
     If this option is set, the ports that will be used must be specified.
     Default to false.

background:

successful running metries, but kubectl top nodes occuied: Error from server (ServiceUnavailable): the server is currently unable to handle the request (get nodes.metrics.k8s.io).


来源: stackexchange

问:
Does Java stream().sorted or list.sort() not increases time complexity?
While making some sortings, some people suggest using stream().sorted or list.sort() methods in Java to reduce time complexity. However, I think these methods also use some sorting algorithms that has a similar time complexity.

```<code>List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());
</code>```

So, does it mean that these algorithms use the most efficient sorting algorithms for sorting less time than I sort in 2 nested for loop?

答: The time complexity of these methods is O(nlog(n)). And it's the best time complexity for sorting an array.

ContentLicense: CC BY-SA 4.0

Body:
While making some sortings, some people suggest using stream().sorted or list.sort() methods in Java to reduce time complexity. However, I think these methods also use some sorting algorithms that has a similar time complexity.

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());

So, does it mean that these algorithms use the most efficient sorting algorithms for sorting less time than I sort in 2 nested for loop?


问:
Problem on performing CRUD operation using Django REST API
Hey I am new to Django Rest Framework.I have recently created REST API name "api/studentapi" using django REST framework in local host. The CRUD operation works perfectly fine in browseable API. But When I try to access the same API from third party python file, I am not able to perform POST operation although I am able to perform GET operation.While performing POST operation the server reponse me as "Unsupported Media Type: /api/studentapi/".I am posting series of code images so that the stuffs gets more clear
The third party python app that I have created to access the "api/studentapi"

The file structure of my project

The model form that I have created

The serializer files that I have created

The urls code

And Finally the view file

答:
```<code>import json
import requests
url = "https://127.0.0.1:8000/api/studentapi/"
data_response = {
   "name": "sa",
   "roll": 1,
   "city": "lam"
}
data_json =  json.dumps(data_response)
req =  requests.post(url, data=data_json)
</code>```


问:
Access n:th element of every list in list of lists
I have a problem in python and one step I need to do is to access the second element of every list in a list of lists. The list is:

```<code>[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')]

[(0, 'A', 'DET' 'det'), (1 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]
</code>```

The list goes on like that with different sentences for each list.

What I am trying to do is access the third (index 2) element of every list of every tuple. So from the first list, I want to get:

PROPN (from 'Gallery')

VERB (from 'unveils')

ADJ (from 'interactive')

And from the second list I want to get:

DET (from 'A')

PROPN (from 'Christmas')

NOUN (from 'nsubjpass)

What I've tried to do is this:

```<code>for word in list:
      print(list[word[0]][2])
</code>```

But that only outputs the second element from the first list. I tried creating another foor-loop but that didn't work, I suspect I did it wrong but I'm not sure how to solve it

Help would be appreciated

Thanks in advance!

答:
you should try:

```<code>all_my_lists= [
    [(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')],
    [(0, 'A', 'DET' 'det'), (1, 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]
]

for my_list in all_my_lists:
    for tup in my_list:
        print(tup[2])
</code>```

First loop iterate every sublist in my_lists list.

Second loop iterate over each tuple(the collection with '(,)' brackets.
i.e tuple = (0, 'Gallery', 'PROPN', 'nsubj')
and prints the third element.

Body:
I have a problem in python and one step I need to do is to access the second element of every list in a list of lists. The list is:

[(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')]

[(0, 'A', 'DET' 'det'), (1 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]

The list goes on like that with different sentences for each list.

What I am trying to do is access the third (index 2) element of every list of every tuple. So from the first list, I want to get:

PROPN (from 'Gallery')

VERB (from 'unveils')

ADJ (from 'interactive')

And from the second list I want to get:

DET (from 'A')

PROPN (from 'Christmas')

NOUN (from 'nsubjpass)

What I've tried to do is this:

for word in list:
      print(list[word[0]][2])

But that only outputs the second element from the first list. I tried creating another foor-loop but that didn't work, I suspect I did it wrong but I'm not sure how to solve it

Help would be appreciated

Thanks in advance!

Body:
you should try:

all_my_lists= [
    [(0, 'Gallery', 'PROPN', 'nsubj'), (1, 'unveils', 'VERB', 'root'), (2, 'interactive', 'ADJ', 'amod')],
    [(0, 'A', 'DET' 'det'), (1, 'Christmas' , 'PROPN', 'compound'), (2, 'tree' ,'NOUN', 'nsubjpass')]
]

for my_list in all_my_lists:
    for tup in my_list:
        print(tup[2])

First loop iterate every sublist in my_lists list.

Second loop iterate over each tuple(the collection with '(,)' brackets.
i.e tuple = (0, 'Gallery', 'PROPN', 'nsubj')
and prints the third element.


问:
when is jQuery UI's destroy() called?
I get that when developing a jQuery UI widget one must override destroy and call super.destroy or destroy on any nested widgets. But when is/should destroy be called? Is it ever being called auto-magically by jQueryUI framework? Or should it be called by a client programmer (using my awesome widget)?

For example, say I have a lightbox (fancybox) that displays an accordion(). Say the accordion is being created in fancybox' onStart callback - as the lightbox is about to be displayed.
Should accordion('destroy') be called in 'on-lightbox-close' callback? Seems unnecessary...

答:
destroy is called by you when you want to destroy the widget.

It is also called by UI when you .remove() an element from the DOM which had been "widgetized."

As for your specific use case, it depends.  Will the same lightbox instance be re-opened at any point in the future of that page-load's lifetime?  If so, destroying would only add overhead as the next showing of the lightbox would require a "re-widgetization". If not, then not destroying would leave memory being taken up for no reason. (this assumes that the close of your lightbox does not cause the elements to be removed from the DOM)

ContentLicense: CC BY-SA 3.0

Title: when is jQuery UI's destroy() called?


问:
How to implement responsive width for Drawer MUI v5 component?
I am using Material UI v5, and am trying to make a responsive drawer where for smaller devices it will take up 100% of screen width while for larger devices it should only take 1/3 of screen width. But I have no idea how to access Paper property to modify the actual width and make it responsive.

My code:

```<code>import { Drawer, styled } from "@mui/material";

const ResponsiveDrawer = styled(Drawer)(({ theme }) => ({
  [theme.breakpoints.up("md")]: {
    width: "33%", // THIS ONLY CHANGES DRAWER WIDTH NOT PAPER WIDTH INSIDE THE DRAWER
  },
  [theme.breakpoints.down("md")]: {
    width: "100%",
  },
}));

export { ResponsiveDrawer };
</code>```

How I use it:

```<code>import { ResponsiveDrawer } from "./Style";

<ResponsiveDrawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
        >
            ...
</ResponsiveDrawer>
</code>```

答:
I figured it out shortly after posting the question. This involves inline styling using useMediaQuery.

```<code>const largeScreen = useMediaQuery(theme.breakpoints.up("sm"))

<Drawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
            PaperProps={largeScreen ? {
                sx: {
                    width: 450,
                }
            } : {
                sx: {
                    width: "100%",
                }
            }
            }
        >
            <CartContent cart={cart} drawer={drawer}/>
        </Drawer>
</code>```

Body:
I am using Material UI v5, and am trying to make a responsive drawer where for smaller devices it will take up 100% of screen width while for larger devices it should only take 1/3 of screen width. But I have no idea how to access Paper property to modify the actual width and make it responsive.

My code:

import { Drawer, styled } from "@mui/material";

const ResponsiveDrawer = styled(Drawer)(({ theme }) => ({
  [theme.breakpoints.up("md")]: {
    width: "33%", // THIS ONLY CHANGES DRAWER WIDTH NOT PAPER WIDTH INSIDE THE DRAWER
  },
  [theme.breakpoints.down("md")]: {
    width: "100%",
  },
}));

export { ResponsiveDrawer };

How I use it:

import { ResponsiveDrawer } from "./Style";

<ResponsiveDrawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
        >
            ...
</ResponsiveDrawer>

Body:
I figured it out shortly after posting the question. This involves inline styling using useMediaQuery.

const largeScreen = useMediaQuery(theme.breakpoints.up("sm"))

<Drawer
            anchor="right"
            open={drawer.state}
            onClose={() => drawer.onClick(false)}
            PaperProps={largeScreen ? {
                sx: {
                    width: 450,
                }
            } : {
                sx: {
                    width: "100%",
                }
            }
            }
        >
            <CartContent cart={cart} drawer={drawer}/>
        </Drawer>


问:
React Router V6 shows blank page
I am facing a problem. I am trying to use React Router but it keeps showing me a blank page.
Here is my code:

App.js:

```<code>import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import HomePage from "./HomePage";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
      </Routes>
    </Router>

  );
};

export default App;
</code>```

HomePage.js:

```<code>import React from "react";
import {withRouter} from "react-router-dom"

const HomePage = () => {

    return <div>hi</div>
}

export default HomePage;
</code>```

index.js:

```<code>import React from "react";
import ReactDom from "react-dom";
import App from './App';

ReactDom.render(<App/>, document.getElementById("root"))
</code>```

I've installed "React Router V6", can anyone tell me what is the problem?
Thanks for all the helpers.

答:
use</p>
```<code>import { Route, HashRouter as Router, Routes } from "react-router-dom";

 <Router>
  <Routes>
    <Route exact path="/" element={<Main />} />
    <Route path="/download" element={<Download />} />
  </Routes>
</Router>
</code>```

Title: React Router V6 shows blank page

Body:
I am facing a problem. I am trying to use React Router but it keeps showing me a blank page.
Here is my code:

App.js:

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import HomePage from "./HomePage";

function App() {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<HomePage />} />
      </Routes>
    </Router>

  );
};

export default App;

HomePage.js:

import React from "react";
import {withRouter} from "react-router-dom"

const HomePage = () => {

    return
hi

}

export default HomePage;

index.js:

import React from "react";
import ReactDom from "react-dom";
import App from './App';

ReactDom.render(<App/>, document.getElementById("root"))

I've installed "React Router V6", can anyone tell me what is the problem?
Thanks for all the helpers.

Body:
use

import { Route, HashRouter as Router, Routes } from "react-router-dom";

 <Router>
  <Routes>
    <Route exact path="/" element={<Main />} />
    <Route path="/download" element={<Download />} />
  </Routes>
</Router>


问:
Google Maps V3 cannot call function from infowindow
I have created a zoom function for my Google maps:

function zoomIn(){

map.setZoom(parseInt(map.getZoom())+2)

}

I keep on getting a 'Object expected' error when I try to call it. When I debug this

Error: zoomIn is not defined

Source File: javascript:zoomIn()

Any ideas of why this is happening is much appreciated.

The map can be seen using the link below, the function is located on line 189

http://tinyurl.com/3ryuxvy

答:
Your problem is with function scope.  You define the zoomIn function inside initialize.  When the user clicks on the control to zoom in and zoomIn() is called it is looking for zoomIn on the global window object but it doesn't exist there.

To fix this you need to refactor your javascript so zoomIn is available in the global scope.  This could mean implementing the function outside of initialize().

Read more about JS scoping here: http://www.digital-web.com/articles/scope_in_javascript/


问:
How to render CKeditor's rich text from a CMS into a Next.js app?
I'm currently using :

```<code><div dangerouslySetInnerHTML={{ __html: article.content }}></div>
</code>```

in order to render the rich text I get from a CKEditor input field from a Strapi CMS backend.
Is there a better way to do this that doesn't use dangerouslySetInnerHTML? I've looked into ReactMarkdown, but that seems to only work with Strapi's built-in old Markdown editor.

答: In our project we are using dangerouslySetInnerHTML as well.

Body:
I'm currently using :

in order to render the rich text I get from a CKEditor input field from a Strapi CMS backend.
Is there a better way to do this that doesn't use dangerouslySetInnerHTML? I've looked into ReactMarkdown, but that seems to only work with Strapi's built-in old Markdown editor.


问:
React-Native loading android contact images
I have an image URI that looks like this: content://com.android.contacts/contacts/3992/photo.jpg

I then use that URI as such

<Image source={{uri: contact.thumbnailPath}} style={styles.thumbnail} />

However, I can't see the picture! Any idea what the issue might be?

答:
Instead of passing a source prop use a simple HTML property src

```<code>src={contact.thumbnailPath}
</code>```

Here thumbnailPath is your image path.

Body:
Instead of passing a source prop use a simple HTML property src

src={contact.thumbnailPath}

Here thumbnailPath is your image path.


问:
Creating ForeignKey reference with 2 different models as choice
Here is what i want to try, I have a User model inherited from Abstract user with custom manager, i need a feeld in CustomUser model to choose either Seller model or Customer model</p>
```<code>class CustomUser(AbstractUser):
    is_seller = models.BooleanField(default=False)
    is_customer = models.BooleanField(default=False)

    user_type = ? "I want to have a choice feild to choose either Seller or
    Customer model"

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = CustomUserManager()

class CustomUserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            return ValueError('Email required')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff true')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser true')

        return self.create_user(email, password, **extra_fields)

class SellerDetails(models.Model):
    pass

class CustomerDetails(models.Model):
    pass
</code>```

答:
Have you looked at Django Content Types Framework? Have a look at it here

This can help you in achieving what you want.

Here is a very simple to understand article on this.

Body:
Here is what i want to try, I have a User model inherited from Abstract user with custom manager, i need a feeld in CustomUser model to choose either Seller model or Customer model

class CustomUser(AbstractUser):
    is_seller = models.BooleanField(default=False)
    is_customer = models.BooleanField(default=False)

    user_type = ? "I want to have a choice feild to choose either Seller or
    Customer model"

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = CustomUserManager()

class CustomUserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, password=None, **extra_fields):
        if not email:
            return ValueError('Email required')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('is_active', True)

        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff true')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser true')

        return self.create_user(email, password, **extra_fields)

class SellerDetails(models.Model):
    pass

class CustomerDetails(models.Model):
    pass


答:
Try this code:

`for sub_list_temp in list:

```<code>for temp_tuple in sub_list_temp:

    print(temp_tuple[2])
</code>```

`

Title: Access n:th element of every list in list of lists

Body:
Try this code:

`for sub_list_temp in list:

for temp_tuple in sub_list_temp:

    print(temp_tuple[2])

`


问:
PyTorch dll issues for Caffe2
I am using a Windows 10 Machine and after re-installing Anaconda and all of the packages I had previously, including torchvision, torch and necessary dependencies, I am still getting this error:

```<code>OSError: [WinError 127] The specified procedure could not be found. Error loading "C:\Users\XXX\Anaconda3\envs\XXX\lib\site-packages\torch\lib\caffe2.dll" or one of its dependencies.
</code>```

I am using python 3.7.9 and:

torchaudio=0.6.0=py37

torchvision=0.7.0=py37_cpu

tornado=6.0.4=py37he774522_1

traitlets=5.0.5=py_0

I've looked into it quite a bit but feel like this should be an easy solve...

I do not have CUDA and have used this:
conda install pytorch torchvision torchaudio cpuonly -c pytorch

as per instructed on the official website of pytorch

答:
I tried to install PyTorch with Anaconda and had the same error.
For me what solved the issue was to uninstall Pytorch using Pip (even though I installed it with conda) and then installing again with Pip as explains at PyTorch guide.

Uninstall:

```<code>pip uninstall torch
pip uninstall torchvision
pip uninstall torchaudio
</code>```

Install:

```<code>pip3 install torch torchvision torchaudio
</code>```

Title: PyTorch dll issues for Caffe2

Body:
I am using a Windows 10 Machine and after re-installing Anaconda and all of the packages I had previously, including torchvision, torch and necessary dependencies, I am still getting this error:

OSError: [WinError 127] The specified procedure could not be found. Error loading "C:\Users\XXX\Anaconda3\envs\XXX\lib\site-packages\torch\lib\caffe2.dll" or one of its dependencies.

I am using python 3.7.9 and:

torchaudio=0.6.0=py37

torchvision=0.7.0=py37_cpu

tornado=6.0.4=py37he774522_1

traitlets=5.0.5=py_0

I've looked into it quite a bit but feel like this should be an easy solve...

I do not have CUDA and have used this:
conda install pytorch torchvision torchaudio cpuonly -c pytorch

as per instructed on the official website of pytorch

Body:
I tried to install PyTorch with Anaconda and had the same error.
For me what solved the issue was to uninstall Pytorch using Pip (even though I installed it with conda) and then installing again with Pip as explains at PyTorch guide.

Uninstall:

pip uninstall torch
pip uninstall torchvision
pip uninstall torchaudio

Install:

pip3 install torch torchvision torchaudio


问:
Change .html URL depending on the active div
I have two html pages: index1.html and index2.html. In index1.html, I have two buttons: Get Started and Login. In index2.html, I have two divs (Sign-up form and Sign-in form), and either one of them is active (by setting them with active class). The default active is the sign-up form:
...</form>, and the other form, which is for signing-in is not yet set as active:
...

Note that index2.html is a double slider page, where it does not scroll down, as the divs are positioned beside each other.

I want my Get Started button from index1.html to redirect to index2.html, but on the active Sign-up form, and I want my Login button from index1.html to redirect to index2.html, but on the active Sign-in form.

The problem is I can't redirect them on a specific active div. The URL of index2.html only goes with "index2.html?#". How do I change the URL depending on the active div? ex. index2.html#sign-up if the Sign-up form is active and index2.html?#sign-in if the Sign-in form is active.

答:
In index1.html you can use hashtag in your href

```<code><a href="index2.html#sign-in"><div>Sign in</div></a>
</code>```

In index2.html you can check if there is sign-in hashtag in the url

```<code>const signInForm = document.getElementById("sign-in-form")
const currentHash = window.location.hash
if(currentHash.includes('sign-in')){
    signInForm.classList.add("active")
    signUpForm.classList.remove("active")
}
</code>```

(Note that i put id in your sign in and sign up button)

```<code><div id="sign-up-form" class="form sign-up-form active">Sign Up</div>
<div id="sign-in-form" class="form sign-in-form">Sign in</div>
</code>```

For explanation, the location.hash property sets or returns the anchor part of a URL, including the hash sign (#). And then after we get the hashtag from the url, we can check if there is 'sign-in' word in our hashtag

Body:
In index1.html you can use hashtag in your href

<a href="index2.html#sign-in"><div>Sign in</div></a>

In index2.html you can check if there is sign-in hashtag in the url

const signInForm = document.getElementById("sign-in-form")
const currentHash = window.location.hash
if(currentHash.includes('sign-in')){
    signInForm.classList.add("active")
    signUpForm.classList.remove("active")
}

(Note that i put id in your sign in and sign up button)

<div id="sign-up-form" class="form sign-up-form active">Sign Up</div>
<div id="sign-in-form" class="form sign-in-form">Sign in</div>

For explanation, the location.hash property sets or returns the anchor part of a URL, including the hash sign (#). And then after we get the hashtag from the url, we can check if there is 'sign-in' word in our hashtag


问:
How do I remove words numerics pyspark
I'm trying to remove only words that are numerical from my words array, but the function I created is not working correctly. When I try to view the information from my dataframe the following error message appears

First I converted my string and word tokens

from pyspark.ml.feature import RegexTokenizer
regexTokenizer = RegexTokenizer(
    inputCol="description",
    outputCol="words_withnumber",
    pattern="\\W"
)

data = regexTokenizer.transform(data)
```

<p>I created the function to remove only the numbers</p>

<pre class="lang-py prettyprint-override"><code>from pyspark.sql.functions import when,udf
from pyspark.sql.types import BooleanType

def is_digit(value):
    if value:
        return value.isdigit()
    else:
        return False

is_digit_udf = udf(is_digit, BooleanType())
</code>```

Call function

data = data.withColumn(
    'words_withoutnumber',
    when(~is_digit_udf(data['words_withnumber']), data['words_withnumber'])
)
```

<p>Error:</p>

<blockquote>
  <p>org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 5.0 failed 4 times, most recent failure: Lost task 0.3 in stage 5.0 (TID 14, 10.139.64.4, executor 0): org.apache.spark.api.python.PythonException: Traceback (most recent call last):</p>
</blockquote>

<p>Sample Dataframe</p>

<pre class="lang-py prettyprint-override"><code>+-----------+-----------------------------------------------------------+
|categoryid |description                                                |
+-----------+-----------------------------------------------------------+
|      33004|["short","sarja", "40567","detalhe","couro"]               |
|      22033|["multipane","6768686868686867868888","220v","branco"]     |
+-----------+-----------------------------------------------------------+
</code>```

expected result

+-----------+-----------------------------------------------------------+
|categoryid |description                                                |
+-----------+-----------------------------------------------------------+
|      33004|["short","sarja","detalhe","couro"]                        |
|      22033|["multipane","220v","branco"]                              |
+-----------+-----------------------------------------------------------+
```

Title: How do I remove words numerics pyspark

Body:
I'm trying to remove only words that are numerical from my words array, but the function I created is not working correctly. When I try to view the information from my dataframe the following error message appears

First I converted my string and word tokens

from pyspark.ml.feature import RegexTokenizer
regexTokenizer = RegexTokenizer(
    inputCol="description",
    outputCol="words_withnumber",
    pattern="\\W"
)

data = regexTokenizer.transform(data)

I created the function to remove only the numbers

from pyspark.sql.functions import when,udf
from pyspark.sql.types import BooleanType

def is_digit(value):
    if value:
        return value.isdigit()
    else:
        return False

is_digit_udf = udf(is_digit, BooleanType())

Call function

data = data.withColumn(
    'words_withoutnumber',
    when(~is_digit_udf(data['words_withnumber']), data['words_withnumber'])
)

Error:

org.apache.spark.SparkException: Job aborted due to stage failure: Task 0 in stage 5.0 failed 4 times, most recent failure: Lost task 0.3 in stage 5.0 (TID 14, 10.139.64.4, executor 0): org.apache.spark.api.python.PythonException: Traceback (most recent call last):

Sample Dataframe

+-----------+-----------------------------------------------------------+
|categoryid |description                                                |
+-----------+-----------------------------------------------------------+
|      33004|["short","sarja", "40567","detalhe","couro"]               |
|      22033|["multipane","6768686868686867868888","220v","branco"]     |
+-----------+-----------------------------------------------------------+

expected result

+-----------+-----------------------------------------------------------+
|categoryid |description                                                |
+-----------+-----------------------------------------------------------+
|      33004|["short","sarja","detalhe","couro"]                        |
|      22033|["multipane","220v","branco"]                              |
+-----------+-----------------------------------------------------------+

Body:
Now that you mentioned pyspark, lets include python.

DataFrame

data =[ (33004     , ['short', 'sarja', '40567', 'detalhe', 'couro']),
       (22033     , ['multipane', '6768686868686867868888', '220v', 'branco']),
       (33033    ,['123', 'x220', '220v', '889'] )
]

df= spark.createDataFrame(data, ('categoryid','description' ))

Code

#Only alphanumeric

df.withColumn("description_filtered", expr("filter(description, x -> x rlike '([a-z]+)')")).show()

Outcome

+----------+--------------------+--------------------+
|categoryid|         description|description_filtered|
+----------+--------------------+--------------------+
|     33004|[short, sarja, 40...|[short, sarja, de...|
|     22033|[multipane, 67686...|[multipane, 220v,...|
|     33033|[123, x220, 220v,...|        [x220, 220v]|
+----------+--------------------+--------------------+

#Only alphabetical

df.withColumn("description_filtered", expr("filter(description, x -> x rlike '([^0-9]{2})')")).show()

Outcome

+----------+--------------------+--------------------+
|categoryid|         description|description_filtered|
+----------+--------------------+--------------------+
|     33004|[short, sarja, 40...|[short, sarja, de...|
|     22033|[multipane, 67686...| [multipane, branco]|
|     33033|[123, x220, 220v,...|                  []|
+----------+--------------------+--------------------+


问:
How to export an Elastic Search index?
We are attempting to export a list of two fields (ID, text) from an existing Elastic Search index into a text file.

The index contains approximately 2 million rows of data.  We tried using the reporting feature in Kibana, but ran into the 10K row limit.

Searched online for other options, but haven't found anything viable because I don't think we'll be able to install any 3rd party tools.

答:
You may use any REST client with pit API to pagenate documents.
https://www.elastic.co/guide/en/elasticsearch/reference/current/point-in-time-api.html

Another option is using one of ELK stack: Logstash, Elasticsearch input plugin and File output plugin.
https://www.elastic.co/guide/en/logstash/current/plugins-outputs-file.html

Title: How to export an Elastic Search index?


问:
How to represent or monitor java.io.InterruptedIOException timeout?
We are getting the Caused by: java.io.InterruptedIOException: timeout exception in the logs from the server. However, the server is not giving the response code to us.

I am looking for the standard practice for the timeout monitoring to be followed in Splunk or Appdynamics to plot the graph for number of timeouts being received per second.

Shall we add the error code like 408 in the exception at client side or we should plot the graph for on basis of text "timeout"  count with over the time.

Exception Logs

```<code>java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:150)
Caused by: java.io.InterruptedIOException: timeout
at okhttp3.internal.connection.Transmitter.timeoutExit(Transmitter.kt:104)
at okhttp3.internal.connection.Transmitter.maybeReleaseConnection(Transmitter.kt:293)
at okhttp3.internal.connection.Transmitter.noMoreExchanges(Transmitter.kt:257)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:192)
at okhttp3.RealCall.execute(RealCall.kt:66)
</code>```

答:
For AppDynamics the ideal solution would be for a "bad error code" to be returned from the server - this would cause an error to be detected (and mark any associated Business Transaction as being in error) - see https://docs.appdynamics.com/22.2/en/application-monitoring/troubleshooting-applications/errors-and-exceptions#ErrorsandExceptions-BusinessTransactionError

Else you can use Custom Error Configuration to set a logger which signals errors - see https://docs.appdynamics.com/22.2/en/application-monitoring/configure-instrumentation/error-detection#ErrorDetection-ErrorDetectionConfiguration

Else you can capture values using a Data Collector and then use these in Analytics to break out errors - see https://docs.appdynamics.com/22.2/en/application-monitoring/configure-instrumentation/data-collectors + https://docs.appdynamics.com/22.2/en/analytics/configure-analytics/collect-transaction-analytics-data

Body:
We are getting the Caused by: java.io.InterruptedIOException: timeout exception in the logs from the server. However, the server is not giving the response code to us.

I am looking for the standard practice for the timeout monitoring to be followed in Splunk or Appdynamics to plot the graph for number of timeouts being received per second.

Shall we add the error code like 408 in the exception at client side or we should plot the graph for on basis of text "timeout"  count with over the time.

Exception Logs

java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at lambdainternal.LambdaRTEntry.main(LambdaRTEntry.java:150)
Caused by: java.io.InterruptedIOException: timeout
at okhttp3.internal.connection.Transmitter.timeoutExit(Transmitter.kt:104)
at okhttp3.internal.connection.Transmitter.maybeReleaseConnection(Transmitter.kt:293)
at okhttp3.internal.connection.Transmitter.noMoreExchanges(Transmitter.kt:257)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:192)
at okhttp3.RealCall.execute(RealCall.kt:66)


问:
How to send a message via url with inline buttons
I can send message, sample:

```<code>https://api.telegram.org/bot[TOKEN]/sendMessage?chat_id=@[USERNAME]&text=hello
</code>```

but I want to send message with inline buttons, please help.

答:
This would be the url you are looking for:

https://api.telegram.org/bot[TOKEN]/sendMessage?chat_id=[CHAT_ID]&text=[TEXT]&reply_markup={"inline_keyboard": [[{"text": "hi", "callback_data": "hi"}]]}

You can pass a JSON toreply_markup field. Here this our JSON:

{
  "inline_keyboard": [
    [
      {
        "text": "hi",
        "callback_data": "hi"
      }
    ]
  ]
}
```
<p>I suggest you use an API library to communicate with Telegram. Using bare urls has its own challenges, like sometimes you should url encode your JSON to avoid errors in URL.</p>
<p>For example this is the url-encoded version of above JSON:</p>
```%7B%22inline_keyboard%22%3A%20%5B%5B%7B%22text%22%3A%20%22hi%22%2C%20%22callback_data%22%3A%20%22hi%22%7D%5D%5D%7D
```

Body:
I can send message, sample:

https://api.telegram.org/bot[TOKEN]/sendMessage?chat_id=@[USERNAME]&text=hello

but I want to send message with inline buttons, please help.

Body:
This would be the url you are looking for:

https://api.telegram.org/bot[TOKEN]/sendMessage?chat_id=[CHAT_ID]&text=[TEXT]&reply_markup={"inline_keyboard": [[{"text": "hi", "callback_data": "hi"}]]}

You can pass a JSON toreply_markup field. Here this our JSON:

{
  "inline_keyboard": [
    [
      {
        "text": "hi",
        "callback_data": "hi"
      }
    ]
  ]
}

I suggest you use an API library to communicate with Telegram. Using bare urls has its own challenges, like sometimes you should url encode your JSON to avoid errors in URL.

For example this is the url-encoded version of above JSON:

%7B%22inline_keyboard%22%3A%20%5B%5B%7B%22text%22%3A%20%22hi%22%2C%20%22callback_data%22%3A%20%22hi%22%7D%5D%5D%7D


问:
How to compare strings matching using Linq?
I'm trying to implement an interface in Notification repository:

```<code>IEnumerable<Notification> INotificationRepository.GetAllNotificationById(int userId)
        {
            return context.Notifications.Where(x => x.receiverUserId.Split(',').Contains(userId.ToString())).ToList();
        }
</code>```

IDE shows error under x.receiverUserId.Split(',') and says:

an expression tree may not contain a call or invocation that uses
optional arguments.

How can I fix it?

答:
Add a value to the optional StringSplitOptions argument:

...context.Notifications.Where(x => x.receiverUserId.Split(',', StringSplitOptions.None)...
```

Body:
I'm trying to implement an interface in Notification repository:

IEnumerable<Notification> INotificationRepository.GetAllNotificationById(int userId)
        {
            return context.Notifications.Where(x => x.receiverUserId.Split(',').Contains(userId.ToString())).ToList();
        }

IDE shows error under x.receiverUserId.Split(',') and says:

an expression tree may not contain a call or invocation that uses
optional arguments.

How can I fix it?


问:
ChromeOption is not working with Selenium-Java
I am using the above code with selenium-java version 4.0.0, selenium-server version 3.11.0, webdrivermanager version 5.0.3 .

Still chrome is not launching in maximised screen and not disbaling the infobars as well.

```<code>import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class chromeOptionsTest {

    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.get("http://www.google.com");
    }
}

</code>```

I am running this test on macbook m1.

答:
Maximizing window on Mac was unstable (works for some cases, and doesn't work for others) and a lot of people mentioned this.

This one is closed:
https://bugs.chromium.org/p/chromedriver/issues/detail?id=2522

But this still in opened
https://bugs.chromium.org/p/chromium/issues/detail?id=868599

This might not work:

```<code>options.addArguments("start-maximized");
</code>```

or

```<code>driver.manage().window().maximize()
</code>```

Workarounds

1 Start in full-screen:

```<code>options.addArguments("start-fullscreen");
</code>```

2 Resize window (it's less flexible, because need to know screen size):

after driver launched

```<code>WebDriver driver = new ChromeDriver(options)
driver.manage().window().setPosition(new Point(0, 0))
driver.manage().window().setSize(new Dimension(1920, 1080))
</code>```

or with option

```<code>options.addArguments("window-size=1920,1080");
</code>```

P.S.

Your code

```<code>WebDriver driver = new ChromeDriver(options)
</code>```

means that you not using selenium-server, but use the local chrome driver. But this should not be related to the issue.

Body:
I am using the above code with selenium-java version 4.0.0, selenium-server version 3.11.0, webdrivermanager version 5.0.3 .

Still chrome is not launching in maximised screen and not disbaling the infobars as well.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class chromeOptionsTest {

    public static void main(String[] args) {
        WebDriverManager.chromedriver().setup();
        ChromeOptions options = new ChromeOptions();
        options.addArguments("start-maximized");
        options.addArguments("disable-infobars");
        WebDriver driver = new ChromeDriver(options);
        driver.get("http://www.google.com");
    }
}

I am running this test on macbook m1.

Body:
Maximizing window on Mac was unstable (works for some cases, and doesn't work for others) and a lot of people mentioned this.

This one is closed:
https://bugs.chromium.org/p/chromedriver/issues/detail?id=2522

But this still in opened
https://bugs.chromium.org/p/chromium/issues/detail?id=868599

This might not work:

options.addArguments("start-maximized");

or

driver.manage().window().maximize()

Workarounds

1 Start in full-screen:

options.addArguments("start-fullscreen");

2 Resize window (it's less flexible, because need to know screen size):

after driver launched

WebDriver driver = new ChromeDriver(options)
driver.manage().window().setPosition(new Point(0, 0))
driver.manage().window().setSize(new Dimension(1920, 1080))

or with option

options.addArguments("window-size=1920,1080");

P.S.

Your code

WebDriver driver = new ChromeDriver(options)

means that you not using selenium-server, but use the local chrome driver. But this should not be related to the issue.


问:
unable to setup cocoapods. Cocoapods setup problem
I am trying to run my flutter app which is connected to Firebase, but when I try to run it on an iOS emulator, it shows these errors -

Warning: CocoaPods installed but not initialized. Skipping pod >install.
CocoaPods is used to retrieve the iOS and macOS platform side's >plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To initialize CocoaPods, run:
pod setup
once to finalize CocoaPods' installation.

So then I do "pod setup" but then it shows this error :

```<code>Cloning into 'master'...
remote: Enumerating objects: 14707, done.
remote: Counting objects: 100% (14707/14707), done.
remote: Compressing objects: 100% (14117/14117), done.
error: RPC failed; curl 18 transfer closed with outstanding read data
remaining
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed
</code>```

答:
I was battling with this issue for days on end. The issue, for me was only when I use my Mac with M1 Chip. Initially, i got this error when I tried to add a audio player package to my project. After a week of seaching I came across the this solutionenter link description here

The worked perfectly until i needed to use a geolocation package and the issue was back again. After days of trying different solutions, I finally found that the solution that worked for me. I reinstalled cocoapods using brew. Once done, I closed the terminal, closed android studio then ran the following command on terminal open /Applications/Android\ Studio.app. Pod now installs with no issues and my project launches on iOS.

Body:
I am trying to run my flutter app which is connected to Firebase, but when I try to run it on an iOS emulator, it shows these errors -

Warning: CocoaPods installed but not initialized. Skipping pod >install.
CocoaPods is used to retrieve the iOS and macOS platform side's >plugin code that responds to your plugin usage on the Dart side.
Without CocoaPods, plugins will not work on iOS or macOS.
For more info, see https://flutter.dev/platform-plugins
To initialize CocoaPods, run:
pod setup
once to finalize CocoaPods' installation.

So then I do "pod setup" but then it shows this error :

Cloning into 'master'...
remote: Enumerating objects: 14707, done.
remote: Counting objects: 100% (14707/14707), done.
remote: Compressing objects: 100% (14117/14117), done.
error: RPC failed; curl 18 transfer closed with outstanding read data
remaining
fatal: the remote end hung up unexpectedly
fatal: early EOF
fatal: index-pack failed


问:
How to call an outer method from within a handler
So I have A MouseListener class inside a public class with a few methods.
I have attached the mouseListener to a component in the public class.

The problem is I can't figure out a simple way to call the methods in the public class, whenever I say for example this.showRemove(); the scope is from within the handler class and not the public class. Here is some example code

```<code>public class Game {

 public Game() {

  JPanel pnl = new JPanel();
  pnl.addMouseListener(new GameMouseListener());

 }

 public void showRemove(){

  //Code Here

 }

 class GameMouseListener implements MouseListener {

  public void mouseClicked(MouseEvent e) {
     this.showRemove(); //Can't Find Symbol Here

  }

 }

}
</code>```

答:
When you use this in an inner class, you are referring to the instance of the inner class, not the host class.

Since your inner class is not a static inner class, you can access the reference to the host class by using it's class name like so:

```<code>HostClass {
    doSomething() {}

    class Inner {
        void blah() {
            HostClass.this.doSomething();
        }
    }
}
</code>```

Unless the method you're calling is also in the inner class, you can avoid the explicit naming and can simply use the method name:

```<code>void blah() {
    doSomething();
}
</code>```

Body:
So I have A MouseListener class inside a public class with a few methods.
I have attached the mouseListener to a component in the public class.

The problem is I can't figure out a simple way to call the methods in the public class, whenever I say for example this.showRemove(); the scope is from within the handler class and not the public class. Here is some example code

public class Game {

 public Game() {

  JPanel pnl = new JPanel();
  pnl.addMouseListener(new GameMouseListener());

 }

 public void showRemove(){

  //Code Here

 }

 class GameMouseListener implements MouseListener {

  public void mouseClicked(MouseEvent e) {
     this.showRemove(); //Can't Find Symbol Here

  }

 }

}

Body:
When you use this in an inner class, you are referring to the instance of the inner class, not the host class.

Since your inner class is not a static inner class, you can access the reference to the host class by using it's class name like so:

HostClass {
    doSomething() {}

    class Inner {
        void blah() {
            HostClass.this.doSomething();
        }
    }
}

Unless the method you're calling is also in the inner class, you can avoid the explicit naming and can simply use the method name:

void blah() {
    doSomething();
}


问:
Metal Core Image Kernel use of DOD
I wrote the following Metal Core Image Kernel to produce constant red color.

```<code>extern "C" float4 redKernel(coreimage::sampler inputImage, coreimage::destination dest)
{
  return float4(1.0, 0.0, 0.0, 1.0);
}
</code>```

And then I have this in Swift code:

```<code>class CIMetalRedColorKernel: CIFilter {
  var inputImage:CIImage?

  static var kernel:CIKernel = { () -> CIKernel in
     let bundle = Bundle.main
     let url = bundle.url(forResource: "Kernels", withExtension: "ci.metallib")!
     let data = try! Data(contentsOf: url)
     return try! CIKernel(functionName: "redKernel", fromMetalLibraryData: data)
  }()

 override var outputImage: CIImage? {
    guard let inputImage = inputImage else {
        return nil
    }

    let dod = inputImage.extent
    return CIMetalRedColorKernel.kernel.apply(extent: dod, roiCallback: { index, rect in
        return rect
    }, arguments: [inputImage])
 }
}
</code>```

As you can see, the dod is given to be the extent of the input image. But when I run the filter, I get a whole red image beyond the extent of the input image (DOD), why? I have multiple filters chained together and the overall size is 1920x1080. Isn't the red filter supposed to run only for DOD rectangle passed in it and produce clear pixels for anything outside the DOD?

答:
With the extent parameter of the kernel call you signal the region for which the kernel produces meaningful results—or, as you correctly named it, the domain of definition.
However, this also means that whatever it produces outside this region is basically undefined and up to you as the kernel developer to decide.

A generator kernel like the one you wrote usually has an infinite domain of definition since it just produces a red color, regardless of the input. To restrict the output to a specific area, you can apply a crop to it:

```<code>let dod = inputImage.extent
let result = CIMetalTestRenderer.kernel.apply(extent: .infinite, roiCallback: { index, rect in
    return rect
}, arguments: [inputImage])
return result.cropped(to: dod)
</code>```

After the cropping, everything outside of dod will be transparent.

Update:

It turns out you have to set the extent parameter of the kernel call to .infinite to make this work. I suspect that cropped(to:) checks if the image already has the given extent and will do nothing in this case. So to make CI really apply the cropping, you have to specify the domain of definition your kernel actually produces.

I think the counter-intuitive thing here is that CI does not apply your kernel to just the pixels of the extent you specify. It seems there is some automatic clamp-to-extent going on when the result is not cropped properly, but honestly, I'm also rather confused by this...

Title: Metal Core Image Kernel use of DOD

Body:
I wrote the following Metal Core Image Kernel to produce constant red color.

extern "C" float4 redKernel(coreimage::sampler inputImage, coreimage::destination dest)
{
  return float4(1.0, 0.0, 0.0, 1.0);
}

And then I have this in Swift code:

class CIMetalRedColorKernel: CIFilter {
  var inputImage:CIImage?

  static var kernel:CIKernel = { () -> CIKernel in
     let bundle = Bundle.main
     let url = bundle.url(forResource: "Kernels", withExtension: "ci.metallib")!
     let data = try! Data(contentsOf: url)
     return try! CIKernel(functionName: "redKernel", fromMetalLibraryData: data)
  }()

 override var outputImage: CIImage? {
    guard let inputImage = inputImage else {
        return nil
    }

    let dod = inputImage.extent
    return CIMetalRedColorKernel.kernel.apply(extent: dod, roiCallback: { index, rect in
        return rect
    }, arguments: [inputImage])
 }
}

As you can see, the dod is given to be the extent of the input image. But when I run the filter, I get a whole red image beyond the extent of the input image (DOD), why? I have multiple filters chained together and the overall size is 1920x1080. Isn't the red filter supposed to run only for DOD rectangle passed in it and produce clear pixels for anything outside the DOD?

Body:
With the extent parameter of the kernel call you signal the region for which the kernel produces meaningful results—or, as you correctly named it, the domain of definition.
However, this also means that whatever it produces outside this region is basically undefined and up to you as the kernel developer to decide.

A generator kernel like the one you wrote usually has an infinite domain of definition since it just produces a red color, regardless of the input. To restrict the output to a specific area, you can apply a crop to it:

let dod = inputImage.extent
let result = CIMetalTestRenderer.kernel.apply(extent: .infinite, roiCallback: { index, rect in
    return rect
}, arguments: [inputImage])
return result.cropped(to: dod)

After the cropping, everything outside of dod will be transparent.

Update:

It turns out you have to set the extent parameter of the kernel call to .infinite to make this work. I suspect that cropped(to:) checks if the image already has the given extent and will do nothing in this case. So to make CI really apply the cropping, you have to specify the domain of definition your kernel actually produces.

I think the counter-intuitive thing here is that CI does not apply your kernel to just the pixels of the extent you specify. It seems there is some automatic clamp-to-extent going on when the result is not cropped properly, but honestly, I'm also rather confused by this...


问:
vscode remote-ssh cannot connect: "Resolver error: SyntaxError: Unexpected token in JSON"
Using the VisualStudioCode extension Remote-SSH.

Development PC is Windows and ssh-host to connect to is Ubuntu.

Executing the ssh-test in Powershell works well (no password needed), but starting "Connect to host" results in:

```<code>[22:02:41.776] remote-ssh@0.64.0
[22:02:41.776] win32 x64
[22:02:41.778] SSH Resolver called for "ssh-remote+7b22686f73744e616d65223a2231302e352e362e3739222c2275736572223a226a747a227d", attempt 1
[22:02:41.778] "remote.SSH.useLocalServer": false
[22:02:41.778] "remote.SSH.showLoginTerminal": false
[22:02:41.779] "remote.SSH.remotePlatform": {}
[22:02:41.779] "remote.SSH.sshPath": undefined
[22:02:41.779] "remote.SSH.sshConfigurationFile": undefined
[22:02:41.779] "remote.SSH.useFlock": true
[22:02:41.779] "remote.SSH.lockfilesInTmp": false
[22:02:41.780] "remote.SSH.localServerDownload": auto
[22:02:41.780] "remote.SSH.remoteServerListenOnSocket": true
[22:02:41.780] "remote.SSH.showLoginTerminal": false
[22:02:41.780] "remote.SSH.defaultExtensions": []
[22:02:41.780] SSH Resolver called for host: jtz@10.5.6.79
[22:02:41.780] Setting up SSH remote "10.5.6.79"
[22:02:41.818] Resolver error: SyntaxError: Unexpected token  in JSON at position 0
    at JSON.parse (<anonymous>)
    at l (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:285459)
    at async Object.t.getProductInfo (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:285517)
    at async c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:309806
    at async I (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:309770)
    at async Object.t.resolve (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:315001)
    at async c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:127:110431
[22:02:41.881] TELEMETRY: {"eventName":"resolver","properties":{"osReleaseId":"","arch":"","askedPw":"0","askedPassphrase":"0","asked2fa":"0","askedHostKey":"0","remoteInConfigFile":"0","gotUnrecognizedPrompt":"0","dynamicForwarding":"1","localServer":"0","didLocalDownload":"0","installUnpackCode":"0","outcome":"failure","reason":"Unknown","exitCodeLabel":""},"measures":{"resolveAttempts":1,"timing.totalResolveTime":33}}
[22:02:41.885] ------```

Any idea welcome :-) Thanks
```

答: Re-Installation of a newer version of vscode helps.</p>

Body:
Using the VisualStudioCode extension Remote-SSH.

Development PC is Windows and ssh-host to connect to is Ubuntu.

Executing the ssh-test in Powershell works well (no password needed), but starting "Connect to host" results in:

[22:02:41.776] remote-ssh@0.64.0
[22:02:41.776] win32 x64
[22:02:41.778] SSH Resolver called for "ssh-remote+7b22686f73744e616d65223a2231302e352e362e3739222c2275736572223a226a747a227d", attempt 1
[22:02:41.778] "remote.SSH.useLocalServer": false
[22:02:41.778] "remote.SSH.showLoginTerminal": false
[22:02:41.779] "remote.SSH.remotePlatform": {}
[22:02:41.779] "remote.SSH.sshPath": undefined
[22:02:41.779] "remote.SSH.sshConfigurationFile": undefined
[22:02:41.779] "remote.SSH.useFlock": true
[22:02:41.779] "remote.SSH.lockfilesInTmp": false
[22:02:41.780] "remote.SSH.localServerDownload": auto
[22:02:41.780] "remote.SSH.remoteServerListenOnSocket": true
[22:02:41.780] "remote.SSH.showLoginTerminal": false
[22:02:41.780] "remote.SSH.defaultExtensions": []
[22:02:41.780] SSH Resolver called for host: jtz@10.5.6.79
[22:02:41.780] Setting up SSH remote "10.5.6.79"
[22:02:41.818] Resolver error: SyntaxError: Unexpected token  in JSON at position 0
    at JSON.parse (<anonymous>)
    at l (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:285459)
    at async Object.t.getProductInfo (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:285517)
    at async c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:309806
    at async I (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:309770)
    at async Object.t.resolve (c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:1:315001)
    at async c:\Users\jtz\.vscode\extensions\ms-vscode-remote.remote-ssh-0.64.0\out\extension.js:127:110431
[22:02:41.881] TELEMETRY: {"eventName":"resolver","properties":{"osReleaseId":"","arch":"","askedPw":"0","askedPassphrase":"0","asked2fa":"0","askedHostKey":"0","remoteInConfigFile":"0","gotUnrecognizedPrompt":"0","dynamicForwarding":"1","localServer":"0","didLocalDownload":"0","installUnpackCode":"0","outcome":"failure","reason":"Unknown","exitCodeLabel":""},"measures":{"resolveAttempts":1,"timing.totalResolveTime":33}}
[22:02:41.885] ------```

Any idea welcome :-) Thanks


问:
Machine learning and Security
I would like to ask you if it is possible to secure a server with AI/machine learning based on the following concepts:

1) the server is implemented in a way to recognize a normal behavior(authorized access, modification, ...) .

2) the server must recognize any abnormal behavior and adapt to it if encountered.

3) if an abnormal behavior is caught, it checks in some kind of pre-known threat list what type of threat it is and a possible solution for it ELSE it adapts "by itself"  and perform changes based on what the normal behavior must be.

PS: If there already is a system similar to this one please let me know.

Thank you for your help!

答:
The general idea is interesting and there is a lot of research on this topic currently: https://github.com/Limmen/awesome-rl-for-cybersecurity

But it's still quite far from being mature enough to use in practical settings.

Title: Machine learning and Security


问:
Related data not saved when added after creation with EF Core 6
I have POCO objects that are exposed through a repository that uses EF Core 6 to access a database. I can persist "parent" objects to the database and related data that is added to the parent object before creating is persisted successfully as well. However, when trying to add children (SingleSimulationResult objects) to a parent object (SingleSimulation objects) after it has been created, the children are not persisted to the database.

Here is the code that tries to add and save children to the parent object.

singleSim.AddResultsToSimulation(allResults);
Console.WriteLine($"# results: {singleSim.Results.Count}"); // # results: 2
await scopedRepository.Save();

var test = await scopedRepository.GetById(singleSim.Id);
Console.WriteLine($"# results test: {test.Results.Count}"); // # results: 0
```
<p>SingleSimulation class (<code>BaseEntity</code> just defines an <code>Id</code> property):</p>
<pre class="lang-cs prettyprint-override"><code>public class SingleSimulation : BaseEntity, IAggregateRoot
{
    public string Name { get; private set; }
    public string Description { get; private set; }

    public double Capital { get; private set; }

    public List<List<double>> Returns { get; private set; }

    private readonly List<SingleSimulationStrategy> _strategies = new List<SingleSimulationStrategy>();
    public IReadOnlyCollection<SingleSimulationStrategy> Strategies => _strategies.AsReadOnly();

    private List<SingleSimulationResult> _results = new List<SingleSimulationResult>();
    public IReadOnlyCollection<SingleSimulationResult> Results => _results.AsReadOnly();

    public SingleSimulation()
    {

    }

    public SingleSimulation(string name, string description, double capital, List<List<double>> returns, List<SingleSimulationStrategy> strategies)
    {
        Name = name;
        Description = description;
        Capital = capital;
        Returns = returns;
        _strategies = strategies;
    }

    public void AddResultsToSimulation(List<SingleSimulationResult> results)
    {
        if (_results is null)
            return;

        foreach (var result in results)
        {
            _results.Add(result);
        }
    }
}
</code>```

Repository class:

public class SingleSimulationRepository : ISingleSimulationRepository
{
    private SimulationDbContext _dbContext;
    public SingleSimulationRepository(SimulationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task Add(SingleSimulation entity)
    {
        await _dbContext.AddAsync(entity);
    }

    public async Task<SingleSimulation> GetById(int id)
    {
        return await _dbContext.SingleSimulations.FindAsync(id);
    }

    ...

    public async Task Save()
    {
        await _dbContext.SaveChangesAsync();
    }
}
```
<p>DbContext:</p>
<pre class="lang-cs prettyprint-override"><code>public class SimulationDbContext : DbContext
{
    public SimulationDbContext(DbContextOptions<SimulationDbContext> options)
        : base(options)
    {
    }

    public DbSet<SingleSimulation> SingleSimulations { get; set; }
    public DbSet<SingleSimulationResult> SingleSimulationResults { get; set; }
    public DbSet<SingleSimulationStrategy> SingleSimulationStrategies { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Seed data and custom conversion functions
    }
}
</code>```

Here's what I have tried (to no avail):

Using Fluent API to configure One-to-Many relationship for Results (using .HasMany()).

modelBuilder.Entity<SingleSimulation>()
    .HasMany(x => x.Results)
    .WithOne();
```

Using AddRange() to add result objects to the DB before adding them to the parent and finally saving to DB (SaveChangesAsync).

Using Attach() to start tracking result objects before adding them to the parent.

Using Include() when loading the parent object from the database before adding children and trying to save them.

It feels like I'm missing something small, but after scouring the docs and other sources I cannot find the problem. What do I need to do to get children added to the parent after the parent has already been created to actually save to the DB?

答:
After debugging by printing the EF Core change tracker's LongView, I noticed that no changes are detected on the object (even if changing a simple string property). It turns out the problem was that the singleSim object I was modifying was returned from a different dbContext than the one used by the scopedRepository.

The model setup wasn't the problem after all. Even without the Fluent API config the setup works as intended (even with the read only collections and private backing fields).

Body:
I have POCO objects that are exposed through a repository that uses EF Core 6 to access a database. I can persist "parent" objects to the database and related data that is added to the parent object before creating is persisted successfully as well. However, when trying to add children (SingleSimulationResult objects) to a parent object (SingleSimulation objects) after it has been created, the children are not persisted to the database.

Here is the code that tries to add and save children to the parent object.

singleSim.AddResultsToSimulation(allResults);
Console.WriteLine($"# results: {singleSim.Results.Count}"); // # results: 2
await scopedRepository.Save();

var test = await scopedRepository.GetById(singleSim.Id);
Console.WriteLine($"# results test: {test.Results.Count}"); // # results: 0

SingleSimulation class (BaseEntity just defines an Id property):

public class SingleSimulation : BaseEntity, IAggregateRoot
{
    public string Name { get; private set; }
    public string Description { get; private set; }

    public double Capital { get; private set; }

    public List<List<double>> Returns { get; private set; }

    private readonly List<SingleSimulationStrategy> _strategies = new List<SingleSimulationStrategy>();
    public IReadOnlyCollection<SingleSimulationStrategy> Strategies => _strategies.AsReadOnly();

    private List<SingleSimulationResult> _results = new List<SingleSimulationResult>();
    public IReadOnlyCollection<SingleSimulationResult> Results => _results.AsReadOnly();

    public SingleSimulation()
    {

    }

    public SingleSimulation(string name, string description, double capital, List<List<double>> returns, List<SingleSimulationStrategy> strategies)
    {
        Name = name;
        Description = description;
        Capital = capital;
        Returns = returns;
        _strategies = strategies;
    }

    public void AddResultsToSimulation(List<SingleSimulationResult> results)
    {
        if (_results is null)
            return;

        foreach (var result in results)
        {
            _results.Add(result);
        }
    }
}

Repository class:

public class SingleSimulationRepository : ISingleSimulationRepository
{
    private SimulationDbContext _dbContext;
    public SingleSimulationRepository(SimulationDbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public async Task Add(SingleSimulation entity)
    {
        await _dbContext.AddAsync(entity);
    }

    public async Task<SingleSimulation> GetById(int id)
    {
        return await _dbContext.SingleSimulations.FindAsync(id);
    }

    ...

    public async Task Save()
    {
        await _dbContext.SaveChangesAsync();
    }
}

DbContext:

public class SimulationDbContext : DbContext
{
    public SimulationDbContext(DbContextOptions<SimulationDbContext> options)
        : base(options)
    {
    }

    public DbSet<SingleSimulation> SingleSimulations { get; set; }
    public DbSet<SingleSimulationResult> SingleSimulationResults { get; set; }
    public DbSet<SingleSimulationStrategy> SingleSimulationStrategies { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        // Seed data and custom conversion functions
    }
}

Here's what I have tried (to no avail):

Using Fluent API to configure One-to-Many relationship for Results (using .HasMany()).

modelBuilder.Entity<SingleSimulation>()
    .HasMany(x => x.Results)
    .WithOne();

Using AddRange() to add result objects to the DB before adding them to the parent and finally saving to DB (SaveChangesAsync).

Using Attach() to start tracking result objects before adding them to the parent.

Using Include() when loading the parent object from the database before adding children and trying to save them.

It feels like I'm missing something small, but after scouring the docs and other sources I cannot find the problem. What do I need to do to get children added to the parent after the parent has already been created to actually save to the DB?


问:
Does app server use jwt id token for user identification or is the jwt id token meant to be sent to resource server to be able to identify the user?
Oauth can be used for authentication, authorization and delegation. The Oauth flow eventually results in the the app server receives an access token (and refresh token) and a jwt ID token (openidconnect).

The app server can use the access token to pass it to the resource server to access resources on behalf of the user (delegation).

Does the app server pass the Jwt id token to the resource server to inform the resource server about who the current user is? Or does the app server use the jwt id token to authenticate the user to allow the app server to know who the current user is?

答:
By the specification, the app server should not pass the id_token to anything else.

The data provided to the Resource server should be determined on the scopes passed to the scopes passed to the Authorization server and contained within the access_token.

You could send the access_token to the Resource server and then the resource server call the userInfo endpoint.

Remember this has to do with who the end-user has authorized to receive what data.

There is a rather lengthly discussion on these topics at https://github.com/IdentityServer/IdentityServer3/issues/2015


问:
Should this smart contract function be marked nonReentrant?
Should this function be marked as nonReentrant or is it overkill?</p>
```<code>function sendEthToTokenOwner(uint256 _tokenId) external payable nonReentrant {
        address _tokenOwner = ownerOf(_tokenId);
        require(msg.sender != _tokenOwner, "Sender can't be owner");

        uint256 _price = tokenIdToPrice[_tokenId];
        require(msg.value == _price, "Please submit the correct amount of ether");

        (bool success, ) = payable(_tokenOwner).call{value: _price}("");
        require(success, "Eth cannot be transferred");
}
</code>```

答:
This particular snippet doesn't require a reentrancy protection because the sendEthToTokenOwner() function simply acts as a "transfer proxy". Performing a validation, and then redirecting the msg.value to the token owner.

If you were transferring out amount larger than msg.value or an amount independent on msg.value, then you might need a reentrancy protection (depending on other context).

Body:
Should this function be marked as nonReentrant or is it overkill?

function sendEthToTokenOwner(uint256 _tokenId) external payable nonReentrant {
        address _tokenOwner = ownerOf(_tokenId);
        require(msg.sender != _tokenOwner, "Sender can't be owner");

        uint256 _price = tokenIdToPrice[_tokenId];
        require(msg.value == _price, "Please submit the correct amount of ether");

        (bool success, ) = payable(_tokenOwner).call{value: _price}("");
        require(success, "Eth cannot be transferred");
}


问:
Objective-C ParseKit Errors
I'm going through the ParseKit example and trying to modify it to suit my needs and running into this problem.  As soon as I pass in the grammar file to parserFromGrammar:assembler, I get an error:

```<code>[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array
</code>```

I thought maybe it was because my grammar files had token names with underscores in them.  Does ParseKit support underscores?  What would the method name be that gets called back?  Aka would the token name "foo_bar" call a method didMatchFoo_bar?

I then took out all the underscored names and it still gives me that error.  I'm using the example grammar file from the ParseKit website:

```<code>@start = sentence+;
sentence = adjectives 'beer' '.';
adjectives = cold adjective*;
adjective = cold | freezing;
cold = 'cold';
freezing = 'freezing';
</code>```

Thanks

答:
Developer of ParseKit here. 2 things:

To answer your first question, I believe the answer is YES.

I just tried out the grammar and it seems to work for me. However, I am using the latest version of ParseKit from Google Code (not GitHub. GitHub is out of date. sorry.)

So checkout ParseKit from Google Code here:

https://parsekit.googlecode.com/svn/trunk

And then select the "DebugApp" target and "DebugApp" Executable and run.

In the Xcode project, do a global search for "cold freezing beer". you'll see I've added your example as the default example run in DebugApp. Seems to work ok.

Title: Objective-C ParseKit Errors

Body:
I'm going through the ParseKit example and trying to modify it to suit my needs and running into this problem.  As soon as I pass in the grammar file to parserFromGrammar:assembler, I get an error:

[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array

I thought maybe it was because my grammar files had token names with underscores in them.  Does ParseKit support underscores?  What would the method name be that gets called back?  Aka would the token name "foo_bar" call a method didMatchFoo_bar?

I then took out all the underscored names and it still gives me that error.  I'm using the example grammar file from the ParseKit website:

@start = sentence+;
sentence = adjectives 'beer' '.';
adjectives = cold adjective*;
adjective = cold | freezing;
cold = 'cold';
freezing = 'freezing';

Thanks


问:
Flutter: Call static code into pubspec.yaml for versioning dependencies
For example, I have a dependecies_version.dart file. And this is the code for that file.

```<code>class DependeciesVersion {
  static const http = "^3.2.1";
  static const bloc = "^6.0.5";
}
</code>```

And on the pubspec.yaml file is like this.

```<code>dependencies:
  flutter:
    sdk: flutter
  http: DependeciesVersion.http
  flutter_bloc: DependeciesVersion.bloc
</code>```

It's possible?

Why I need this approach? Because I have each module with implemented same dependencies. So I just focus on dependecies_version.dart file for updating the version of dependencies instead of checking all pubspec.yaml file on each module.

In Native we have kotlin-dsl for handle this if implementation modular concept

答:
I think for now not supported that way, but I fix it by creating a module/package only for handling dependencies.

So if your feature module needs those dependencies, just add it in pubspec.yaml in your feature modules.

dependencies:
  flutter:
    sdk: flutter

  dependencies:
    path: ../dependencies
```

Here is the example: https://github.com/rrifafauzikomara/NewsApp

Body:
For example, I have a dependecies_version.dart file. And this is the code for that file.

class DependeciesVersion {
  static const http = "^3.2.1";
  static const bloc = "^6.0.5";
}

And on the pubspec.yaml file is like this.

dependencies:
  flutter:
    sdk: flutter
  http: DependeciesVersion.http
  flutter_bloc: DependeciesVersion.bloc

It's possible?

Why I need this approach? Because I have each module with implemented same dependencies. So I just focus on dependecies_version.dart file for updating the version of dependencies instead of checking all pubspec.yaml file on each module.

In Native we have kotlin-dsl for handle this if implementation modular concept

Body:
I think for now not supported that way, but I fix it by creating a module/package only for handling dependencies.

So if your feature module needs those dependencies, just add it in pubspec.yaml in your feature modules.

dependencies:
  flutter:
    sdk: flutter

  dependencies:
    path: ../dependencies

Here is the example: https://github.com/rrifafauzikomara/NewsApp


问:
modrewrite how can all files to index.php?
actual .htaccess

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule index.php [L]
</code>```

target:
All files should point to index.php
also png/xml ect.

call on browser:
http://localhost:8080/test.png

browser message:
enter image description here

log:

```<code>[Sun Feb  6 01:23:29 2022] [::1]:57052 Accepted
[Sun Feb  6 01:23:29 2022] [::1]:57052 [404]: GET /test.png - No such file or directory
[Sun Feb  6 01:23:29 2022] [::1]:57052 Closing
</code>```

my server start to test with:

php -S localhost:8080 -dxdebug.mode=debug -dxdebug.client_host=127.0.0.1 -dxdebug.client_port=9003 -dxdebug.start_with_request=yes

my actual server:

```<code>PHP 8.1.1 (cli) (built: Dec 17 2021 22:38:05) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Xdebug v3.1.2, Copyright (c) 2002-2021, by Derick Rethans
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies
</code>```

works on macbook ...

have an idea to solve my problem?

答:
PHP 8.1.1 (cli) (built: Dec 17 2021 22:38:05) (NTS)

You are using the built-in PHP webserver. .htaccess (and by extension mod_rewrite) is an Apache config file and is not supported by the PHP webserver.

To implement a front-controller/router using the PHP built-in webserver you need to use PHP, as described in the PHP docs:

https://www.php.net/manual/en/features.commandline.webserver.php

Aside: The mod_rewrite rule is also incorrect and won't work as written:

```<code>RewriteRule index.php [L]
</code>```

You are missing the first argument to the RewriteRule directive, so it will never match the request you are making. It should be something like this:

```<code>RewriteRule . index.php [L]
</code>```

Where . (a single dot) is a regular expression (pattern) that matches at least 1 character (ie. everything except the document root, which is handled by the DirectoryIndex).

Further Reference:

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule

works on MacBook ...

You must be using Apache, with a different .htaccess file!

Body:
actual .htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule index.php [L]

target:
All files should point to index.php
also png/xml ect.

call on browser:
http://localhost:8080/test.png

browser message:
enter image description here

log:

[Sun Feb  6 01:23:29 2022] [::1]:57052 Accepted
[Sun Feb  6 01:23:29 2022] [::1]:57052 [404]: GET /test.png - No such file or directory
[Sun Feb  6 01:23:29 2022] [::1]:57052 Closing

my server start to test with:

php -S localhost:8080 -dxdebug.mode=debug -dxdebug.client_host=127.0.0.1 -dxdebug.client_port=9003 -dxdebug.start_with_request=yes

my actual server:

PHP 8.1.1 (cli) (built: Dec 17 2021 22:38:05) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.1, Copyright (c) Zend Technologies
    with Xdebug v3.1.2, Copyright (c) 2002-2021, by Derick Rethans
    with Zend OPcache v8.1.1, Copyright (c), by Zend Technologies

works on macbook ...

have an idea to solve my problem?

Body:
PHP 8.1.1 (cli) (built: Dec 17 2021 22:38:05) (NTS)

You are using the built-in PHP webserver. .htaccess (and by extension mod_rewrite) is an Apache config file and is not supported by the PHP webserver.

To implement a front-controller/router using the PHP built-in webserver you need to use PHP, as described in the PHP docs:

https://www.php.net/manual/en/features.commandline.webserver.php

Aside: The mod_rewrite rule is also incorrect and won't work as written:

RewriteRule index.php [L]

You are missing the first argument to the RewriteRule directive, so it will never match the request you are making. It should be something like this:

RewriteRule . index.php [L]

Where . (a single dot) is a regular expression (pattern) that matches at least 1 character (ie. everything except the document root, which is handled by the DirectoryIndex).

Further Reference:

https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#rewriterule

works on MacBook ...

You must be using Apache, with a different .htaccess file!


问:
What is the decoded output of a video codec?
Folks,

I am wondering if someone can explain to me what exactly is the output of video decoding. Let's say it is a H.264 stream in an MP4 container.

From displaying something on the screen, I guess decoder can provider two different types of output:

Point - (x, y) coordinate of the location and the (R, G, B) color for the pixel

Rectangle (x, y, w, h) units for the rectangle and the (R, G, B) color to display

There is also the issue of time stamp.

Can you please enlighten me or point me the right link on what is generated out of a decoder and how a video client can use this information to display something on screen?

I intend to download VideoLAN source and examine it but some explanation would be helpful.

Thank you in advance for your help.

Regards,
Peter

答:
cdhowie got most of it.
When it comes to timestamps the MPEG4 container contains tables for each frame that tells the video client when to display each frame. You should look at the spec for MPEG4. You normally have to pay for this I think but it's definitely downloadable from places.

http://en.wikipedia.org/wiki/MPEG-4_Part_14


问:
Is it possible to get the visual studio build folder name over azure devops?
We are using azure devops for CI/CD, but we got a problem with our build pipelines.
When creating visual studio build, we would like to get the specific folder where the build is created, so we can copy the folder (add outputpath parameter to visual studio task doesn't work with some projects).

The main problem is, that name of the project and the repo can be different.
We would need something like:

```<code>$(agent.builddirectory)\s\PROJECT-NAME\bin\Release
</code>```

Is there a way to get the project name or the output folder?
$(agent.builddirectory) isn't working.

EDIT: We need to use the build pipelines at this point, so currently we don't work with artifacts or release pipelines (we know we should...)

答:
It seems like you are using Azure Pipelines to do what MSBuild / dotnet cli are made to help you.

You can instead use msbuild / dotnet cli to build and pack your project output to a designated location, like output in the repository root folder, that is common across all projects that use the pipeline.

If you only checkout 1 repository, all tasks will be executed in the repository folder. You do not need to mess with $(agent.builddirectory)\s\xxxx. Accessing output is as simple as output/ in your pipeline.

Body:
We are using azure devops for CI/CD, but we got a problem with our build pipelines.
When creating visual studio build, we would like to get the specific folder where the build is created, so we can copy the folder (add outputpath parameter to visual studio task doesn't work with some projects).

The main problem is, that name of the project and the repo can be different.
We would need something like:

$(agent.builddirectory)\s\PROJECT-NAME\bin\Release

Is there a way to get the project name or the output folder?
$(agent.builddirectory) isn't working.

EDIT: We need to use the build pipelines at this point, so currently we don't work with artifacts or release pipelines (we know we should...)


问:
Selenium: How to deal with web elements that get hidden when you try to inspect them? Python 3.x related
I'm about to finish developing an automated program on Python and the only thing that's stopping me it's a web element that gets immediately hidden when I try to inspect it from an OpenSea page (can't share the link here since it requires to be connected to my wallet):

So far, I have only managed to get the XPATH and the CSS_SELECTOR of this problematic element (div#tippy-298) which is the following:

```<code>button_problematic_xpath = driver.find_element(By.XPATH, '//*[@id="tippy-298"]')
button_problematic_css = driver.find_element(By.CSS_SELECTOR, '#tippy-298')
</code>```

But what I need is to get the XPATH or CSS_SELECTOR of the Web Elements that button_problematic_css contains, more specifically the "Starting" and "Ending" Textboxes :

Also, just in case, the element that's on top of button_problematic_css is called "Duration", here's its XPATH:

```<code>button_duration = driver.find_element(By.XPATH, '//*[@id="duration"]').click #after clicked it deploys div#tippy-298 element
</code>```

I was wondering if there could be any method to force the visibility of this button_problematic_css using the Chrome Console in the Inspection of Web Elements, or by using an specific method from Selenium on Python3.x to inmediately download all of the web elements this page has right after button_problematic_css is visible.

What I have tried so far is to manually inspect the element, by pressing Ctrl + Shift + C and and then clicking the elements contained in button_problematic_css which just ends up hiding this element before even clicking its content, the same happens when trying to display the contents of this element in the DOM of this page, it just dissapears.

I just wish my program could be capable of editing the dates in the "Starting" and "Ending" Textboxes

答:
After several days of working, I managed to solve this, it happened that in order to get the XPATH from these particular elements, I had to use the Chrome Console and type $('#duration').click();.

In this case, #duration is a Selector that can be used to get the web element button that allows you to edit the period of time you want to set when clicked.

I guess the general statement would be something like this:

$('#your_css_selector').click();

Now, this way I could managed to look deeper in the DOM without making them hide again.

Body:
I'm about to finish developing an automated program on Python and the only thing that's stopping me it's a web element that gets immediately hidden when I try to inspect it from an OpenSea page (can't share the link here since it requires to be connected to my wallet):

So far, I have only managed to get the XPATH and the CSS_SELECTOR of this problematic element (div#tippy-298) which is the following:

button_problematic_xpath = driver.find_element(By.XPATH, '//*[@id="tippy-298"]')
button_problematic_css = driver.find_element(By.CSS_SELECTOR, '#tippy-298')

But what I need is to get the XPATH or CSS_SELECTOR of the Web Elements that button_problematic_css contains, more specifically the "Starting" and "Ending" Textboxes :

Also, just in case, the element that's on top of button_problematic_css is called "Duration", here's its XPATH:

button_duration = driver.find_element(By.XPATH, '//*[@id="duration"]').click #after clicked it deploys div#tippy-298 element

I was wondering if there could be any method to force the visibility of this button_problematic_css using the Chrome Console in the Inspection of Web Elements, or by using an specific method from Selenium on Python3.x to inmediately download all of the web elements this page has right after button_problematic_css is visible.

What I have tried so far is to manually inspect the element, by pressing Ctrl + Shift + C and and then clicking the elements contained in button_problematic_css which just ends up hiding this element before even clicking its content, the same happens when trying to display the contents of this element in the DOM of this page, it just dissapears.

I just wish my program could be capable of editing the dates in the "Starting" and "Ending" Textboxes