问:
can't display data in the table (angular 9)
enter image description here`     Hi ! i am using angular 9.1.7 , the code works correctly , and i succeed to get data from base , but i can't display them in the html table , i don't understand the source of this. you find below some source code , and thank you in advance

`

==>Interface package:
     public universites:Universite[];
      public universitesall:Universite[];
      public mot_cle:string="";
      constructor(private universitesService:UniversitesService) { }

      ngOnInit(): void {
        this.Afficheruniversites();
      }
      Afficheruniversites()`enter code here`
      {
        this.universitesService.tous_universites().subscribe(data=>{
          this.universites=data;
          this.universitesall=data;
          console.log(data);
        },err=>{console.log(err);
      })
      }

      ==>> model
      export class Universite {
        code_UNV:number
        nom_UNV:String
        adresse_site_UNV:String

        constructor(Code_uni:number, Nom_uni:String,Adr:String)
        {
            this.code_UNV=Code_uni;
            this.nom_UNV=Nom_uni;
            this.adresse_site_UNV=Adr;
        }
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>==>> Html
     <table *ngIf="universites" class="table table-striped">
                    <tr>
                        <th>
                            Code
                        </th>
                        <th>
                            Nom
                        </th>
                        <th>
                            Adresse
                        </th><th></th>
                        <tr *ngFor="let c of universites">
                            <td>
                                {{c.code_UNV}}
                            </td>
                            <td>
                                {{c.nom_UNV}}
                            </td>
                            <td>
                                {{c.adresse_site_UNV}}
                            </td>
                        </tr>
                </table></code>```

答:
```<code>   <table *ngIf="universites" class="table table-striped">
                    <tr>
                        <th>
                            Code
                        </th>
                        <th>
                            Nom
                        </th>
                        <th>
                            Adresse
                        </th><th></th>
                        </tr>
                        <tr *ngFor="let c of universites">
                            <td>
                                {{c.codeUNV}}
                            </td>
                            <td>
                                {{c.nomUNV}}
                            </td>
                            <td>
                                {{c.adresseSite}}
                            </td>
                        </tr>
                </table>
</code>```

Body:
enter image description here`     Hi ! i am using angular 9.1.7 , the code works correctly , and i succeed to get data from base , but i can't display them in the html table , i don't understand the source of this. you find below some source code , and thank you in advance

`

==>Interface package:
     public universites:Universite[];
      public universitesall:Universite[];
      public mot_cle:string="";
      constructor(private universitesService:UniversitesService) { }

      ngOnInit(): void {
        this.Afficheruniversites();
      }
      Afficheruniversites()`enter code here`
      {
        this.universitesService.tous_universites().subscribe(data=>{
          this.universites=data;
          this.universitesall=data;
          console.log(data);
        },err=>{console.log(err);
      })
      }

      ==>> model
      export class Universite {
        code_UNV:number
        nom_UNV:String
        adresse_site_UNV:String

        constructor(Code_uni:number, Nom_uni:String,Adr:String)
        {
            this.code_UNV=Code_uni;
            this.nom_UNV=Nom_uni;
            this.adresse_site_UNV=Adr;
        }
    }

==>> Html

                            Code

                            Nom

                            Adresse

                                {{c.code_UNV}}

                                {{c.nom_UNV}}

                                {{c.adresse_site_UNV}}


来源: stackexchange

问:
What do these Spring debug messages mean?
I use Spring IoC in my stand-alone Java application. When the application starts it creates a log with start-up info. Some messages I don't understand, please help me to understand them and explain how to fix them if they must be fixed? Also I am curious: Is there any danger for my application stability because of these messages?

Messages that scare me off starts with word "Unable". At the moment the application works quite well.

```<code>INFO - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: startup date     [Thu Jun 02 16:02:12 MSD 2011]; root of context hierarchy
INFO - Loading XML bean definitions from class path resource [application-config.xml]
DEBUG - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
DEBUG - Loading schema mappings from [META-INF/spring.schemas]
DEBUG - Loaded schema mappings: {http://www.springframework.org/schema/tx/spring-tx-2.5.xsd=org/springframework/transaction/config/spring-tx-2.5.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.0.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd}
DEBUG - Loading bean definitions
DEBUG - Loaded 3 bean definitions from location pattern [application-config.xml]
DEBUG - Bean factory for org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Creating shared instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating instance of bean 'propertyPlaceholderConfigurer'
DEBUG - Eagerly caching bean 'propertyPlaceholderConfigurer' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'propertyPlaceholderConfigurer'
INFO - Loading properties file from class path resource [config.properties]
DEBUG - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@49bdc9d8]
DEBUG - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@255d17d7]
INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Returning cached instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating shared instance of singleton bean 'dbWorker'
DEBUG - Creating instance of bean 'dbWorker'
DEBUG - Eagerly caching bean 'dbWorker' to allow for resolving potential circular references
DEBUG - Creating shared instance of singleton bean 'connectionPool'
DEBUG - Creating instance of bean 'connectionPool'
DEBUG - Eagerly caching bean 'connectionPool' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'connectionPool'
DEBUG - Finished creating instance of bean 'dbWorker'
DEBUG - Returning cached instance of singleton bean 'connectionPool'
DEBUG - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@4b1c2b67]
DEBUG - Returning cached instance of singleton bean 'lifecycleProcessor'
</code>```

答: This is just debug level output which you probably don't need. Essentially it's telling you that you haven't defined any particular classes which override its default functionality, so it's going to use the default functionality. There's nothing to worry about here.</p>

ContentLicense: CC BY-SA 3.0

Body:
I use Spring IoC in my stand-alone Java application. When the application starts it creates a log with start-up info. Some messages I don't understand, please help me to understand them and explain how to fix them if they must be fixed? Also I am curious: Is there any danger for my application stability because of these messages?

Messages that scare me off starts with word "Unable". At the moment the application works quite well.

INFO - Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: startup date     [Thu Jun 02 16:02:12 MSD 2011]; root of context hierarchy
INFO - Loading XML bean definitions from class path resource [application-config.xml]
DEBUG - Using JAXP provider [com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl]
DEBUG - Loading schema mappings from [META-INF/spring.schemas]
DEBUG - Loaded schema mappings: {http://www.springframework.org/schema/tx/spring-tx-2.5.xsd=org/springframework/transaction/config/spring-tx-2.5.xsd, http://www.springframework.org/schema/tx/spring-tx-2.0.xsd=org/springframework/transaction/config/spring-tx-2.0.xsd, http://www.springframework.org/schema/tx/spring-tx.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd, http://www.springframework.org/schema/tx/spring-tx-3.0.xsd=org/springframework/transaction/config/spring-tx-3.0.xsd}
DEBUG - Loading bean definitions
DEBUG - Loaded 3 bean definitions from location pattern [application-config.xml]
DEBUG - Bean factory for org.springframework.context.support.ClassPathXmlApplicationContext@52cc95d: org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Creating shared instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating instance of bean 'propertyPlaceholderConfigurer'
DEBUG - Eagerly caching bean 'propertyPlaceholderConfigurer' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'propertyPlaceholderConfigurer'
INFO - Loading properties file from class path resource [config.properties]
DEBUG - Unable to locate MessageSource with name 'messageSource': using default [org.springframework.context.support.DelegatingMessageSource@49bdc9d8]
DEBUG - Unable to locate ApplicationEventMulticaster with name 'applicationEventMulticaster': using default [org.springframework.context.event.SimpleApplicationEventMulticaster@255d17d7]
INFO - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@33aae94f: defining beans [propertyPlaceholderConfigurer,dbWorker,connectionPool]; root of factory hierarchy
DEBUG - Returning cached instance of singleton bean 'propertyPlaceholderConfigurer'
DEBUG - Creating shared instance of singleton bean 'dbWorker'
DEBUG - Creating instance of bean 'dbWorker'
DEBUG - Eagerly caching bean 'dbWorker' to allow for resolving potential circular references
DEBUG - Creating shared instance of singleton bean 'connectionPool'
DEBUG - Creating instance of bean 'connectionPool'
DEBUG - Eagerly caching bean 'connectionPool' to allow for resolving potential circular references
DEBUG - Finished creating instance of bean 'connectionPool'
DEBUG - Finished creating instance of bean 'dbWorker'
DEBUG - Returning cached instance of singleton bean 'connectionPool'
DEBUG - Unable to locate LifecycleProcessor with name 'lifecycleProcessor': using default [org.springframework.context.support.DefaultLifecycleProcessor@4b1c2b67]
DEBUG - Returning cached instance of singleton bean 'lifecycleProcessor'


问:
C language strlen function with new line character in the string
Generally strlen() function in C language returns unsigned int but if the string has new line character then what will be the output ?
For example :
What will be the output of strlen("stack\n") in C language ?</p>

答: strlen("stack\n") --> 6.  Nothing special about '\n'.

ContentLicense: CC BY-SA 4.0


问:
Calling obj_id in html using django
why is it i can update the College record but when i tried to update for example Grade 1 it didnt update. when i tried to print the id = request.POST.get('id')
    print("id", id) i always get ("id", 14)

How do i fix my html?

I have this code in my html

```<code><form  method="post" action="/UpdateEducationLevel/" style="width: 100%" enctype="multipart/form-data">{% csrf_token %}
{% for gradelevel in gradelevels %}
<tr>
<td  class="tdcell"><input type="hidden" name="id" value="{{gradelevel.id}}">{{gradelevel.id}}</td>
<td colspan="2" class="tdcell"><input type="text" value="{{gradelevel.Description}}" name="gradelevel"></td>
<td colspan="2" class="tdcell">
    <select name="status">
        <option>{{gradelevel.Status}}</option>
        <option value="Active">Active</option>
        <option value="Inactive">Inactive</option>
    </select>
</td>
</tr>
<tr>
    <td>
        <div>
            <h3>
                <button class="save">+ Update</button>
            </h3>
        </div>
    </td>
</tr>
{% endfor %}
</form>
</code>```

this is what its looks ln web view

this is my logic on updating what i selecting data to update

```<code>def UpdateEducationLevel(request):
    id = request.POST.get('id')
    print("id", id)
    desc = request.POST.get('gradelevel')
    status = request.POST.get('status')
    update = EducationLevel.objects.get(id=id)
    update.Description=desc
    update.Status = status
    update.save()
</code>```

答:
The problem you're facing is due to having a single form for multiple inputs with the same name, therefore making one overwrite the other when submitting, hence always the same id.

I believe you should add the update button once per row, that way you can make a form per gradelevel and when submitting you will get the id of the row you're updating.

```<code>{% for gradelevel in gradelevels %}
<form  method="post" action="/UpdateEducationLevel/" style="width: 100%" enctype="multipart/form-data">{% csrf_token %}
<tr>
<td  class="tdcell"><input type="hidden" name="id" value="{{gradelevel.id}}">{{gradelevel.id}}</td>
<td colspan="2" class="tdcell"><input type="text" value="{{gradelevel.Description}}" name="gradelevel"></td>
<td colspan="2" class="tdcell">
    <select name="status">
        <option>{{gradelevel.Status}}</option>
        <option value="Active">Active</option>
        <option value="Inactive">Inactive</option>
    </select>
</td>
<td>
    <button class="save">+ Update</button>
</td>
</tr>
</form>
{% endfor %}
</code>```

Title: Calling obj_id in html using django

Body:
why is it i can update the College record but when i tried to update for example Grade 1 it didnt update. when i tried to print the id = request.POST.get('id')
    print("id", id) i always get ("id", 14)

How do i fix my html?

I have this code in my html

<form  method="post" action="/UpdateEducationLevel/" style="width: 100%" enctype="multipart/form-data">{% csrf_token %}
{% for gradelevel in gradelevels %}

<input type="hidden" name="id" value="{{gradelevel.id}}">{{gradelevel.id}}
<input type="text" value="{{gradelevel.Description}}" name="gradelevel">

    <select name="status">
        <option>{{gradelevel.Status}}</option>
        <option value="Active">Active</option>
        <option value="Inactive">Inactive</option>
    </select>

                <button class="save">+ Update</button>

{% endfor %}
</form>

this is what its looks ln web view

this is my logic on updating what i selecting data to update

def UpdateEducationLevel(request):
    id = request.POST.get('id')
    print("id", id)
    desc = request.POST.get('gradelevel')
    status = request.POST.get('status')
    update = EducationLevel.objects.get(id=id)
    update.Description=desc
    update.Status = status
    update.save()

Body:
The problem you're facing is due to having a single form for multiple inputs with the same name, therefore making one overwrite the other when submitting, hence always the same id.

I believe you should add the update button once per row, that way you can make a form per gradelevel and when submitting you will get the id of the row you're updating.

{% for gradelevel in gradelevels %}
<form  method="post" action="/UpdateEducationLevel/" style="width: 100%" enctype="multipart/form-data">{% csrf_token %}
<tr>
<td  class="tdcell"><input type="hidden" name="id" value="{{gradelevel.id}}">{{gradelevel.id}}</td>
<td colspan="2" class="tdcell"><input type="text" value="{{gradelevel.Description}}" name="gradelevel"></td>
<td colspan="2" class="tdcell">
    <select name="status">
        <option>{{gradelevel.Status}}</option>
        <option value="Active">Active</option>
        <option value="Inactive">Inactive</option>
    </select>
</td>
<td>
    <button class="save">&plus;&nbsp;Update</button>
</td>
</tr>
</form>
{% endfor %}


问:
AWS SAM: No 'Access-Control-Allow-Origin' header is present on the requested resource response
I'm working to get a static website to call API gateway using CORS. I've got the code below running using SAM local, but I'm getting the following CORS error trying to call my API with jQuery from my static website (hosted locally):

```<code>Failed to load http://localhost:3000/notify: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.
</code>```

My template.yaml:

```<code>AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Api:
    # enable CORS; to make more specific, change the origin wildcard
    # to a particular domain name, e.g. "'www.example.com'"
    Cors: "'*'"

Parameters:
  RecaptchaSecret:
    Type: String

Resources:
  NotifierFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: notifier/build
      Handler: app.lambda_handler
      Runtime: python3.6
      Environment:
        Variables:
          PARAM1: VALUE
      Events:
        Notify:
          Type: Api
          Properties:
            Path: /notify
            Method: post

Outputs:
    NotifierApi:
      Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/notify/"
    NotifierFunction:
      Value: !GetAtt NotifierFunction.Arn
    NotifierFunctionIamRole:
      Value: !GetAtt NotifierFunctionRole.Arn
</code>```

My understanding of the Globals section in SAM is that it should apply the Api field to my (inferred) API gateway.

I've seen a few examples of CORS with API gateway online where others have utilized standard API gateway templates, and some where people have used SAM in addition to a swagger file, but I've been unable to see a successful example of someone getting CORS to work using SAM without a swagger file (see below references). I feel like I must be missing something obvious!

I'm using a regular POST request from jQuery, I can post my front end code, or the "compiled" CloudForamtion as well if it's helpful.

Any help is very appreciated!

Cheers :)

References I've looked at:

https://github.com/awslabs/serverless-application-model/tree/master/examples/apps/api-gateway-multiple-origin-cors

https://github.com/awslabs/serverless-application-model/issues/373

https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#data-types

Here is my function code:

```<code>import json
import boto3
import requests

def lambda_handler(event, context):
    print "REACHED"
    print event
    ip = requests.get('http://checkip.amazonaws.com/')

    return {
        "statusCode": 200,
        "headers": {"Access-Control-Allow-Origin": "*"},
        "body": json.dumps({
            'message': 'hello world',
            'location': ip.text.replace('\n', ''),
        })
    }
</code>```

答:
If your still interested in how to achieve this, can be done directly through the cloudformation template as per the below, its best if you define a root mock resource to begin with before your post child resource.

```<code>  MockMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      AuthorizationType: NONE
      RestApiId: STRING
      ResourceId: STRING
      HttpMethod: OPTIONS
      Integration:
        Type: MOCK
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin:* #Note * allows all origins
            SelectionPattern: 2\d{2}
            ResponseTemplates:
              application/json: Empty
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: Empty
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200
</code>```

Note, OPTIONS is what handles your preflight CORS request prior to POST method. Additionally if you are using AWS_PROXY as per below you need to handle the header CORS response in your lambda function.

```<code>  POSTmethod:
    Type: AWS::ApiGateway::Method
    Properties:
      HttpMethod: POST
      RestApiId: STRING
      ResourceId: STRING
      Integration:
        Type: AWS_PROXY
        ConnectionType: INTERNET
        IntegrationHttpMethod: POST
        Credentials: STRING
        Uri: STRING
        PassthroughBehavior: WHEN_NO_TEMPLATES
        TimeoutInMillis: 10000 #Timeout in 10seconds
      MethodResponses:
        - StatusCode: 200
          ResponseModels:
            application/json: Empty
          ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: true
              method.response.header.Access-Control-Allow-Origin: true
        - StatusCode: 400
          ResponseModels:
            application/json: Empty

  OPTIONSmethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      AuthorizationType: NONE
      RestApiId: STRING
      ResourceId: STRING
      HttpMethod: OPTIONS
      Integration:
        Type: MOCK
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,x-api-key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            SelectionPattern: 2\d{2}
            ResponseTemplates:
              application/json: Empty
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: Empty
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200
</code>```

Body:
I'm working to get a static website to call API gateway using CORS. I've got the code below running using SAM local, but I'm getting the following CORS error trying to call my API with jQuery from my static website (hosted locally):

Failed to load http://localhost:3000/notify: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4000' is therefore not allowed access.

My template.yaml:

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Globals:
  Api:
    # enable CORS; to make more specific, change the origin wildcard
    # to a particular domain name, e.g. "'www.example.com'"
    Cors: "'*'"

Parameters:
  RecaptchaSecret:
    Type: String

Resources:
  NotifierFunction:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: notifier/build
      Handler: app.lambda_handler
      Runtime: python3.6
      Environment:
        Variables:
          PARAM1: VALUE
      Events:
        Notify:
          Type: Api
          Properties:
            Path: /notify
            Method: post

Outputs:
    NotifierApi:
      Value: !Sub "https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/notify/"
    NotifierFunction:
      Value: !GetAtt NotifierFunction.Arn
    NotifierFunctionIamRole:
      Value: !GetAtt NotifierFunctionRole.Arn

My understanding of the Globals section in SAM is that it should apply the Api field to my (inferred) API gateway.

I've seen a few examples of CORS with API gateway online where others have utilized standard API gateway templates, and some where people have used SAM in addition to a swagger file, but I've been unable to see a successful example of someone getting CORS to work using SAM without a swagger file (see below references). I feel like I must be missing something obvious!

I'm using a regular POST request from jQuery, I can post my front end code, or the "compiled" CloudForamtion as well if it's helpful.

Any help is very appreciated!

Cheers :)

References I've looked at:

https://github.com/awslabs/serverless-application-model/tree/master/examples/apps/api-gateway-multiple-origin-cors

https://github.com/awslabs/serverless-application-model/issues/373

https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#data-types

Here is my function code:

import json
import boto3
import requests

def lambda_handler(event, context):
    print "REACHED"
    print event
    ip = requests.get('http://checkip.amazonaws.com/')

    return {
        "statusCode": 200,
        "headers": {"Access-Control-Allow-Origin": "*"},
        "body": json.dumps({
            'message': 'hello world',
            'location': ip.text.replace('\n', ''),
        })
    }

Body:
If your still interested in how to achieve this, can be done directly through the cloudformation template as per the below, its best if you define a root mock resource to begin with before your post child resource.

  MockMethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      AuthorizationType: NONE
      RestApiId: STRING
      ResourceId: STRING
      HttpMethod: OPTIONS
      Integration:
        Type: MOCK
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin:* #Note * allows all origins
            SelectionPattern: 2\d{2}
            ResponseTemplates:
              application/json: Empty
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: Empty
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200

Note, OPTIONS is what handles your preflight CORS request prior to POST method. Additionally if you are using AWS_PROXY as per below you need to handle the header CORS response in your lambda function.

  POSTmethod:
    Type: AWS::ApiGateway::Method
    Properties:
      HttpMethod: POST
      RestApiId: STRING
      ResourceId: STRING
      Integration:
        Type: AWS_PROXY
        ConnectionType: INTERNET
        IntegrationHttpMethod: POST
        Credentials: STRING
        Uri: STRING
        PassthroughBehavior: WHEN_NO_TEMPLATES
        TimeoutInMillis: 10000 #Timeout in 10seconds
      MethodResponses:
        - StatusCode: 200
          ResponseModels:
            application/json: Empty
          ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: true
              method.response.header.Access-Control-Allow-Origin: true
        - StatusCode: 400
          ResponseModels:
            application/json: Empty

  OPTIONSmethod:
    Type: 'AWS::ApiGateway::Method'
    Properties:
      AuthorizationType: NONE
      RestApiId: STRING
      ResourceId: STRING
      HttpMethod: OPTIONS
      Integration:
        Type: MOCK
        IntegrationResponses:
          - StatusCode: 200
            ResponseParameters:
              method.response.header.Access-Control-Allow-Headers: "'Content-Type,X-Amz-Date,Authorization,x-api-key,X-Amz-Security-Token'"
              method.response.header.Access-Control-Allow-Methods: "'POST,OPTIONS'"
              method.response.header.Access-Control-Allow-Origin: "'*'"
            SelectionPattern: 2\d{2}
            ResponseTemplates:
              application/json: Empty
        PassthroughBehavior: WHEN_NO_MATCH
        RequestTemplates:
          application/json: '{"statusCode": 200}'
      MethodResponses:
        - ResponseModels:
            application/json: Empty
          ResponseParameters:
            method.response.header.Access-Control-Allow-Headers: true
            method.response.header.Access-Control-Allow-Methods: true
            method.response.header.Access-Control-Allow-Origin: true
          StatusCode: 200


问:
DATEDIFF across several months grouped by months
I need to get this output at the bottom.

答:
You can achieve this by using MASTER..SPT_VALUES this default SQL Server table which is used for creating VIRTUAL TABLES

```<code>DECLARE @T TABLE(
ID INT ,ST_DATE DATE,ED_DATE DATE,DURATION INT)
INSERT INTO @T VALUES(5555,'30-Mar-2020','02-Apr-2020',4)

Declare @T1 Table(
ID INT,WK_MONTH VARCHAR(10))
Insert into @T1 values(5555,'Mar-2020')
Insert into @T1 values(5555,'Apr-2020')
select * from @T
select * from @T1
</code>```

Main Query:

```<code>SELECT T.ID,FORMAT(DATEADD(D, NUMBER, T.ST_DATE),'MMM-yy') as [Work
Month],COUNT(MONTH(DATEADD(D, NUMBER, T.ST_DATE) )) as [Absent Days]
FROM MASTER..SPT_VALUES cross apply @T t
WHERE TYPE = 'P' AND NUMBER BETWEEN 0 AND DATEDIFF(DD, T.ST_DATE,   T.ED_DATE)
GROUP BY FORMAT(DATEADD(D, NUMBER, T.ST_DATE),'MMM-yy'),T.ID
</code>```

Output

```<code>ID  Work Month  Absent Days
5555    Apr-20  2
5555    Mar-20  2
</code>```

Body:
You can achieve this by using MASTER..SPT_VALUES this default SQL Server table which is used for creating VIRTUAL TABLES

DECLARE @T TABLE(
ID INT ,ST_DATE DATE,ED_DATE DATE,DURATION INT)
INSERT INTO @T VALUES(5555,'30-Mar-2020','02-Apr-2020',4)

Declare @T1 Table(
ID INT,WK_MONTH VARCHAR(10))
Insert into @T1 values(5555,'Mar-2020')
Insert into @T1 values(5555,'Apr-2020')
select * from @T
select * from @T1

Main Query:

SELECT T.ID,FORMAT(DATEADD(D, NUMBER, T.ST_DATE),'MMM-yy') as [Work
Month],COUNT(MONTH(DATEADD(D, NUMBER, T.ST_DATE) )) as [Absent Days]
FROM MASTER..SPT_VALUES cross apply @T t
WHERE TYPE = 'P' AND NUMBER BETWEEN 0 AND DATEDIFF(DD, T.ST_DATE,   T.ED_DATE)
GROUP BY FORMAT(DATEADD(D, NUMBER, T.ST_DATE),'MMM-yy'),T.ID

Output

ID  Work Month  Absent Days
5555    Apr-20  2
5555    Mar-20  2


问:
Can I make Python check my list to see if user input contains strings in my list using if statements? If not are there any alternatives?
Beginner with Python but I wanted to use a list to contain multiple potential string responses that the user may give in the input.

```<code>def Front_Door():
    print("Welcome to the Party Friend!")
    Emotional_state = input("How are You Today?  ")
    Positive_Emotion = ["good", "fine", "happy"]
</code>```

I tried to use an if statement to get python to check through my list to see if the input contained any of the strings listed in the e.g. I gave.

```<code>if Positive_Emotion in Emotional_state:
    print("That's Great! Happy to have you here!")
</code>```

The code still manages to prompt me for Emotional_state but it just repeats the question one more time, if I respond with one of then strings I've listed again it gives me this error:

```<code>if Positive_Emotion in Emotional_state:
TypeError: 'in <string>' requires string as left operand, not list
</code>```

I'm guessing there is a method to make Python search through my list of strings and cross reference it with my inputs and give me the response I want?

Any help is appreciated :).

答:
You are checking if the whole list is in the string!
What you probably want to do is check if any of the items in the list are in the string.

Something like:

```<code>if any( [emotion in Emotional_state for emotion in Positive_Emotion] ):
    print("That's Great! Happy to have you here!")
</code>```

This will check each emotion in the list, and if any of them are in the string it will return True.

Hope this helps.

Body:
Beginner with Python but I wanted to use a list to contain multiple potential string responses that the user may give in the input.

def Front_Door():
    print("Welcome to the Party Friend!")
    Emotional_state = input("How are You Today?  ")
    Positive_Emotion = ["good", "fine", "happy"]

I tried to use an if statement to get python to check through my list to see if the input contained any of the strings listed in the e.g. I gave.

if Positive_Emotion in Emotional_state:
    print("That's Great! Happy to have you here!")

The code still manages to prompt me for Emotional_state but it just repeats the question one more time, if I respond with one of then strings I've listed again it gives me this error:

if Positive_Emotion in Emotional_state:
TypeError: 'in <string>' requires string as left operand, not list

I'm guessing there is a method to make Python search through my list of strings and cross reference it with my inputs and give me the response I want?

Any help is appreciated :).

Body:
You are checking if the whole list is in the string!
What you probably want to do is check if any of the items in the list are in the string.

Something like:

if any( [emotion in Emotional_state for emotion in Positive_Emotion] ):
    print("That's Great! Happy to have you here!")

This will check each emotion in the list, and if any of them are in the string it will return True.

Hope this helps.


问:
React State with object
I am trying to update my state from my react dynamically, this is my current state.

```<code>this.state = {
      title: "",
      image: "",
      imageFile: "",
      formTitle: "",
      formMessage: "",
      formImage: "",
      Item: {
        name: "Name",
        price: "",
        quantity: "",
        discount: "",
        shipping: "",
        image: "",
        formType: ""
      }
    }
</code>```

How do I update in my Textbox dynamically instead of one by one?

```<code> setItemName = (name) => {
    this.setState({
      Item: {
        ...this.state.Item,
        name
      }
    });
  };
</code>```

this is my attempt at solving this

and this is my Textbox using material UI

```<code><TextField
                      className="my-24"
                      label="Item Name"
                      autoFocus
                      id="itemName"
                      name="itemName"
                      width={1}
                      value={this.state.Item.name}
                      onChange={this.setItemName}
                      variant="outlined"
                    />

</code>```

Thanks!!

答:
You can also try the following code

```<code>handleChange = e => {
  this.setState({
     Item: {
       ...this.state.Item,
      [e.target.name]: e.target.value
     }
});
</code>```

Use name attribute as your state key :

```<code><TextField
    rowsMax={4}
    placeholder="Enter name"
    value={name}
    name="name"
    onChange={this.handleChange}
  />
</code>```

Title: React State with object

Body:
I am trying to update my state from my react dynamically, this is my current state.

this.state = {
      title: "",
      image: "",
      imageFile: "",
      formTitle: "",
      formMessage: "",
      formImage: "",
      Item: {
        name: "Name",
        price: "",
        quantity: "",
        discount: "",
        shipping: "",
        image: "",
        formType: ""
      }
    }

How do I update in my Textbox dynamically instead of one by one?

 setItemName = (name) => {
    this.setState({
      Item: {
        ...this.state.Item,
        name
      }
    });
  };

this is my attempt at solving this

and this is my Textbox using material UI

<TextField
                      className="my-24"
                      label="Item Name"
                      autoFocus
                      id="itemName"
                      name="itemName"
                      width={1}
                      value={this.state.Item.name}
                      onChange={this.setItemName}
                      variant="outlined"
                    />

Thanks!!

Body:
You can also try the following code

handleChange = e => {
  this.setState({
     Item: {
       ...this.state.Item,
      [e.target.name]: e.target.value
     }
});

Use name attribute as your state key :

<TextField
    rowsMax={4}
    placeholder="Enter name"
    value={name}
    name="name"
    onChange={this.handleChange}
  />


问:
Loop Iteration Efficient
You have a loop that iterates over 1,000 items. You want to add a newline to every four items. The items are in an array structure that have numeric index starting at 0. How do you do it?</p>

答:
Just in case what you are really trying to ask is "How do I print these items, four to a line?" here's one way</p>

```<code>int nOnLine = 0;
for (i = 0; i < 1000; i++){
  // print item i
  nOnLine++;
  if (nOnLine >= 4){
    // print newline
    nOnLine = 0;
  }
}
if (nOnLine > 0){
  // print newline
  nOnLine = 0;
}
</code>```

Title: Loop Iteration Efficient

Body:
Just in case what you are really trying to ask is "How do I print these items, four to a line?" here's one way

int nOnLine = 0;
for (i = 0; i < 1000; i++){
  // print item i
  nOnLine++;
  if (nOnLine >= 4){
    // print newline
    nOnLine = 0;
  }
}
if (nOnLine > 0){
  // print newline
  nOnLine = 0;
}


问:
How to present new view in SwiftUI after login
I need to know who to present a new view using SwiftUI (following MVVM design pattern).

For example, once the user enters the credentials to login, pressing the "login" button should take them to the home page of the app without being able to return to the login page.

I have been looking at the documentation from Apple, as well as other questions in Stackoverflow, but they all seem to be using navigation views (i.e. there is a navigation bar at the top which allows the user to return to the previous view).

Below is the code of how I would have accomplished this using UIKit, as well as an image to visually represent what I want to accomplish.

let vc = MainMenuController()

vc.modalPresentationStyle = .fullScreen

self.present(vc, animated: true, completion: nil);

Sample image of desired outcome

答:
this is how i implemented it in my code in ContentView.swift:

```<code>@State var loggedIn: Bool = false

var body: some View {
  VStack {
    if loggedIn {
      ShowSomeTabView()
    } else {
      ShowLoginScreen()
    }
  }.onAppear {
    self.checkAuthorized()
  }
}

private func checkAuthorized() {
  if loggedIn() {
    self.loggedIn = true
  }
}
</code>```

Body:
this is how i implemented it in my code in ContentView.swift:

@State var loggedIn: Bool = false

var body: some View {
  VStack {
    if loggedIn {
      ShowSomeTabView()
    } else {
      ShowLoginScreen()
    }
  }.onAppear {
    self.checkAuthorized()
  }
}

private func checkAuthorized() {
  if loggedIn() {
    self.loggedIn = true
  }
}


问:
How can I fix my code for an Arduino LED string controller?
I'm getting :
invalid types 'int[int]' for array subscript
when I try to compile my code for my Arduino and for the life of me I can't figure out what I'm doing wrong.
Here's my code (feel free to use it although it isn't done yet).

```<code>/*
 * Changelog 0.5
 * pins[], pinFV[], pinV[], pinDelay[] moved
 * to pins[][]
 */
int analogPins[6] = {A0, A1, A2, A3, A4, A5};
int pins[4][4];
int mode = 0;
void setup() {
  int x = 6;
  do {
    pinMode(analogPins[x], INPUT);
    x--;
  } while (x > 0);
  int pins[4] = {9, 5, 6, 3};
  x = 4;
  do {
    pinMode(pins[0][x], INPUT);
    x--;
  } while (x > 0);
  x = 4;
  do{
    pins[1][x] = random(5, 10);
    x--;
    }while(x>0);
  x = 4;
  do{
    pins[2][x] = random(50, 75);
    x--;
    }while(x>0);
  x = 4;
  do{
    pins[3][x] = 255;
    x--;
    }while(x>0);
 //this is the section causing the problem
  pins[0][0] = 8;
  pins[0][1] = 9;
  pins[0][2] = 10;
  pins[0][3] = 11;
//end section
  pinMode(8, OUTPUT);
  Serial.begin(19200);
}
void readAnalogDecode() {
  //analogAverage(pin);
  //elseIf statements to set what mode to use
  //catch anything out of bounds for mode select
  if (analogRead(A5) > 800 || analogRead(A5) < 0) {
    mode = 0;
  }
  if (analogRead(A5) > 4 && analogRead(A5) < 8) {
    mode = 0;
  }
  if (analogRead(A5) > 8 && analogRead(A5) < 15) {
    mode = 1;
  }
  if (analogRead(A5) > 15 && analogRead(A5) < 20) {
    mode = 2;
  }
  if (analogRead(A5) > 20 && analogRead(A5) < 26) {
    mode = 3;
  }
  if (analogRead(A5) > 26 && analogRead(A5) < 47) {
    mode = 4;
  }
  if (analogRead(A5) > 47 && analogRead(A5) < 185) {
    mode = 5;
  }
  if (analogRead(A5) > 185 && analogRead(A5) < 345) {
    mode = 6;
  }
}

void pinFader(int pin, int value) {
  digitalWrite(8, LOW);

  if (pins[3][pin] < value) {
    do {
      pins[3][pin] = pins[3][pin] + pins[1][pin];
      if (pins[3][pin] > 255) {
        pins[3][pin] = 255;
      }
      Serial.println(analogRead(A5));
      Serial.println(" ");
      Serial.println(analogRead(A4));
      analogWrite(pins[0][pin], pins[3][pin]);
      digitalWrite(8, LOW);
      delay(pins[2][pin]);
    } while (pins[3][pin] < value);
  }
  if (pins[3][pin] > value) {
    do {
      pins[3][pin] = pins[3][pin] - pins[1][pin];
      if (pins[3][pin] < 0 ) {
        pins[3][pin] = 0;
      }
      digitalWrite(8, LOW);
      analogWrite(pins[0][pin], pins[3][pin]);
      delay(pins[2][pin]);
    } while (pins[3][pin] > value);
  }
}
void loop() {
  Serial.println(" " );
  Serial.print(analogRead(A0));
  Serial.print(" " );
  Serial.print(analogRead(A1));
  Serial.print(" " );
  Serial.print(analogRead(A2));
  Serial.print(" " );
  Serial.print(analogRead(A3));
  Serial.print(" " );
  Serial.print(analogRead(A4));
  Serial.print(" " );
  Serial.print(analogRead(A5));
  Serial.print(" " );
  Serial.print(mode);
  readAnalogDecode();

  if (mode == 0) {
    pinFader(1, 255); //no green
    pinFader(2, 255); //no red
    pinFader(1, 0); //green on
    pinFader(3, 255); //no blue
    pinFader(2, 0);   //red on
    pinFader(1, 255); //no green
    pinFader(3, 0);   //blue on
    pinFader(1, 0);   //green on
    readAnalogDecode();}
  if (mode == 1) {
    analogWrite(9, 0);
    delay(500);
    analogWrite(9, 255);
    /* delay(500);
      analogWrite(10, 0);
      delay(500);
      analogWrite(10, 255);
      delay(500);
      analogWrite(11, 0);
      delay(500);
      analogWrite(11, 255);
    */delay(500);
    readAnalogDecode();
  }
}
</code>```

Is this not how to assign a value to a 2-d array? pins[0][0] = 8;
I apologize in advance if the problem is related to syntax. I'm used to java and python.

答:
You have 2 arrays with the same name.  Inside setup the local one is the one that is referred to and it isn't a 2D array so you can't use it as such.

At global scope:

```<code>int pins[4][4];
</code>```

And inside setup:

```<code>int pins[4] = {9, 5, 6, 3};
</code>```

Try naming one of them something different.  Having two things with the same name can be terribly confusing.

Body:
I'm getting :
invalid types 'int[int]' for array subscript
when I try to compile my code for my Arduino and for the life of me I can't figure out what I'm doing wrong.
Here's my code (feel free to use it although it isn't done yet).

/*
 * Changelog 0.5
 * pins[], pinFV[], pinV[], pinDelay[] moved
 * to pins[][]
 */
int analogPins[6] = {A0, A1, A2, A3, A4, A5};
int pins[4][4];
int mode = 0;
void setup() {
  int x = 6;
  do {
    pinMode(analogPins[x], INPUT);
    x--;
  } while (x > 0);
  int pins[4] = {9, 5, 6, 3};
  x = 4;
  do {
    pinMode(pins[0][x], INPUT);
    x--;
  } while (x > 0);
  x = 4;
  do{
    pins[1][x] = random(5, 10);
    x--;
    }while(x>0);
  x = 4;
  do{
    pins[2][x] = random(50, 75);
    x--;
    }while(x>0);
  x = 4;
  do{
    pins[3][x] = 255;
    x--;
    }while(x>0);
 //this is the section causing the problem
  pins[0][0] = 8;
  pins[0][1] = 9;
  pins[0][2] = 10;
  pins[0][3] = 11;
//end section
  pinMode(8, OUTPUT);
  Serial.begin(19200);
}
void readAnalogDecode() {
  //analogAverage(pin);
  //elseIf statements to set what mode to use
  //catch anything out of bounds for mode select
  if (analogRead(A5) > 800 || analogRead(A5) < 0) {
    mode = 0;
  }
  if (analogRead(A5) > 4 && analogRead(A5) < 8) {
    mode = 0;
  }
  if (analogRead(A5) > 8 && analogRead(A5) < 15) {
    mode = 1;
  }
  if (analogRead(A5) > 15 && analogRead(A5) < 20) {
    mode = 2;
  }
  if (analogRead(A5) > 20 && analogRead(A5) < 26) {
    mode = 3;
  }
  if (analogRead(A5) > 26 && analogRead(A5) < 47) {
    mode = 4;
  }
  if (analogRead(A5) > 47 && analogRead(A5) < 185) {
    mode = 5;
  }
  if (analogRead(A5) > 185 && analogRead(A5) < 345) {
    mode = 6;
  }
}

void pinFader(int pin, int value) {
  digitalWrite(8, LOW);

  if (pins[3][pin] < value) {
    do {
      pins[3][pin] = pins[3][pin] + pins[1][pin];
      if (pins[3][pin] > 255) {
        pins[3][pin] = 255;
      }
      Serial.println(analogRead(A5));
      Serial.println(" ");
      Serial.println(analogRead(A4));
      analogWrite(pins[0][pin], pins[3][pin]);
      digitalWrite(8, LOW);
      delay(pins[2][pin]);
    } while (pins[3][pin] < value);
  }
  if (pins[3][pin] > value) {
    do {
      pins[3][pin] = pins[3][pin] - pins[1][pin];
      if (pins[3][pin] < 0 ) {
        pins[3][pin] = 0;
      }
      digitalWrite(8, LOW);
      analogWrite(pins[0][pin], pins[3][pin]);
      delay(pins[2][pin]);
    } while (pins[3][pin] > value);
  }
}
void loop() {
  Serial.println(" " );
  Serial.print(analogRead(A0));
  Serial.print(" " );
  Serial.print(analogRead(A1));
  Serial.print(" " );
  Serial.print(analogRead(A2));
  Serial.print(" " );
  Serial.print(analogRead(A3));
  Serial.print(" " );
  Serial.print(analogRead(A4));
  Serial.print(" " );
  Serial.print(analogRead(A5));
  Serial.print(" " );
  Serial.print(mode);
  readAnalogDecode();

  if (mode == 0) {
    pinFader(1, 255); //no green
    pinFader(2, 255); //no red
    pinFader(1, 0); //green on
    pinFader(3, 255); //no blue
    pinFader(2, 0);   //red on
    pinFader(1, 255); //no green
    pinFader(3, 0);   //blue on
    pinFader(1, 0);   //green on
    readAnalogDecode();}
  if (mode == 1) {
    analogWrite(9, 0);
    delay(500);
    analogWrite(9, 255);
    /* delay(500);
      analogWrite(10, 0);
      delay(500);
      analogWrite(10, 255);
      delay(500);
      analogWrite(11, 0);
      delay(500);
      analogWrite(11, 255);
    */delay(500);
    readAnalogDecode();
  }
}

Is this not how to assign a value to a 2-d array? pins[0][0] = 8;
I apologize in advance if the problem is related to syntax. I'm used to java and python.

Body:
You have 2 arrays with the same name.  Inside setup the local one is the one that is referred to and it isn't a 2D array so you can't use it as such.

At global scope:

int pins[4][4];

And inside setup:

int pins[4] = {9, 5, 6, 3};

Try naming one of them something different.  Having two things with the same name can be terribly confusing.


问:
Fastest way to save/load enum[] (byte) to a file
The array has duplicate elements and their order is important (must be kept).  I have to save/load hundreds of these files constantly and each file may hold an array up to 100,000 elements.

The code bellow is an example of what I'm currently doing to save/load the files. Since IO is slow I got a significant speed improvement by casting the enums to byte before serialization (reducing the file size by 10x). I'm not sure I should be using BinaryFormatter though.

I'm still looking for improvements as everything should be as quick as possible, is there a better alternative to what I'm currently doing? How would you do it?

```<code>enum DogBreed : byte { Bulldog, Poodle, Beagle, Rottweiler, Chihuahua }

DogBreed[] myDogs = { DogBreed.Beagle, DogBreed.Poodle, DogBreed.Beagle, DogBreed.Bulldog };

public void Save(string path)
{
    BinaryFormatter formatter = new BinaryFormatter();
    FileStream stream = new FileStream(path, FileMode.Create);
    byte[] myDogsInByte = Array.ConvertAll(myDogs, new Converter<DogBreed, byte>(DogBreedToByte));
    formatter.Serialize(stream, myDogsInByte);
    stream.Close();
}

public bool Load(string path)
{
    if (!File.Exists(path))
    {
        return false;
    }

    BinaryFormatter formatter = new BinaryFormatter();
    FileStream stream = new FileStream(path, FileMode.Open);
    byte[] myDogsInByte = formatter.Deserialize(stream) as byte[];
    myDogs = Array.ConvertAll(myDogsInByte, new Converter<byte, DogBreed>(ByteToDogBreed));
    stream.Close();
    return true;
}

private byte DogBreedToByte(DogBreed db)
{
    return (byte)db;
}

private DogBreed ByteToDogBreed(byte bt)
{
    return (DogBreed)bt;
}
</code>```

EDIT: New code based on Jeremy suggestion, the code is working, I'll try to test the performance of it and post the results here as soon as I can.

```<code>enum DogBreed : byte { Bulldog, Poodle, Beagle, Rottweiler, Chihuahua }

DogBreed[] myDogs = { DogBreed.Beagle, DogBreed.Poodle, DogBreed.Beagle, DogBreed.Bulldog };

public void Save(string path)
{
    byte[] myDogsInByte = new byte[myDogs.Length];
    Array.Copy(myDogs,myDogsInByte,myDogs.Length);
    File.WriteAllBytes(path, myDogsInByte);
}

public bool Load(string path)
{
    if (!File.Exists(path))
    {
        return false;
    }

    byte[] myDogsInByte = File.ReadAllBytes(path);
    myDogs = (DogBreed[])(object)myDogsInByte;
    return true;
}
</code>```

答:
While the C# compiler will complain if you attempt to directly assign a byte[] to an enum   array. The runtime doesn't care.

var bytes = File.ReadAllBytes(path);
myDogs = (DogBreed[])(object)bytes;
```

<p>The VS debugger will show that myDogs is really a byte array, but accessing an element from the array works just fine.</p>

<p>Update;</p>

<blockquote>
  <p>ArgumentException: Object must be an array of primitives.</p>
</blockquote>

<p>So <code>File.WriteAllBytes()</code> doesn't like being tricked with an <code>enum[]</code>. You should be able to to use <code>Array.Copy</code> to quickly duplicate the enum values into a <code>byte[]</code>.</p>

<pre class="lang-cs prettyprint-override"><code>   var buffer = new byte[myDogs.Length];
   Array.Copy(myDogs, buffer, myDogs.Length);
   File.WriteAllBytes(path, buffer);
</code>```

Of course that's not a free operation, but it should be fairly fast even for large arrays.

Body:
The array has duplicate elements and their order is important (must be kept).  I have to save/load hundreds of these files constantly and each file may hold an array up to 100,000 elements.

The code bellow is an example of what I'm currently doing to save/load the files. Since IO is slow I got a significant speed improvement by casting the enums to byte before serialization (reducing the file size by 10x). I'm not sure I should be using BinaryFormatter though.

I'm still looking for improvements as everything should be as quick as possible, is there a better alternative to what I'm currently doing? How would you do it?

enum DogBreed : byte { Bulldog, Poodle, Beagle, Rottweiler, Chihuahua }

DogBreed[] myDogs = { DogBreed.Beagle, DogBreed.Poodle, DogBreed.Beagle, DogBreed.Bulldog };

public void Save(string path)
{
    BinaryFormatter formatter = new BinaryFormatter();
    FileStream stream = new FileStream(path, FileMode.Create);
    byte[] myDogsInByte = Array.ConvertAll(myDogs, new Converter<DogBreed, byte>(DogBreedToByte));
    formatter.Serialize(stream, myDogsInByte);
    stream.Close();
}

public bool Load(string path)
{
    if (!File.Exists(path))
    {
        return false;
    }

    BinaryFormatter formatter = new BinaryFormatter();
    FileStream stream = new FileStream(path, FileMode.Open);
    byte[] myDogsInByte = formatter.Deserialize(stream) as byte[];
    myDogs = Array.ConvertAll(myDogsInByte, new Converter<byte, DogBreed>(ByteToDogBreed));
    stream.Close();
    return true;
}

private byte DogBreedToByte(DogBreed db)
{
    return (byte)db;
}

private DogBreed ByteToDogBreed(byte bt)
{
    return (DogBreed)bt;
}

EDIT: New code based on Jeremy suggestion, the code is working, I'll try to test the performance of it and post the results here as soon as I can.

enum DogBreed : byte { Bulldog, Poodle, Beagle, Rottweiler, Chihuahua }

DogBreed[] myDogs = { DogBreed.Beagle, DogBreed.Poodle, DogBreed.Beagle, DogBreed.Bulldog };

public void Save(string path)
{
    byte[] myDogsInByte = new byte[myDogs.Length];
    Array.Copy(myDogs,myDogsInByte,myDogs.Length);
    File.WriteAllBytes(path, myDogsInByte);
}

public bool Load(string path)
{
    if (!File.Exists(path))
    {
        return false;
    }

    byte[] myDogsInByte = File.ReadAllBytes(path);
    myDogs = (DogBreed[])(object)myDogsInByte;
    return true;
}

Body:
While the C# compiler will complain if you attempt to directly assign a byte[] to an enum   array. The runtime doesn't care.

var bytes = File.ReadAllBytes(path);
myDogs = (DogBreed[])(object)bytes;

The VS debugger will show that myDogs is really a byte array, but accessing an element from the array works just fine.

Update;

ArgumentException: Object must be an array of primitives.

So File.WriteAllBytes() doesn't like being tricked with an enum[]. You should be able to to use Array.Copy to quickly duplicate the enum values into a byte[].

   var buffer = new byte[myDogs.Length];
   Array.Copy(myDogs, buffer, myDogs.Length);
   File.WriteAllBytes(path, buffer);

Of course that's not a free operation, but it should be fairly fast even for large arrays.


问:
The links rotate but end up in a completely different area of the page?
I would like the link to rotate in place but they end up rotating and being in a different area of the page..

/* CSS: */

.link:hover {
  transform: rotate(90deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--HTML:-->

<div class="link">
  <h2>Food</h2>
</div>
<div class="link">
  <h2>Entertainment</h2>
</div>
<div class="link">
  <h2>Entertainment Schedule</h2>
</div>
<div class="link">
  <h2>Past Lou Fests</h2>
</div>
<div class="link">
  <h2>Take the Lou Fest survey!</h2>
</div></code>```

答:
Instead of hover the .link. I modified the code to have
 to be inline-block and hover over

/* CSS: */

.link>h2 {
  display: inline-block;
}

.link>h2:hover {
  transform: rotate(90deg);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--HTML:-->

<div class="link">
  <h2>Food</h2>
</div>
<div class="link">
  <h2>Entertainment</h2>
</div>
<div class="link">
  <h2>Entertainment Schedule</h2>
</div>
<div class="link">
  <h2>Past Lou Fests</h2>
</div>
<div class="link">
  <h2>Take the Lou Fest survey!</h2>
</div></code>```

Body:
I would like the link to rotate in place but they end up rotating and being in a different area of the page..

/* CSS: */

.link:hover {
  transform: rotate(90deg);
}

Food

Entertainment

Entertainment Schedule

Past Lou Fests

Take the Lou Fest survey!

Body:
Instead of hover the .link. I modified the code to have <h2> to be inline-block and hover over <h2>

/* CSS: */

.link>h2 {
  display: inline-block;
}

.link>h2:hover {
  transform: rotate(90deg);
}

<!--HTML:-->

<div class="link">
  <h2><a href="loufestfood.html">Food</a></h2>
</div>
<div class="link">
  <h2><a href="loufestent.html">Entertainment</a></h2>
</div>
<div class="link">
  <h2><a href="LfEntSched.html">Entertainment Schedule</a></h2>
</div>
<div class="link">
  <h2><a href="pastLouFests.html">Past Lou Fests</a></h2>
</div>
<div class="link">
  <h2><a href="LouFestSurvey.html">Take the Lou Fest survey!</a></h2>
</div>


问:
Why is onclick for the first button in a form triggered when I hit ENTER key (and no keyCode in event)?
Why is onclick for the first button in a form triggered when I hit ENTER key? I am trying to figure out why onclick was triggered by the ENTER key, and then have the function go ahead if it was an actual mouse/tap button click, or have the function ignore the key press if it was the ENTER key.

I tried checking the event.keyCode (passed into javascript function), but it is undefined.

In fact the only property that seems to be set is event.isTrusted but no other properties exist.

EDIT: Created new demo code to better explain the issue I am having...

Here is js fiddle with the issue: https://jsfiddle.net/Ld142qx3/24/

When you put the cursor in the Quantity 2 input box (the second box) and you click enter, it fires the onclick event for the first LESS button in front of the Quantity 1 input box.

There is no keyCode property passed in with event to identify whether onclick was actually triggered by clicking with a mouse or triggered by ENTER key.

My original test code HTML is:

```<code><form onsubmit="return false;">
  Quantity 1: <button id="b1-less" onclick="return b1Less(this.id, event);">less</button>
  <input type="text" id="q1" value="10" size="10">
  <button id="b1-more" onclick="return b1More(this.id, event);">more</button>
  <br>
  Quantity 2: <button id="b2-less" onclick="return b2Less(this.id, event);">less</button>
  <input type="text" id="q2" value="5" size="10">
  <button id="b2-more" onclick="return b2More(this.id, event);">more</button>
</form>
</code>```

And my original javascript to go with it is:

```<code>function b1Less(_id, _event) {
  alert(_event.keyCode);
  _val = parseInt(document.getElementById('q1').value);
  _val = _val - 1;
  document.getElementById('q1').value = _val;
  return false;
}
function b1More(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val + 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b2Less(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val - 1;
  document.getElementById('q2').value = _val;
  return false;
}
function b2More(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val + 1;
  document.getElementById('q2').value = _val;
  return false;
}
</code>```

答:
As checked doClickMeButton function event is a mouse event and mouse event doesn't have keyboard binding details.

     You can bind a keyboard-based events on an input tag.
     I have mentioned the code below which behaves the same as you wanted.

function doClickMeButton() {
  alert("I am called");
}

function doMoreLess(_id) {
  alert("clicked on " + _id);
  return false;
}

function myFunction(event) {
  var x = event.which || event.keyCode;
  if (x === 13) {
    console.log(event.which, "which"), console.log(event.keyCode, "keycode");
    doClickMeButton();
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <form>

         // first thing I dont know why you need this button
        <button id="my-button"

        onclick="">CLICK ME</button>

        <br>
        Enter something in the input textbox below, and hit the ENTER key and notice that:<br>
          (1) keyCode is undefined, and<br>
          (2) ENTER fires the onclick action of the first element with an onclick in it.
        <br>

        <button id="less" onclick="return doMoreLess(this.id);">
        less
        </button>
        <input type="text" size="10"  onkeypress="myFunction(event)">
        <button id="more" onclick="return doMoreLess(this.id);">
        more
        </button>
      </form></code>```

Body:
Why is onclick for the first button in a form triggered when I hit ENTER key? I am trying to figure out why onclick was triggered by the ENTER key, and then have the function go ahead if it was an actual mouse/tap button click, or have the function ignore the key press if it was the ENTER key.

I tried checking the event.keyCode (passed into javascript function), but it is undefined.

In fact the only property that seems to be set is event.isTrusted but no other properties exist.

EDIT: Created new demo code to better explain the issue I am having...

Here is js fiddle with the issue: https://jsfiddle.net/Ld142qx3/24/

When you put the cursor in the Quantity 2 input box (the second box) and you click enter, it fires the onclick event for the first LESS button in front of the Quantity 1 input box.

There is no keyCode property passed in with event to identify whether onclick was actually triggered by clicking with a mouse or triggered by ENTER key.

My original test code HTML is:

<form onsubmit="return false;">
  Quantity 1: <button id="b1-less" onclick="return b1Less(this.id, event);">less</button>
  <input type="text" id="q1" value="10" size="10">
  <button id="b1-more" onclick="return b1More(this.id, event);">more</button>

  Quantity 2: <button id="b2-less" onclick="return b2Less(this.id, event);">less</button>
  <input type="text" id="q2" value="5" size="10">
  <button id="b2-more" onclick="return b2More(this.id, event);">more</button>
</form>

And my original javascript to go with it is:

function b1Less(_id, _event) {
  alert(_event.keyCode);
  _val = parseInt(document.getElementById('q1').value);
  _val = _val - 1;
  document.getElementById('q1').value = _val;
  return false;
}
function b1More(_id, _event) {
  _val = parseInt(document.getElementById('q1').value);
  _val = _val + 1;
  document.getElementById('q1').value = _val;
  return false;
}

function b2Less(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val - 1;
  document.getElementById('q2').value = _val;
  return false;
}
function b2More(_id, _event) {
  _val = parseInt(document.getElementById('q2').value);
  _val = _val + 1;
  document.getElementById('q2').value = _val;
  return false;
}

Body:
As checked doClickMeButton function event is a mouse event and mouse event doesn't have keyboard binding details.

     You can bind a keyboard-based events on an input tag.
     I have mentioned the code below which behaves the same as you wanted.

function doClickMeButton() {
  alert("I am called");
}

function doMoreLess(_id) {
  alert("clicked on " + _id);
  return false;
}

function myFunction(event) {
  var x = event.which || event.keyCode;
  if (x === 13) {
    console.log(event.which, "which"), console.log(event.keyCode, "keycode");
    doClickMeButton();
  }
}

 <form>

         // first thing I dont know why you need this button
        <button id="my-button"

        onclick="">CLICK ME</button>

        <br>
        Enter something in the input textbox below, and hit the ENTER key and notice that:<br>
        &nbsp;&nbsp;(1) keyCode is undefined, and<br>
        &nbsp;&nbsp;(2) ENTER fires the onclick action of the first element with an onclick in it.
        <br>

        <button id="less" onclick="return doMoreLess(this.id);">
        less
        </button>
        <input type="text" size="10"  onkeypress="myFunction(event)">
        <button id="more" onclick="return doMoreLess(this.id);">
        more
        </button>
      </form>


问:
How to configure Deployment Source in VSCODE?
I am trying to deploy basic Angular App to Azure. I installed these extensions:

When I right click on my AppService, I see this menu:

If I try to select Configure Deployment source, I do not see any browse option that numerous articles on the web speak about. I see only this:

How can I enter the directory of my compiled app there? Simple deployment results in my whole uncompiled app being placed into the wwwroot of my AppService.

This is the only confirmation dialog that I see when I click Deploy web app:

答:
Before deploying the app to Azure , you need to  build the angular application for production environment by running this command in the terminal tab in Visual Code:

```<code>ng build --configuration=production
</code>```

Once you login to azure with the extension, you will see all the App Services under your subscription

Next right click on you App Service application and choose “Deploy to Web App”, a command popup will be showing on the right. Click on Browse and choose “dist\yourApp” folder under your application and then Click Deploy

Body:
Before deploying the app to Azure , you need to  build the angular application for production environment by running this command in the terminal tab in Visual Code:

ng build --configuration=production

Once you login to azure with the extension, you will see all the App Services under your subscription

Next right click on you App Service application and choose “Deploy to Web App”, a command popup will be showing on the right. Click on Browse and choose “dist\yourApp” folder under your application and then Click Deploy


问:
How to disable checkbox on specific row in react-table checkboxHOC (6.8.6)
I am using react-table 6.8.6, and I want to disable the checkbox on a specific row with react-table using checkboxHOC. Is that possible?</p>

答: As mentioned in this GitHub issue, you will have to create your own component for the checkbox. The checkbox HOC is an example and is a fairly short piece of code that was meant to be hacked. </p>


问:
Does IAsyncDisposable Have a Reference Implementation?
With IDisposable, I often used an abstract base class because implementing it was so difficult. Mostly because you can use the interface to dispose both managed and unmanaged references and each is disposed differently.

```<code>public abstract class Disposable : IDisposable
{
    ~Disposable() => this.Dispose(false);

    public bool IsDisposed { get; private set; }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void DisposeManaged() {}
    protected virtual void DisposeUnmanaged() {}

    protected void ThrowIfDisposed()
    {
        if (this.IsDisposed)
        {
            throw new ObjectDisposedException(this.GetType().Name);
        }
    }

    private void Dispose(bool disposing)
    {
        if (!this.IsDisposed)
        {
            if (disposing)
            {
                this.DisposeManaged();
            }

            this.DisposeUnmanaged();
            this.IsDisposed = true;
        }
    }
}
</code>```

With IAsyncDisposable, I can't find a reference implementation. Also, I believe it only handles managed resources mainly because it's so new and there are no unmanaged resources that require async to be disposed. Is this correct? If so, is the implementation then trivial?

答:
The pattern that we decided on for the framework, and will publish in Framework Design Guidelines, 3rd Edition is:

```<code>public async ValueTask DisposeAsync()
{
    await DisposeAsyncCore().ConfigureAwait(false);
    Dispose(false);
    GC.SuppressFinalize(this);
}

protected virtual ValueTask DisposeAsyncCore()
{
    // Code goes here that is the async equivalent to Dispose(true)
}
</code>```

That does, of course, imply that all IAsyncDisposable types are also IDisposable.  Also, sealed types can skip DisposeAsyncCore().

Body:
With IDisposable, I often used an abstract base class because implementing it was so difficult. Mostly because you can use the interface to dispose both managed and unmanaged references and each is disposed differently.

public abstract class Disposable : IDisposable
{
    ~Disposable() => this.Dispose(false);

    public bool IsDisposed { get; private set; }

    public void Dispose()
    {
        this.Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void DisposeManaged() {}
    protected virtual void DisposeUnmanaged() {}

    protected void ThrowIfDisposed()
    {
        if (this.IsDisposed)
        {
            throw new ObjectDisposedException(this.GetType().Name);
        }
    }

    private void Dispose(bool disposing)
    {
        if (!this.IsDisposed)
        {
            if (disposing)
            {
                this.DisposeManaged();
            }

            this.DisposeUnmanaged();
            this.IsDisposed = true;
        }
    }
}

With IAsyncDisposable, I can't find a reference implementation. Also, I believe it only handles managed resources mainly because it's so new and there are no unmanaged resources that require async to be disposed. Is this correct? If so, is the implementation then trivial?

Body:
The pattern that we decided on for the framework, and will publish in Framework Design Guidelines, 3rd Edition is:

public async ValueTask DisposeAsync()
{
    await DisposeAsyncCore().ConfigureAwait(false);
    Dispose(false);
    GC.SuppressFinalize(this);
}

protected virtual ValueTask DisposeAsyncCore()
{
    // Code goes here that is the async equivalent to Dispose(true)
}

That does, of course, imply that all IAsyncDisposable types are also IDisposable.  Also, sealed types can skip DisposeAsyncCore().


问:
custom validation attribute not working on client, just on server
I am trying to implement custom attribute validation, similar to one demonstrated here in ScottGu's blog:
http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

I have this custom validator attribute for Email:

```<code>public class EmailAttribute : RegularExpressionAttribute
      {
      public EmailAttribute() :
                base("^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$") { }
      }
</code>```

My class uses it like this:

```<code>    [Required(ErrorMessage = ValidationCiM.MsgObaveznoPolje)]
    [Email(ErrorMessage = ValidationCiM.MsgMailNeispravan)]
    [StringLength(ValidationCiM.LenSrednjePolje, ErrorMessage = ValidationCiM.MsgSrednjePolje)]
    public string Mail { get; set; }
</code>```

and it all works well on server side, model is validated ok, and everything. But client side validation does not activate for this the second attribute, it works for Required, and it also works for StringLength but not for Email.
i have tried including both jquery and Microsoft ajax scripts, but there seems to be no difference.

In ScottGu's blog, he states that the custom validation if implemented like this should work without the need to add custom script.

Any ideas please?

答:
What you actually needed to do was this (on application start):

```<code>DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));
</code>```

It hooks up the client validation to your custom attribute.

Body:
I am trying to implement custom attribute validation, similar to one demonstrated here in ScottGu's blog:
http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

I have this custom validator attribute for Email:

public class EmailAttribute : RegularExpressionAttribute
      {
      public EmailAttribute() :
                base("^[A-Za-z0-9](([_\\.\\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\\.\\-]?[a-zA-Z0-9]+)*)\\.([A-Za-z]{2,})$") { }
      }

My class uses it like this:

    [Required(ErrorMessage = ValidationCiM.MsgObaveznoPolje)]
    [Email(ErrorMessage = ValidationCiM.MsgMailNeispravan)]
    [StringLength(ValidationCiM.LenSrednjePolje, ErrorMessage = ValidationCiM.MsgSrednjePolje)]
    public string Mail { get; set; }

and it all works well on server side, model is validated ok, and everything. But client side validation does not activate for this the second attribute, it works for Required, and it also works for StringLength but not for Email.
i have tried including both jquery and Microsoft ajax scripts, but there seems to be no difference.

In ScottGu's blog, he states that the custom validation if implemented like this should work without the need to add custom script.

Any ideas please?

Body:
What you actually needed to do was this (on application start):

DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailAttribute), typeof(RegularExpressionAttributeAdapter));

It hooks up the client validation to your custom attribute.


问:
RuboCop Naming/FileName cop complains about standard files when ExpectMatchingDefinition: true
I've searched for information about this on the Rubocop documentation but can't seem to understand what's going on.

Starting with a fresh Rails app (6.0.2.2) called "Foo", I add the following gems to my Gemfile and install them:

gem 'rubocop', '~> 0.80.0', require: false
gem 'rubocop-checkstyle_formatter', require: false
gem 'rubocop-rails_config', require: false
```

<p>Currently the resolved version of RuboCop (given the version restriction I have) is <code>0.80.1</code>.</p>

<p>I then add a simple model: <code>rails g model user name:string</code>, which creates <code>app/models/user.rb</code>. Run RuboCop on that file only <em>without</em> any custom configuration file and it only complains about not having the frozen string literal. I do this under the context of my bundle with <code>bundle exec rubocop app/models/user.rb</code> and get the following:</p>

```Inspecting 1 file
C

Offenses:

app/models/user.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class User < ApplicationRecord
^
```

<p>Then add my custom <code>.rubocop.yml</code> file to the project with this rule enabled, which is different than the default value from the standard configuration:</p>

```Naming/FileName:
  ExpectMatchingDefinition: true
```

<p>Upon re-running the analysis, this new offense shows up:</p>

```app/models/user.rb:1:1: C: Naming/FileName: user.rb should define a class or module called Foo::App::Models::User.
class User < ApplicationRecord
^
```

Notice how it wants the User class to be defined as Foo::App::Models::User. This happens to me on every file I evaluate. I've wiped out all my gems and even my Ruby and reinstalled, but the issue persists. The strange thing is that other colleagues can't reproduce the issue.

Has anybody seen this? I appreciate the help!

答:
We just recently merged a pull request which adds a new configuration option, CheckDefinitionPathHierarchy, to this cop. When enabled, the cop will ignore the path and only check that your defined class or module matches the file name.

Once the next version of RuboCop is released, you can update you configuration file to:

```<code>Naming/FileName:
  ExpectMatchingDefinition: true
  CheckDefinitionPathHierarchy: false
</code>```

and the offences relating to the namespace should go away.

Body:
I've searched for information about this on the Rubocop documentation but can't seem to understand what's going on.

Starting with a fresh Rails app (6.0.2.2) called "Foo", I add the following gems to my Gemfile and install them:

gem 'rubocop', '~> 0.80.0', require: false
gem 'rubocop-checkstyle_formatter', require: false
gem 'rubocop-rails_config', require: false

Currently the resolved version of RuboCop (given the version restriction I have) is 0.80.1.

I then add a simple model: rails g model user name:string, which creates app/models/user.rb. Run RuboCop on that file only without any custom configuration file and it only complains about not having the frozen string literal. I do this under the context of my bundle with bundle exec rubocop app/models/user.rb and get the following:

Inspecting 1 file
C

Offenses:

app/models/user.rb:1:1: C: Style/FrozenStringLiteralComment: Missing frozen string literal comment.
class User < ApplicationRecord
^

Then add my custom .rubocop.yml file to the project with this rule enabled, which is different than the default value from the standard configuration:

Naming/FileName:
  ExpectMatchingDefinition: true

Upon re-running the analysis, this new offense shows up:

app/models/user.rb:1:1: C: Naming/FileName: user.rb should define a class or module called Foo::App::Models::User.
class User < ApplicationRecord
^

Notice how it wants the User class to be defined as Foo::App::Models::User. This happens to me on every file I evaluate. I've wiped out all my gems and even my Ruby and reinstalled, but the issue persists. The strange thing is that other colleagues can't reproduce the issue.

Has anybody seen this? I appreciate the help!

Body:
We just recently merged a pull request which adds a new configuration option, CheckDefinitionPathHierarchy, to this cop. When enabled, the cop will ignore the path and only check that your defined class or module matches the file name.

Once the next version of RuboCop is released, you can update you configuration file to:

Naming/FileName:
  ExpectMatchingDefinition: true
  CheckDefinitionPathHierarchy: false

and the offences relating to the namespace should go away.


答:
I like @AnnZen's comprehension approach (+1) though my tendency would be to go more symbolic at the waste of some time and space:

```<code>dates = [ \
    ('12', '10', '1987'), \
    ('13', '09', '2010'), \
    ('34', '02', '2002'), \
    ('02', '15', '2005'), \
    ('37', '10', '2016'), \
    ('39', '11', '2001'), \
]

dates = [date for (day, month, _), date in zip(dates, dates) if day < '31' and month < '12']

print(dates)
</code>```

OUTPUT

```<code>> python3 test.py
[('12', '10', '1987'), ('13', '09', '2010')]
>
</code>```

As far as @np8's "Never modify the list you are looping over.", that's excellent advice.  Though, again, I might waste some space making the copy upfront to make my code simpler:

```<code>for date in list(dates):  # iterate over a copy
    day, month, _ = date

    if int(day) > 31 or int(month) > 12:
        dates.remove(date)
</code>```

Though in the end, @np8's filtering through datetime seems the most reliable solution.  (+1)

Title: Looping through a list of tuples and removing them

Body:
Im having some difficulty understanding why my loop is not deleting invalid dates from a list of date tuples in the format of dd/mm/yyyy . heres what i have so far :

dates = [('12','10','1987'),('13','09','2010'), ('34','02','2002'), ('02','15','2005'),('37','10','2016'),('39','11','2001')]
print(dates)

for date in dates :
    day = int(date[0])
    month = int(date[1])
    year = int(date[2])

    if day > 31 :
        dates.remove(date)

    if month > 12 :
        dates.remove(date)

print(dates)

and heres the result :

[('12', '10', '1987'), ('13', '09', '2010'), ('34', '02', '2002'), ('02', '15', '2005'), ('37', '10', '2016'), ('39', '11', '2001')]

[('12', '10', '1987'), ('13', '09', '2010'), ('02', '15', '2005'), ('39', '11', '2001')]

I'm a total beginner and any help would be much appreciated.

Body:
I like @AnnZen's comprehension approach (+1) though my tendency would be to go more symbolic at the waste of some time and space:

dates = [ \
    ('12', '10', '1987'), \
    ('13', '09', '2010'), \
    ('34', '02', '2002'), \
    ('02', '15', '2005'), \
    ('37', '10', '2016'), \
    ('39', '11', '2001'), \
]

dates = [date for (day, month, _), date in zip(dates, dates) if day < '31' and month < '12']

print(dates)

OUTPUT

> python3 test.py
[('12', '10', '1987'), ('13', '09', '2010')]
>

As far as @np8's "Never modify the list you are looping over.", that's excellent advice.  Though, again, I might waste some space making the copy upfront to make my code simpler:

for date in list(dates):  # iterate over a copy
    day, month, _ = date

    if int(day) > 31 or int(month) > 12:
        dates.remove(date)

Though in the end, @np8's filtering through datetime seems the most reliable solution.  (+1)


问:
How to set Javascript's variable value inside <input value=''">
I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.

This is my code:

```<code>$(".agregarListaF").click(function (e) {
  e.preventDefault();
  var padre = $(this);
  var hijos = padre.children().children("span");
  var i = 0;
  var datos = new Array();

  hijos.each(function () {
    switch (i) {
      case 0:
        datos[0] = $(this).text();
        break;

      case 1:
        padre;
        datos[1] = $(this).text();
        break;

      case 2:
        padre;
        datos[2] = $(this).text();
        break;
    }

    i++;
  });
  console.log(datos[0]);
  console.log(datos[1]);

  $(".detallefactura").append(
    "<tr>" +
      "<td>" +
      datos[0] +
      "</td>" +
      "<td>" +
      datos[1] +
      "</td>" +
      "<td>" +
      "<input type='text' class='form-control text-center' value='1'>" +
      "</td>" +
      "<td>" +
      "<input type='text' class='form-control text-center' value=''>" +
      "</td>" +
      "<td class='tota-sub-fila'>" +
      parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
      "</td>"
  );
});
</code>```

My issue is in the line:

```<code> + "<td>" + "<input type='text' class='form-control text-center' value=''>" + "</td>"
</code>```

I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:

```<code>+ "<td>" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "</td>"
</code>```

This is my point of sale view:

In the column precio is where I want to set the price inside that textbox.

How do I solve this?

答:
you can use Template literals like this instead of having this concatenation:</p>

```<code>$(.detallefactura").append(`<tr>
    <td> ${datos[0]} </td>
    <td> ${datos[1]} </td>
    <td> <input type='text' class='form-control text-center' value='1'> </td>
    <td> <input type='text' class='form-control text-center' value='${datos[2]}'> </td>
    <td class='tota-sub-fila'> ${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)} </td>
`);
</code>```

Body:
I do not know how to formulate this question but it is near close to my issue. I am trying to make a Point of sale system so when client clicks in each product it adds in the table. There are no issues in my code but I do not know how to set the product's price using a textbox when using .append.

This is my code:

$(".agregarListaF").click(function (e) {
  e.preventDefault();
  var padre = $(this);
  var hijos = padre.children().children("span");
  var i = 0;
  var datos = new Array();

  hijos.each(function () {
    switch (i) {
      case 0:
        datos[0] = $(this).text();
        break;

      case 1:
        padre;
        datos[1] = $(this).text();
        break;

      case 2:
        padre;
        datos[2] = $(this).text();
        break;
    }

    i++;
  });
  console.log(datos[0]);
  console.log(datos[1]);

  $(".detallefactura").append(
    "
" +
      "" +
      datos[0] +
      "	" +
      "" +
      datos[1] +
      "	" +
      "" +
      "<input type='text' class='form-control text-center' value='1'>" +
      "	" +
      "" +
      "<input type='text' class='form-control text-center' value=''>" +
      "	" +
      "" +
      parseFloat(Math.floor(datos[2]) * parseFloat(1)).toFixed(2) +
      "	"
  );
});

My issue is in the line:

 + "" + "<input type='text' class='form-control text-center' value=''>" + "	"

I want to add javascript value variable inside * input value=''* but I know It wont work but I tried it:

+ "" + "<input type='text' class='form-control text-center' value='datos[2]'>" + "	"

This is my point of sale view:

In the column precio is where I want to set the price inside that textbox.

How do I solve this?

Body:
you can use Template literals like this instead of having this concatenation:

$(.detallefactura").append(`<tr>
    <td> ${datos[0]} </td>
    <td> ${datos[1]} </td>
    <td> <input type='text' class='form-control text-center' value='1'> </td>
    <td> <input type='text' class='form-control text-center' value='${datos[2]}'> </td>
    <td class='tota-sub-fila'> ${parseFloat((Math.floor(datos[2])) * parseFloat(1)).toFixed(2)} </td>
`);


问:
Windows Server 2003: Task Scheduler is not running successfully VBS file jobs
We have an old Windows Server 2003 r2 which is doing nothing but using the task scheduler and a VBS file to check and rename some regularly re-occurring data files.  It is setup to run every hour using my credentials.  If I "run" it while I'm logged on the task runs and completes correctly.  When no one is logged on the task runs but completes with an 0x1 code, ie it failed.
I have checked the event logs and see nothing which I can identify as an error or failure.  We believe that it was running successfully until about 6-8 months ago (yes, it was one of those set it up and forget it things and we have not been regularly checking it).

=================Additional Information===============

I ran assoc .vbs and got this output: .vbs=VBSFile

I'm not sure how to determine the user environment variables?

For the task I have tried both the vbs file and also a bat file containing the reference to the vbs file.  Both run when I'm logged and both fail to complete successfully when I'm not.

Here is the vbs script:

```<code>Dim fso, file, recentDate, recentFile, theFile, myfolder, mypath
set fso = CreateObject("Scripting.FileSystemObject")
set recentFile = Nothing

mypath = "D:\TheFTP\Main\Camera\lobby"

set myfolder = fso.GetFolder(mypath)
For Each file in myfolder.Files
  If (recentFile is Nothing) Then
    set recentFile = file
  ElseIf (file.DateLastModified > recentFile.DateLastModified) Then
    set recentFile = file
  End If
Next

fso.CopyFile mypath& "\" & recentFile.name, "D:\TheFTP\main\camera\cam3.jpg"
set recentFile = nothing
set fso = nothing
</code>```

Here is the last bat file where I have piped the output to a file:

```<code>C:\windows\system32\cscript.exe c:\CopyWebCamFile.vbs > c:\debug.txt
</code>```

Debug.txt output when I'm not logged on shows an error, see below, which is not there when I run it and am logged on:

Microsoft (R) Windows Script Host Version 5.6

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

CScript Error: Initialization of the Windows Script Host failed. (The system cannot find the file specified.

=====================================================

More information, I added several Wscript.Echo statements to my script, before the first line, after the FOR loop and before the "copyFile" command.  When I'm logged on I see all of the output in C:\debug.txt.  When NOT logged on I see the same above error message, ie no Wscript.Echo output.  This would see to indicate that it can not find my vbs file when I'm not logged on.

===========================

Still no happiness here.  I moved and modified the .bat file to also output the contents of the script file:

```<code>type H:\Task_Stuff\CopyWebCamFileTest.vbs > H:\Task_Stuff\debug2.txt
C:\windows\system32\cscript.exe H:\Task_Stuff\CopyWebCamFileTest.vbs > H:\Task_Stuff\debug.txt
</code>```

As before I get output to both .txt files when it runs while I'm logged on and nothing in debug2.txt and the usual messages in debug.txt when I'm not.

I'll fiddle with the antivirus settings, but I need to ask about that first.  We are using Symantec SEP.

How can I check on the user environment variables?

====================

Maybe this will clarify my problem or suggest a solution??

Can you offer any ideas...RDK

答:
First off we would like to thank LeeHarvey1 for his time and suggestions as we searched for the cause of this issue.  In the end it was one of his suggestions that fixed the problem, but we still have no idea what caused it.

A reboot of the system cleared up all of the issues surrounding the task scheduler and running VB Scripts!  We had considered his early suggestion, but discounted it as this server had only been up for a little over 3 months.  Not excessive in our experience.  However, when all else failed we elected to do that and "voila" it fixed the issue.  We wish we knew what caused it but are now just happy we can move on to other things.

Thanks again LeeHarvey1....

Body:
We have an old Windows Server 2003 r2 which is doing nothing but using the task scheduler and a VBS file to check and rename some regularly re-occurring data files.  It is setup to run every hour using my credentials.  If I "run" it while I'm logged on the task runs and completes correctly.  When no one is logged on the task runs but completes with an 0x1 code, ie it failed.
I have checked the event logs and see nothing which I can identify as an error or failure.  We believe that it was running successfully until about 6-8 months ago (yes, it was one of those set it up and forget it things and we have not been regularly checking it).

=================Additional Information===============

I ran assoc .vbs and got this output: .vbs=VBSFile

I'm not sure how to determine the user environment variables?

For the task I have tried both the vbs file and also a bat file containing the reference to the vbs file.  Both run when I'm logged and both fail to complete successfully when I'm not.

Here is the vbs script:

Dim fso, file, recentDate, recentFile, theFile, myfolder, mypath
set fso = CreateObject("Scripting.FileSystemObject")
set recentFile = Nothing

mypath = "D:\TheFTP\Main\Camera\lobby"

set myfolder = fso.GetFolder(mypath)
For Each file in myfolder.Files
  If (recentFile is Nothing) Then
    set recentFile = file
  ElseIf (file.DateLastModified > recentFile.DateLastModified) Then
    set recentFile = file
  End If
Next

fso.CopyFile mypath& "\" & recentFile.name, "D:\TheFTP\main\camera\cam3.jpg"
set recentFile = nothing
set fso = nothing

Here is the last bat file where I have piped the output to a file:

C:\windows\system32\cscript.exe c:\CopyWebCamFile.vbs > c:\debug.txt

Debug.txt output when I'm not logged on shows an error, see below, which is not there when I run it and am logged on:

Microsoft (R) Windows Script Host Version 5.6

Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

CScript Error: Initialization of the Windows Script Host failed. (The system cannot find the file specified.

=====================================================

More information, I added several Wscript.Echo statements to my script, before the first line, after the FOR loop and before the "copyFile" command.  When I'm logged on I see all of the output in C:\debug.txt.  When NOT logged on I see the same above error message, ie no Wscript.Echo output.  This would see to indicate that it can not find my vbs file when I'm not logged on.

===========================

Still no happiness here.  I moved and modified the .bat file to also output the contents of the script file:

type H:\Task_Stuff\CopyWebCamFileTest.vbs > H:\Task_Stuff\debug2.txt
C:\windows\system32\cscript.exe H:\Task_Stuff\CopyWebCamFileTest.vbs > H:\Task_Stuff\debug.txt

As before I get output to both .txt files when it runs while I'm logged on and nothing in debug2.txt and the usual messages in debug.txt when I'm not.

I'll fiddle with the antivirus settings, but I need to ask about that first.  We are using Symantec SEP.

How can I check on the user environment variables?

====================

Maybe this will clarify my problem or suggest a solution??

Can you offer any ideas...RDK


问:
Converting object to string JQuery/JS/HTML
I am trying to append a list of countries to my select tag, but whatever I try it keeps showing as [object Object]. Here is my JS code:

I've tried var x = JSON.Stringify(country); and passing that into var o, and I've also tried country.toLocaleString('en-US); and that has not worked either. How can I have the countries show in the select list? Thanks

答:
You need to use world_list[i].country to access country.

Here is demo code :

//your json
var report={"last_updated":"2020-06-02T04:15:21Z","regions":{"world":{"name":"World","totals":{"confirmed":6370499,"recovered":2904076,"deaths":377515,"critical":2811064,"tests":11709},"list":[{"country":"Hong Kong","confirmed":1088,"deaths":4,"recovered":1037,"Incidence_Rate":"14.49915619446103","Case-Fatality_Ratio":"0.36798528058877644","last_updated":"2020-06-02T04:15:21Z","country_code":"hk","daily_confirmed":0,"daily_deaths":0,"critical":47,"tests":5},{"country":"Macao","confirmed":45,"deaths":-1,"recovered":45,"Incidence_Rate":"6.930092308829553","Case-Fatality_Ratio":"0.0","last_updated":"2020-06-02T04:15:21Z","country_code":"mo","daily_confirmed":0,"daily_deaths":-1,"critical":0,"tests":-1}]}}};

var world_list = report.regions.world.list;

    for(var i in world_list){
      //use word_list[i].country  to retrieve slected value
      var o = new Option(world_list[i].country, i);
      $("select").append(o);
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select></code>```

Body:
You need to use world_list[i].country to access country.

Here is demo code :

//your json
var report={"last_updated":"2020-06-02T04:15:21Z","regions":{"world":{"name":"World","totals":{"confirmed":6370499,"recovered":2904076,"deaths":377515,"critical":2811064,"tests":11709},"list":[{"country":"Hong Kong","confirmed":1088,"deaths":4,"recovered":1037,"Incidence_Rate":"14.49915619446103","Case-Fatality_Ratio":"0.36798528058877644","last_updated":"2020-06-02T04:15:21Z","country_code":"hk","daily_confirmed":0,"daily_deaths":0,"critical":47,"tests":5},{"country":"Macao","confirmed":45,"deaths":-1,"recovered":45,"Incidence_Rate":"6.930092308829553","Case-Fatality_Ratio":"0.0","last_updated":"2020-06-02T04:15:21Z","country_code":"mo","daily_confirmed":0,"daily_deaths":-1,"critical":0,"tests":-1}]}}};

var world_list = report.regions.world.list;

    for(var i in world_list){
      //use word_list[i].country  to retrieve slected value
      var o = new Option(world_list[i].country, i);
      $("select").append(o);
    }

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select>
</select>


问:
how to run python script in ruby on rails from a react frontend
I am currently writing a web-app with Rails backend and react.js frontend. Meanwhile, my project partner wrote some scripts in python to do some web scraping. I am thinking how can I run the python script. I have a customary action in one of my controllers. But now I am not very sure how do I call such action from my react frontend. I am guessing maybe Axios can help but I only know Axios can do POST and GET and not very sure how to define my own action.</p>
```<code>class DeadlinesController < ApplicationController
  def import
    exec(" python Users/sherrywu1999/Desktop/pythonweb.py")
  end
end
</code>```

答:
This is entirely possible. The safest method here is probably executing the script from a background job (sidekiq, resque, etc.).

If you don't want to set anything like that up I would recommend

```<code>fork { exec("python Users/sherrywu1999/Desktop/pythonweb.py > /some/path/to/output/log/to.log") }
</code>```

Using this, we are not blocking the execution of your rails app. If you just fire off the script with exec(...), the page will continue to load until the process exits which may result in a timeout or other bad behavior. Using this method allows your main ruby process to continue execution while the script is run in a separate process. You can then check the log output at a later time if needed.

Wherever you place this code, make sure to configure a get route to it, then perform a get request with axios to that path to execute the script when you want to.

Body:
I am currently writing a web-app with Rails backend and react.js frontend. Meanwhile, my project partner wrote some scripts in python to do some web scraping. I am thinking how can I run the python script. I have a customary action in one of my controllers. But now I am not very sure how do I call such action from my react frontend. I am guessing maybe Axios can help but I only know Axios can do POST and GET and not very sure how to define my own action.

class DeadlinesController < ApplicationController
  def import
    exec(" python Users/sherrywu1999/Desktop/pythonweb.py")
  end
end

Body:
This is entirely possible. The safest method here is probably executing the script from a background job (sidekiq, resque, etc.).

If you don't want to set anything like that up I would recommend

fork { exec("python Users/sherrywu1999/Desktop/pythonweb.py > /some/path/to/output/log/to.log") }

Using this, we are not blocking the execution of your rails app. If you just fire off the script with exec(...), the page will continue to load until the process exits which may result in a timeout or other bad behavior. Using this method allows your main ruby process to continue execution while the script is run in a separate process. You can then check the log output at a later time if needed.

Wherever you place this code, make sure to configure a get route to it, then perform a get request with axios to that path to execute the script when you want to.


问:
FontFamily React Native App overwrite with device custom font (Samsung & Oppo)
In React Native, I define font family for all text with Rubik font but for some devices (SAMSUNG & OPPO), the font looks like overwrite with a custom device font because that brand can choose a custom font for their device.

I don't know why sometimes some text looks like overwrite with custom device font & some text still uses the Rubik font.

Environment:

OS: macOS HighSierra

Node: 9.3.0

Yarn: 1.3.2

npm: 5.7.0

Watchman: 4.9.0

Packages:

react-native: "^0.47.2,

react: "^16.0.0-alpha.12,

react-native-vector-icons: ^4.4.2,

Target Platform: Android

Any ideas on how to make a device font can't overwrite the set font family font?

答:
In your package.json add the key </p>

```<code>{
.
.
.
  sideEffects:false,
.
.
.
}
</code>```

Body:
In your package.json add the key

{
.
.
.
  sideEffects:false,
.
.
.
}