问:
Minikube dashboard ingress
Im trying to make an ingress for the minikube dashboard using the embedded dashboard internal service.

I enabled both ingress and dashboard minikube addons.

I also wrote this ingress YAML file :

```<code>apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: dashboard-ingress
  namespace: kubernetes-dashboard
spec:
  rules:
  - host: dashboard.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: kubernetes-dashboard
            port:
              number: 80
</code>```

My Ingress is being created well as u can see :

```<code>NAME                CLASS   HOSTS           ADDRESS     PORTS   AGE
dashboard-ingress   nginx   dashboard.com   localhost   80      15s
</code>```

I edited my /etc/hosts to add this line : 127.0.0.1    dashboard.com.

Now im trying to access the dashboard trough dashboard.com. But it's not working.

kubectl describe ingress dashboard-ingress -n kubernetes-dashboard gives me this :

```<code>Name:             dashboard-ingress
Namespace:        kubernetes-dashboard
Address:          localhost
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host           Path  Backends
  ----           ----  --------
  dashboard.com
                 /   kubernetes-dashboard:80 (172.17.0.4:9090)
Annotations:     <none>
Events:
  Type    Reason  Age                From                      Message
  ----    ------  ----               ----                      -------
  Normal  Sync    14m (x2 over 14m)  nginx-ingress-controller  Scheduled for sync
</code>```

I don't really understand what <error: endpoints "default-http-backend" not found> means, but maybe my issue comes from this.

kubectl get pods -n ingress-nginx result :

```<code>NAME                                        READY   STATUS      RESTARTS   AGE
ingress-nginx-admission-create--1-8krc7     0/1     Completed   0          100m
ingress-nginx-admission-patch--1-qblch      0/1     Completed   1          100m
ingress-nginx-controller-5f66978484-hvk9j   1/1     Running     0          100m
</code>```

Logs for nginx-controller pod :

```<code>-------------------------------------------------------------------------------
NGINX Ingress controller
  Release:       v1.0.4
  Build:         9b78b6c197b48116243922170875af4aa752ee59
  Repository:    https://github.com/kubernetes/ingress-nginx
  nginx version: nginx/1.19.9

-------------------------------------------------------------------------------

W1205 19:33:42.303136       7 client_config.go:615] Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.
I1205 19:33:42.303261       7 main.go:221] "Creating API client" host="https://10.96.0.1:443"
I1205 19:33:42.319750       7 main.go:265] "Running in Kubernetes cluster" major="1" minor="22" git="v1.22.3" state="clean" commit="c92036820499fedefec0f847e2054d824aea6cd1" platform="linux/amd64"
I1205 19:33:42.402223       7 main.go:104] "SSL fake certificate created" file="/etc/ingress-controller/ssl/default-fake-certificate.pem"
I1205 19:33:42.413477       7 ssl.go:531] "loading tls certificate" path="/usr/local/certificates/cert" key="/usr/local/certificates/key"
I1205 19:33:42.420838       7 nginx.go:253] "Starting NGINX Ingress controller"
I1205 19:33:42.424731       7 event.go:282] Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx", Name:"ingress-nginx-controller", UID:"f2d27cc7-b103-490f-807f-18ccaa614e6b", APIVersion:"v1", ResourceVersion:"664", FieldPath:""}): type: 'Normal' reason: 'CREATE' ConfigMap ingress-nginx/ingress-nginx-controller
I1205 19:33:42.427171       7 event.go:282] Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx", Name:"tcp-services", UID:"e174971d-df1c-4826-85d4-194598ab1912", APIVersion:"v1", ResourceVersion:"665", FieldPath:""}): type: 'Normal' reason: 'CREATE' ConfigMap ingress-nginx/tcp-services
I1205 19:33:42.427195       7 event.go:282] Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx", Name:"udp-services", UID:"0ffc7ee9-2435-4005-983d-ed41aac1c9aa", APIVersion:"v1", ResourceVersion:"666", FieldPath:""}): type: 'Normal' reason: 'CREATE' ConfigMap ingress-nginx/udp-services
I1205 19:33:43.622661       7 nginx.go:295] "Starting NGINX process"
I1205 19:33:43.622746       7 leaderelection.go:243] attempting to acquire leader lease ingress-nginx/ingress-controller-leader...
I1205 19:33:43.623402       7 nginx.go:315] "Starting validation webhook" address=":8443" certPath="/usr/local/certificates/cert" keyPath="/usr/local/certificates/key"
I1205 19:33:43.623683       7 controller.go:152] "Configuration changes detected, backend reload required"
I1205 19:33:43.643547       7 leaderelection.go:253] successfully acquired lease ingress-nginx/ingress-controller-leader
I1205 19:33:43.643635       7 status.go:84] "New leader elected" identity="ingress-nginx-controller-5f66978484-hvk9j"
I1205 19:33:43.691342       7 controller.go:169] "Backend successfully reloaded"
I1205 19:33:43.691395       7 controller.go:180] "Initial sync, sleeping for 1 second"
I1205 19:33:43.691435       7 event.go:282] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx", Name:"ingress-nginx-controller-5f66978484-hvk9j", UID:"55d45c26-eda7-4b37-9b04-5491cde39fd4", APIVersion:"v1", ResourceVersion:"697", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration
I1205 21:06:47.402756       7 main.go:101] "successfully validated configuration, accepting" ingress="dashboard-ingress/kubernetes-dashboard"
I1205 21:06:47.408929       7 store.go:371] "Found valid IngressClass" ingress="kubernetes-dashboard/dashboard-ingress" ingressclass="nginx"
I1205 21:06:47.409343       7 controller.go:152] "Configuration changes detected, backend reload required"
I1205 21:06:47.409352       7 event.go:282] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"kubernetes-dashboard", Name:"dashboard-ingress", UID:"be1ebfe9-fdb3-4d0c-925b-0c206cd0ece3", APIVersion:"networking.k8s.io/v1", ResourceVersion:"5529", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync
I1205 21:06:47.458273       7 controller.go:169] "Backend successfully reloaded"
I1205 21:06:47.458445       7 event.go:282] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx", Name:"ingress-nginx-controller-5f66978484-hvk9j", UID:"55d45c26-eda7-4b37-9b04-5491cde39fd4", APIVersion:"v1", ResourceVersion:"697", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration
I1205 21:07:43.654037       7 status.go:300] "updating Ingress status" namespace="kubernetes-dashboard" ingress="dashboard-ingress" currentValue=[] newValue=[{IP: Hostname:localhost Ports:[]}]
I1205 21:07:43.660598       7 event.go:282] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"kubernetes-dashboard", Name:"dashboard-ingress", UID:"be1ebfe9-fdb3-4d0c-925b-0c206cd0ece3", APIVersion:"networking.k8s.io/v1", ResourceVersion:"5576", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync
</code>```

Anyone has a clue on how i can solve my problem ?

(Im using minikube v1.24.0)

Regards,

答:
I have also faced the same issue with minikube(v1.25.1) running in my local.

kubectl get ingress -n kubernetes-dashboard

```<code>NAME                CLASS   HOSTS           ADDRESS     PORTS   AGE
dashboard-ingress   nginx   dashboard.com   localhost   80      34m
</code>```

After  debug I have found this.
"If you are running Minikube locally, use minikube ip to get the external IP. The IP address displayed within the ingress list will be the internal IP".

Run this command

```<code>minikube ip
XXX.XXX.64.2
</code>```

add this ip in the host file,after that I am able to access dashboard.com

Title: Minikube dashboard ingress

Body:
Im trying to make an ingress for the minikube dashboard using the embedded dashboard internal service.

I enabled both ingress and dashboard minikube addons.

I also wrote this ingress YAML file :

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: dashboard-ingress
  namespace: kubernetes-dashboard
spec:
  rules:
  - host: dashboard.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: kubernetes-dashboard
            port:
              number: 80

My Ingress is being created well as u can see :

NAME                CLASS   HOSTS           ADDRESS     PORTS   AGE
dashboard-ingress   nginx   dashboard.com   localhost   80      15s

I edited my /etc/hosts to add this line : 127.0.0.1    dashboard.com.

Now im trying to access the dashboard trough dashboard.com. But it's not working.

kubectl describe ingress dashboard-ingress -n kubernetes-dashboard gives me this :

Name:             dashboard-ingress
Namespace:        kubernetes-dashboard
Address:          localhost
Default backend:  default-http-backend:80 (<error: endpoints "default-http-backend" not found>)
Rules:
  Host           Path  Backends
  ----           ----  --------
  dashboard.com
                 /   kubernetes-dashboard:80 (172.17.0.4:9090)
Annotations:     <none>
Events:
  Type    Reason  Age                From                      Message
  ----    ------  ----               ----                      -------
  Normal  Sync    14m (x2 over 14m)  nginx-ingress-controller  Scheduled for sync

I don't really understand what <error: endpoints "default-http-backend" not found> means, but maybe my issue comes from this.

kubectl get pods -n ingress-nginx result :

NAME                                        READY   STATUS      RESTARTS   AGE
ingress-nginx-admission-create--1-8krc7     0/1     Completed   0          100m
ingress-nginx-admission-patch--1-qblch      0/1     Completed   1          100m
ingress-nginx-controller-5f66978484-hvk9j   1/1     Running     0          100m

Logs for nginx-controller pod :

-------------------------------------------------------------------------------
NGINX Ingress controller
  Release:       v1.0.4
  Build:         9b78b6c197b48116243922170875af4aa752ee59
  Repository:    https://github.com/kubernetes/ingress-nginx
  nginx version: nginx/1.19.9

-------------------------------------------------------------------------------

W1205 19:33:42.303136       7 client_config.go:615] Neither --kubeconfig nor --master was specified.  Using the inClusterConfig.  This might not work.
I1205 19:33:42.303261       7 main.go:221] "Creating API client" host="https://10.96.0.1:443"
I1205 19:33:42.319750       7 main.go:265] "Running in Kubernetes cluster" major="1" minor="22" git="v1.22.3" state="clean" commit="c92036820499fedefec0f847e2054d824aea6cd1" platform="linux/amd64"
I1205 19:33:42.402223       7 main.go:104] "SSL fake certificate created" file="/etc/ingress-controller/ssl/default-fake-certificate.pem"
I1205 19:33:42.413477       7 ssl.go:531] "loading tls certificate" path="/usr/local/certificates/cert" key="/usr/local/certificates/key"
I1205 19:33:42.420838       7 nginx.go:253] "Starting NGINX Ingress controller"
I1205 19:33:42.424731       7 event.go:282] Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx", Name:"ingress-nginx-controller", UID:"f2d27cc7-b103-490f-807f-18ccaa614e6b", APIVersion:"v1", ResourceVersion:"664", FieldPath:""}): type: 'Normal' reason: 'CREATE' ConfigMap ingress-nginx/ingress-nginx-controller
I1205 19:33:42.427171       7 event.go:282] Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx", Name:"tcp-services", UID:"e174971d-df1c-4826-85d4-194598ab1912", APIVersion:"v1", ResourceVersion:"665", FieldPath:""}): type: 'Normal' reason: 'CREATE' ConfigMap ingress-nginx/tcp-services
I1205 19:33:42.427195       7 event.go:282] Event(v1.ObjectReference{Kind:"ConfigMap", Namespace:"ingress-nginx", Name:"udp-services", UID:"0ffc7ee9-2435-4005-983d-ed41aac1c9aa", APIVersion:"v1", ResourceVersion:"666", FieldPath:""}): type: 'Normal' reason: 'CREATE' ConfigMap ingress-nginx/udp-services
I1205 19:33:43.622661       7 nginx.go:295] "Starting NGINX process"
I1205 19:33:43.622746       7 leaderelection.go:243] attempting to acquire leader lease ingress-nginx/ingress-controller-leader...
I1205 19:33:43.623402       7 nginx.go:315] "Starting validation webhook" address=":8443" certPath="/usr/local/certificates/cert" keyPath="/usr/local/certificates/key"
I1205 19:33:43.623683       7 controller.go:152] "Configuration changes detected, backend reload required"
I1205 19:33:43.643547       7 leaderelection.go:253] successfully acquired lease ingress-nginx/ingress-controller-leader
I1205 19:33:43.643635       7 status.go:84] "New leader elected" identity="ingress-nginx-controller-5f66978484-hvk9j"
I1205 19:33:43.691342       7 controller.go:169] "Backend successfully reloaded"
I1205 19:33:43.691395       7 controller.go:180] "Initial sync, sleeping for 1 second"
I1205 19:33:43.691435       7 event.go:282] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx", Name:"ingress-nginx-controller-5f66978484-hvk9j", UID:"55d45c26-eda7-4b37-9b04-5491cde39fd4", APIVersion:"v1", ResourceVersion:"697", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration
I1205 21:06:47.402756       7 main.go:101] "successfully validated configuration, accepting" ingress="dashboard-ingress/kubernetes-dashboard"
I1205 21:06:47.408929       7 store.go:371] "Found valid IngressClass" ingress="kubernetes-dashboard/dashboard-ingress" ingressclass="nginx"
I1205 21:06:47.409343       7 controller.go:152] "Configuration changes detected, backend reload required"
I1205 21:06:47.409352       7 event.go:282] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"kubernetes-dashboard", Name:"dashboard-ingress", UID:"be1ebfe9-fdb3-4d0c-925b-0c206cd0ece3", APIVersion:"networking.k8s.io/v1", ResourceVersion:"5529", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync
I1205 21:06:47.458273       7 controller.go:169] "Backend successfully reloaded"
I1205 21:06:47.458445       7 event.go:282] Event(v1.ObjectReference{Kind:"Pod", Namespace:"ingress-nginx", Name:"ingress-nginx-controller-5f66978484-hvk9j", UID:"55d45c26-eda7-4b37-9b04-5491cde39fd4", APIVersion:"v1", ResourceVersion:"697", FieldPath:""}): type: 'Normal' reason: 'RELOAD' NGINX reload triggered due to a change in configuration
I1205 21:07:43.654037       7 status.go:300] "updating Ingress status" namespace="kubernetes-dashboard" ingress="dashboard-ingress" currentValue=[] newValue=[{IP: Hostname:localhost Ports:[]}]
I1205 21:07:43.660598       7 event.go:282] Event(v1.ObjectReference{Kind:"Ingress", Namespace:"kubernetes-dashboard", Name:"dashboard-ingress", UID:"be1ebfe9-fdb3-4d0c-925b-0c206cd0ece3", APIVersion:"networking.k8s.io/v1", ResourceVersion:"5576", FieldPath:""}): type: 'Normal' reason: 'Sync' Scheduled for sync

Anyone has a clue on how i can solve my problem ?

(Im using minikube v1.24.0)

Regards,

Body:
I have also faced the same issue with minikube(v1.25.1) running in my local.

kubectl get ingress -n kubernetes-dashboard

NAME                CLASS   HOSTS           ADDRESS     PORTS   AGE
dashboard-ingress   nginx   dashboard.com   localhost   80      34m

After  debug I have found this.
"If you are running Minikube locally, use minikube ip to get the external IP. The IP address displayed within the ingress list will be the internal IP".

Run this command

minikube ip
XXX.XXX.64.2

add this ip in the host file,after that I am able to access dashboard.com


来源: stackexchange

问:
Cypress - Get [value] value property from mat-button-toggle-group
I have a selector to <mat-button-toggle-group [value]="myValue"></mat-button-toggle-group>

I want to have access to [value] value, and for that I do.

buttonToggleGroupSelector.should('exist').and('has.value', 'MyValue');
```

But this returns an empty string and not the attribute value.

答:
When you use

buttonToggleGroupSelector.should('exist').and('has.value', 'MyValue');
```
<p>Cypress is looking for a <code>value</code> property, but you want the <code>value</code> attribute</p>
<pre class="lang-js prettyprint-override"><code>buttonToggleGroupSelector.should('exist').and('has.attr', 'value', 'MyValue');
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a selector to <mat-button-toggle-group [value]="myValue"></mat-button-toggle-group>

I want to have access to [value] value, and for that I do.

buttonToggleGroupSelector.should('exist').and('has.value', 'MyValue');

But this returns an empty string and not the attribute value.

Body:
When you use

buttonToggleGroupSelector.should('exist').and('has.value', 'MyValue');

Cypress is looking for a value property, but you want the value attribute

buttonToggleGroupSelector.should('exist').and('has.attr', 'value', 'MyValue');


问:
Most efficient way to query with two keys in either order?
I have some data I receive of the following format:

```<code>{ gameId: 1, playerId: "john", score: .12 }
{ gameId: 1, playerId: "mary", score: .75 }
{ gameId: 1, playerId: "jane", score: .32 }
{ gameId: 2, playerId: "john", score: .89 }
{ gameId: 2, playerId: "mary", score: .91 }
{ gameId: 2, playerId: "jane", score: .99 }
</code>```

And I want to expose these endpoints:

GET games => get a list of all games

GET games/{id} => list all the games for the gameId and the average score among all players

GET players => get a list of all games

GET players/{id} => list all the scores for the player and their average score across all games

So setting DBs aside for a moment, I thought of a hash map approach where I basically have two maps:

gameScores[gameId][playerId] = score

playerScores[playerId][gameId] = score

This way I could very efficiently return results as the following:

GET games => array_keys(gameScores)

GET games/{id} => ['average' => avg(gameScores[id]), 'games' => gameScores[id]]

GET players => array_keys(playerScores)

GET players/{id} => ['average' => avg(playerScores[id]), 'games' => playerScores[id]]

This seems like a very efficient way to return results in near O(1) time, but is it too great a drawback to be duplicating the dataset by 2? Imagine if score was some very large object instead.

I'm doing this in PHP, so not using something like a Python tuple solution here, but I feel like this problem is very generalizable (hash map with 2 keys) and I'm wondering if there's a better way to approach this rather than duplicating the hash map for both key orders.

Is using a database the only more optimal approach here? If so, would it be best to enter the data into a single table with those 3 columns, or should I be splitting the tables?

答:
You only need one array and search it with</p>
```<code>array_search($search, array_column($array, $field));
</code>```

Body:
I have some data I receive of the following format:

{ gameId: 1, playerId: "john", score: .12 }
{ gameId: 1, playerId: "mary", score: .75 }
{ gameId: 1, playerId: "jane", score: .32 }
{ gameId: 2, playerId: "john", score: .89 }
{ gameId: 2, playerId: "mary", score: .91 }
{ gameId: 2, playerId: "jane", score: .99 }

And I want to expose these endpoints:

GET games => get a list of all games

GET games/{id} => list all the games for the gameId and the average score among all players

GET players => get a list of all games

GET players/{id} => list all the scores for the player and their average score across all games

So setting DBs aside for a moment, I thought of a hash map approach where I basically have two maps:

gameScores[gameId][playerId] = score

playerScores[playerId][gameId] = score

This way I could very efficiently return results as the following:

GET games => array_keys(gameScores)

GET games/{id} => ['average' => avg(gameScores[id]), 'games' => gameScores[id]]

GET players => array_keys(playerScores)

GET players/{id} => ['average' => avg(playerScores[id]), 'games' => playerScores[id]]

This seems like a very efficient way to return results in near O(1) time, but is it too great a drawback to be duplicating the dataset by 2? Imagine if score was some very large object instead.

I'm doing this in PHP, so not using something like a Python tuple solution here, but I feel like this problem is very generalizable (hash map with 2 keys) and I'm wondering if there's a better way to approach this rather than duplicating the hash map for both key orders.

Is using a database the only more optimal approach here? If so, would it be best to enter the data into a single table with those 3 columns, or should I be splitting the tables?

Body:
You only need one array and search it with

array_search($search, array_column($array, $field));


问:
Image is not covering the whole div
I am trying to make my image cover the whole div which is 50% of the parent div. I used object-fit:cover but it's still not working. The problem is as I reduce the width of window the image also shortens.

In (1) the width is full
The 2nd picture is 900px window size.

* {
  box-sizing: border-box;
}

body {
  background: yellow;
}

section {
  background: red;
  widtth: 100%;
  min-height: 700px;
}

article {
  background: green;
  width: 50%;
  min-height: 700px;
  padding: 100px;
  float: left;
}

picture {
  float: left;
  width: 50%;
  min-height: 700px;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

section::after {
  content: "";
  clear: both;
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <section class="about">
    <article>
      <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur expedita laudantium, ea eos fugiat dolores laboriosam voluptas illo deleniti pariatur ratione nobis perferendis in consectetur rerum ipsa debitis quis numquam! Lorem ipsum dolor
        sit amet consectetur adipisicing elit. Veniam unde placeat ratione magnam tempore velit accusamus ipsam quaerat aspernatur maiores?</p>
    </article>
    <picture>
      <img src="https://www.loveinartsz.com/wp-content/uploads/2021/03/b04803919effa1914ae6754d8bee30fb.jpg" alt="">
    </picture>
  </section>

</body></code>```

I have linked the code pen link below for reference.

https://codepen.io/YASH_KR18/pen/LYObNrB

答:
Floating elements (removing them from the normal flow of the html structure) is the source of a lot of problems. If you would use a flexbox or gridbox for the parent element then there would be no need to float the children to position them next to eachother and then I believe your problem is solved. Well that is if the snippet below does what you're after at least! If not I might not understand your question yet.

/* Colors for visibilty */
body{ background-color: yellow;}
article{ background-color: green; padding: 100px;}
picture{ background-color: red; }

/* The problem fix*/
section
{
  display: grid;
  grid-template-columns: 50% 50%;
  width: 80%;
  max-width: 1100px;
  min-height: 700px;
  margin: auto;
}

picture img{
  object-position: center;
  object-fit: cover;
  width: 100%;
  height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section>
  <article>
     <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur expedita laudantium, ea eos fugiat dolores laboriosam voluptas illo deleniti pariatur ratione nobis perferendis in consectetur rerum ipsa debitis quis numquam! Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam unde placeat ratione magnam tempore velit accusamus ipsam quaerat aspernatur maiores?</p>
  </article>
  <picture>
     <img src="https://www.loveinartsz.com/wp-content/uploads/2021/03/b04803919effa1914ae6754d8bee30fb.jpg" alt="">
  </picture>
</section></code>```

Title: Image is not covering the whole div

Body:
I am trying to make my image cover the whole div which is 50% of the parent div. I used object-fit:cover but it's still not working. The problem is as I reduce the width of window the image also shortens.

In (1) the width is full
The 2nd picture is 900px window size.

* {
  box-sizing: border-box;
}

body {
  background: yellow;
}

section {
  background: red;
  widtth: 100%;
  min-height: 700px;
}

article {
  background: green;
  width: 50%;
  min-height: 700px;
  padding: 100px;
  float: left;
}

picture {
  float: left;
  width: 50%;
  min-height: 700px;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

section::after {
  content: "";
  clear: both;
  display: block;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur expedita laudantium, ea eos fugiat dolores laboriosam voluptas illo deleniti pariatur ratione nobis perferendis in consectetur rerum ipsa debitis quis numquam! Lorem ipsum dolor
        sit amet consectetur adipisicing elit. Veniam unde placeat ratione magnam tempore velit accusamus ipsam quaerat aspernatur maiores?

    <picture>

    </picture>

I have linked the code pen link below for reference.

https://codepen.io/YASH_KR18/pen/LYObNrB

Body:
Floating elements (removing them from the normal flow of the html structure) is the source of a lot of problems. If you would use a flexbox or gridbox for the parent element then there would be no need to float the children to position them next to eachother and then I believe your problem is solved. Well that is if the snippet below does what you're after at least! If not I might not understand your question yet.

/* Colors for visibilty */
body{ background-color: yellow;}
article{ background-color: green; padding: 100px;}
picture{ background-color: red; }

/* The problem fix*/
section
{
  display: grid;
  grid-template-columns: 50% 50%;
  width: 80%;
  max-width: 1100px;
  min-height: 700px;
  margin: auto;
}

picture img{
  object-position: center;
  object-fit: cover;
  width: 100%;
  height: 100%;
}

<section>
  <article>
     <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Consequatur expedita laudantium, ea eos fugiat dolores laboriosam voluptas illo deleniti pariatur ratione nobis perferendis in consectetur rerum ipsa debitis quis numquam! Lorem ipsum dolor sit amet consectetur adipisicing elit. Veniam unde placeat ratione magnam tempore velit accusamus ipsam quaerat aspernatur maiores?</p>
  </article>
  <picture>
     <img src="https://www.loveinartsz.com/wp-content/uploads/2021/03/b04803919effa1914ae6754d8bee30fb.jpg" alt="">
  </picture>
</section>


问:
Python equivalent to PHPs parse_ini_string
I'm currently porting a PHP script to Python to learn Python.
But currently I'm stuck, because I'm calling an API which always returns an ini-formatted answer something like this:

```<code>error=0
---
asin=
name=Haftnotizen
detailname=info flags Haftnotizen
vendor=GlobalNotes
maincat=Haushalt, Büro
---
</code>```

I've already learnt that I can use ConfigParser to parse ini-files.
But in this case, the ini-answer has no headings (which wouldn't be a problem with this solution) and also has these --- separators.

My code right now is:

import configparser

with open('test.ini', 'r') as f:
    config_string = '[dummy_section]\n' + f.read()
config = configparser.ConfigParser()
config.read_string(config_string)
```
<p>but unfortunately it's throwing the following error message at me:</p>
<pre class="lang-sh prettyprint-override"><code>configparser.ParsingError: Source contains parsing errors: '<string>'
        [line  3]: '---\n'
        [line  9]: '---'
</code>```

How can I ignore those lines? (Also, they're not always in the same line)

I don't know what to do next, any help would be much appreciated!

答:
It's not pretty, but if the error string is always exactly the same you can just remove that substring from the data. You would do that with this:</p>
```<code>config_string = config_string.replace("---", "")
</code>```

Body:
I'm currently porting a PHP script to Python to learn Python.
But currently I'm stuck, because I'm calling an API which always returns an ini-formatted answer something like this:

error=0
---
asin=
name=Haftnotizen
detailname=info flags Haftnotizen
vendor=GlobalNotes
maincat=Haushalt, Büro
---

I've already learnt that I can use ConfigParser to parse ini-files.
But in this case, the ini-answer has no headings (which wouldn't be a problem with this solution) and also has these --- separators.

My code right now is:

import configparser

with open('test.ini', 'r') as f:
    config_string = '[dummy_section]\n' + f.read()
config = configparser.ConfigParser()
config.read_string(config_string)

but unfortunately it's throwing the following error message at me:

configparser.ParsingError: Source contains parsing errors: '<string>'
        [line  3]: '---\n'
        [line  9]: '---'

How can I ignore those lines? (Also, they're not always in the same line)

I don't know what to do next, any help would be much appreciated!

Body:
It's not pretty, but if the error string is always exactly the same you can just remove that substring from the data. You would do that with this:

config_string = config_string.replace("---", "")


问:
how does one match EOL (newline) with lark?
I'm using the lark parser with python. I'd like to use EOL as part of the grammar since it is line oriented. I'm getting an error when I try to put the regex in for matching EOL. I see some examples like this:

```<code>CR : /\r/
LF : /\n/
NEWLINE: (CR? LF)+
</code>```

but they don't work for me. this is my code:

```<code>import sys
import lark

class Parser:
    grammar = '''
        start : STRING EOL
        STRING : /\w+/
        EOL : /\n/x
    '''

    parser = lark.Lark(grammar)

    def __init__(self, fname):
        self.fname = fname
        self.ast(open(fname))

    def ast(self, fh):
        tree = self.parser.parse(fh.read())
        print(tree.pretty())

def main():
    x = Parser(sys.argv[1])

main()
</code>```

and here's the error I get:

```<code>Traceback (most recent call last):
  File "./p2.py", line 6, in <module>
    class Parser:
  File "./p2.py", line 13, in Parser
    parser = lark.Lark(grammar)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/lark.py", line 413, in __init__
    self.parser = self._build_parser()
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/lark.py", line 456, in _build_parser
    return parser_class(self.lexer_conf, parser_conf, options=self.options)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 242, in __call__
    return ParsingFrontend(lexer_conf, parser_conf, options)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 61, in __init__
    self.parser = create_parser(lexer_conf, parser_conf, options)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 209, in create_earley_parser
    return f(lexer_conf, parser_conf, options, resolve_ambiguity=resolve_ambiguity, debug=debug, tree_class=tree_class, **extra)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 186, in create_earley_parser__dynamic
    earley_matcher = EarleyRegexpMatcher(lexer_conf)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 172, in __init__
    raise GrammarError("Dynamic Earley doesn't allow zero-width regexps", t)
lark.exceptions.GrammarError: ("Dynamic Earley doesn't allow zero-width regexps", TerminalDef('EOL', '(?x:\n)'))
</code>```

答:
I forgot about needing to use raw strings.  had to add an "r". the new code looks like:</p>
```<code>class Parser:
    grammar = r'''
        start : STRING EOL
        STRING : /\w+/
        EOL : /\n/
    '''
</code>```

Body:
I'm using the lark parser with python. I'd like to use EOL as part of the grammar since it is line oriented. I'm getting an error when I try to put the regex in for matching EOL. I see some examples like this:

CR : /\r/
LF : /\n/
NEWLINE: (CR? LF)+

but they don't work for me. this is my code:

import sys
import lark

class Parser:
    grammar = '''
        start : STRING EOL
        STRING : /\w+/
        EOL : /\n/x
    '''

    parser = lark.Lark(grammar)

    def __init__(self, fname):
        self.fname = fname
        self.ast(open(fname))

    def ast(self, fh):
        tree = self.parser.parse(fh.read())
        print(tree.pretty())

def main():
    x = Parser(sys.argv[1])

main()

and here's the error I get:

Traceback (most recent call last):
  File "./p2.py", line 6, in <module>
    class Parser:
  File "./p2.py", line 13, in Parser
    parser = lark.Lark(grammar)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/lark.py", line 413, in __init__
    self.parser = self._build_parser()
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/lark.py", line 456, in _build_parser
    return parser_class(self.lexer_conf, parser_conf, options=self.options)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 242, in __call__
    return ParsingFrontend(lexer_conf, parser_conf, options)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 61, in __init__
    self.parser = create_parser(lexer_conf, parser_conf, options)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 209, in create_earley_parser
    return f(lexer_conf, parser_conf, options, resolve_ambiguity=resolve_ambiguity, debug=debug, tree_class=tree_class, **extra)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 186, in create_earley_parser__dynamic
    earley_matcher = EarleyRegexpMatcher(lexer_conf)
  File "/grid/common/pkgs/python/v3.7.2/lib/python3.7/site-packages/lark/parser_frontends.py", line 172, in __init__
    raise GrammarError("Dynamic Earley doesn't allow zero-width regexps", t)
lark.exceptions.GrammarError: ("Dynamic Earley doesn't allow zero-width regexps", TerminalDef('EOL', '(?x:\n)'))

Body:
I forgot about needing to use raw strings.  had to add an "r". the new code looks like:

class Parser:
    grammar = r'''
        start : STRING EOL
        STRING : /\w+/
        EOL : /\n/
    '''


问:
Iterate over two strings checking to see if it matches with its pair
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

```<code>    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }
</code>```

'''

答:
Make these refactorings:

To make the comparisons easy to code and understand, create a Map whose entires are each pair (both directions)

Iterate over the Strings up to the length of the shortest one, adding up the number of matching pairs as you go

The result is the length of the longest String minus the number of pairs

Like this:

```<code>public static int count_mismatches(String seq1, String seq2) {
    Map<Character, Character> pairs = Map.of('A', 'T', 'T', 'A', 'G', 'C', 'C', 'G');
    int count = 0;
    for (int i = 0; i < Math.min(seq1.length(), seq2.length()); i++) {
        if (pairs.get(seq1.charAt(i)) == seq2.charAt(i)) {
            count++;
        }
    }
    return Math.max(seq1.length(), seq2.length()) - count;
}
</code>```

See live demo, which returns 5 for your sample input.

Body:
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }

'''

Body:
Make these refactorings:

To make the comparisons easy to code and understand, create a Map whose entires are each pair (both directions)

Iterate over the Strings up to the length of the shortest one, adding up the number of matching pairs as you go

The result is the length of the longest String minus the number of pairs

Like this:

public static int count_mismatches(String seq1, String seq2) {
    Map<Character, Character> pairs = Map.of('A', 'T', 'T', 'A', 'G', 'C', 'C', 'G');
    int count = 0;
    for (int i = 0; i < Math.min(seq1.length(), seq2.length()); i++) {
        if (pairs.get(seq1.charAt(i)) == seq2.charAt(i)) {
            count++;
        }
    }
    return Math.max(seq1.length(), seq2.length()) - count;
}

See live demo, which returns 5 for your sample input.


问:
Error: Can't bind to 'ngIf' since it isn't a known property of 'form'
My problem is error with message: Can't bind to 'ngIf' since it isn't a known property of 'form'.

app.module.ts

```<code> @NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    UsersComponent,
    BackButtonComponent,
    BooksComponent,
    NewBookComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    AppRoutingModule,
    RouterModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    CommonModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
</code>```

new-user.component.html

```<code><form [formGroup]="entityForm" *ngIf="entityForm">
</form>
</code>```

new-user.component.ts

```<code>entity: User = new User();
entityForm: FormGroup;
</code>```

答: add your new-user component to the NgModule declarations</p>

Body:
My problem is error with message: Can't bind to 'ngIf' since it isn't a known property of 'form'.

app.module.ts

 @NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    UsersComponent,
    BackButtonComponent,
    BooksComponent,
    NewBookComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    AppRoutingModule,
    RouterModule,
    HttpClientModule,
    FormsModule,
    ReactiveFormsModule,
    CommonModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})

new-user.component.html

<form [formGroup]="entityForm" *ngIf="entityForm">
</form>

new-user.component.ts

entity: User = new User();
entityForm: FormGroup;


问:
IntelliJ does not show project folders
I have an issue with IntelliJ. It doesn't show any folders in my project view on the left.
My setting is "View As: Project"
How can I manage it so that the folders and packages are shown again?
I don't have any clue because I didn't change any options!

I'm using IntelliJ 10.0.3.
I am working on a Maven Lift Project.

答: for me removing the .idea folder from the project directory worked.

ContentLicense: CC BY-SA 3.0

Title: IntelliJ does not show project folders


问:
Get enum value by name stored in a string in PHP
I want to get the value of an Enum in PHP by its name.
My enum is like:

```<code>enum Status : int
{
    case ACTIVE = 1;
    case REVIEWED = 2;
    // ...
}
</code>```

Status::from(2) can be used to get "REVIEWED", but how can I resolve the value from the name stored in a string ?

答:
Well, it seems there is not any built-in solution in PHP. I've solve this with a custom function:

```<code>enum Status : int
{
    case ACTIVE = 1;
    case REVIEWED = 2;
    // ...

    public static function fromName(string $name): string
    {
        foreach (self::cases() as $status) {
            if( $name === $status->name ){
                return $status->value;
            }
        }
        throw new \ValueError("$name is not a valid backing value for enum " . self::class );
    }

}
</code>```

Then, I simply use Status::fromName('ACTIVE') and get 1

If you want to mimic the from and tryFrom enum functions, you can also add:

```<code>public static function tryFromName(string $name): string|null
{
    try {
        return self::fromName($name);
    } catch (\ValueError $error) {
        return null;
    }
}
</code>```

Body:
I want to get the value of an Enum in PHP by its name.
My enum is like:

enum Status : int
{
    case ACTIVE = 1;
    case REVIEWED = 2;
    // ...
}

Status::from(2) can be used to get "REVIEWED", but how can I resolve the value from the name stored in a string ?

Body:
Well, it seems there is not any built-in solution in PHP. I've solve this with a custom function:

enum Status : int
{
    case ACTIVE = 1;
    case REVIEWED = 2;
    // ...

    public static function fromName(string $name): string
    {
        foreach (self::cases() as $status) {
            if( $name === $status->name ){
                return $status->value;
            }
        }
        throw new \ValueError("$name is not a valid backing value for enum " . self::class );
    }

}

Then, I simply use Status::fromName('ACTIVE') and get 1

If you want to mimic the from and tryFrom enum functions, you can also add:

public static function tryFromName(string $name): string|null
{
    try {
        return self::fromName($name);
    } catch (\ValueError $error) {
        return null;
    }
}


问:
Item in list found but when I ask for location by index it says that the item can't be found
I am writing some code to get a list of certain counties in Florida for a database. These counties are listed on a website but are each on individual webpages. To make the collection process less tedious I am writing a webscraper. I have gotten the links to all of the websites with the counties. I have written code that will then inspect the website, find the line that says "COUNTY:" and then I want to get the location so I can actually get the county on the next line. The only problem is when I ask for the location it says it can't be found. I know it is in there because when I ask my code to find it and then return the line (Not the placement) it doesn't return empty. I will give some of the code for reference and an image of the problem.

Broken code:

```<code>links = ['https://www.ghosttowns.com/states/fl/acron.html', 'https://www.ghosttowns.com/states/fl/acton.html']
import requests
r = requests.get(links[1])
r = str(r.text)
r = r.split("\n")
county_before_location = [x for x in r if 'COUNTY' in x]
print(county_before_location)
print(r.index(county_before_location))
</code>```

Returns:

```<code>['    </font><b><font color="#80ff80">COUNTY:</font><font color="#ffffff">'] is not in list
</code>```

Code that shows the item:

```<code>links = ['https://www.ghosttowns.com/states/fl/acron.html', 'https://www.ghosttowns.com/states/fl/acton.html']
import requests
r = requests.get(links[1])
r = str(r.text)
r = r.split("\n")
county_before_location = [x for x in r if 'COUNTY' in x]
print(county_before_location)
</code>```

Returns:

```<code>['    </font><b><font color="#80ff80">COUNTY:</font><font color="#ffffff">']
</code>```

Photo

答: county_before_location is a list and you are asking for the index of said list, which is not in r. Instead you would need to ask for r.index(county_before_location[0]).

Body:
I am writing some code to get a list of certain counties in Florida for a database. These counties are listed on a website but are each on individual webpages. To make the collection process less tedious I am writing a webscraper. I have gotten the links to all of the websites with the counties. I have written code that will then inspect the website, find the line that says "COUNTY:" and then I want to get the location so I can actually get the county on the next line. The only problem is when I ask for the location it says it can't be found. I know it is in there because when I ask my code to find it and then return the line (Not the placement) it doesn't return empty. I will give some of the code for reference and an image of the problem.

Broken code:

links = ['https://www.ghosttowns.com/states/fl/acron.html', 'https://www.ghosttowns.com/states/fl/acton.html']
import requests
r = requests.get(links[1])
r = str(r.text)
r = r.split("\n")
county_before_location = [x for x in r if 'COUNTY' in x]
print(county_before_location)
print(r.index(county_before_location))

Returns:

['    COUNTY:'] is not in list

Code that shows the item:

links = ['https://www.ghosttowns.com/states/fl/acron.html', 'https://www.ghosttowns.com/states/fl/acton.html']
import requests
r = requests.get(links[1])
r = str(r.text)
r = r.split("\n")
county_before_location = [x for x in r if 'COUNTY' in x]
print(county_before_location)

Returns:

['    COUNTY:']

Photo


问:
Customize PlaneGeometry edges for each segment in ThreeJS
Currently PlaneGeometry has an option to change segment width and height but this has no effect on edges. Each segment currently has indexed positions to create an 'N' shape when viewing the geometry in wireframe mode:

Indexes currently are:

0 = South West

1 = North West

2 = South East

3 = North East

This gives us an 'N' shape for each segment with wireframes, however instead of this 'N' Shape i would like to create an 'X' shape with edges for every segment. Currently i'm using planes to create different heights and having an 'X' shape would make the result look less edgy shaped (screenshots below).

I think all required vertices already exists, but how is it possible to get an extra edge between point 0 and 3 for each segment?

I've tried looking for the answer online but couldn't find a clear answer on this matter, besides many articles are older than version R125 which made breaking changes to Geometries. Currently I'm using version R135.

I'm guessing i will need to create a custom Buffer Geometry, but am in doubt of how to execute this properly and not losing too much performance.

All red and blue lines are currently existing edges in wireframe mode.

All green lines are desired and currently not existing, what would be the best way to do this without losing performance?

Thanks in advance!

答:
It took me a fair amount of attempts but in the end it didn't turn out to be too hard. I've created this custom PlaneGeometry by creating a custom BufferGeometry. Although it's probably 3x heavier to use;

At the moment it holds 36 (12 * 3) positions per tile segment as where the default PlaneGeometry holds 12 (4 * 3) positions. Although i'm not sure if 3x more positions automatically means 3x more performance usage, but it definitely uses more than the default PlaneGeometry.

Here are the results (changes in height smoothen out prettier):

Code to create the geometry:

```<code>    const geometry = new THREE.BufferGeometry();
    const vertices = new Float32Array([

        // (North Face)
        .5, -.5, 0, // 0:  Center
        1, -1, 0,   // 1:  NE
        1, 0, 0,    // 2:  NW

        // (East Face)
        .5, -.5, 0, // 3:  Center
        0, -1, 0,   // 4:  SE
        1, -1, 0,   // 5:  NE

        // (South Face)
        .5, -.5, 0, // 6:  Center
        0, 0, 0,    // 7:  SW
        0, -1, 0,   // 8:  SE

        // (West Face)
        .5, -.5, 0, // 9:  Center
        1, 0, 0,    // 10: NW
        0, 0, 0,    // 11: SW

    ]);

    geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );

    const material = new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true  } );
    const mesh = new THREE.Mesh( geometry, material );

    mesh.rotation.x = - Math.PI / 2;
    scene.add( mesh );
</code>```

Body:
It took me a fair amount of attempts but in the end it didn't turn out to be too hard. I've created this custom PlaneGeometry by creating a custom BufferGeometry. Although it's probably 3x heavier to use;

At the moment it holds 36 (12 * 3) positions per tile segment as where the default PlaneGeometry holds 12 (4 * 3) positions. Although i'm not sure if 3x more positions automatically means 3x more performance usage, but it definitely uses more than the default PlaneGeometry.

Here are the results (changes in height smoothen out prettier):

Code to create the geometry:

    const geometry = new THREE.BufferGeometry();
    const vertices = new Float32Array([

        // (North Face)
        .5, -.5, 0, // 0:  Center
        1, -1, 0,   // 1:  NE
        1, 0, 0,    // 2:  NW

        // (East Face)
        .5, -.5, 0, // 3:  Center
        0, -1, 0,   // 4:  SE
        1, -1, 0,   // 5:  NE

        // (South Face)
        .5, -.5, 0, // 6:  Center
        0, 0, 0,    // 7:  SW
        0, -1, 0,   // 8:  SE

        // (West Face)
        .5, -.5, 0, // 9:  Center
        1, 0, 0,    // 10: NW
        0, 0, 0,    // 11: SW

    ]);

    geometry.setAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );

    const material = new THREE.MeshBasicMaterial( { color: 0xffffff, wireframe: true  } );
    const mesh = new THREE.Mesh( geometry, material );

    mesh.rotation.x = - Math.PI / 2;
    scene.add( mesh );


问:
Converting string with datetime value to one with date and time in C/C++ on Visual Studio
I am developing a C++ application on Visual Studio in which I have a string that contains a datetime value and I must convert it into another string with the date and time in the format dd-mm-yyyy HH:MM:SS

For example, if the string sDateTime has the value "1643873040", I must get another string sDateAndTime with the value "02/03/2022, 08:24:00"

I have not found any tutorials or forums that explain how to do this conversion in a C or C++ program developed with Visual Studio and I would appreciate any help or suggestions.

答:
I have modified the previous example, obtained based on your answers, so that now it works in VisualStudio:

```<code>    uint64_t timeStamp = 0;

    std::istringstream iss("1550267535");
    iss >> timeStamp;

    time_t localTime = timeStamp;

    struct tm timeInfo;
    localtime_s(&timeInfo, &localTime);

    printf ("%d-%02d-%02d %02d:%02d:%02d",
        1900 + timeInfo.tm_year, timeInfo.tm_mon, timeInfo.tm_mday,
        timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);

</code>```

Thanks a lot.

Body:
I have modified the previous example, obtained based on your answers, so that now it works in VisualStudio:

    uint64_t timeStamp = 0;

    std::istringstream iss("1550267535");
    iss >> timeStamp;

    time_t localTime = timeStamp;

    struct tm timeInfo;
    localtime_s(&timeInfo, &localTime);

    printf ("%d-%02d-%02d %02d:%02d:%02d",
        1900 + timeInfo.tm_year, timeInfo.tm_mon, timeInfo.tm_mday,
        timeInfo.tm_hour, timeInfo.tm_min, timeInfo.tm_sec);

Thanks a lot.


问:
File Not Found exception: (file exists) - after manually deleting it
I've stumbled upon an issue that has been puzzling me. I'm writing an app that creates mp3 files on the external storage. The thing is, if I manually go to the created directory on the phone and delete the file, whenever I try to the create the same file it throws this error:

java.io.FileNotFoundException: /storage/emulated/0/Ringtones/sound1.mp3: open failed: EEXIST (File exists)

Selecting other sounds to be created works just fine, but after I manually delete them they can't be created again due to that issue.

I've already tried deleting the file right after indicating the path and before FileOutputStream but didn't work.

Any tips?
Cheers.

答:
You need to acknowledge the media database before trying to create another copy of the same file. So you need to call this before copying:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(folder path in which your file was)));

Edit: The above answer is deprecated! Please use the following method:

```<code>File file = new File(outputPath + fileName);
String filePath = file.toString();
String mimeType = "video/mp4";

MediaScannerConnection.scanFile(this, new String[]{filePath}, new String[]{mimeType}, null);
</code>```

Example of outputPath and fileName:

```<code>String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "My App Name") + "/";
String fileName = "break dance" + ".mp4";
</code>```

So the File file should be the path of the media you want to update either because it's just deleted or it's newly added, to be visible in Gallery.

Body:
You need to acknowledge the media database before trying to create another copy of the same file. So you need to call this before copying:

sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(folder path in which your file was)));

Edit: The above answer is deprecated! Please use the following method:

File file = new File(outputPath + fileName);
String filePath = file.toString();
String mimeType = "video/mp4";

MediaScannerConnection.scanFile(this, new String[]{filePath}, new String[]{mimeType}, null);

Example of outputPath and fileName:

String outputPath = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), "My App Name") + "/";
String fileName = "break dance" + ".mp4";

So the File file should be the path of the media you want to update either because it's just deleted or it's newly added, to be visible in Gallery.


问:
How to find the one hour period with the most datapoints?
I have a database table with hundreds of thousands of forum posts, and I would like to find out what hour-long period contains the most number of posts.

I could crawl forward one minute at a time, keeping an array of timestamps and keeping track of what hour had the most in it, but I feel like there is a much better way to do this. I will be running this operation on a year of posts so checking every minute in a year seems pretty awful.

Ideally there would be a way to do this inside a single database query.

答:
This will do it.

SELECT DateOfEvent HourBegin, DATEADD(hh, 1, DateOfEvent)) HourEnd, COUNT(*) AS NumEventsPerHour
FROM tEvents AS A
JOIN tEvents AS B
ON A.DateOfEvent >= B.DateOfEvents AND DATEADD(hh, 1, A.DateOfEvent) <= B.DateOfEvent
GROUP BY A.DateOfEvent

OwnerDisplayName: OverloadUT

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Sam


问:
PHP/Magento - Variables within foreach not being updated properly
I'm having problems with a foreach loop in a magento template:

```<code>$cats = Mage::helper('catalog/category')->getStoreCategories();
foreach ($cats as $cat) {
    if($cat->getIsActive()&&$cat->getProductCount()) {
        echo "<div class=\"grid_6\">";
        echo $this->getLayout()->createBlock('catalog/product_new')
            ->setTemplate('catalog/product/new.phtml')
            ->setCategoryId($cat->getId())
            ->setColumnCount(2)
            ->setBlockTitle("Just Added in <a href=".$cat->getUrl().">".$cat->getName()."</a>")
            ->toHtml();
        echo "</div>";
    }
}
</code>```

Results in an identical block being repeated 4 times (I have 4 main categories) when it should show 4 different blocks, one for each category.  It's as if the $cat->getId(), $cat->getName() and $cat->getUrl() statements are not being updated on each new iteration.

What am I doing wrong here?

Thanks...

答:
Just a guess here, but it looks like the catalog/product_new block wasn't designed to be used multiple times on one request.  If you look at the class definition in Mage_Catalog_Block_Product_New, its pseudo-constructor includes the following

```<code>    $this->addData(array(
        'cache_lifetime'    => 86400,
        'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
    ));
</code>```

The presence of a cache_lifetime and cache_tags property are hints to Magento's Layout rendering system that this block should be cached.

So, what's happening is the first time you render the block, the results are cached.  The next time you render the block, instead of re-rendering this the results are pulled out of cache.

My advice here would be to create a custom code module, write a new block class that extends the old block class and redefines either _construct or getCacheKeyInfo in a such a way that you're "allowed" to render the Block multiple times.

Body:
I'm having problems with a foreach loop in a magento template:

$cats = Mage::helper('catalog/category')->getStoreCategories();
foreach ($cats as $cat) {
    if($cat->getIsActive()&&$cat->getProductCount()) {
        echo "
";
        echo $this->getLayout()->createBlock('catalog/product_new')
            ->setTemplate('catalog/product/new.phtml')
            ->setCategoryId($cat->getId())
            ->setColumnCount(2)
            ->setBlockTitle("Just Added in getUrl().">".$cat->getName()."")
            ->toHtml();
        echo "
";
    }
}

Results in an identical block being repeated 4 times (I have 4 main categories) when it should show 4 different blocks, one for each category.  It's as if the $cat->getId(), $cat->getName() and $cat->getUrl() statements are not being updated on each new iteration.

What am I doing wrong here?

Thanks...

Body:
Just a guess here, but it looks like the catalog/product_new block wasn't designed to be used multiple times on one request.  If you look at the class definition in Mage_Catalog_Block_Product_New, its pseudo-constructor includes the following

    $this->addData(array(
        'cache_lifetime'    => 86400,
        'cache_tags'        => array(Mage_Catalog_Model_Product::CACHE_TAG),
    ));

The presence of a cache_lifetime and cache_tags property are hints to Magento's Layout rendering system that this block should be cached.

So, what's happening is the first time you render the block, the results are cached.  The next time you render the block, instead of re-rendering this the results are pulled out of cache.

My advice here would be to create a custom code module, write a new block class that extends the old block class and redefines either _construct or getCacheKeyInfo in a such a way that you're "allowed" to render the Block multiple times.


问:
how can i turn of kinematics using any kind of collision
i have this wall and would like to turn off the kinematics thats holding up each brick using any type of collision any ideas?enter image description here</p>

答:
```<code>public GameObject cube;

private void OnCollisionEnter(Collision collision)
{
    if (collision.gameObject.CompareTag("KineOff"))
    {
     Rigidbody cubeRigidbody = cube.GetComponent<Rigidbody> ();
     cubeRigidbody.isKinematic = false;
    }
}
</code>```


问:
tkinter upload image and save it to local directory
I want the user to select a file an then save it on a local directory.

This is my current code.

```<code>def open_file(self):
    curr_directory = os.getcwd()
    self.file_path = askopenfilename(initialdir=curr_directory, title="Select Image", filetypes=[('Image Files', '*.jpg')])
    if self.file_path is not None:
        pass

def uploadFiles(self):
    curr_directory = os.getcwd()
    os.chdir(curr_directory + "/images")

    completeName = os.path.join(os.getcwd(), "test.jpg")

    file = open(self.file_path, 'r')

    file1 = open(completeName, "w")
    file1.write(file.read())
    file.close()
    file1.close()
    os.chdir(curr_directory)
</code>```

Although it creates the file, it is empty. Any help?

答:
I believe I can help with the saving. To save it use this:</p>
```<code>img = open_file() #Whatever the given image is
save_path = "/images"
file_name = "test.jpg"
complete_name = os.path.join(save_path, file_name)
img.save(complete_name) #This adds it to the directory
</code>```

Body:
I want the user to select a file an then save it on a local directory.

This is my current code.

def open_file(self):
    curr_directory = os.getcwd()
    self.file_path = askopenfilename(initialdir=curr_directory, title="Select Image", filetypes=[('Image Files', '*.jpg')])
    if self.file_path is not None:
        pass

def uploadFiles(self):
    curr_directory = os.getcwd()
    os.chdir(curr_directory + "/images")

    completeName = os.path.join(os.getcwd(), "test.jpg")

    file = open(self.file_path, 'r')

    file1 = open(completeName, "w")
    file1.write(file.read())
    file.close()
    file1.close()
    os.chdir(curr_directory)

Although it creates the file, it is empty. Any help?

Body:
I believe I can help with the saving. To save it use this:

img = open_file() #Whatever the given image is
save_path = "/images"
file_name = "test.jpg"
complete_name = os.path.join(save_path, file_name)
img.save(complete_name) #This adds it to the directory


问:
Allow only specific special characters with 3-15 length of digits regex
This is what is have tried

^(?=.(?=.?[+-,() ]))(?:\D*\d){3,15}\D*$

a regex that follows the following parameters:

Minimum length of digits not including special characters: 3

The maximum length of digits not including special characters: 15

The total number of digits has to be between 3,15

Space and Special characters allowed: '+', '-', '(', ')', ' '

No alphabets allowed

The length of the string is determined by the number of digits.
There can be n number of special characters in the string, but the length of the digit should not exceed 15.

The acceptable responses are

((((((((((12345 (Valid)

123---------------- (Valid)

123-5678-9123456 (Valid)

((((( (Invalid)

((((((((((123(Valid)

 122!!!!!(invalid)

The regex used here is accepting the response when at least one special is present. However, if anything is present beside  '+', '-', '(', ')', ' ' and digits, it's should not match

答:
You can use

^(?:[(),+ -]*\d){3,15}[(),+ -]*$
```

See the regex demo. Details:

^ - start of string

(?:[(),+ -]*\d){3,15} - three to fifteen sequences of a (, ), ,, +, space or - char and then any digit

[(),+ -]* - zero or more chars from the (, ), ,, +, space or - charset.

$ - end of string.

Body:
You can use

^(?:[(),+ -]*\d){3,15}[(),+ -]*$

See the regex demo. Details:

^ - start of string

(?:[(),+ -]*\d){3,15} - three to fifteen sequences of a (, ), ,, +, space or - char and then any digit

[(),+ -]* - zero or more chars from the (, ), ,, +, space or - charset.

$ - end of string.


问:
R shinydashboard collapsible menuItem with inputs
I am trying to implement a fileInput using library(shinydashboard) to provide the user with the option to upload files (as it was done here with a basic shiny UI - please find the example code below).

I would like to place the fileInput in the dashboardSidebar in an expandable menuItem, but don't know where it should go into the shinydashboard structure.

```<code>library(shiny)

ui <- fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),
      tags$hr(),
      checkboxInput("header", "Header", TRUE),
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)

server <- function(input, output) {
  output$contents <- renderTable({
    req(input$file1)
    df <- read.csv(input$file1$datapath,
                   header = input$header,
                   sep = input$sep,
                   quote = input$quote)
    if(input$disp == "head") {
      return(head(df))
    }
    else {
      return(df)
    }
  })
}

shinyApp(ui, server)
</code>```

答:
Edit: I cleaned up the code a little to make the difference between childfull and childless menuItem's more clear - the parameters expandedName and startExpanded can only be used with a childfull menuItem in contrast tabName and selected is only used with childless menuItem's.

```<code>library(shiny)
library(shinydashboard)

ui <- function(req) {
  dashboardPage(
    dashboardHeader(title = "Simple tabs"),
    dashboardSidebar(sidebarMenu(
      id = "sidebarItemSelected",
      menuItem(
        "Childfull menuItem",
        menuItem(
          "Childless menuItem 1",
          tabName = "childlessTab1",
          icon = icon("dashboard"),
          selected = TRUE
        ),
        fileInput("upload", "Upload"),
        bookmarkButton(),
        expandedName = "childfullMenuItem",
        startExpanded = TRUE
      ),
      menuItem(
        "Childless menuItem 2",
        icon = icon("th"),
        tabName = "childlessTab2",
        badgeLabel = "new",
        badgeColor = "green"
      )
    )),
    dashboardBody(tabItems(
      tabItem(tabName = "childlessTab1",
              h2("Dashboard tab content")),

      tabItem(tabName = "childlessTab2",
              h2("Widgets tab content"))
    ))
  )
}

server <- function(input, output, session) {
  observe({
    cat(
      paste(
        "\nsidebarItemSelected:",
        input$sidebarItemSelected,
        "\nsidebarItemExpanded:",
        input$sidebarItemExpanded,
        "\nsidebarCollapsed:",
        input$sidebarCollapsed,
        "\n"
      )
    )
  })
}

shinyApp(ui, server, enableBookmarking = "url")
</code>```

Initial answer:

Sure - this is possible (modified version of this example):

```<code>library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Simple tabs"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Dashboard", fileInput("upload", "Upload"), tabName = "dashboard", icon = icon("dashboard")),
      menuItem("Widgets", icon = icon("th"), tabName = "widgets",
               badgeLabel = "new", badgeColor = "green")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "dashboard",
              h2("Dashboard tab content")
      ),

      tabItem(tabName = "widgets",
              h2("Widgets tab content")
      )
    )
  )
)

server <- function(input, output, session) {}

shinyApp(ui, server)
</code>```

Body:
I am trying to implement a fileInput using library(shinydashboard) to provide the user with the option to upload files (as it was done here with a basic shiny UI - please find the example code below).

I would like to place the fileInput in the dashboardSidebar in an expandable menuItem, but don't know where it should go into the shinydashboard structure.

library(shiny)

ui <- fluidPage(
  titlePanel("Uploading Files"),
  sidebarLayout(
    sidebarPanel(
      fileInput("file1", "Choose CSV File",
                multiple = TRUE,
                accept = c("text/csv",
                           "text/comma-separated-values,text/plain",
                           ".csv")),
      tags$hr(),
      checkboxInput("header", "Header", TRUE),
      radioButtons("sep", "Separator",
                   choices = c(Comma = ",",
                               Semicolon = ";",
                               Tab = "\t"),
                   selected = ","),
      radioButtons("quote", "Quote",
                   choices = c(None = "",
                               "Double Quote" = '"',
                               "Single Quote" = "'"),
                   selected = '"'),
      tags$hr(),
      radioButtons("disp", "Display",
                   choices = c(Head = "head",
                               All = "all"),
                   selected = "head")
    ),
    mainPanel(
      tableOutput("contents")
    )
  )
)

server <- function(input, output) {
  output$contents <- renderTable({
    req(input$file1)
    df <- read.csv(input$file1$datapath,
                   header = input$header,
                   sep = input$sep,
                   quote = input$quote)
    if(input$disp == "head") {
      return(head(df))
    }
    else {
      return(df)
    }
  })
}

shinyApp(ui, server)

Body:
Edit: I cleaned up the code a little to make the difference between childfull and childless menuItem's more clear - the parameters expandedName and startExpanded can only be used with a childfull menuItem in contrast tabName and selected is only used with childless menuItem's.

library(shiny)
library(shinydashboard)

ui <- function(req) {
  dashboardPage(
    dashboardHeader(title = "Simple tabs"),
    dashboardSidebar(sidebarMenu(
      id = "sidebarItemSelected",
      menuItem(
        "Childfull menuItem",
        menuItem(
          "Childless menuItem 1",
          tabName = "childlessTab1",
          icon = icon("dashboard"),
          selected = TRUE
        ),
        fileInput("upload", "Upload"),
        bookmarkButton(),
        expandedName = "childfullMenuItem",
        startExpanded = TRUE
      ),
      menuItem(
        "Childless menuItem 2",
        icon = icon("th"),
        tabName = "childlessTab2",
        badgeLabel = "new",
        badgeColor = "green"
      )
    )),
    dashboardBody(tabItems(
      tabItem(tabName = "childlessTab1",
              h2("Dashboard tab content")),

      tabItem(tabName = "childlessTab2",
              h2("Widgets tab content"))
    ))
  )
}

server <- function(input, output, session) {
  observe({
    cat(
      paste(
        "\nsidebarItemSelected:",
        input$sidebarItemSelected,
        "\nsidebarItemExpanded:",
        input$sidebarItemExpanded,
        "\nsidebarCollapsed:",
        input$sidebarCollapsed,
        "\n"
      )
    )
  })
}

shinyApp(ui, server, enableBookmarking = "url")

Initial answer:

Sure - this is possible (modified version of this example):

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Simple tabs"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Dashboard", fileInput("upload", "Upload"), tabName = "dashboard", icon = icon("dashboard")),
      menuItem("Widgets", icon = icon("th"), tabName = "widgets",
               badgeLabel = "new", badgeColor = "green")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "dashboard",
              h2("Dashboard tab content")
      ),

      tabItem(tabName = "widgets",
              h2("Widgets tab content")
      )
    )
  )
)

server <- function(input, output, session) {}

shinyApp(ui, server)


问:
How to move a glTF model in the direction it is facing in A-frame?
I have a gltf model of my robot loaded in A-frame scene version 1.0.4. So far I can turn the robot about its x,y, z axes, but when I try to move it forward it still moves in its initial direction rather than the direction it's facing. I want to be able to control its movements with my keyboard without using any external libraries. I believe I have to use Quaternions, but I haven't figured out how to use them yet. Here is my A-frame code so far.

```
</div>
</div>
</p>
<p>And here is my script</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const robot = document.getElementById('robot');

const update = () => {
   if (keys.forward) {
       let {x,y,z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z += Math.cos(ry * Math.PI/180)/12;
       x += Math.sin(ry * Math.PI/180)/12;
       robot.object3D.position.set(x, y, z);
}
   else if (keys.backwards) {
       let {x, y, z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z -= Math.cos(ry * Math.PI/180)/10;
       x -= Math.sin(ry * Math.PI/180)/10;
       robot.object3D.position.set(x, y, z);
}
 if (keys.turnLeft) {
       let {x, y, z} = robot.getAttribute('rotation');
       y += 0.25;
       robot.setAttribute('rotation',{x,y,z});
}
    else if (keys.turnRight) {
        let {x, y, z} = robot.getAttribute('rotation');
        y -= 0.25;
        robot.setAttribute('rotation',{x,y,z});
}
}</code>```

答:
```<code>let ry = robot.object3D.rotation.y;
z += Math.cos(ry * Math.PI/180)/12;
</code>```

Although a-frame uses degrees for rotation, threejs uses radians, so there is no need to convert them again:

const robot = document.querySelector("a-box")
document.body.addEventListener("keydown", (evt) => {
   if (evt.key === 's') {
       let {x,y,z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z += Math.cos(ry)/12;
       x += Math.sin(ry)/12;
       robot.object3D.position.set(x, y, z);
    } else if (evt.key === 'w') {
       let {x, y, z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       console.log(ry)
       z -= Math.cos(ry)/10;
       x -= Math.sin(ry)/10;
       robot.object3D.position.set(x, y, z);
     }
     if (evt.key === 'a') {
       let {x, y, z} = robot.getAttribute('rotation');
       y += 1;
       robot.setAttribute('rotation',{x,y,z});
     } else if (evt.key === 'd') {
       let {x, y, z} = robot.getAttribute('rotation');
       y -= 1;
       robot.setAttribute('rotation',{x: x,y: y,z: z});
     }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<a-scene>
  <a-box position="-1 0.5 -3" rotation="0 0 0" color="#4CC3D9">
    <a-sphere radius="0.5" position="0 0 -1"></a-sphere>
  </a-box>
  <a-entity camera position="0 1.6 0"></a-entity>
</a-scene></code>```

Same with getWorldDirection:

const robot = document.querySelector("a-box")
const direction = new THREE.Vector3();
document.body.addEventListener("keydown", (evt) => {
   if (evt.key === 's') {
     // get robot direction
     robot.object3D.getWorldDirection(direction);
     // add a "speed" value
     direction.multiplyScalar(0.1)
     // add the new vector to the actual position
     robot.object3D.position.add(direction)
    } else if (evt.key === 'w') {
     robot.object3D.getWorldDirection(direction);
     direction.multiplyScalar(-0.1)
     robot.object3D.position.add(direction)
    }
    if (evt.key === 'a') {
     let {x, y, z} = robot.getAttribute('rotation');
     y=y+1
     robot.setAttribute('rotation',{x,y,z});
    } else if (evt.key === 'd') {
     let {x, y, z} = robot.getAttribute('rotation');
     y=y-1
     robot.setAttribute('rotation',{x: x,y: y,z: z});
    }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<a-scene>
  <a-box position="-1 0.5 -3" rotation="0 0 0" color="#4CC3D9">
    <a-sphere radius="0.5" position="0 0 -1"></a-sphere>
  </a-box>
  <a-entity camera position="0 1.6 0"></a-entity>
</a-scene></code>```

Body:
I have a gltf model of my robot loaded in A-frame scene version 1.0.4. So far I can turn the robot about its x,y, z axes, but when I try to move it forward it still moves in its initial direction rather than the direction it's facing. I want to be able to control its movements with my keyboard without using any external libraries. I believe I have to use Quaternions, but I haven't figured out how to use them yet. Here is my A-frame code so far.

And here is my script

const robot = document.getElementById('robot');

const update = () => {
   if (keys.forward) {
       let {x,y,z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z += Math.cos(ry * Math.PI/180)/12;
       x += Math.sin(ry * Math.PI/180)/12;
       robot.object3D.position.set(x, y, z);
}
   else if (keys.backwards) {
       let {x, y, z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z -= Math.cos(ry * Math.PI/180)/10;
       x -= Math.sin(ry * Math.PI/180)/10;
       robot.object3D.position.set(x, y, z);
}
 if (keys.turnLeft) {
       let {x, y, z} = robot.getAttribute('rotation');
       y += 0.25;
       robot.setAttribute('rotation',{x,y,z});
}
    else if (keys.turnRight) {
        let {x, y, z} = robot.getAttribute('rotation');
        y -= 0.25;
        robot.setAttribute('rotation',{x,y,z});
}
}

Body:
let ry = robot.object3D.rotation.y;
z += Math.cos(ry * Math.PI/180)/12;

Although a-frame uses degrees for rotation, threejs uses radians, so there is no need to convert them again:

const robot = document.querySelector("a-box")
document.body.addEventListener("keydown", (evt) => {
   if (evt.key === 's') {
       let {x,y,z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       z += Math.cos(ry)/12;
       x += Math.sin(ry)/12;
       robot.object3D.position.set(x, y, z);
    } else if (evt.key === 'w') {
       let {x, y, z} = robot.object3D.position;
       let ry = robot.object3D.rotation.y;
       console.log(ry)
       z -= Math.cos(ry)/10;
       x -= Math.sin(ry)/10;
       robot.object3D.position.set(x, y, z);
     }
     if (evt.key === 'a') {
       let {x, y, z} = robot.getAttribute('rotation');
       y += 1;
       robot.setAttribute('rotation',{x,y,z});
     } else if (evt.key === 'd') {
       let {x, y, z} = robot.getAttribute('rotation');
       y -= 1;
       robot.setAttribute('rotation',{x: x,y: y,z: z});
     }
})

<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<a-scene>
  <a-box position="-1 0.5 -3" rotation="0 0 0" color="#4CC3D9">
    <a-sphere radius="0.5" position="0 0 -1"></a-sphere>
  </a-box>
  <a-entity camera position="0 1.6 0"></a-entity>
</a-scene>

Same with getWorldDirection:

const robot = document.querySelector("a-box")
const direction = new THREE.Vector3();
document.body.addEventListener("keydown", (evt) => {
   if (evt.key === 's') {
     // get robot direction
     robot.object3D.getWorldDirection(direction);
     // add a "speed" value
     direction.multiplyScalar(0.1)
     // add the new vector to the actual position
     robot.object3D.position.add(direction)
    } else if (evt.key === 'w') {
     robot.object3D.getWorldDirection(direction);
     direction.multiplyScalar(-0.1)
     robot.object3D.position.add(direction)
    }
    if (evt.key === 'a') {
     let {x, y, z} = robot.getAttribute('rotation');
     y=y+1
     robot.setAttribute('rotation',{x,y,z});
    } else if (evt.key === 'd') {
     let {x, y, z} = robot.getAttribute('rotation');
     y=y-1
     robot.setAttribute('rotation',{x: x,y: y,z: z});
    }
})

<script src="https://aframe.io/releases/1.3.0/aframe.min.js"></script>
<a-scene>
  <a-box position="-1 0.5 -3" rotation="0 0 0" color="#4CC3D9">
    <a-sphere radius="0.5" position="0 0 -1"></a-sphere>
  </a-box>
  <a-entity camera position="0 1.6 0"></a-entity>
</a-scene>


问:
The transaction declared chain ID 5777, but the connected node is on 1337
I am trying to deploy my SimpleStorage.sol contract to a ganache local chain by making a transaction using python. It seems to have trouble connecting to the chain.

```<code>from solcx import compile_standard
from web3 import Web3
import json
import os
from dotenv import load_dotenv

load_dotenv()

with open("./SimpleStorage.sol", "r") as file:
    simple_storage_file = file.read()

compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
        "settings": {
            "outputSelection": {
                "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"]}
            }
        },
    },
    solc_version="0.6.0",
)

with open("compiled_code.json", "w") as file:
    json.dump(compiled_sol, file)

# get bytecode
bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
    "bytecode"
]["object"]

# get ABI
abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]

# to connect to ganache blockchain
w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545"))
chain_id = 5777
my_address = "0xca1EA31e644F13E3E36631382686fD471c62267A"
private_key = os.getenv("PRIVATE_KEY")

# create the contract in python

SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)

# get the latest transaction
nonce = w3.eth.getTransactionCount(my_address)

# 1. Build a transaction
# 2. Sign a transaction
# 3. Send a transaction

transaction = SimpleStorage.constructor().buildTransaction(
    {"chainId": chain_id, "from": my_address, "nonce": nonce}
)
print(transaction)

</code>```

It seems to be connected to the ganache chain because it prints the nonce, but when I build and try to print the transaction
here is the entire traceback call I am receiving

```<code>Traceback (most recent call last):
File "C:\Users\evens\demos\web3_py_simple_storage\deploy.py", line
52, in <module>
transaction = SimpleStorage.constructor().buildTransaction(
File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
18, in _wrapper
return self.method(obj, *args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\contract.py", line 684, in buildTransaction
return fill_transaction_defaults(self.web3, built_transaction)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\_utils\transactions.py", line 114, in
fill_transaction_defaults
default_val = default_getter(web3, transaction)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\_utils\transactions.py", line 60, in <lambda>
'gas': lambda web3, tx: web3.eth.estimate_gas(tx),
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\eth.py", line 820, in estimate_gas
return self._estimate_gas(transaction, block_identifier)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\manager.py", line 197, in request_blocking
response = self._make_request(method, params)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\manager.py", line 150, in _make_request
return request_func(method, params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 76, in
apply_formatters
response = make_request(method, params)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\gas_price_strategy.py", line 90, in
middleware
return make_request(method, params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 74, in
apply_formatters
response = make_request(method, formatted_params)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\attrdict.py", line 33, in middleware
response = make_request(method, params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 74, in
apply_formatters
response = make_request(method, formatted_params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 73, in
apply_formatters
formatted_params = formatter(params)
File "cytoolz/functoolz.pyx", line 503, in
cytoolz.functoolz.Compose.__call__
ret = PyObject_Call(self.first, args, kwargs)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
91, in wrapper
return ReturnType(result)  # type: ignore
File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
22, in apply_formatter_at_index
yield formatter(item)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
72, in apply_formatter_if
return formatter(value)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\validation.py", line 57, in
validate_chain_id
raise ValidationError(
web3.exceptions.ValidationError: The transaction declared chain ID
5777, but the connected node is on 1337
</code>```

答:
Hey it happened to me too, you need to build the constructor like this

```<code> SimpleStorage.constructor().buildTransaction( {
    "gasPrice": w3.eth.gas_price,
    "chainId": chain_id,
    "from": my_address,
    "nonce": nonce,
</code>```

You need to add the gas price part.
Worked for me

Body:
I am trying to deploy my SimpleStorage.sol contract to a ganache local chain by making a transaction using python. It seems to have trouble connecting to the chain.

from solcx import compile_standard
from web3 import Web3
import json
import os
from dotenv import load_dotenv

load_dotenv()

with open("./SimpleStorage.sol", "r") as file:
    simple_storage_file = file.read()

compiled_sol = compile_standard(
    {
        "language": "Solidity",
        "sources": {"SimpleStorage.sol": {"content": simple_storage_file}},
        "settings": {
            "outputSelection": {
                "*": {"*": ["abi", "metadata", "evm.bytecode", "evm.sourceMap"]}
            }
        },
    },
    solc_version="0.6.0",
)

with open("compiled_code.json", "w") as file:
    json.dump(compiled_sol, file)

# get bytecode
bytecode = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["evm"][
    "bytecode"
]["object"]

# get ABI
abi = compiled_sol["contracts"]["SimpleStorage.sol"]["SimpleStorage"]["abi"]

# to connect to ganache blockchain
w3 = Web3(Web3.HTTPProvider("HTTP://127.0.0.1:7545"))
chain_id = 5777
my_address = "0xca1EA31e644F13E3E36631382686fD471c62267A"
private_key = os.getenv("PRIVATE_KEY")

# create the contract in python

SimpleStorage = w3.eth.contract(abi=abi, bytecode=bytecode)

# get the latest transaction
nonce = w3.eth.getTransactionCount(my_address)

# 1. Build a transaction
# 2. Sign a transaction
# 3. Send a transaction

transaction = SimpleStorage.constructor().buildTransaction(
    {"chainId": chain_id, "from": my_address, "nonce": nonce}
)
print(transaction)

It seems to be connected to the ganache chain because it prints the nonce, but when I build and try to print the transaction
here is the entire traceback call I am receiving

Traceback (most recent call last):
File "C:\Users\evens\demos\web3_py_simple_storage\deploy.py", line
52, in <module>
transaction = SimpleStorage.constructor().buildTransaction(
File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
18, in _wrapper
return self.method(obj, *args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\contract.py", line 684, in buildTransaction
return fill_transaction_defaults(self.web3, built_transaction)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\_utils\transactions.py", line 114, in
fill_transaction_defaults
default_val = default_getter(web3, transaction)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\_utils\transactions.py", line 60, in <lambda>
'gas': lambda web3, tx: web3.eth.estimate_gas(tx),
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\eth.py", line 820, in estimate_gas
return self._estimate_gas(transaction, block_identifier)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\module.py", line 57, in caller
result = w3.manager.request_blocking(method_str,
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\manager.py", line 197, in request_blocking
response = self._make_request(method, params)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\manager.py", line 150, in _make_request
return request_func(method, params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 76, in
apply_formatters
response = make_request(method, params)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\gas_price_strategy.py", line 90, in
middleware
return make_request(method, params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 74, in
apply_formatters
response = make_request(method, formatted_params)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\attrdict.py", line 33, in middleware
response = make_request(method, params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 74, in
apply_formatters
response = make_request(method, formatted_params)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\formatting.py", line 73, in
apply_formatters
formatted_params = formatter(params)
File "cytoolz/functoolz.pyx", line 503, in
cytoolz.functoolz.Compose.__call__
ret = PyObject_Call(self.first, args, kwargs)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Python310\lib\site-packages\eth_utils\decorators.py", line
91, in wrapper
return ReturnType(result)  # type: ignore
File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
22, in apply_formatter_at_index
yield formatter(item)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Python310\lib\site-packages\eth_utils\applicators.py", line
72, in apply_formatter_if
return formatter(value)
File "cytoolz/functoolz.pyx", line 250, in
cytoolz.functoolz.curry.__call__
return self.func(*args, **kwargs)
File "C:\Users\evens\AppData\Roaming\Python\Python310\site-
packages\web3\middleware\validation.py", line 57, in
validate_chain_id
raise ValidationError(
web3.exceptions.ValidationError: The transaction declared chain ID
5777, but the connected node is on 1337

Body:
Hey it happened to me too, you need to build the constructor like this

 SimpleStorage.constructor().buildTransaction( {
    "gasPrice": w3.eth.gas_price,
    "chainId": chain_id,
    "from": my_address,
    "nonce": nonce,

You need to add the gas price part.
Worked for me


答:
Good Evening,

Something seems off here, this snippet of code:

```<code>
     for(int i = 0; i < seq1.length(); i++)
       if (seq1.charAt(i) == seq2.charAt(i)) {
           break; //checks to see if the length of seq1 and seq2 are the same
       }

</code>```

Does not do what you think it does. This cycle will loop through all characters in sequence1 using i < seq1.length() and for each character that exists in seq1, it will check if said character is equal to the character with the same index in seq2.

This means that a correction is in order:

```<code>int countMismatches = 0;

 for(int i = 0; i < seq1.length();i++){
   switch(seq1.charAt(i)){
      case 'A':
         if(seq2.charAt(i) != 'T') countMismatches++;
         break;
   }
 }
</code>```

Repeat this process for the other letters, and voilá, you should be able to count your mismatches this way.

Do be careful with sequences having different lengths, as if that happens, as soon as you step out of a bound, you will receive an IndexOutOfBoundsException, indicating you've tried to check a character that does not exist.

Title: Iterate over two strings checking to see if it matches with its pair

Body:
I am still new to Java, and I am currently working on a program that will take two strings as arguments and return the number of mismatched pairs. For my program I am working with ATGC because in science, A's always match up with T's and G's always match up with C's. I cant quite figure out how to iterate over the strings and see that the first character in string one (T for example) matches up with its intended pair (A), and if it doesn't it is a mismatched pair and it should be added to a counter to be totaled at the end. I believe I can use something called charAt(), but I am unsure of how that works.

I also need to figure out how to be able to take the absolute value of counter before it is added to the finalCounter. The main reason for this is because I just want to worry about getting the length difference between the two rather than making sure that the longer string is subracted from the smaller string.

Any help would be greatly appreciated!

''''

    public class CountMismatches {

        public static void main(String[] args) {
            {
                String seq1 = "TTCGATGGAGCTGTA";
                String seq2 = "TAGCTAGCTCGGCATGA";
                System.out.println(count_mismatches(seq1, seq2))
                //*expected to print out 5 because there are 3 mismatched pairs and 2 that do not have a pair*
            }
        }

        public static int count_mismatches(String seq1, String seq2) {
            int mismatchCount = 0;
            int counter = seq1.length() - seq2.length();
            int finalCounter = mismatchCount + counter;

            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) == seq2.charAt(i)) {
                break; //checks to see if the length of seq1 and seq2 are the same
            }
            for(int i = 0; i < seq1.length(); i++) if (seq1.charAt(i) != seq2.charAt(i)) {
                return counter; //figure out how to do absolute value for negative numbers
            }
            return finalCounter;

        }
    }

'''

Body:
Good Evening,

Something seems off here, this snippet of code:

     for(int i = 0; i < seq1.length(); i++)
       if (seq1.charAt(i) == seq2.charAt(i)) {
           break; //checks to see if the length of seq1 and seq2 are the same
       }

Does not do what you think it does. This cycle will loop through all characters in sequence1 using i < seq1.length() and for each character that exists in seq1, it will check if said character is equal to the character with the same index in seq2.

This means that a correction is in order:

int countMismatches = 0;

 for(int i = 0; i < seq1.length();i++){
   switch(seq1.charAt(i)){
      case 'A':
         if(seq2.charAt(i) != 'T') countMismatches++;
         break;
   }
 }

Repeat this process for the other letters, and voilá, you should be able to count your mismatches this way.

Do be careful with sequences having different lengths, as if that happens, as soon as you step out of a bound, you will receive an IndexOutOfBoundsException, indicating you've tried to check a character that does not exist.