答:
You need to initialize the array outside of the function, otherwise every time you call the function, it will be reset to []

```<code><script type="text/javascript">

  let myArray = []; // create array here

  const insertOptions = x=>{
    console.log(x);
  }

  const circleInsertOptions = () => {
    let x = 48;
    myArray.push(48);
    console.log(myArray);
    return myArray;
  };

  document.getElementById('me').addEventListener('click', circleInsertOptions);

</script>
</code>```

Title: Why is this Array is not saving the pushed elements each time the event is triggered?

Body:
You need to initialize the array outside of the function, otherwise every time you call the function, it will be reset to []

<script type="text/javascript">

  let myArray = []; // create array here

  const insertOptions = x=>{
    console.log(x);
  }

  const circleInsertOptions = () => {
    let x = 48;
    myArray.push(48);
    console.log(myArray);
    return myArray;
  };

  document.getElementById('me').addEventListener('click', circleInsertOptions);

</script>


来源: stackexchange

问:
AWS SES verifyemailidentity
I wrote the following .net code to add run time email address in AWS-SES "Email Address Identities list" and sending email to user for verification, but its not working, though the response saying "WaitingforActivation". But neither email address is added in SES "Email Address Identities" nor email went to the respective email address for verification. Any help on the same is appreciated.</p>

```<code>public void SESVerifyEmailIdentity()
{
    var sesClient = new AmazonSimpleEmailServiceClient("XXXXXXXXXXXXX", "XXXXXXXXXXX", "USEast1");

    var request = new VerifyEmailIdentityRequest
    {
        EmailAddress = "Joe@example.com"
    };
    var response = sesClient.VerifyEmailIdentityAsync(request);
}
</code>```

答:
I resolved my issue, I was not using the right credentials for AWS. When I used my AWS credentials, its working for me.</p>

```<code>   public  void SESVerifyEmailIdentity()
       {
           #region SESVerifyEmailIdentity

          var awsCredentials = new
              Amazon.Runtime.BasicAWSCredentials("YOUR-ACCESS-KEY-HERE", "YOUR-SECRET-KEY-HERE);

            var sesClient = new AmazonSimpleEmailServiceClient(awsCredentials, RegionEndpoint.USEast1);

        var request = new VerifyEmailIdentityRequest
        {
            EmailAddress = "Joe@Example.com"
        };

        var response = sesClient.VerifyEmailIdentityAsync(request);

        #endregion
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: AWS SES verifyemailidentity

Body:
I wrote the following .net code to add run time email address in AWS-SES "Email Address Identities list" and sending email to user for verification, but its not working, though the response saying "WaitingforActivation". But neither email address is added in SES "Email Address Identities" nor email went to the respective email address for verification. Any help on the same is appreciated.

public void SESVerifyEmailIdentity()
{
    var sesClient = new AmazonSimpleEmailServiceClient("XXXXXXXXXXXXX", "XXXXXXXXXXX", "USEast1");

    var request = new VerifyEmailIdentityRequest
    {
        EmailAddress = "Joe@example.com"
    };
    var response = sesClient.VerifyEmailIdentityAsync(request);
}

Body:
I resolved my issue, I was not using the right credentials for AWS. When I used my AWS credentials, its working for me.

   public  void SESVerifyEmailIdentity()
       {
           #region SESVerifyEmailIdentity

          var awsCredentials = new
              Amazon.Runtime.BasicAWSCredentials("YOUR-ACCESS-KEY-HERE", "YOUR-SECRET-KEY-HERE);

            var sesClient = new AmazonSimpleEmailServiceClient(awsCredentials, RegionEndpoint.USEast1);

        var request = new VerifyEmailIdentityRequest
        {
            EmailAddress = "Joe@Example.com"
        };

        var response = sesClient.VerifyEmailIdentityAsync(request);

        #endregion
    }


问:
Redis using 100% CPU after 6 hours of uptime

As seen in the image above, I'm experiencing performance issues with Redis after it has been running for an extended period of time; specially, 6 hours.

I'm using Redis to cache responses from an API so I don't have to re-fetch dozens of rows on every request, and I thought - hey this should work. Apparently not.

```<code>module.exports = (app, csrfProtection, jsonParser) => {
    app.get("/api/steam/getPlayerSummaries", [steamRateLimits.getPlayerSummaries, jsonParser, csrfProtection], async(req, res) => {
        redisClient.hmget("steam_user", req.query.steamids, (err, reply) => {
            if(err) return res.status(500).send({ message: `Could not read from Redis with error ${err}`});

            redisClient.hmget(`steam_user_expires_${req.query.steamids}`, "expires", (err, expire) => {
                if(err) return res.status(500).send({ message: `Could not read from Redis with error ${err}`});

                if(reply[0] && (CURRENT_UNIX_TIME - expire < REDIS_EXPIRE_LIMIT)) return res.status(200).send(JSON.parse(reply));

                const queryParams = querystring.stringify({
                    key: process.env.STEAM_API_KEY,
                    steamids: req.query.steamids
                }),
                options = {
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    }
                };

                http.get(`http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?${queryParams}`, options, response => {
                    const { statusCode } = response;

                    if(statusCode != 200) {
                        response.resume();
                        return res.status(statusCode).send({ message: `Could not fetch Steam API getPlayerSummaries with status code ${statusCode}`});
                    }

                    response.setEncoding("utf8");
                    let rawData = "";

                    response.on("data", chunk => rawData += chunk);
                    response.on("end", _ => {
                        try {
                            const parsedData = JSON.parse(rawData);

                            redisClient.hmset(["steam_user", req.query.steamids, rawData]);
                            redisClient.hmset([`steam_user_expires_${req.query.steamids}`, "expires", CURRENT_UNIX_TIME]);

                            return res.status(200).send(parsedData);
                        } catch (e) {
                            console.error(e.message);
                        }
                    });
                }).on("error", e => {
                    console.error(`Got error: ${e.message}`);
                    return res.status(500).send(e);
                });
            });
        });
    });
}
</code>```

Here's the progress overview of what happens in chronological order when a user tries to access this route:

User loads the index (default) webpage. This page can have over 20
rows that need to run 20 API queries from the remote API (one of the
reasons I cache this).

Check if user is already cached in redis

Check if there exists an expiration key for said steam user (even if it doesn't exist).

If cache exists and it was fetched in less than 15 minutes ago, display result from Redis cache.

If cache doesn't exist, we query the remote API.

If request was successful, cache data into Redis and return response.

For some reason this gets caught up in itself and after some time running Redis uses so much CPU and RAM it's insane and I thought I was dealing with this properly.

I am also clearing ALL cache once a day using a shell script and crontab.

```<code>redis-cli KEYS "steam_user*" | xargs redis-cli DEL
</code>```

Why does it continue to use up more CPU and RAM (even if there is literally no visitors, and I'm scared to think what would happen if there were a lot of visitors), and how can I work around this issue to fix it?

答: The process that is using all your resources is /tmp/kdevtmpfsi. A quick google search showed that it's mining malware. This means that not Redis nor your program has some kind of error. This comment on Github explains how to get rid of it.</p>

Body:
As seen in the image above, I'm experiencing performance issues with Redis after it has been running for an extended period of time; specially, 6 hours.

I'm using Redis to cache responses from an API so I don't have to re-fetch dozens of rows on every request, and I thought - hey this should work. Apparently not.

module.exports = (app, csrfProtection, jsonParser) => {
    app.get("/api/steam/getPlayerSummaries", [steamRateLimits.getPlayerSummaries, jsonParser, csrfProtection], async(req, res) => {
        redisClient.hmget("steam_user", req.query.steamids, (err, reply) => {
            if(err) return res.status(500).send({ message: `Could not read from Redis with error ${err}`});

            redisClient.hmget(`steam_user_expires_${req.query.steamids}`, "expires", (err, expire) => {
                if(err) return res.status(500).send({ message: `Could not read from Redis with error ${err}`});

                if(reply[0] && (CURRENT_UNIX_TIME - expire < REDIS_EXPIRE_LIMIT)) return res.status(200).send(JSON.parse(reply));

                const queryParams = querystring.stringify({
                    key: process.env.STEAM_API_KEY,
                    steamids: req.query.steamids
                }),
                options = {
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded"
                    }
                };

                http.get(`http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?${queryParams}`, options, response => {
                    const { statusCode } = response;

                    if(statusCode != 200) {
                        response.resume();
                        return res.status(statusCode).send({ message: `Could not fetch Steam API getPlayerSummaries with status code ${statusCode}`});
                    }

                    response.setEncoding("utf8");
                    let rawData = "";

                    response.on("data", chunk => rawData += chunk);
                    response.on("end", _ => {
                        try {
                            const parsedData = JSON.parse(rawData);

                            redisClient.hmset(["steam_user", req.query.steamids, rawData]);
                            redisClient.hmset([`steam_user_expires_${req.query.steamids}`, "expires", CURRENT_UNIX_TIME]);

                            return res.status(200).send(parsedData);
                        } catch (e) {
                            console.error(e.message);
                        }
                    });
                }).on("error", e => {
                    console.error(`Got error: ${e.message}`);
                    return res.status(500).send(e);
                });
            });
        });
    });
}

Here's the progress overview of what happens in chronological order when a user tries to access this route:

User loads the index (default) webpage. This page can have over 20
rows that need to run 20 API queries from the remote API (one of the
reasons I cache this).

Check if user is already cached in redis

Check if there exists an expiration key for said steam user (even if it doesn't exist).

If cache exists and it was fetched in less than 15 minutes ago, display result from Redis cache.

If cache doesn't exist, we query the remote API.

If request was successful, cache data into Redis and return response.

For some reason this gets caught up in itself and after some time running Redis uses so much CPU and RAM it's insane and I thought I was dealing with this properly.

I am also clearing ALL cache once a day using a shell script and crontab.

redis-cli KEYS "steam_user*" | xargs redis-cli DEL

Why does it continue to use up more CPU and RAM (even if there is literally no visitors, and I'm scared to think what would happen if there were a lot of visitors), and how can I work around this issue to fix it?


问:
Flutter inputformatter for date
I am looking for an example of an inputformatter for text field that will be a date mm/dd/yyyy, what I am trying to do as the user types update the format.  For instance user starts to type mm and the / is put in, then when the dd is typed in the / is put in.

Anyone done this or have an example?  I have done it in other languages but could not find a similar way to do in flutter/dart.

This is what I have tried so far, but can not get the logic correct.  Any ideas?

```<code>    class _DateFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue,
      TextEditingValue newValue
      ) {
    final int newTextLength = newValue.text.length;
    int selectionIndex = newValue.selection.end;
    int usedSubstringIndex = 0;
    final StringBuffer newText = new StringBuffer();
    if (newTextLength == 2) {
      newText.write(newValue.text.substring(0, 2) + '/ ');
      if (newValue.selection.end == 3)
        selectionIndex+=3;
    }
    if (newTextLength == 5) {
      newText.write(newValue.text.substring(0, 5) + '/ ');
      if (newValue.selection.end == 6)
        selectionIndex += 6;
    }
    // Dump the rest.
    if (newTextLength >= usedSubstringIndex)
      newText.write(newValue.text.substring(usedSubstringIndex));
    return new TextEditingValue(
      text: newText.toString(),
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}
</code>```

Thanks

答:
Here is an improved version based on Jochem Toolenaar answer. This version will automatically remove the forward slashes for you and limit the user to 8 digits.</p>

```<code>class DateTextFormatter extends TextInputFormatter {
  static const _maxChars = 8;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    var text = _format(newValue.text, '/');
    return newValue.copyWith(text: text, selection: updateCursorPosition(text));
  }

  String _format(String value, String seperator) {
    value = value.replaceAll(seperator, '');
    var newString = '';

    for (int i = 0; i < min(value.length, _maxChars); i++) {
      newString += value[i];
      if ((i == 1 || i == 3) && i != value.length - 1) {
        newString += seperator;
      }
    }

    return newString;
  }

  TextSelection updateCursorPosition(String text) {
    return TextSelection.fromPosition(TextPosition(offset: text.length));
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Flutter inputformatter for date

Body:
I am looking for an example of an inputformatter for text field that will be a date mm/dd/yyyy, what I am trying to do as the user types update the format.  For instance user starts to type mm and the / is put in, then when the dd is typed in the / is put in.

Anyone done this or have an example?  I have done it in other languages but could not find a similar way to do in flutter/dart.

This is what I have tried so far, but can not get the logic correct.  Any ideas?

    class _DateFormatter extends TextInputFormatter {
  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue,
      TextEditingValue newValue
      ) {
    final int newTextLength = newValue.text.length;
    int selectionIndex = newValue.selection.end;
    int usedSubstringIndex = 0;
    final StringBuffer newText = new StringBuffer();
    if (newTextLength == 2) {
      newText.write(newValue.text.substring(0, 2) + '/ ');
      if (newValue.selection.end == 3)
        selectionIndex+=3;
    }
    if (newTextLength == 5) {
      newText.write(newValue.text.substring(0, 5) + '/ ');
      if (newValue.selection.end == 6)
        selectionIndex += 6;
    }
    // Dump the rest.
    if (newTextLength >= usedSubstringIndex)
      newText.write(newValue.text.substring(usedSubstringIndex));
    return new TextEditingValue(
      text: newText.toString(),
      selection: new TextSelection.collapsed(offset: selectionIndex),
    );
  }
}

Thanks

Body:
Here is an improved version based on Jochem Toolenaar answer. This version will automatically remove the forward slashes for you and limit the user to 8 digits.

class DateTextFormatter extends TextInputFormatter {
  static const _maxChars = 8;

  @override
  TextEditingValue formatEditUpdate(
      TextEditingValue oldValue, TextEditingValue newValue) {
    var text = _format(newValue.text, '/');
    return newValue.copyWith(text: text, selection: updateCursorPosition(text));
  }

  String _format(String value, String seperator) {
    value = value.replaceAll(seperator, '');
    var newString = '';

    for (int i = 0; i < min(value.length, _maxChars); i++) {
      newString += value[i];
      if ((i == 1 || i == 3) && i != value.length - 1) {
        newString += seperator;
      }
    }

    return newString;
  }

  TextSelection updateCursorPosition(String text) {
    return TextSelection.fromPosition(TextPosition(offset: text.length));
  }
}


问:
Routing Issue when using static content (Angular 8) with NestJS and Fastify
I've been searching for the last several days for a way to fix a routing issue when using static content with NestJS and Fastify.  Specifically I am trying to use Angular 8 hosted by NestJS with Fastify under the hood.  I've been following the example given in by the tutorial: https://www.djamware.com/post/5d2898430707cc5968d9d57f/build-a-web-app-using-nestjs-fastify-mongodb-and-angular-8

The issue is that if you try to navigate directly to a specific URL, such as http://localhost:3000/articles, the Fastify server responds with a JSON string containing a 404 error message.  I've narrowed down the issue to something specifically problematic with Fastify by cloning the tutorial's GitHub repo and doing nothing more to it than is required to replace Fastify with Express, which does work.

I'm posting my code in the hope that someone can tell me what I am doing wrong.  I'd like to use Fastify instead of Express, because if the speed claims are accurate I could really use the increased performance. I've left the commented out code that I used to switch the project of Express. Thank you to anyone who takes the time to look this over and even try to help.

EDIT:  I just realized that I forgot to provide a link to the GitHub repo, here it is: https://github.com/didinj/nestjs-fastify-mongodb-angular8.git

main.ts

```<code>import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { join } from 'path';

async function bootstrap() {
  // const app = await NestFactory.create(AppModule);

  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      wildcard: false,
      logger: {
        level: 'trace',
        file: '/Users/jcorekin/fastify.log' // Will use pino.destination()
      }
    }),
  );
  app.useStaticAssets({
    root: join(__dirname, '../client/dist/
  });

  await app.listen(3000, '0.0.0.0');
}
bootstrap();
</code>```

app.module.ts

```<code>import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ArticleModule } from './article/article.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports:
  [
    // ArticleModule,
    // ServeStaticModule.forRoot({
    //   rootPath: join(__dirname, '../client/dist/client'),
    // }),
  ],
  // controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }
</code>```

app.service.ts

```<code>import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}
</code>```

答:
I found a solution, but annoyingly it requires replacing Fastify with Express. It seems that Fastify has some issues with routing.

main.ts

```<code>import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.setGlobalPrefix('api');
  await app.listen(3000);
}
bootstrap();
</code>```

app.module.ts

```<code>import { CommentModule } from './comment/comment.module';
import { Module, HttpModule } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ProfessorModule } from './professor/professor.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', '..', 'client/dist/client'),
    }),
    HttpModule,
    ...
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }
</code>```

I really wanted to keep Fastify, but I spent the whole day today trying to figure out why the routing was broken, when I could simply change to express and it works perfectly!

I will also admit that I didn't try this exact solution with fastify, so it may work with fastify, if you just keep the old fastify app creation code, get rid of that weird "useStaticAssets" call, and just use serve-static on app.module.ts

Body:
I've been searching for the last several days for a way to fix a routing issue when using static content with NestJS and Fastify.  Specifically I am trying to use Angular 8 hosted by NestJS with Fastify under the hood.  I've been following the example given in by the tutorial: https://www.djamware.com/post/5d2898430707cc5968d9d57f/build-a-web-app-using-nestjs-fastify-mongodb-and-angular-8

The issue is that if you try to navigate directly to a specific URL, such as http://localhost:3000/articles, the Fastify server responds with a JSON string containing a 404 error message.  I've narrowed down the issue to something specifically problematic with Fastify by cloning the tutorial's GitHub repo and doing nothing more to it than is required to replace Fastify with Express, which does work.

I'm posting my code in the hope that someone can tell me what I am doing wrong.  I'd like to use Fastify instead of Express, because if the speed claims are accurate I could really use the increased performance. I've left the commented out code that I used to switch the project of Express. Thank you to anyone who takes the time to look this over and even try to help.

EDIT:  I just realized that I forgot to provide a link to the GitHub repo, here it is: https://github.com/didinj/nestjs-fastify-mongodb-angular8.git

main.ts

import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import { join } from 'path';

async function bootstrap() {
  // const app = await NestFactory.create(AppModule);

  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter({
      wildcard: false,
      logger: {
        level: 'trace',
        file: '/Users/jcorekin/fastify.log' // Will use pino.destination()
      }
    }),
  );
  app.useStaticAssets({
    root: join(__dirname, '../client/dist/
  });

  await app.listen(3000, '0.0.0.0');
}
bootstrap();

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ArticleModule } from './article/article.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports:
  [
    // ArticleModule,
    // ServeStaticModule.forRoot({
    //   rootPath: join(__dirname, '../client/dist/client'),
    // }),
  ],
  // controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

app.service.ts

import { Injectable } from '@nestjs/common';

@Injectable()
export class AppService {
  getHello(): string {
    return 'Hello World!';
  }
}

Body:
I found a solution, but annoyingly it requires replacing Fastify with Express. It seems that Fastify has some issues with routing.

main.ts

import { NestExpressApplication } from '@nestjs/platform-express';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.setGlobalPrefix('api');
  await app.listen(3000);
}
bootstrap();

app.module.ts

import { CommentModule } from './comment/comment.module';
import { Module, HttpModule } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ProfessorModule } from './professor/professor.module';
import { ServeStaticModule } from '@nestjs/serve-static';
import { join } from 'path';

@Module({
  imports: [
    ServeStaticModule.forRoot({
      rootPath: join(__dirname, '..', '..', 'client/dist/client'),
    }),
    HttpModule,
    ...
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule { }

I really wanted to keep Fastify, but I spent the whole day today trying to figure out why the routing was broken, when I could simply change to express and it works perfectly!

I will also admit that I didn't try this exact solution with fastify, so it may work with fastify, if you just keep the old fastify app creation code, get rid of that weird "useStaticAssets" call, and just use serve-static on app.module.ts


问:
Recording\Playing audio directly with libmedia\AudioFlinger
I'm checking out the possibility of interfacing directly to libmedia\AudioFlinger for playing\recording raw audio (like AudioTrack\AudioRecord do).

The purpose is to workaround the minimum buffer size limitation of those 2 Java classes.
I know that 2.3 introduces OpenSL, but I want to do that for 2.2 and below.

Has anyone done that before? Is there any good reference implementation that uses that?
If not, how would you approach linking against this library and using it to workaround the minimum buffer size?

Thanks

答: Unfortunately there are only two supported audio APIs available, and you have mentioned both (AudioTrack and OpenSL). Any lower level than that and you would be interfering with the audio mixing already being done by the device for things like SFX and phone calls. Also as there is no API for lower layer audio you would need to go hacking, which probably isn't what you want to do for obvious compatibility reasons.</p>


问:
Why are wrong bits extracted in python?
I need several k bits at position p extracted in order to convert to decimal value. I use a standard function but still when I test it for a 6/7/8 byte long binary code it is not correct. When I have a 1 byte code it is little-endian but once I use a 8 byte code it is shifted. For one signal (of a 7byte code) it was shifted +7bits but another signal (another ID, 8byte code) was shifted by -21bits. I cannot explain this to myself so I thought of playing around and manually add or subtract bits in order to use the correct bits for calculation. Do you have any idea why this is happening?

Example 8bytes:

```<code>extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',16,0)
</code>```

Output: 001110100111101 instead of 1000011110000000

```<code>extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',16,24)
</code>```

Output: 0110010001110111 instead of 1011001000111011

This is the code I am working with:

```<code>import openpyxl
from openpyxl import Workbook

theFile = openpyxl.load_workbook('Adapted_T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active

def extract_k_bits(inputBIN,k,p):
        end = len(inputBIN) - p
        start = end - k + 1
        kBitSub = inputBIN[start : end+1]
        print(kBitSub)
        Dec_Values=int(kBitSub,2)
</code>```

答:
Here's a working solution:

def extract_k_bits(inputBIN,k):
    # Since you always extract 16 bits
    # just use the point where you want to extract from
        kBitSub = inputBIN[k : k+16]
        print(kBitSub)

extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',0)
extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',23)
```

Output

Title: Why are wrong bits extracted in python?

Body:
I need several k bits at position p extracted in order to convert to decimal value. I use a standard function but still when I test it for a 6/7/8 byte long binary code it is not correct. When I have a 1 byte code it is little-endian but once I use a 8 byte code it is shifted. For one signal (of a 7byte code) it was shifted +7bits but another signal (another ID, 8byte code) was shifted by -21bits. I cannot explain this to myself so I thought of playing around and manually add or subtract bits in order to use the correct bits for calculation. Do you have any idea why this is happening?

Example 8bytes:

extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',16,0)

Output: 001110100111101 instead of 1000011110000000

extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',16,24)

Output: 0110010001110111 instead of 1011001000111011

This is the code I am working with:

import openpyxl
from openpyxl import Workbook

theFile = openpyxl.load_workbook('Adapted_T013.xlsx')
allSheetNames = theFile.sheetnames
print("All sheet names {} " .format(theFile.sheetnames))
sheet = theFile.active

def extract_k_bits(inputBIN,k,p):
        end = len(inputBIN) - p
        start = end - k + 1
        kBitSub = inputBIN[start : end+1]
        print(kBitSub)
        Dec_Values=int(kBitSub,2)

Body:
Here's a working solution:

def extract_k_bits(inputBIN,k):
    # Since you always extract 16 bits
    # just use the point where you want to extract from
        kBitSub = inputBIN[k : k+16]
        print(kBitSub)

extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',0)
extract_k_bits('100001111000000001110111011001000111011111111000001110100111101',23)

Output


问:
How to fix 'Failed to compile in ./src/global.scss'
I had created project in ionic v4 and I got error in ./src/global.scss, see error in the below

```<code>>ERROR in ./src/global.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/global.scss)
[ng] Module build failed (from ./node_modules/sass-loader/lib/loader.js):
[ng] Error: Cannot find module 'node-sass'
[ng]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
[ng]     at Function.Module._load (internal/modules/cjs/loader.js:507:25)
[ng]     at Module.require (internal/modules/cjs/loader.js:637:17)
[ng]     at require (internal/modules/cjs/helpers.js:22:18)
[ng]     at Object.sassLoader (/home/manish/newionic_workspace/latest100days/node_modules/sass-loader/lib/loader.js:46:72)
[ng] ERROR in ./src/theme/variables.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/theme/variables.scss)
[ng] Module build failed (from ./node_modules/sass-loader/lib/loader.js):
[ng] Error: Cannot find module 'node-sass'
[ng]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
[ng]     at Function.Module._load (internal/modules/cjs/loader.js:507:25)
[ng]     at Module.require (internal/modules/cjs/loader.js:637:17)
[ng]     at require (internal/modules/cjs/helpers.js:22:18)
[ng]     at Object.sassLoader (/home/manish/newionic_workspace
/latest100days/node_modules/sass-loader/lib/loader.js:46:72)
</code>```

I have used the rebuild command also

```<code>npm rebuild node-sass
</code>```

but it's not work

答:
You have to give global permission first, add sudo at the beggining.

sudo npm i node-sass

Hope this works for you too!

Body:
I had created project in ionic v4 and I got error in ./src/global.scss, see error in the below

>ERROR in ./src/global.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/global.scss)
[ng] Module build failed (from ./node_modules/sass-loader/lib/loader.js):
[ng] Error: Cannot find module 'node-sass'
[ng]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
[ng]     at Function.Module._load (internal/modules/cjs/loader.js:507:25)
[ng]     at Module.require (internal/modules/cjs/loader.js:637:17)
[ng]     at require (internal/modules/cjs/helpers.js:22:18)
[ng]     at Object.sassLoader (/home/manish/newionic_workspace/latest100days/node_modules/sass-loader/lib/loader.js:46:72)
[ng] ERROR in ./src/theme/variables.scss (./node_modules/@angular-devkit/build-angular/src/angular-cli-files/plugins/raw-css-loader.js!./node_modules/postcss-loader/src??embedded!./node_modules/sass-loader/lib/loader.js??ref--14-3!./src/theme/variables.scss)
[ng] Module build failed (from ./node_modules/sass-loader/lib/loader.js):
[ng] Error: Cannot find module 'node-sass'
[ng]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:581:15)
[ng]     at Function.Module._load (internal/modules/cjs/loader.js:507:25)
[ng]     at Module.require (internal/modules/cjs/loader.js:637:17)
[ng]     at require (internal/modules/cjs/helpers.js:22:18)
[ng]     at Object.sassLoader (/home/manish/newionic_workspace
/latest100days/node_modules/sass-loader/lib/loader.js:46:72)

I have used the rebuild command also

npm rebuild node-sass

but it's not work


问:
C++: How do I assign a value from a 2D dynamic array to another 2D dynamic array since 'temp[0][0] = array[0][0]' doesn't work?
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!</p>

```<code>    ...
    //initializing first 2D dynamic array
    int x=2;
    int y=2;
    int** array = new int*[x];
    for(int i=0; i<x; i++) array[i] = new int[y];

    //initializing second 2D dynamic array
    int new_x=3;
    int new_y=3;
    int** temp = new int*[new_x];
    for(int i=0; i<new_x; i++) temp[i] = new int[new_y];

    //assigning values
    array[0][0] = 1;
    cout << array[0][0] << endl; //output is 1

    //before assigning values to temp[0][0]
    cout << temp[0][0] << endl; //out is a huge random number

    temp[0][0] = array[0][0];
    cout << temp[0][0] << endl; //output is the same huge random number

    temp[0][0] = 2;
    cout << temp[0][0] << endl; //output is 2
    ...
</code>```

答: I have tried running the code,and the output indeed is 1 after assigning the value.</p>

Body:
I'm new to c++, and I'm trying to figure out how to get a 2D dynamic array called temp to get values from another 2D dynamic array called array. I couldn't figure out how to assign any values from array to temp because the statement 'temp[0][0] = array[0][0];' doesn't seem to assign the value of array[0][0] which is 1 to temp[0][0]. Instead, temp[0][0] seems to have the same random number in it after 'temp[0][0] = array[0][0]' before any value was assign to temp[0][0]. I tried to assign temp[0][0] to 2 and it works. I don't really know how to exactly assign values from one 2d dynamic array to another. Anyway thanks in advance for helping me out!

    ...
    //initializing first 2D dynamic array
    int x=2;
    int y=2;
    int** array = new int*[x];
    for(int i=0; i<x; i++) array[i] = new int[y];

    //initializing second 2D dynamic array
    int new_x=3;
    int new_y=3;
    int** temp = new int*[new_x];
    for(int i=0; i<new_x; i++) temp[i] = new int[new_y];

    //assigning values
    array[0][0] = 1;
    cout << array[0][0] << endl; //output is 1

    //before assigning values to temp[0][0]
    cout << temp[0][0] << endl; //out is a huge random number

    temp[0][0] = array[0][0];
    cout << temp[0][0] << endl; //output is the same huge random number

    temp[0][0] = 2;
    cout << temp[0][0] << endl; //output is 2
    ...


问:
Bash echo output mix of string and character
I am taking an assessment and stumbled across the following sample question, but when I run the line it's none of the options?  Which is the correct answer?

答:
That code looks more like PHP. . is the concatenation operator, and it can be used with both strings and numbers (it will convert the number to a string). The output will be

```<code>Tomorrow will be January 3rd
</code>```

In bash, . has no special meaning, so it will be echoed literally. The echo command puts a space between each argument, so the output will be

```<code>Tomorrow .  will be January  . 3 . rd
</code>```

Body:
That code looks more like PHP. . is the concatenation operator, and it can be used with both strings and numbers (it will convert the number to a string). The output will be

Tomorrow will be January 3rd

In bash, . has no special meaning, so it will be echoed literally. The echo command puts a space between each argument, so the output will be

Tomorrow .  will be January  . 3 . rd


问:
Is there a way to get all the test methods in a maven project
I am working on a project which requires me to get all the test methods under a project in maven. In other words, I need to get all methods that have @Test annotation. I wanted to check if there is a way/plugin which I can use to get it.

Thanks
Kiran

答:
```<code>ag --skip-vcs-ignores --xml "<testcase name" | cut -d' ' -f 4,5 | awk '{ print $2 " " $1}' | sed 's/classname="//' | sed 's/" name="/#/' | sed 's/"//'
</code>```

Gives:

```<code>aPackage.TestClass#testMethod1
aPackage.TestClass#testMethod2
</code>```

... etc

Body:
ag --skip-vcs-ignores --xml "<testcase name" | cut -d' ' -f 4,5 | awk '{ print $2 " " $1}' | sed 's/classname="//' | sed 's/" name="/#/' | sed 's/"//'

Gives:

aPackage.TestClass#testMethod1
aPackage.TestClass#testMethod2

... etc


问:
"object 'i' not found" the for loop
I am trying to make a simple for loop, that would add a new column to the existing data frame, by assigning a time class to each observation. I am getting 'object 'i' not found' and not sure where is a mistake. I am not that experienced with R, so thank you for any help!

for (i in 1:nrow(my.data)) {
    if(my.data$RTime[i] <= 3600){
        my.data$RTimeHour[i] <- 1
    }ifelse (my.data$RTime[i] > 3601 & my.data$RTime[i] < 7200){
        my.data$RTimeHour[i] <- 2
    }esle {
        my.data$RTimeHour[i] <- 3
    }
}
```

答:
The error is probably coming from the ifelse() you have:

```<code>for (i in 1:nrow(my.data)) {
    if(my.data$RTime[i] <= 3600){
        my.data$RTimeHour[i] <- 1
    }ifelse (my.data$RTime[i] > 3601 & my.data$RTime[i] < 7200){
        my.data$RTimeHour[i] <- 2
    }esle {
        my.data$RTimeHour[i] <- 3
    }
}
</code>```

Try this instead:

```<code>    if(my.data$RTime[i] <= 3600){
        my.data$RTimeHour[i] <- 1
    }else if(my.data$RTime[i] > 3601 & my.data$RTime[i] < 7200){
        my.data$RTimeHour[i] <- 2
    }else {
        my.data$RTimeHour[i] <- 3
    }
}

ifelse vectorizes how the problem, so ifelse(x[i]) will try to refer to something outside of the loop.
</code>```

Title: "object 'i' not found" the for loop

Body:
The error is probably coming from the ifelse() you have:

for (i in 1:nrow(my.data)) {
    if(my.data$RTime[i] <= 3600){
        my.data$RTimeHour[i] <- 1
    }ifelse (my.data$RTime[i] > 3601 & my.data$RTime[i] < 7200){
        my.data$RTimeHour[i] <- 2
    }esle {
        my.data$RTimeHour[i] <- 3
    }
}

Try this instead:

    if(my.data$RTime[i] <= 3600){
        my.data$RTimeHour[i] <- 1
    }else if(my.data$RTime[i] > 3601 & my.data$RTime[i] < 7200){
        my.data$RTimeHour[i] <- 2
    }else {
        my.data$RTimeHour[i] <- 3
    }
}

ifelse vectorizes how the problem, so ifelse(x[i]) will try to refer to something outside of the loop.


问:
Button being cut off by mat-step element
Problem Statement

My button is being cut off by the mat-step element or so it seems.

What I've Tried

I played around with the padding and margins of the mat-step element and it doesn't work.

I played around with the positioning and it doesn't work.

I played with the z-index but to no avail.

Picture of Problem

Explanation of Picture

As you can see, the next button is being cut off by the mat-step element, and I made sure that the problem is the mat-step. I did this by making the background of the stepper grey and found that it adjusts just fine. I made the mat-step grey, but nothing showed up, and it doesn't adjust with any CSS. There is clearly something wrong with the mat-step.

My Code

CSS

```<code>.stepper {
  position: relative;
  top: 50px;
}

.stepBtns {
  position: relative;
  font-size: 20pt;
  padding: 10px 30px;
  box-sizing: border-box;
  border: 1px solid #000000;
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25), 0px 4px 4px rgba(0, 0, 0, 0.25);
  border-radius: 16px;
  text-align: center;
  top: 50px;
}

</code>```

HTML

```<code><mat-horizontal-stepper class="stepper">
    <!-- Step 1 -->
    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <!-- Step 2 -->
    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <!-- Step 3 -->
    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <!-- Step 4 -->
    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <!-- Step 5 -->
    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

  </mat-horizontal-stepper>
</code>```

Expected Results

I want to button to function normally and to be seen completely.

Actual Results

The button is being cut off by the mat-step.

答:
The error is due to the use of relative position (and top styling). You will either need to work around these settings or, preferably, remove them all together.

StackBlitz:
https://stackblitz.com/edit/angular-mat-stepper-program-jgsasc

Body:
Problem Statement

My button is being cut off by the mat-step element or so it seems.

What I've Tried

I played around with the padding and margins of the mat-step element and it doesn't work.

I played around with the positioning and it doesn't work.

I played with the z-index but to no avail.

Picture of Problem

Explanation of Picture

As you can see, the next button is being cut off by the mat-step element, and I made sure that the problem is the mat-step. I did this by making the background of the stepper grey and found that it adjusts just fine. I made the mat-step grey, but nothing showed up, and it doesn't adjust with any CSS. There is clearly something wrong with the mat-step.

My Code

CSS

.stepper {
  position: relative;
  top: 50px;
}

.stepBtns {
  position: relative;
  font-size: 20pt;
  padding: 10px 30px;
  box-sizing: border-box;
  border: 1px solid #000000;
  box-shadow: 0px 4px 4px rgba(0, 0, 0, 0.25), 0px 4px 4px rgba(0, 0, 0, 0.25);
  border-radius: 16px;
  text-align: center;
  top: 50px;
}

HTML

<mat-horizontal-stepper class="stepper">

    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

    <mat-step>

      <button class="stepBtns" mat-raised-button matStepperPrevious>Back</button>
      <button class="stepBtns" mat-raised-button matStepperNext>Next</button>
    </mat-step>

  </mat-horizontal-stepper>

Expected Results

I want to button to function normally and to be seen completely.

Actual Results

The button is being cut off by the mat-step.


问:
Set Vector of Eigen Matrices to 0
I'm adapting the Hough Transform for a special application, and for this I need to store a lot of Eigen Matrixes in a vector and I need them all to be 0 at the beginning.
This is how I have initialized this:

```<code>typedef Eigen::Matrix<int,30,150> HoughMatrix
std::vector<HoughMatrix> hough_spaces(num_spaces)
</code>```

My question now is, what is the fastest way to make all elements of all those Matrixes equal to 0?
I tried looping over each Vector element and do:

```<code>hough_spaces[i].setZero()
</code>```

But that was rather slow. Is there a faster way? Or a way to directly initialize them as 0?
Thank you for your help

答:
The interesting part is that Eigen::Matrix appears to have no constructor to initialize the elements. From Eigen: The Matrix class:

```<code>Matrix3f a;
</code>```

-> no allocations, no initialization of elements

```<code>MatrixXf a(10,15);
</code>```

-> allocated but uninitialized elements

Finally (!) some constructors that allow to initialize elements for small sized vectors:

```<code>Vector2d a(5.0, 6.0);
Vector3d b(5.0, 6.0, 7.0);
Vector4d c(5.0, 6.0, 7.0, 8.0);
</code>```

If you read on to Eigen: Advanced initialization you can find

Special matrices and arrays

The Matrix and Array classes have static methods like Zero(), which
  can be used to initialize all coefficients to zero. [...]

Example

```<code>std::cout << "A fixed-size array:\n";
Array33f a1 = Array33f::Zero();
std::cout << a1 << "\n\n";
</code>```

PS

But that was rather slow. Is there a faster way?

Whithout knowing more details about what exaclt you mean with "slow" it is hard to discuss details. All I can say is that I would expect initialization only to be faster than allocating unitialized elements and then setZero().

Title: Set Vector of Eigen Matrices to 0

Body:
I'm adapting the Hough Transform for a special application, and for this I need to store a lot of Eigen Matrixes in a vector and I need them all to be 0 at the beginning.
This is how I have initialized this:

typedef Eigen::Matrix<int,30,150> HoughMatrix
std::vector<HoughMatrix> hough_spaces(num_spaces)

My question now is, what is the fastest way to make all elements of all those Matrixes equal to 0?
I tried looping over each Vector element and do:

hough_spaces[i].setZero()

But that was rather slow. Is there a faster way? Or a way to directly initialize them as 0?
Thank you for your help

Body:
The interesting part is that Eigen::Matrix appears to have no constructor to initialize the elements. From Eigen: The Matrix class:

Matrix3f a;

-> no allocations, no initialization of elements

MatrixXf a(10,15);

-> allocated but uninitialized elements

Finally (!) some constructors that allow to initialize elements for small sized vectors:

Vector2d a(5.0, 6.0);
Vector3d b(5.0, 6.0, 7.0);
Vector4d c(5.0, 6.0, 7.0, 8.0);

If you read on to Eigen: Advanced initialization you can find

Special matrices and arrays

The Matrix and Array classes have static methods like Zero(), which
  can be used to initialize all coefficients to zero. [...]

Example

std::cout << "A fixed-size array:\n";
Array33f a1 = Array33f::Zero();
std::cout << a1 << "\n\n";

PS

But that was rather slow. Is there a faster way?

Whithout knowing more details about what exaclt you mean with "slow" it is hard to discuss details. All I can say is that I would expect initialization only to be faster than allocating unitialized elements and then setZero().


问:
How to add classes or ids to built-in idyll components
We have several button elements that we would like to style in different ways. We originally added styling to them in the style.css file by adding css to the .button tag. The problem with this is now we would like to add more buttons, but with different styles. Since we added the styling to .button they all end up looking the same. Is there any way to add classes or ids to built-in idyll components?

答: You can add the className property to a button like [button className:”newName”]...[/button]


问:
How to ignore JsonProperty(PropertyName = "someName") when serializing json?
I have some C# code using ASP.Net MVC, which is making use of Json.Net to serialize some DTOs.  In order to reduce payload, I have made use of the [JsonProperty(PropertyName = "shortName")] attribute to use shorter property names during serialization.

This works great when the client is another .Net app or service, as the deserialization puts the object hierarchy back together, using the longer more friendly names, while keeping actual transfer payload low.

The problem comes into play when the client is javascript/ajax through a browser.  It makes the request, and gets the json ... but that json is using the shortened less-friendly names.

How can I make the json.net serialization engine ignore the [JsonProperty(PropertyName = "shortName")] attribute programmatically?  Ideally, my MVC service is going to sit there running and normally serialize using the shortened property names.  When my code detects a particular parameter, I'd like to get the data serialized using the longer names and ignore the [JsonProperty()] attribute.

Any suggestions?

Thanks,

Kevin

答:
Just want to "extend" Brian's answer with Deserializer class,</p>

```<code>static T Deserialize<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings()
    {
        ContractResolver = new LongNameContractResolver()
    });
}
</code>```

Body:
Just want to "extend" Brian's answer with Deserializer class,

static T Deserialize<T>(string json)
{
    return JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings()
    {
        ContractResolver = new LongNameContractResolver()
    });
}


问:
WSDL for REST WCF
I've created a REST WCF in C# by specifying WebGET and WebHttpBinding in web.config. The service works fine through IE. My wsdl starts as below and it has soap in wsdl. Since this is REST, should'nt the soap be present in wsdl.

WSDL :

```<code>  <?xml version="1.0" encoding="utf-8" ?>
 <wsdl:definitions name="ServiceImp" targetNamespace="http://tempuri.org/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
    xmlns:tns="http://tempuri.org/"
    xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
    xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract"
    xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
    xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
    xmlns:wsa10="http://www.w3.org/2005/08/addressing"
    xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex">
</code>```

In the above wsdl, Since this is HTTP, why is the soap content coming in REST service?

Thanks,
Vinoth Khanna.S

答:
As stated above, REST has no concept of a WSDL in WCF, only SOAP.  If the URL for ?wsdl works, then you probably have a 'mex' (Metadata Exchange) endpoint defined in your configuration, which is what serves up the WSDL. This is usually added by default if you add a WCF service through the VisualStudio wizards. If it is there, it can be removed if you don't plan on using SOAP. It will usually look something like this:

```<code><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</code>```

On a side-note; it is possible to have WCF serve up the same services as both SOAP and REST, as detailed here: REST / SOAP endpoints for a WCF service

Title: WSDL for REST WCF

Body:
I've created a REST WCF in C# by specifying WebGET and WebHttpBinding in web.config. The service works fine through IE. My wsdl starts as below and it has soap in wsdl. Since this is REST, should'nt the soap be present in wsdl.

WSDL :

  <?xml version="1.0" encoding="utf-8" ?>
 <wsdl:definitions name="ServiceImp" targetNamespace="http://tempuri.org/"
    xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
    xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
    xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
    xmlns:wsam="http://www.w3.org/2007/05/addressing/metadata"
    xmlns:tns="http://tempuri.org/"
    xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing"
    xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy"
    xmlns:wsap="http://schemas.xmlsoap.org/ws/2004/08/addressing/policy"
    xmlns:xsd="http://www.w3.org/2001/XMLSchema"
    xmlns:msc="http://schemas.microsoft.com/ws/2005/12/wsdl/contract"
    xmlns:wsaw="http://www.w3.org/2006/05/addressing/wsdl"
    xmlns:soap12="http://schemas.xmlsoap.org/wsdl/soap12/"
    xmlns:wsa10="http://www.w3.org/2005/08/addressing"
    xmlns:wsx="http://schemas.xmlsoap.org/ws/2004/09/mex">

In the above wsdl, Since this is HTTP, why is the soap content coming in REST service?

Thanks,
Vinoth Khanna.S

Body:
As stated above, REST has no concept of a WSDL in WCF, only SOAP.  If the URL for ?wsdl works, then you probably have a 'mex' (Metadata Exchange) endpoint defined in your configuration, which is what serves up the WSDL. This is usually added by default if you add a WCF service through the VisualStudio wizards. If it is there, it can be removed if you don't plan on using SOAP. It will usually look something like this:

<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

On a side-note; it is possible to have WCF serve up the same services as both SOAP and REST, as detailed here: REST / SOAP endpoints for a WCF service


问:
How to use ChangeNotifier with Navigator
In my app, I have a model that store the user logged in my app.

```<code>class AuthenticationModel extends ChangeNotifier {
  User _user;
  User get user => _user;

  void authenticate(LoginData loginData) async {
    // _user = // get user from http call
    notifyListeners();
  }

  void restoreUser() async {
    //_user = // get user from shared prefs
    notifyListeners();
  }
}
</code>```

The model is registered at the top of the widget tree :

```<code>void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthenticationModel(),
      child: MaterialApp(
        title: 'My App',
        initialRoute: '/',
        routes: {
          '/': (context) => PrehomeScreen(),
          '/home': (context) => HomeScreen()
        },
      ),
    );
  }
}
</code>```

Somewhere down the widget tree, I have a button that calls the Model :

```<code>          child: Consumer<AuthenticationModel>(
            builder: (context, authModel, child) {
              return MyCustomButton(
                text: 'Connect',
                onPressed: () {
                  authModel.authenticate(...)
                },
              );
            },
          ),
</code>```

Now, I would like, somewhere, listen to the changes on the AuthenticationModel to trigger a Navigator.pushReplacmentNamed('/home') when the user is not null in the model.

I tried to do it in the builder of Prehome :

```<code>class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<AuthenticationModel>(
      builder: (context, authModel, child) {
        if (authModel.user != null) {
          Navigator.of(context).pushReplacementNamed("/home")
        }
        return Container(
          child: // Prehome UI
        );
      },
    );
  }
}
</code>```

but I have a error when doing it like this :

```<code>════════ (2) Exception caught by widgets library ═══════════════════════════════════════════════════
setState() or markNeedsBuild() called during build.
The relevant error-causing widget was:
  Consumer<AuthenticationModel> file:///Users/pierre.degand/Projects/cdc/course_du_coeur/lib/Prehome.dart:13:12
═══════════════════════════════════════════════════════════════════════════════
</code>```

How can I setup such a listener ? Is it a good practice to trigger navigation on model changes like this ?

Thanks

EDIT: I found a way to make this work. Instead of using Consumer inside the PrehomeScreen builder, I used the following code :

```<code>class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Provider.of<AuthenticationModel>(context).addListener(() {
      Navigator.of(context).pushReplacementNamed("/home");
    });

    return Container(
      child: // UI
    );
  }
}
</code>```

It works fine, the navigation is executed when the model changes. But there is an error message in the console (printed 3 times) :

```<code>════════ (4) Exception caught by foundation library ════════════════════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
════════════════════════════════════════════════════════════════════════════════════════════════════
</code>```

The app does not crash so, for now, I'm ok with this.
I still want to know if this is a good approach or not.

答:
I don't think ChangeNotifier is needed.

```<code>void main() async {
  final isLoggedIn = await Future.value(true); // get value from shared prefs or your model

  runApp(MyApp(isLoggedIn));
}

class MyApp extends StatelessWidget {
  MyApp(this.isLoggedIn);

  final bool isLoggedIn;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: isLoggedIn ? '/home' : '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/login': (context) => LoginScreen()
      },
    );
  }
}
</code>```

```<code>
class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('Logout'),
      onPressed: () => Navigator.of(context).pushReplacementNamed("/login"),
    );
  }
}

class LoginScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('Login'),
      onPressed: () => Navigator.of(context).pushReplacementNamed("/"),
    );
  }
}
</code>```

Body:
In my app, I have a model that store the user logged in my app.

class AuthenticationModel extends ChangeNotifier {
  User _user;
  User get user => _user;

  void authenticate(LoginData loginData) async {
    // _user = // get user from http call
    notifyListeners();
  }

  void restoreUser() async {
    //_user = // get user from shared prefs
    notifyListeners();
  }
}

The model is registered at the top of the widget tree :

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AuthenticationModel(),
      child: MaterialApp(
        title: 'My App',
        initialRoute: '/',
        routes: {
          '/': (context) => PrehomeScreen(),
          '/home': (context) => HomeScreen()
        },
      ),
    );
  }
}

Somewhere down the widget tree, I have a button that calls the Model :

          child: Consumer<AuthenticationModel>(
            builder: (context, authModel, child) {
              return MyCustomButton(
                text: 'Connect',
                onPressed: () {
                  authModel.authenticate(...)
                },
              );
            },
          ),

Now, I would like, somewhere, listen to the changes on the AuthenticationModel to trigger a Navigator.pushReplacmentNamed('/home') when the user is not null in the model.

I tried to do it in the builder of Prehome :

class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Consumer<AuthenticationModel>(
      builder: (context, authModel, child) {
        if (authModel.user != null) {
          Navigator.of(context).pushReplacementNamed("/home")
        }
        return Container(
          child: // Prehome UI
        );
      },
    );
  }
}

but I have a error when doing it like this :

════════ (2) Exception caught by widgets library ═══════════════════════════════════════════════════
setState() or markNeedsBuild() called during build.
The relevant error-causing widget was:
  Consumer<AuthenticationModel> file:///Users/pierre.degand/Projects/cdc/course_du_coeur/lib/Prehome.dart:13:12
═══════════════════════════════════════════════════════════════════════════════

How can I setup such a listener ? Is it a good practice to trigger navigation on model changes like this ?

Thanks

EDIT: I found a way to make this work. Instead of using Consumer inside the PrehomeScreen builder, I used the following code :

class PrehomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    Provider.of<AuthenticationModel>(context).addListener(() {
      Navigator.of(context).pushReplacementNamed("/home");
    });

    return Container(
      child: // UI
    );
  }
}

It works fine, the navigation is executed when the model changes. But there is an error message in the console (printed 3 times) :

════════ (4) Exception caught by foundation library ════════════════════════════════════════════════
Looking up a deactivated widget's ancestor is unsafe.
════════════════════════════════════════════════════════════════════════════════════════════════════

The app does not crash so, for now, I'm ok with this.
I still want to know if this is a good approach or not.

Body:
I don't think ChangeNotifier is needed.

void main() async {
  final isLoggedIn = await Future.value(true); // get value from shared prefs or your model

  runApp(MyApp(isLoggedIn));
}

class MyApp extends StatelessWidget {
  MyApp(this.isLoggedIn);

  final bool isLoggedIn;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      initialRoute: isLoggedIn ? '/home' : '/',
      routes: {
        '/': (context) => HomeScreen(),
        '/login': (context) => LoginScreen()
      },
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('Logout'),
      onPressed: () => Navigator.of(context).pushReplacementNamed("/login"),
    );
  }
}

class LoginScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
      child: Text('Login'),
      onPressed: () => Navigator.of(context).pushReplacementNamed("/"),
    );
  }
}


问:
AWS CDK - Stop Generating Policies
The following CDK code

```<code>    const queue = new sqs.Queue(this, 'my-sqs-queue', {
      visibilityTimeout: cdk.Duration.seconds(300)
    });

    const role = iam.Role.fromRoleArn(this, "myrole", "arn:aws:iam::1234:role/myrole")

    const evtHandler = new lambda.Function(this, 'MyLambda', {
      code: lambda.Code.fromInline(`
        exports.handler =  async function(event, context) {
        console.log("EVENT: \n" + JSON.stringify(event, null, 2))
        return context.logStreamName
      }`),
      handler: 'index.handler',
      runtime: lambda.Runtime.NODEJS_8_10,
      role
    });

    evtHandler.addEventSource(new SqsEventSource(queue, {
      batchSize: 10 // default
    }));
</code>```

will set up a lambda that polls SQS. Awesome! However, it also generates this CF

```<code>myrolePolicy99283C52:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - sqs:ReceiveMessage
              - sqs:ChangeMessageVisibility
              - sqs:GetQueueUrl
              - sqs:DeleteMessage
              - sqs:GetQueueAttributes
            Effect: Allow
            Resource:
              Fn::GetAtt:
                - sqseventloaderusw2tstF27FC9C7
                - Arn
        Version: "2012-10-17"
      PolicyName: snssqslambdaPolicy16AEE704
      Roles:
        - myrole
</code>```

The problem is, myrole already has a policy that will allow those things. It also means the thing executing this script needs to have permissions to create/update Policies/Roles :(

Security in my org will not be super happy with allowing that kind of thing. Is there a way to stop it from generating policies and attaching them to roles?

答:
For anyone coming across this later, setting the option mutable to false solved this for me.

So, in OP's example, the role would change to:

```<code>const role = iam.Role.fromRoleArn(this, "myrole", "arn:aws:iam::1234:role/myrole", {mutable: false})
</code>```

For reference: https://github.com/aws/aws-cdk/issues/4422

Title: AWS CDK - Stop Generating Policies

Body:
The following CDK code

    const queue = new sqs.Queue(this, 'my-sqs-queue', {
      visibilityTimeout: cdk.Duration.seconds(300)
    });

    const role = iam.Role.fromRoleArn(this, "myrole", "arn:aws:iam::1234:role/myrole")

    const evtHandler = new lambda.Function(this, 'MyLambda', {
      code: lambda.Code.fromInline(`
        exports.handler =  async function(event, context) {
        console.log("EVENT: \n" + JSON.stringify(event, null, 2))
        return context.logStreamName
      }`),
      handler: 'index.handler',
      runtime: lambda.Runtime.NODEJS_8_10,
      role
    });

    evtHandler.addEventSource(new SqsEventSource(queue, {
      batchSize: 10 // default
    }));

will set up a lambda that polls SQS. Awesome! However, it also generates this CF

myrolePolicy99283C52:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - sqs:ReceiveMessage
              - sqs:ChangeMessageVisibility
              - sqs:GetQueueUrl
              - sqs:DeleteMessage
              - sqs:GetQueueAttributes
            Effect: Allow
            Resource:
              Fn::GetAtt:
                - sqseventloaderusw2tstF27FC9C7
                - Arn
        Version: "2012-10-17"
      PolicyName: snssqslambdaPolicy16AEE704
      Roles:
        - myrole

The problem is, myrole already has a policy that will allow those things. It also means the thing executing this script needs to have permissions to create/update Policies/Roles :(

Security in my org will not be super happy with allowing that kind of thing. Is there a way to stop it from generating policies and attaching them to roles?

Body:
For anyone coming across this later, setting the option mutable to false solved this for me.

So, in OP's example, the role would change to:

const role = iam.Role.fromRoleArn(this, "myrole", "arn:aws:iam::1234:role/myrole", {mutable: false})

For reference: https://github.com/aws/aws-cdk/issues/4422


问:
Keras LSTM online learning
I have a sequence that is very predictable. Below, you can see a slice of it:

```<code>deque([4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4])
</code>```

Basically, it's a varying but still predictable number of 4s, followed by an 8, and by 28 every three 8s.

I want to build a very simple LSTM model for online prediction: each time a new number arrives, it is appended on the right of the deque. Thus, the LSTM is trained on the old sequence comprised of [0:seq_length] elements of the deque, with the training target being the [seq_length] element. Then, the window shifts and prediction is performed on the [1:seq_length+1] elements. At the end, the leftmost element of the deque is discarded. My intuition tells me that this should make the network memorize the sequence.

However, my network has been answering only 4. After a (long) while, surprisingly, it starts answering only 8, missing almost all of the time. And then, a (long) while later, it goes back to answering only 4.

My model is structured as shown. Naturally, I've already experimented with different values for seq_length and lstm_cells, none of which gave me success. These were from the latest run:

```<code>seq_length = 64  #Length of the sequence to be inserted into the LSTM
vocab_size = 4  #Size of the final dense layer of the model
lstm_cells = 16  #Size of the LSTM layer

model = Sequential()
model.add(LSTM(lstm_cells, input_shape=(seq_length, 1)))
model.add(Dense(vocab_size))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['categorical_accuracy'])
</code>```

The following is how data is prepared, trained, and predicted on the model. The variable sequence is the deque shown at the start of this post. I maintain a list vocab = [4,8,28] that is built on execution time as new numbers are seen, so vocab[i] translates class i into its corresponding number of the sequence. I then create a dictionary legend to do the opposite. This is more or less the ongoing online loop:

```<code>while True:

    # Receives new number and puts it into the deque:
    sequence.append(generateNextNumber())

    # At this point, please note that the length of the deque is seq_length + 1.

    # Dictionary to convert numbers to classes:
    legend = dict([(v, k) for k, v in enumerate(vocab)])
    # Converts the deque into a list:
    seq_list = list(sequence)
    # Each iteration is comprised of 1 training and 1 prediction. These are the training sequence and target:
    train_seq = [ [legend[i]] for i in seq_list[:seq_length] ]
    train_target = legend[ seq_list[seq_length] ]
    # And the prediction sequence just shifts the window by 1:
    pred_seq = [ [legend[i]] for i in seq_list[1:] ]

    # Batches data into a batch of size 1:
    x = np.zeros((1, seq_length, 1))
    y = np.zeros((1, vocab_size))
    x[0,:] = train_seq
    y[0,:] = to_categorical( train_target, num_classes=vocab_size )
    # Online training:
    model.fit(x=x, y=y, batch_size=1, epochs=1, verbose=0)

    # Now that one training step is done, make a prediction:
    x_pred = np.zeros((1, seq_length, 1))
    x[0,:] = pred_seq
    predicted_onehot = model.predict(x_pred)
    # Avoids "index out of range" erros when the LSTM vocab is still being built:
    predicted_index = min(np.argmax(predicted_onehot), len(vocab)-1)
    predicted_number = vocab[ predicted_index ]
    # Reverts deque length to seq_length:
    sequence.popleft()
</code>```

And, finally, this is an example output:

```<code>HIT! Current hit rate: 34.753665869071725 (predicted: 4, sequence was: deque([4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4]))

HIT! Current hit rate: 34.75566735175926 (predicted: 4, sequence was: deque([4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4]))

Predicted 4 but it was 8

HIT! Current hit rate: 34.75660255820374 (predicted: 4, sequence was: deque([4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4]))

HIT! Current hit rate: 34.758603766640086 (predicted: 4, sequence was: deque([4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4]))

HIT! Current hit rate: 34.7606048523142 (predicted: 4, sequence was: deque([4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4]))

HIT! Current hit rate: 34.76260581523739 (predicted: 4, sequence was: deque([4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4]))

HIT! Current hit rate: 34.76460665542095 (predicted: 4, sequence was: deque([4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4]))

HIT! Current hit rate: 34.76660737287616 (predicted: 4, sequence was: deque([4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4]))

Predicted 4 but it was 28

HIT! Current hit rate: 34.767541707556425 (predicted: 4, sequence was: deque([4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4]))
</code>```

What is going so wrong?

Thank you very much in advance.

答:
I had an issue in line:

```<code>x[0,:] = pred_seq
</code>```

which was supposed to be:

```<code>x_pred[0,:] = pred_seq
</code>```

Now everything is working more or less correctly. I'll still leave this question here since it offers some nice insights into LSTM online learning.

Title: Keras LSTM online learning

Body:
I have a sequence that is very predictable. Below, you can see a slice of it:

deque([4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4])

Basically, it's a varying but still predictable number of 4s, followed by an 8, and by 28 every three 8s.

I want to build a very simple LSTM model for online prediction: each time a new number arrives, it is appended on the right of the deque. Thus, the LSTM is trained on the old sequence comprised of [0:seq_length] elements of the deque, with the training target being the [seq_length] element. Then, the window shifts and prediction is performed on the [1:seq_length+1] elements. At the end, the leftmost element of the deque is discarded. My intuition tells me that this should make the network memorize the sequence.

However, my network has been answering only 4. After a (long) while, surprisingly, it starts answering only 8, missing almost all of the time. And then, a (long) while later, it goes back to answering only 4.

My model is structured as shown. Naturally, I've already experimented with different values for seq_length and lstm_cells, none of which gave me success. These were from the latest run:

seq_length = 64  #Length of the sequence to be inserted into the LSTM
vocab_size = 4  #Size of the final dense layer of the model
lstm_cells = 16  #Size of the LSTM layer

model = Sequential()
model.add(LSTM(lstm_cells, input_shape=(seq_length, 1)))
model.add(Dense(vocab_size))
model.add(Activation('softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['categorical_accuracy'])

The following is how data is prepared, trained, and predicted on the model. The variable sequence is the deque shown at the start of this post. I maintain a list vocab = [4,8,28] that is built on execution time as new numbers are seen, so vocab[i] translates class i into its corresponding number of the sequence. I then create a dictionary legend to do the opposite. This is more or less the ongoing online loop:

while True:

    # Receives new number and puts it into the deque:
    sequence.append(generateNextNumber())

    # At this point, please note that the length of the deque is seq_length + 1.

    # Dictionary to convert numbers to classes:
    legend = dict([(v, k) for k, v in enumerate(vocab)])
    # Converts the deque into a list:
    seq_list = list(sequence)
    # Each iteration is comprised of 1 training and 1 prediction. These are the training sequence and target:
    train_seq = [ [legend[i]] for i in seq_list[:seq_length] ]
    train_target = legend[ seq_list[seq_length] ]
    # And the prediction sequence just shifts the window by 1:
    pred_seq = [ [legend[i]] for i in seq_list[1:] ]

    # Batches data into a batch of size 1:
    x = np.zeros((1, seq_length, 1))
    y = np.zeros((1, vocab_size))
    x[0,:] = train_seq
    y[0,:] = to_categorical( train_target, num_classes=vocab_size )
    # Online training:
    model.fit(x=x, y=y, batch_size=1, epochs=1, verbose=0)

    # Now that one training step is done, make a prediction:
    x_pred = np.zeros((1, seq_length, 1))
    x[0,:] = pred_seq
    predicted_onehot = model.predict(x_pred)
    # Avoids "index out of range" erros when the LSTM vocab is still being built:
    predicted_index = min(np.argmax(predicted_onehot), len(vocab)-1)
    predicted_number = vocab[ predicted_index ]
    # Reverts deque length to seq_length:
    sequence.popleft()

And, finally, this is an example output:

HIT! Current hit rate: 34.753665869071725 (predicted: 4, sequence was: deque([4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4]))

HIT! Current hit rate: 34.75566735175926 (predicted: 4, sequence was: deque([4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4]))

Predicted 4 but it was 8

HIT! Current hit rate: 34.75660255820374 (predicted: 4, sequence was: deque([4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4]))

HIT! Current hit rate: 34.758603766640086 (predicted: 4, sequence was: deque([4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4]))

HIT! Current hit rate: 34.7606048523142 (predicted: 4, sequence was: deque([4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4]))

HIT! Current hit rate: 34.76260581523739 (predicted: 4, sequence was: deque([4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4]))

HIT! Current hit rate: 34.76460665542095 (predicted: 4, sequence was: deque([4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4]))

HIT! Current hit rate: 34.76660737287616 (predicted: 4, sequence was: deque([4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4]))

Predicted 4 but it was 28

HIT! Current hit rate: 34.767541707556425 (predicted: 4, sequence was: deque([4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 8, 4, 4, 4, 4, 4, 4, 28, 4]))

What is going so wrong?

Thank you very much in advance.

Body:
I had an issue in line:

x[0,:] = pred_seq

which was supposed to be:

x_pred[0,:] = pred_seq

Now everything is working more or less correctly. I'll still leave this question here since it offers some nice insights into LSTM online learning.


问:
How to parse XML and get instances of a particular node attribute?
I have many rows in XML and I'm trying to get instances of a particular node attribute.

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>
```

How do I access the values of the attribute foobar? In this example, I want "1" and "2".

答:
```<code>#If the xml is in the form of a string as shown below then
from lxml  import etree, objectify
'''sample xml as a string with a name space {http://xmlns.abc.com}'''
message =b'<?xml version="1.0" encoding="UTF-8"?>\r\n<pa:Process xmlns:pa="http://xmlns.abc.com">\r\n\t<pa:firsttag>SAMPLE</pa:firsttag></pa:Process>\r\n'  # this is a sample xml which is a string

print('************message coversion and parsing starts*************')

message=message.decode('utf-8')
message=message.replace('<?xml version="1.0" encoding="UTF-8"?>\r\n','') #replace is used to remove unwanted strings from the 'message'
message=message.replace('pa:Process>\r\n','pa:Process>')
print (message)

print ('******Parsing starts*************')
parser = etree.XMLParser(remove_blank_text=True) #the name space is removed here
root = etree.fromstring(message, parser) #parsing of xml happens here
print ('******Parsing completed************')

dict={}
for child in root: # parsed xml is iterated using a for loop and values are stored in a dictionary
    print(child.tag,child.text)
    print('****Derving from xml tree*****')
    if child.tag =="{http://xmlns.abc.com}firsttag":
        dict["FIRST_TAG"]=child.text
        print(dict)

### output
'''************message coversion and parsing starts*************
<pa:Process xmlns:pa="http://xmlns.abc.com">

    <pa:firsttag>SAMPLE</pa:firsttag></pa:Process>
******Parsing starts*************
******Parsing completed************
{http://xmlns.abc.com}firsttag SAMPLE
****Derving from xml tree*****
{'FIRST_TAG': 'SAMPLE'}'''
</code>```

Body:
I have many rows in XML and I'm trying to get instances of a particular node attribute.

<foo>
   <bar>
      <type foobar="1"/>
      <type foobar="2"/>
   </bar>
</foo>

How do I access the values of the attribute foobar? In this example, I want "1" and "2".


问:
Firebase data not showing
I have retrieved data from Firebase regarding name and score. I am being able to see the list view for first name and scores of the data retrieved but for the second data retrieved i can not see no scores or names. When I have debugged the app, I have received this "com.example.gymtastic.SquatScore (fields/setters are case sensitive!)".

```<code>private ListView listView, listview2;
DatabaseReference databaseReference;
DatabaseReference ddatabase;
private FirebaseDatabase firebaseDatabase;
List<ScoreProfile> scoreList;
List<SquatScore> squatList;

@Override
protected void onStart() {
     super.onStart();
      ddatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot squatsnapshot : dataSnapshot.getChildren()){

                    SquatScore squatScore = squatsnapshot.getValue(SquatScore.class);
                    squatList.add(squatScore);
                }
                SquatInfoAddapter squatInfoAddapter =new SquatInfoAddapter(RankT.this, squatList);
                listview2.setAdapter(squatInfoAddapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
               throw databaseError.toException();
            }
        }); // This one doesnt

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rank_t);

        firebaseDatabase = FirebaseDatabase.getInstance();

        databaseReference = firebaseDatabase.getReference("Bench");

        ddatabase = firebaseDatabase.getReference("Squat");

        databaseReference.orderByChild("userScore").limitToFirst(5);
        ddatabase.orderByChild("userScore").limitToFirst(5);

        squatList = new ArrayList<>();

        scoreList = new ArrayList<>();

        firebaseAuth = FirebaseAuth.getInstance();

</code>```

This is my code. The first value listener displays but for the second one created, it just shows empty list views.

This is my Firebase data that i am retrieving but does not show.

```<code> "Squat" : {
    "Jn8SOKDgGRMewEHjVG8LaXoYtrl2" : {
      "suserName" : "ace",
      "suserScore" : "369"
    },
    "mooFelp2soMtDmRlg5IQ6AYpKhO2" : {
      "suserName" : "ACe",
      "suserScore" : "1222"
    }

</code>```

Here is my SquatScore class:

```<code>public class SquatScore {

    private String SuserName;
    private String SuserScore;
    public SquatScore(){};

    public SquatScore(String suserName, String suserScore) {
        SuserName = suserName;
        SuserScore = suserScore;
    }

    public String getSuserName() {
        return SuserName;
    }

    public String getSuserScore() {
        return SuserScore;
    }
}

</code>```

答:
The error you get is:

W/ClassMapper: No setter/field for suserName found on class com.example.gymtastic.SquatScore (fields/setters are case sensitive!)"

If we look at your class that is correct:

there is no field suserName, only SuserName with an uppercase S.

there is no setter method for a property called userName, which would be called setSusername.

Without those, the Firebase SDK has no way to know how to set the value from the suserName property in the JSON on to your SquatScore object.

To fix this, you'll want to either rename the field to suserName, or create the setter method.

Title: Firebase data not showing

Body:
I have retrieved data from Firebase regarding name and score. I am being able to see the list view for first name and scores of the data retrieved but for the second data retrieved i can not see no scores or names. When I have debugged the app, I have received this "com.example.gymtastic.SquatScore (fields/setters are case sensitive!)".

private ListView listView, listview2;
DatabaseReference databaseReference;
DatabaseReference ddatabase;
private FirebaseDatabase firebaseDatabase;
List<ScoreProfile> scoreList;
List<SquatScore> squatList;

@Override
protected void onStart() {
     super.onStart();
      ddatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                for(DataSnapshot squatsnapshot : dataSnapshot.getChildren()){

                    SquatScore squatScore = squatsnapshot.getValue(SquatScore.class);
                    squatList.add(squatScore);
                }
                SquatInfoAddapter squatInfoAddapter =new SquatInfoAddapter(RankT.this, squatList);
                listview2.setAdapter(squatInfoAddapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
               throw databaseError.toException();
            }
        }); // This one doesnt

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_rank_t);

        firebaseDatabase = FirebaseDatabase.getInstance();

        databaseReference = firebaseDatabase.getReference("Bench");

        ddatabase = firebaseDatabase.getReference("Squat");

        databaseReference.orderByChild("userScore").limitToFirst(5);
        ddatabase.orderByChild("userScore").limitToFirst(5);

        squatList = new ArrayList<>();

        scoreList = new ArrayList<>();

        firebaseAuth = FirebaseAuth.getInstance();

This is my code. The first value listener displays but for the second one created, it just shows empty list views.

This is my Firebase data that i am retrieving but does not show.

 "Squat" : {
    "Jn8SOKDgGRMewEHjVG8LaXoYtrl2" : {
      "suserName" : "ace",
      "suserScore" : "369"
    },
    "mooFelp2soMtDmRlg5IQ6AYpKhO2" : {
      "suserName" : "ACe",
      "suserScore" : "1222"
    }

Here is my SquatScore class:

public class SquatScore {

    private String SuserName;
    private String SuserScore;
    public SquatScore(){};

    public SquatScore(String suserName, String suserScore) {
        SuserName = suserName;
        SuserScore = suserScore;
    }

    public String getSuserName() {
        return SuserName;
    }

    public String getSuserScore() {
        return SuserScore;
    }
}


问:
Why is this Array is not saving the pushed elements each time the event is triggered?
I am facing a problem: I want the array to save the x value each time the button is clicked.

So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]

```<code><button id="me">Click me to print form E to Z</button>

<script type="text/javascript">

      const insertOptions = x=>{
    console.log(x);
  }

  const circleInsertOptions = () => {
    let myArray = [];
    let x = 48;
    myArray.push(48);
    console.log(myArray);
    return myArray;
  };

  document.getElementById('me').addEventListener('click', circleInsertOptions);

</script>
</code>```

答:
```<code>let myArray = []; // ARRAY STORED ONCE AS GLOBAL.
  const insertOptions = x=>{
    console.log(x);
 };
const circleInsertOptions = () => {
    let x = 48;
    myArray.push(48);
    console.log(myArray);
   return myArray;
};
  document.getElementById('me').addEventListener('click', circleInsertOptions);
</code>```

Body:
I am facing a problem: I want the array to save the x value each time the button is clicked.

So, the first time the button is clicked, the console is going to print: [48], the next time [48,48] and the third time [48,48,48]

<button id="me">Click me to print form E to Z</button>