问:
How to deal with identifier fields in Lucene?
I've stumbled upon a problem similar to the one described in this other question: I have a field named like 'type', which is an identifier, ie, it's case sensitive and I want to use it for exact searches, no tokenisation, no similarity searches, just plain "find exactly 'Sport:01'". I might benefit from 'Sport*', but it's not extremely important in my case.

I cannot make it work: I thought the right kind of field to store this is: StringField.TYPE_STORED, with DOCS_AND_FREQS_AND_POSITIONS and setOmitNorms ( true ). However, this way I can't correctly resolve a query like: +type:"RockMusic" +title: "a sample title" using the standard analyzer, because, as far as I understand, the analyzer converts the input into lower case (ie, rockmusic) and the type is stored in its original mixed-case form (hence, I cannot resolve it even if I remove the title clause).

I'd like to mix case-insensitive search over title with case-sensitive over type, since I've cases where type := BRAIN is an acronym and it's different than 'Brain'.

So, what's the best way to manage fields and searches like the above? Are there alternatives other than text and string fields?

I'm using Lucene 6.6.0, but this is a general issue, regarding multiple (all?) Lucene versions.

Some code showing details is here (see testIdMixedCaseID*). The real use case is rather more complicated, if you want to give a look, the problem is with the field CC_FIELD, which might be 'BioProc' and nothing can be found in such a case.

Please note I need to use the plain Lucene, not Solr or Elastic search.

答:
The following notes are based on Lucene 8.x, not on Lucene 6.6 - so there may be some syntax differences - but I take your point about how any such differences should be coincidental to your question.

Here are some notes, where I will focus on the following aspect of your question:

However, this way I can't correctly resolve a query like: +type:"RockMusic" +title:"a sample title" using the standard analyzer

I think there are 2 parts to this:

Firstly, the query example using "a sample title" will - as you say - not work well with how a standard analyzer works - for the reasons you state.

But, secondly, it is possible to combine the two types of query you want to use, in a way which I believe gets you what you need: An exact match for the type field (e.g. RockMusic) and a more traditional tokenized & case-insensitive result for the title field (a sample title).

Here is how I would do that:

Here is some simple test data:

```<code>public static void buildIndex() throws IOException {
    final Directory dir = FSDirectory.open(Paths.get(INDEX_PATH));
    Analyzer analyzer = new StandardAnalyzer();
    IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
    iwc.setOpenMode(OpenMode.CREATE);
    Document doc;

    try (IndexWriter writer = new IndexWriter(dir, iwc)) {
        doc = new Document();
        doc.add(new StringField("type", "RockMusic", Field.Store.YES));
        doc.add(new TextField("title", "a sample title", Field.Store.YES));
        writer.addDocument(doc);

        doc = new Document();
        doc.add(new StringField("type", "RockMusic", Field.Store.YES));
        doc.add(new TextField("title", "another different title", Field.Store.YES));
        writer.addDocument(doc);

        doc = new Document();
        doc.add(new StringField("type", "Rock Music", Field.Store.YES));
        doc.add(new TextField("title", "a sample title", Field.Store.YES));
        writer.addDocument(doc);

    }
}
</code>```

Here is the query code:

```<code>public static void doSearch() throws QueryNodeException, ParseException, IOException {

    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(INDEX_PATH)));
    IndexSearcher searcher = new IndexSearcher(reader);

    TermQuery typeQuery = new TermQuery(new Term("type", "RockMusic"));

    Analyzer analyzer = new StandardAnalyzer();
    QueryParser parser = new QueryParser("title", analyzer);
    Query titleQuery = parser.parse("A Sample Title");

    Query query = new BooleanQuery.Builder()
            .add(typeQuery, BooleanClause.Occur.MUST)
            .add(titleQuery, BooleanClause.Occur.MUST)
            .build();

    System.out.println("Query: " + query.toString());
    System.out.println();

    TopDocs results = searcher.search(query, 100);
    ScoreDoc[] hits = results.scoreDocs;
    for (ScoreDoc hit : hits) {
        System.out.println("doc = " + hit.doc + "; score = " + hit.score);
        Document doc = searcher.doc(hit.doc);
        System.out.println("Type = " + doc.get("type")
                + "; Title = " + doc.get("title"));
        System.out.println();
    }
}
</code>```

The output from the above query is as follows:

```<code>Query: +type:RockMusic +(title:a title:sample title:title)

doc = 0; score = 0.7016101
Type = RockMusic; Title = a sample title

doc = 1; score = 0.2743341
Type = RockMusic; Title = another different title
</code>```

As you can see, this query is a little different from the one taken from your question.

But the list of found documents shows that (a) the Rock Music document was not found at all (good - because Rock Music does not match the "type" search term of RockMusic); and (b) the title a sample title got a far higher match score than the another different title document, when searching for A Sample Title.

Additional notes:

This query works by combining a StringField exact search with a more traditional TextField tokenized search - this latter search being processed by the StandardAnalyzer (matching how the data was indexed in the first place).

I am making an assumption about the score ranking being useful to you - but for title searches, I think that is reasonable.

This approach would also apply to your BRAIN vs. brain example, for StringField data.

(I also assume that, for a user interface, a user could select the "RockMusic" type value from a drop-down, and enter the "A Sample Title" search in an input field - but this is getting off-topic, I think).

You could obviously enhance the analyzer to include stop-words, and so on, as needed.

Of course, my examples involve hard-coded data - but it would not take much to generalize this approach to handle dynamically-provided search terms.

Hope that this makes sense - and that I understood the problem correctly.

Body:
The following notes are based on Lucene 8.x, not on Lucene 6.6 - so there may be some syntax differences - but I take your point about how any such differences should be coincidental to your question.

Here are some notes, where I will focus on the following aspect of your question:

However, this way I can't correctly resolve a query like: +type:"RockMusic" +title:"a sample title" using the standard analyzer

I think there are 2 parts to this:

Firstly, the query example using "a sample title" will - as you say - not work well with how a standard analyzer works - for the reasons you state.

But, secondly, it is possible to combine the two types of query you want to use, in a way which I believe gets you what you need: An exact match for the type field (e.g. RockMusic) and a more traditional tokenized & case-insensitive result for the title field (a sample title).

Here is how I would do that:

Here is some simple test data:

public static void buildIndex() throws IOException {
    final Directory dir = FSDirectory.open(Paths.get(INDEX_PATH));
    Analyzer analyzer = new StandardAnalyzer();
    IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
    iwc.setOpenMode(OpenMode.CREATE);
    Document doc;

    try (IndexWriter writer = new IndexWriter(dir, iwc)) {
        doc = new Document();
        doc.add(new StringField("type", "RockMusic", Field.Store.YES));
        doc.add(new TextField("title", "a sample title", Field.Store.YES));
        writer.addDocument(doc);

        doc = new Document();
        doc.add(new StringField("type", "RockMusic", Field.Store.YES));
        doc.add(new TextField("title", "another different title", Field.Store.YES));
        writer.addDocument(doc);

        doc = new Document();
        doc.add(new StringField("type", "Rock Music", Field.Store.YES));
        doc.add(new TextField("title", "a sample title", Field.Store.YES));
        writer.addDocument(doc);

    }
}

Here is the query code:

public static void doSearch() throws QueryNodeException, ParseException, IOException {

    IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(INDEX_PATH)));
    IndexSearcher searcher = new IndexSearcher(reader);

    TermQuery typeQuery = new TermQuery(new Term("type", "RockMusic"));

    Analyzer analyzer = new StandardAnalyzer();
    QueryParser parser = new QueryParser("title", analyzer);
    Query titleQuery = parser.parse("A Sample Title");

    Query query = new BooleanQuery.Builder()
            .add(typeQuery, BooleanClause.Occur.MUST)
            .add(titleQuery, BooleanClause.Occur.MUST)
            .build();

    System.out.println("Query: " + query.toString());
    System.out.println();

    TopDocs results = searcher.search(query, 100);
    ScoreDoc[] hits = results.scoreDocs;
    for (ScoreDoc hit : hits) {
        System.out.println("doc = " + hit.doc + "; score = " + hit.score);
        Document doc = searcher.doc(hit.doc);
        System.out.println("Type = " + doc.get("type")
                + "; Title = " + doc.get("title"));
        System.out.println();
    }
}

The output from the above query is as follows:

Query: +type:RockMusic +(title:a title:sample title:title)

doc = 0; score = 0.7016101
Type = RockMusic; Title = a sample title

doc = 1; score = 0.2743341
Type = RockMusic; Title = another different title

As you can see, this query is a little different from the one taken from your question.

But the list of found documents shows that (a) the Rock Music document was not found at all (good - because Rock Music does not match the "type" search term of RockMusic); and (b) the title a sample title got a far higher match score than the another different title document, when searching for A Sample Title.

Additional notes:

This query works by combining a StringField exact search with a more traditional TextField tokenized search - this latter search being processed by the StandardAnalyzer (matching how the data was indexed in the first place).

I am making an assumption about the score ranking being useful to you - but for title searches, I think that is reasonable.

This approach would also apply to your BRAIN vs. brain example, for StringField data.

(I also assume that, for a user interface, a user could select the "RockMusic" type value from a drop-down, and enter the "A Sample Title" search in an input field - but this is getting off-topic, I think).

You could obviously enhance the analyzer to include stop-words, and so on, as needed.

Of course, my examples involve hard-coded data - but it would not take much to generalize this approach to handle dynamically-provided search terms.

Hope that this makes sense - and that I understood the problem correctly.


来源: stackexchange

问:
Can't add user with "owner" role in GCP : via gcloud
I wasn't able to add a new member in GCP (IAM) with the role owner using the gcloud command
The below command fails:

```<code>gcloud projects add-iam-policy-binding linuxacademy-3 --member user:rohithmn3@gmail.com --role roles/owner
</code>```

With the below Error/Exception:

```<code>ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: Request contains an invalid argument.
- '@type': type.googleapis.com/google.cloudresourcemanager.v1.ProjectIamPolicyError
  member: user:rohithmn3@gmail.com
  role: roles/owner
  type: SOLO_MUST_INVITE_OWNERS
</code>```

But, the same command works well for other roles like: viewer, browser...! It just doesn't work for "owner".
Is there any alternative for this; if yes, How to add this in my Python Code.
Please help me here..!

Regards,
Rohith

答: You cannot grant the owner role to a member for a project using the Cloud IAM API or the gcloud command-line tool. You can only add owners to a project using the Cloud Console. An invitation will be sent to the member via email and the member must accept the invitation to be made an owner of the project, Documentation</p>

ContentLicense: CC BY-SA 4.0

Body:
I wasn't able to add a new member in GCP (IAM) with the role owner using the gcloud command
The below command fails:

gcloud projects add-iam-policy-binding linuxacademy-3 --member user:rohithmn3@gmail.com --role roles/owner

With the below Error/Exception:

ERROR: (gcloud.projects.add-iam-policy-binding) INVALID_ARGUMENT: Request contains an invalid argument.
- '@type': type.googleapis.com/google.cloudresourcemanager.v1.ProjectIamPolicyError
  member: user:rohithmn3@gmail.com
  role: roles/owner
  type: SOLO_MUST_INVITE_OWNERS

But, the same command works well for other roles like: viewer, browser...! It just doesn't work for "owner".
Is there any alternative for this; if yes, How to add this in my Python Code.
Please help me here..!

Regards,
Rohith


问:
Get custom attributes via ActionExecutingContext from controller .Net Core
This used used to work with earlier version of .Net. What's the equivalent in .net core terms. Now I get following error:

'ActionDescriptor' does not contain a definition for 'GetCustomAttributes' and no extension method 'GetCustomAttributes' accepting a first argument of type 'ActionDescriptor' could be found

```<code>public virtual void SetupMetadata(ActionExecutingContext filterContext)
{
    var myAttr = filterContext.ActionDescriptor.GetCustomAttributes(typeof(MyAttribute), false);
    if (myAttr.Length == 1)
        //do something
}
</code>```

Attribute definition:

```<code>public class MyAttribute : Attribute
{
    private readonly string _parameter;

    public PageTitleAttribute(string parameter)
    {
        _parameter = parameter;
    }

    public string Parameter { get { return _parameter; } }
}
</code>```

Code Usage:

```<code>[MyAttribute("Attribute value is set here")]
public ActionResult About()
{
    ViewBag.Message = "Your application description page.";
    return View();
}
</code>```

答:
For ASP.NET Core 3+:

    var filters = context.Filters;
    // And filter it like this:
    var filtered = filters.OfType<OurFilterType>();

```

ContentLicense: CC BY-SA 3.0

Body:
This used used to work with earlier version of .Net. What's the equivalent in .net core terms. Now I get following error:

'ActionDescriptor' does not contain a definition for 'GetCustomAttributes' and no extension method 'GetCustomAttributes' accepting a first argument of type 'ActionDescriptor' could be found

public virtual void SetupMetadata(ActionExecutingContext filterContext)
{
    var myAttr = filterContext.ActionDescriptor.GetCustomAttributes(typeof(MyAttribute), false);
    if (myAttr.Length == 1)
        //do something
}

Attribute definition:

public class MyAttribute : Attribute
{
    private readonly string _parameter;

    public PageTitleAttribute(string parameter)
    {
        _parameter = parameter;
    }

    public string Parameter { get { return _parameter; } }
}

Code Usage:

[MyAttribute("Attribute value is set here")]
public ActionResult About()
{
    ViewBag.Message = "Your application description page.";
    return View();
}


问:
Use of promises in NODE.js // console log prints the result several times
I'm making a program that takes an array of links and returns how many are broken and how many are working. Right now, I'm testing it with an array that has four working links and two broken links. Here's my code:

```<code>function getBrokenLinks(linksArr){
    let links = linksArr
    let brokenLinks = 0
    links.forEach(link => {
        fetch(link.href)
            .then( res => {
                if ( res.status != 200 ){
                    brokenLinks++
                }
            }).then( () => {console.log(brokenLinks)})
    })
    return brokenLinks
}
</code>```

and this is the output i receive:

output

I want the console to print the total of broken links only once, and after it has completed fetching all the links.

答:
You need to wait for all promises first. Then you can print the result. Also, to return anything, you need to make the function async and then all your outer code must also be async!

async function getBrokenLinks (linksArr) {
    let brokenLinks = 0
    await Promise.all(linksArr.map(link => (async () => {
      try {
        const res = await fetch(link.href)
        if (res.status != 200) brokenLinks++
      } catch (e) {
        brokenLinks++
      }
    })()))

    console.log(brokenLinks)
    return brokenLinks
}
```

Body:
I'm making a program that takes an array of links and returns how many are broken and how many are working. Right now, I'm testing it with an array that has four working links and two broken links. Here's my code:

function getBrokenLinks(linksArr){
    let links = linksArr
    let brokenLinks = 0
    links.forEach(link => {
        fetch(link.href)
            .then( res => {
                if ( res.status != 200 ){
                    brokenLinks++
                }
            }).then( () => {console.log(brokenLinks)})
    })
    return brokenLinks
}

and this is the output i receive:

output

I want the console to print the total of broken links only once, and after it has completed fetching all the links.


问:
How to register non-standarized SQL functions manually in Spring Boot application?
I'm using JPA query in my current spring-boot project. How can I add non-standardized SQL functions like GROUP_CONCAT?

Prior, to my previous problem :
How to show a column result in a one line comma separated list in JPA query

I found that GROUP_CONCAT is not a registered function in JPA query but could be accessed by registering it manually. I already tried following links but didn't work for me :

How to add non-standardized sql functions in Spring Boot application?

Registering a SQL function with JPA and Hibernate

https://thoughts-on-java.org/database-functions/

https://vladmihalcea.com/hibernate-sql-function-jpql-criteria-api-query/

1.

```<code>public class SqlFunctionsMetadataBuilderContributor
        implements MetadataBuilderContributor {

    @Override
    public void contribute(MetadataBuilder metadataBuilder) {
        metadataBuilder.applySqlFunction(
                "group_concat",
                new StandardSQLFunction(
                        "group_concat",
                        StandardBasicTypes.STRING
                )
        );
    }
}
</code>```

2.

```<code> public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory)
            throws QueryException {
        if (arguments.size() < 1) {
            throw new QueryException(new IllegalArgumentException("group_concat should have at least one arg"));
        }

        StringBuilder builder = new StringBuilder();
        if (arguments.size() > 1 && arguments.get(0).equals("'distinct'")) {
            builder.append("distinct ");
            builder.append(arguments.get(1));
        } else {
            builder.append(arguments.get(0));
        }

        return "group_concat(" + builder.toString() + ")";
    }
</code>```

3.

```<code>@Configuration
public class DataSource {
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(true);
        adapter.setDatabase(Database.MYSQL);
        // package to CustomMysqlDialect
        adapter.setDatabasePlatform("com.myprojet.admin.configuration.RegisterSqlFunction");
        adapter.setGenerateDdl(false);
        return adapter;
    }
}

    public RegisterSqlFunction() {
        super();

         registerFunction("group_concat, new StandardSQLFunction("group_concat",
       StandardBasicTypes.STRING));
    }

</code>```

I except using group_concat with JPA query.

答:
In case someone is having issues when registering this in a SpringBoot app this is the right way:

Create a class that implements: MetadataBuilderContributor interface.

```<code>package com.application.config;

public class SqlFunctionsMetadataBuilderContributor implements MetadataBuilderContributor {

  @Override
  public void contribute(MetadataBuilder metadataBuilder) {
    metadataBuilder.applySqlFunction(
        "STRING_AGG",
        new StandardSQLFunction(
            "STRING_AGG",
            StandardBasicTypes.STRING
        )
    );
  }
}
</code>```

In your application .yml (or .properties) refer to the previously created class in the following properties path: spring.jpa.properties.hibernate.metadata_builder_contributor

```<code>  spring:
    jpa:
      properties:
        hibernate:
          metadata_builder_contributor: com.application.config.SqlFunctionsMetadataBuilderContributor
</code>```

Body:
I'm using JPA query in my current spring-boot project. How can I add non-standardized SQL functions like GROUP_CONCAT?

Prior, to my previous problem :
How to show a column result in a one line comma separated list in JPA query

I found that GROUP_CONCAT is not a registered function in JPA query but could be accessed by registering it manually. I already tried following links but didn't work for me :

How to add non-standardized sql functions in Spring Boot application?

Registering a SQL function with JPA and Hibernate

https://thoughts-on-java.org/database-functions/

https://vladmihalcea.com/hibernate-sql-function-jpql-criteria-api-query/

1.

public class SqlFunctionsMetadataBuilderContributor
        implements MetadataBuilderContributor {

    @Override
    public void contribute(MetadataBuilder metadataBuilder) {
        metadataBuilder.applySqlFunction(
                "group_concat",
                new StandardSQLFunction(
                        "group_concat",
                        StandardBasicTypes.STRING
                )
        );
    }
}

2.

 public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory)
            throws QueryException {
        if (arguments.size() < 1) {
            throw new QueryException(new IllegalArgumentException("group_concat should have at least one arg"));
        }

        StringBuilder builder = new StringBuilder();
        if (arguments.size() > 1 && arguments.get(0).equals("'distinct'")) {
            builder.append("distinct ");
            builder.append(arguments.get(1));
        } else {
            builder.append(arguments.get(0));
        }

        return "group_concat(" + builder.toString() + ")";
    }

3.

@Configuration
public class DataSource {
    @Bean
    public JpaVendorAdapter jpaVendorAdapter() {
        AbstractJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
        adapter.setShowSql(true);
        adapter.setDatabase(Database.MYSQL);
        // package to CustomMysqlDialect
        adapter.setDatabasePlatform("com.myprojet.admin.configuration.RegisterSqlFunction");
        adapter.setGenerateDdl(false);
        return adapter;
    }
}

    public RegisterSqlFunction() {
        super();

         registerFunction("group_concat, new StandardSQLFunction("group_concat",
       StandardBasicTypes.STRING));
    }

I except using group_concat with JPA query.

Body:
In case someone is having issues when registering this in a SpringBoot app this is the right way:

Create a class that implements: MetadataBuilderContributor interface.

package com.application.config;

public class SqlFunctionsMetadataBuilderContributor implements MetadataBuilderContributor {

  @Override
  public void contribute(MetadataBuilder metadataBuilder) {
    metadataBuilder.applySqlFunction(
        "STRING_AGG",
        new StandardSQLFunction(
            "STRING_AGG",
            StandardBasicTypes.STRING
        )
    );
  }
}

In your application .yml (or .properties) refer to the previously created class in the following properties path: spring.jpa.properties.hibernate.metadata_builder_contributor

  spring:
    jpa:
      properties:
        hibernate:
          metadata_builder_contributor: com.application.config.SqlFunctionsMetadataBuilderContributor


问:
AnyLogic Sensitivity analysis visualization
I am new to this and lost about how to create visualization for the AnyLogic sensitivity analysis. Here is the summary:

I have dataset that captures dependent and independent variables at the end of simulation run (just captures one pair at the end). Trying to vary independent variable to see the impact on dependent variable. The resulting dataset is correct (when I copy and paste in Excel) but the chart looks blank.

Also, output states that it completed 5 iterations but I specified 10 and the data shows that there were in fact 10 iterations.

There are no parameters for the chart data (see the screenshot) but I am guessing it is automatically populated at the end simulation based on the code (also copied below)? Otherwise, I cannot figure out what goes into the chart data (tried to manually enter variables/datasets to no avail).

This is the code after each simulation runs:

```<code>Color color = lerpColor( (getCurrentIteration() - 1) / (double) (getMaximumIterations() - 1), blue, red );
chart0.addDataSet( root.died_friend, format( root.SocFriendBrave ), color, true, `Chart.INTERPOLATION_LINEAR, 1, Chart.POINT_NONE );`
</code>```

I realize this is a very basic question but I am lost and cannot get on the right path based on the help I found. thank you.

答:
Let's say you have 2 experiments: simulation (normal one) and sensitivity analysis (new one)

The only way for the chart to look blank is if your dataset died_friend is empty. This can happen for many reasons, but the reason I suspect it happens here, is because you fill this dataset with information at the end of the simulation run, which means that you are probably using the java actions of the simulation experiment.

The sensitivity experiment DOES NOT read what you write on the java actions of the simulation experiment, so that might be the problem.

If this is not the case, you need to check other possible reasons on why your dataset is empty when you run the sensitivity analysis.

Remember: the fact that your dataset has data in your simulation experiment, does not necessarily mean the dataset will not be empty on the sensitivity experiment.

Body:
I am new to this and lost about how to create visualization for the AnyLogic sensitivity analysis. Here is the summary:

I have dataset that captures dependent and independent variables at the end of simulation run (just captures one pair at the end). Trying to vary independent variable to see the impact on dependent variable. The resulting dataset is correct (when I copy and paste in Excel) but the chart looks blank.

Also, output states that it completed 5 iterations but I specified 10 and the data shows that there were in fact 10 iterations.

There are no parameters for the chart data (see the screenshot) but I am guessing it is automatically populated at the end simulation based on the code (also copied below)? Otherwise, I cannot figure out what goes into the chart data (tried to manually enter variables/datasets to no avail).

This is the code after each simulation runs:

Color color = lerpColor( (getCurrentIteration() - 1) / (double) (getMaximumIterations() - 1), blue, red );
chart0.addDataSet( root.died_friend, format( root.SocFriendBrave ), color, true, `Chart.INTERPOLATION_LINEAR, 1, Chart.POINT_NONE );`

I realize this is a very basic question but I am lost and cannot get on the right path based on the help I found. thank you.


问:
Opposite code behind in Flex
Why in Flex the code behind pattern is using the Actionscript class as a base class instead of using the MXML component for that?

I mean, instead of extending our AS3 code behind class, why we don't extend our MXML in a new AS3 class?

Using that approach seems more natural, because is a real extension, we are adding code and functionalities to our MXML base.

Using the code behind pattern is a hack to OOP, every time we add a component to our MXML we need to modify our AS3 class, that is, if we modify the child (MXML) we need to modify the parent (AS3) too.

What's wrong with the opposite code behind ("code in front"?) ?

答:
The main reason code behind got popularity was because of the tooling.  You just can't drag an AS3 based component around in the Flex Builder 3 design environment.  I've tried various work-arounds, but they were all problematic.  In fact it was the first thing I ever blogged about:
http://www.rogue-development.com/blog2/2007/03/code-in-front/

I haven't re-tried this in Flash Builder 4.  Mostly because, since then, I've come to the realization that the flex layout tool is crap, and I rarely use it.  Because of that, all of my recent development has been code-in-front.

If you need to bind to a variable in your MXML, you define that variable in MXML, it's then available through inheritance in your subclass.

I'm not a huge fan of spark skinning for single-skin components.  If you have a component that has exactly one visual look to it, code in front is far easier to develop with.  (Skinning is perfect for components that do need multiple skins)

Title: Opposite code behind in Flex


问:
When calculating a CRC, should the remainder be set to something if it becomes 0?
Are there CRC algorithms in which the remainder is checked for zero during the generation, and changed when that happens?

When calculating a CRC, if you start with an initial value (the CRC value, aka the remainder value) of 0, leading zeroes in the data being CRCd will not have an effect. So the CRC for "\0\0\0Hello" will be the same as "Hello".

https://xcore.github.io/doc_tips_and_tricks/crc.html#the-initial-value

This means that if, as the CRC is being calculated, the value becomes zero at some point, any zeroes immediately following that point will have no effect on the CRC. If one or more of the zeroes is lost, the CRC will not be changed.

I want to generate a CRC for some data, so that I can determine when a byte is lost. Is this an esoteric application of the CRC? Because when looking for examples of calculating a CRC, I have not found any examples where the CRC value is checked for 0 during the computation, and some non-zero bits fed in a that point. I would think that this would be the only way to be sure to detect a loss of one or more bits at a point in the data, if the CRC up to that point happened to be 0.

答:
To detect and/or correct dropped bits, something like Marker Code or Watermark Code is needed.

https://link.springer.com/article/10.1007/BF03219806

https://ieeexplore.ieee.org/document/866775

Marker codes and Watermark codes are usually implemented in hardware, such as the read / write logic in a hard drive, and operate at the bit level and the media interface. Additional bits are intermixed with data bits to allow detection of lost synchronization or signal, which could otherwise lead to dropped or inserted bits. Here is a better link that describes this. The turbopaper.pdf file mentions LDPC, low density parity codes, which Wiki has an article for. Note that when receiving or reading data, the Marker | Watermark code is handled first at the hardware interface, and the LDPC (or CRC or Reed Solomon) is done after the hardware has detected no dropped or inserted bits.

http://www.inference.org.uk/ear23/turbopaper.pdf

https://en.wikipedia.org/wiki/Low-density_parity-check_code


问:
CSS Pseudo elements not positioned properly on Safari
I've wrote the following CSS that uses pseudo elements to design a footer.
Looks like it works fine on Chrome & Firefox on windows but on Safari the footer_il::after goes on the bottom of the page.

When im adding margin-top: -20em; on .footer_il::after it's working the way i want it but it obviously breaks on other browsers.

.footer_il::before {
  width: 75px;
  height: 70px;
  -webkit-transform: rotate(134deg);
  -ms-transform: rotate(134deg);
  transform: rotate(134deg);
  left: calc(100% - 463px - 85px);
  margin-top: -2em;
}

.footer_il::after {
  height: 54px;
  left: 0;
  width: calc(100% - 449px - 63px);
}

.footer_il::before,
.footer_il::after {
  z-index: 100;
  position: absolute;
  content: "";
  background-color: #f7f7f7
}

.footer {
  height: 20em;
  background-color: #000;
  width: 100%;
  display: inline-flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <!-- Footer -->
  <footer class="footer_il bg-light">
    <div class="footer">
      <div class="footer_section_1">
        <div class="footer_container">
          <div class="footer_branding">
            <div class ="footer_logo">

            </div>
        </div>
      </div>
      </div>
      <div class="footer_section_2">

      </div>
      <div class="footer_section_3">
        <div class="footer_container">
        </div>
      </div>
      <div class="footer_section_4">

      </div>
    </div>
  </footer></code>```

答:
So just by playing around a bit i ended up with the following result. Thanks to  pschueller for the hint.

I've added the entire footer into a container. Set the class in absolute position and 100% width. Then added inside the ::after class 0 distance from top.

Now it's working on Mac OS Safari. Because there wasn't a top before it was getting outside of it's intended position.

.footer_entire_container {
  position: absolute;
  width: 100%;
}

.footer_il::before {
  width: 75px;
  height: 70px;
  -webkit-transform: rotate(134deg);
  -ms-transform: rotate(134deg);
  transform: rotate(134deg);
  left: calc(100% - 463px - 85px);
  margin-top: -2em;
}

.footer_il::after {
  height: 54px;
  left: 0;
  top: 0;
  width: calc(100% - 449px - 63px);
}

.footer_il::before,
.footer_il::after {
  z-index: 100;
  position: absolute;
  content: "";
  background-color: #f7f7f7
}

.footer {
  height: 20em;
  background-color: #000;
  width: 100%;
  display: inline-flex;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!-- Footer -->
  <div class="footer_entire_container">
    <footer class="footer_il bg-light">
      <div class="footer">
        <div class="footer_section_1">
          <div class="footer_container">
            <div class="footer_branding">
              <div class ="footer_logo">

              </div>
          </div>
        </div>
        </div>
        <div class="footer_section_2">

        </div>
        <div class="footer_section_3">
          <div class="footer_container">
          </div>
        </div>
        <div class="footer_section_4">

        </div>
      </div>
    </footer>
  </div></code>```

Body:
So just by playing around a bit i ended up with the following result. Thanks to  pschueller for the hint.

I've added the entire footer into a container. Set the class in absolute position and 100% width. Then added inside the ::after class 0 distance from top.

Now it's working on Mac OS Safari. Because there wasn't a top before it was getting outside of it's intended position.

.footer_entire_container {
  position: absolute;
  width: 100%;
}

.footer_il::before {
  width: 75px;
  height: 70px;
  -webkit-transform: rotate(134deg);
  -ms-transform: rotate(134deg);
  transform: rotate(134deg);
  left: calc(100% - 463px - 85px);
  margin-top: -2em;
}

.footer_il::after {
  height: 54px;
  left: 0;
  top: 0;
  width: calc(100% - 449px - 63px);
}

.footer_il::before,
.footer_il::after {
  z-index: 100;
  position: absolute;
  content: "";
  background-color: #f7f7f7
}

.footer {
  height: 20em;
  background-color: #000;
  width: 100%;
  display: inline-flex;
}

<!-- Footer -->
  <div class="footer_entire_container">
    <footer class="footer_il bg-light">
      <div class="footer">
        <div class="footer_section_1">
          <div class="footer_container">
            <div class="footer_branding">
              <div class ="footer_logo">

              </div>
          </div>
        </div>
        </div>
        <div class="footer_section_2">

        </div>
        <div class="footer_section_3">
          <div class="footer_container">
          </div>
        </div>
        <div class="footer_section_4">

        </div>
      </div>
    </footer>
  </div>


问:
Typescript: Is it possible to type an array to include every key of an enum
Is it possible to type the enum array in a way that forces it to contain every single value of the EPostFromField  enum?

This is a mongodb schema, and the use case would be to future proof the enum field if more enums are added later on (ie: have the compiler throw an error because the array doesn't have all the enum values enumerated).

As a bonus I guess the next level would be a solution that also guarantees that the enum array values are unique :)

```<code>export const enum EPostFromField {
  Resident = 'resident',
  AdminUser = 'admin-user', // Admin <user name>
  BoardUser = 'board-user', // Board <user name>
  AdminSociety = 'admin-society', // Admin <community name>
  BoardSociety = 'board-society', // Board <community name>
}

showPostAs: {
    type: String,
    default: EPostFromField.Resident,
    enum: [
      EPostFromField.Resident,
      EPostFromField.AdminUser,
      EPostFromField.BoardUser,
      EPostFromField.AdminSociety,
      EPostFromField.BoardSociety,
    ] as EPostFromField[], // DEVNOTE: Improve typing to enforce *every* unique key of enum
  },
</code>```

答:
You could define a string enum and do the following:

```<code>enum EPostFromField {
    Resident = "Resident",
    AdminUser = "AdminUser",
    BoardUser = "BoardUser",
    AdminSociety = "AdminSociety",
    BoardSociety = "BoardSociety"
}

const epostFromFieldKeys = Object.keys(EPostFromField);

const epostFromFields = epostFromFieldKeys as EPostFromField[]
</code>```

You can see this running in this playground link.

The values in the array would be unique if you define the string values in the enum uniquely(!).

Body:
Is it possible to type the enum array in a way that forces it to contain every single value of the EPostFromField  enum?

This is a mongodb schema, and the use case would be to future proof the enum field if more enums are added later on (ie: have the compiler throw an error because the array doesn't have all the enum values enumerated).

As a bonus I guess the next level would be a solution that also guarantees that the enum array values are unique :)

export const enum EPostFromField {
  Resident = 'resident',
  AdminUser = 'admin-user', // Admin <user name>
  BoardUser = 'board-user', // Board <user name>
  AdminSociety = 'admin-society', // Admin <community name>
  BoardSociety = 'board-society', // Board <community name>
}

showPostAs: {
    type: String,
    default: EPostFromField.Resident,
    enum: [
      EPostFromField.Resident,
      EPostFromField.AdminUser,
      EPostFromField.BoardUser,
      EPostFromField.AdminSociety,
      EPostFromField.BoardSociety,
    ] as EPostFromField[], // DEVNOTE: Improve typing to enforce *every* unique key of enum
  },

Body:
You could define a string enum and do the following:

enum EPostFromField {
    Resident = "Resident",
    AdminUser = "AdminUser",
    BoardUser = "BoardUser",
    AdminSociety = "AdminSociety",
    BoardSociety = "BoardSociety"
}

const epostFromFieldKeys = Object.keys(EPostFromField);

const epostFromFields = epostFromFieldKeys as EPostFromField[]

You can see this running in this playground link.

The values in the array would be unique if you define the string values in the enum uniquely(!).


问:
Unity, Spawn a prefab to "nearestTarget" gameObject's location
I'm creating a game where objects are being created. These objects are moving left and the player has to press space bar before the object reaches the end of the screen. Every thing works fine with the exception of spawning a prefab on the moving objects.

The idea is to spawn a animation on the nearest target. But when instantiated, the prefab always instantiate at the prefab location (0,0,0). How do I make the instantiated prefab spawn at the correct place? (I've tested with print(nearestTarget.transform.position) and the print always gives me a different location depending on the "nearestTarget")

Trying to spawn the prefab in HandSlapAnimation() Method.

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerInput : MonoBehaviour
{
    // Reference to levelManager
    [SerializeField] LevelManager levelManager;
    // Array of all present entities
    private GameObject[] targets;
    // Nearest entity
    private GameObject nearestTarget;
    // Array of all x position of all present entities
    private float[] locationOfTargets;
    // Nearest x position (transform.position.x) in all entities
    private float nearestLocation;
    // Finds the index location of the float value
    private int index;
    // Hand prefab to be instantiate during Keypress
    public GameObject handPrefab;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        targets = GameObject.FindGameObjectsWithTag("Entities");

        if (targets.Length > 0)
        {
            FindLocationOfEntities();
            AssignNearestTarget();
            HandSlapAnimation();
            DestroyNearestTarget();
        }
    }
}

void FindLocationOfEntities()
{
    locationOfTargets = new float[targets.Length];

    for (int i = 0; i < targets.Length; i++)
    {
        locationOfTargets[i] = targets[i].transform.position.x;
    }
}

void AssignNearestTarget()
{
    nearestLocation = Mathf.Min(locationOfTargets);
    index = System.Array.IndexOf(locationOfTargets, nearestLocation);
    nearestTarget = targets[index];
}

void DestroyNearestTarget()
{
    if (nearestTarget.GetComponent<CubeMovement>().isCat == true)
    {
        levelManager.LoadLevel("Game Over");
    }
    else
    {
        Destroy(nearestTarget);
    }
}

void HandSlapAnimation()
{
    // Instantiate  prefab Hand GameObject at the nearest target to execute the Hand Slap animation
    Instantiate(handPrefab, transform.position, Quaternion.identity);
    handPrefab.transform.SetParent(nearestTarget.transform);
    print(nearestTarget.transform.position);
}
</code>```

}

答:
The problem is that in:

```<code>Instantiate(handPrefab, transform.position, Quaternion.identity);
</code>```

The transform.positionis the position of the actual object, your PlayerInput instance.

Then, you do: handPrefab.transform.SetParent(nearestTarget.transform) but that doesn't move the position, only sets the parent.

Instead of using transform.position in the Instantiate method, use nearestTarget.transform.position.

```<code>Instantiate(handPrefab, nearestTarget.transform.position, Quaternion.identity);
</code>```

Body:
I'm creating a game where objects are being created. These objects are moving left and the player has to press space bar before the object reaches the end of the screen. Every thing works fine with the exception of spawning a prefab on the moving objects.

The idea is to spawn a animation on the nearest target. But when instantiated, the prefab always instantiate at the prefab location (0,0,0). How do I make the instantiated prefab spawn at the correct place? (I've tested with print(nearestTarget.transform.position) and the print always gives me a different location depending on the "nearestTarget")

Trying to spawn the prefab in HandSlapAnimation() Method.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerInput : MonoBehaviour
{
    // Reference to levelManager
    [SerializeField] LevelManager levelManager;
    // Array of all present entities
    private GameObject[] targets;
    // Nearest entity
    private GameObject nearestTarget;
    // Array of all x position of all present entities
    private float[] locationOfTargets;
    // Nearest x position (transform.position.x) in all entities
    private float nearestLocation;
    // Finds the index location of the float value
    private int index;
    // Hand prefab to be instantiate during Keypress
    public GameObject handPrefab;

void Update()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        targets = GameObject.FindGameObjectsWithTag("Entities");

        if (targets.Length > 0)
        {
            FindLocationOfEntities();
            AssignNearestTarget();
            HandSlapAnimation();
            DestroyNearestTarget();
        }
    }
}

void FindLocationOfEntities()
{
    locationOfTargets = new float[targets.Length];

    for (int i = 0; i < targets.Length; i++)
    {
        locationOfTargets[i] = targets[i].transform.position.x;
    }
}

void AssignNearestTarget()
{
    nearestLocation = Mathf.Min(locationOfTargets);
    index = System.Array.IndexOf(locationOfTargets, nearestLocation);
    nearestTarget = targets[index];
}

void DestroyNearestTarget()
{
    if (nearestTarget.GetComponent<CubeMovement>().isCat == true)
    {
        levelManager.LoadLevel("Game Over");
    }
    else
    {
        Destroy(nearestTarget);
    }
}

void HandSlapAnimation()
{
    // Instantiate  prefab Hand GameObject at the nearest target to execute the Hand Slap animation
    Instantiate(handPrefab, transform.position, Quaternion.identity);
    handPrefab.transform.SetParent(nearestTarget.transform);
    print(nearestTarget.transform.position);
}

}

Body:
The problem is that in:

Instantiate(handPrefab, transform.position, Quaternion.identity);

The transform.positionis the position of the actual object, your PlayerInput instance.

Then, you do: handPrefab.transform.SetParent(nearestTarget.transform) but that doesn't move the position, only sets the parent.

Instead of using transform.position in the Instantiate method, use nearestTarget.transform.position.

Instantiate(handPrefab, nearestTarget.transform.position, Quaternion.identity);


问:
Pasting an Excel range into an email as a picture
I'm creating an Outlook email from Excel (Office 2013). I want to paste a range of cells (C3:S52) into the email as a picture.

Below is the code I have so far. Where am I going wrong?

```<code> Sub Button193_Click()
 '
 ' Button193_Click Macro
 '

 '
 ActiveWindow.ScrollColumn = 2
 ActiveWindow.ScrollColumn = 1
 Range("C3:S52").Select
 Selection.Copy
 End Sub
 Sub CreateMail()

 Dim objOutlook As Object
 Dim objMail As Object
 Dim rngTo As Range
 Dim rngSubject As Range
 Dim rngBody As Range
 Dim rngAttach As Range

 Set objOutlook = CreateObject("Outlook.Application")
 Set objMail = objOutlook.CreateItem(0)

 With ActiveSheet
 Set rngTo = .Range("E55")
 Set rngSubject = .Range("E56")
 Set rngBody = .Range("E57")
 End With

 With objMail
 .To = rngTo.Value
 .Subject = rngSubject.Value
 .Body = rngBody.Value
 .Display 'Instead of .Display, you can use .Send to send the email _
 or .Save to save a copy in the drafts folder
 End With

 Set objOutlook = Nothing
 Set objMail = Nothing
 Set rngTo = Nothing
 Set rngSubject = Nothing
 Set rngBody = Nothing
 Set rngAttach = Nothing

 End Sub
 Sub Button235_Click()
 '
 ' Button235_Click Macro
 '

 '
 ActiveWindow.ScrollColumn = 2
 ActiveWindow.ScrollColumn = 1
 Range("A1:M27").Select
 Selection.Copy
 End Sub
 Sub RunThemAll()

 Application.Run "Button193_Click"

 Application.Run "CreateMail"

 End Sub
</code>```

答:
I am providing an alternative solution to the above problem as Outlook.MailItem.GetInspector.WordEditor does not work in some organizational environments.

For security purposes, the HTMLBody, HTMLEditor, Body and WordEditor properties all are subject to address-information security prompts because the body of a message often contains the sender's or other people's e-mail addresses. And, if Group Policy does not permit then these prompts do not come on-screen. In simple words, as a developer, you are bound to change your code, because neither registry changes can be made nor group policy can be modified.

Hence, if your code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the code below. Comments have been added for easy understanding and implementation.

If you have administrative rights then try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, as developer, I recommend a code that's rather compatible with all versions of Excel instead of making system changes because system changes will be required on each end user's machine as well.

Code Compatible: Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Office 365

```<code>Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:DashboardFile.png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub
</code>```

Body:
I'm creating an Outlook email from Excel (Office 2013). I want to paste a range of cells (C3:S52) into the email as a picture.

Below is the code I have so far. Where am I going wrong?

 Sub Button193_Click()
 '
 ' Button193_Click Macro
 '

 '
 ActiveWindow.ScrollColumn = 2
 ActiveWindow.ScrollColumn = 1
 Range("C3:S52").Select
 Selection.Copy
 End Sub
 Sub CreateMail()

 Dim objOutlook As Object
 Dim objMail As Object
 Dim rngTo As Range
 Dim rngSubject As Range
 Dim rngBody As Range
 Dim rngAttach As Range

 Set objOutlook = CreateObject("Outlook.Application")
 Set objMail = objOutlook.CreateItem(0)

 With ActiveSheet
 Set rngTo = .Range("E55")
 Set rngSubject = .Range("E56")
 Set rngBody = .Range("E57")
 End With

 With objMail
 .To = rngTo.Value
 .Subject = rngSubject.Value
 .Body = rngBody.Value
 .Display 'Instead of .Display, you can use .Send to send the email _
 or .Save to save a copy in the drafts folder
 End With

 Set objOutlook = Nothing
 Set objMail = Nothing
 Set rngTo = Nothing
 Set rngSubject = Nothing
 Set rngBody = Nothing
 Set rngAttach = Nothing

 End Sub
 Sub Button235_Click()
 '
 ' Button235_Click Macro
 '

 '
 ActiveWindow.ScrollColumn = 2
 ActiveWindow.ScrollColumn = 1
 Range("A1:M27").Select
 Selection.Copy
 End Sub
 Sub RunThemAll()

 Application.Run "Button193_Click"

 Application.Run "CreateMail"

 End Sub

Body:
I am providing an alternative solution to the above problem as Outlook.MailItem.GetInspector.WordEditor does not work in some organizational environments.

For security purposes, the HTMLBody, HTMLEditor, Body and WordEditor properties all are subject to address-information security prompts because the body of a message often contains the sender's or other people's e-mail addresses. And, if Group Policy does not permit then these prompts do not come on-screen. In simple words, as a developer, you are bound to change your code, because neither registry changes can be made nor group policy can be modified.

Hence, if your code suddenly stopped working after migrating to Office 365 or for any other reasons, please refer to the code below. Comments have been added for easy understanding and implementation.

If you have administrative rights then try the registry changes given at below link:
https://support.microsoft.com/en-au/help/926512/information-for-administrators-about-e-mail-security-settings-in-outlo

However, as developer, I recommend a code that's rather compatible with all versions of Excel instead of making system changes because system changes will be required on each end user's machine as well.

Code Compatible: Excel 2003, Excel 2007, Excel 2010, Excel 2013, Excel 2016, Office 365

Option Explicit

Sub Create_Email(ByVal strTo As String, ByVal strSubject As String)

    Dim rngToPicture As Range
    Dim outlookApp As Object
    Dim Outmail As Object
    Dim strTempFilePath As String
    Dim strTempFileName As String

    'Name it anything, doesn't matter
    strTempFileName = "RangeAsPNG"

    'rngToPicture is defined as NAMED RANGE in the workbook, do modify this name before use
    Set rngToPicture = Range("rngToPicture")
    Set outlookApp = CreateObject("Outlook.Application")
    Set Outmail = outlookApp.CreateItem(olMailItem)

    'Create an email
    With Outmail
        .To = strTo
        .Subject = strSubject

        'Create the range as a PNG file and store it in temp folder
        Call createPNG(rngToPicture, strTempFileName)

        'Embed the image in Outlook
        strTempFilePath = Environ$("temp") & "\" & strTempFileName & ".png"
        .Attachments.Add strTempFilePath, olByValue, 0

        'Change the HTML below to add Header (Dear John) or signature (Kind Regards) using newline tag (<br />)
        .HTMLBody = "<img src='cid:DashboardFile.png' style='border:0'>"

        .Display

    End With

    Set Outmail = Nothing
    Set outlookApp = Nothing
    Set rngToPicture = Nothing

End Sub

Sub createPNG(ByRef rngToPicture As Range, nameFile As String)

    Dim wksName As String

    wksName = rngToPicture.Parent.Name

    'Delete the existing PNG file of same name, if exists
    On Error Resume Next
        Kill Environ$("temp") & "\" & nameFile & ".png"
    On Error GoTo 0

    'Copy the range as picture
    rngToPicture.CopyPicture

    'Paste the picture in Chart area of same dimensions
    With ThisWorkbook.Worksheets(wksName).ChartObjects.Add(rngToPicture.Left, rngToPicture.Top, rngToPicture.Width, rngToPicture.Height)
        .Activate
        .Chart.Paste
        'Export the chart as PNG File to Temp folder
        .Chart.Export Environ$("temp") & "\" & nameFile & ".png", "PNG"
    End With
    Worksheets(wksName).ChartObjects(Worksheets(wksName).ChartObjects.Count).Delete

End Sub


问:
How can I shorten these repetitive while/try/except/else input blocks?
I am trying to make an exchange app and I am trying to make it shorter (mostly by changing those whiles). </p>

```<code>def key_check(currency):
    import re
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception(
            "This is not a currency")
    else:
        rates = json.loads(rates)

while True:
    try:
        yourCurrency = input("Which currency do you have?: ").upper()
        key_check(yourCurrency)
    except Exception as error:
        print(error)
    else:
        break

while True:
    try:
        yourMoney = float(input("How much money do you have?: "))
    except:
        print("This is not a float!")
    else:
        break

while True:
    try:
        exchangeCurrency = input(
            "Which currency would you like to buy?: ").upper()
        key_check(exchangeCurrency)
    except Exception as error:
        print(error)
    else:
        break
</code>```

答:
I've come up with the following solution and I had quite a bit of fun writing it.

class Input:
    def __init__(self, question, required_type, check_against = None):
        self.question = question
        self.required_type = required_type
        self.check_against = check_against

    def get(self):
        while True:
            try:
                answer = self.required_type(input(self.question))
                if self.check_against:
                    assert self.check_against(answer)
                return answer
            except (ValueError, AssertionError):
                pass
```

<p>Example usage</p>

<pre class="lang-py prettyprint-override"><code>def isTen(a):
    return isinstance(a, int) and a == 10

print(Input("Number: ", int, isTen).get())
</code>```

This will force the user to keep entering until the correct value is given, example output

```<code>Number: test
Number: 123
Number: 10.0
Number: 10
10
>>>
</code>```

You can handle error messages in the check_against optional parameter, for example

def isTen(a):
    if isinstance(a, int) and a == 10:
        print("Good job!")
        return True
    print("Bad input, give me TEN")
    return False
```

<p>If you want an error message when the type is incorrect, you can manually add that into the <code>get</code> function or make it a parameter in the class constructor.</p>

<h1>Edit</h1>

<p>This is how it might look in your code</p>

<pre class="lang-py prettyprint-override"><code>yourCurrency = Input("Which currency do you have?: ", str, key_check).get()
yourMoney = Input("How much money do you have?: ", float).get()
exchangeCurrency = Input("Which currency would you like to buy?: ", str, key_check).get()
print(f"You have {yourMoney} {yourCurrency} and would like to buy {exchangeCurrency}")
</code>```

Results in

```<code>Which currency do you have?: GBP
How much money do you have?: 650.30
Which currency would you like to buy?: USD
You have 650.3 GBP and would like to buy USD
</code>```

Body:
I am trying to make an exchange app and I am trying to make it shorter (mostly by changing those whiles).

def key_check(currency):
    import re
    rates = website["rates"]
    rates.update({"EUR": 1})
    rates = json.dumps(rates)
    if not re.search(currency, rates):
        raise Exception(
            "This is not a currency")
    else:
        rates = json.loads(rates)

while True:
    try:
        yourCurrency = input("Which currency do you have?: ").upper()
        key_check(yourCurrency)
    except Exception as error:
        print(error)
    else:
        break

while True:
    try:
        yourMoney = float(input("How much money do you have?: "))
    except:
        print("This is not a float!")
    else:
        break

while True:
    try:
        exchangeCurrency = input(
            "Which currency would you like to buy?: ").upper()
        key_check(exchangeCurrency)
    except Exception as error:
        print(error)
    else:
        break

Body:
I've come up with the following solution and I had quite a bit of fun writing it.

class Input:
    def __init__(self, question, required_type, check_against = None):
        self.question = question
        self.required_type = required_type
        self.check_against = check_against

    def get(self):
        while True:
            try:
                answer = self.required_type(input(self.question))
                if self.check_against:
                    assert self.check_against(answer)
                return answer
            except (ValueError, AssertionError):
                pass

Example usage

def isTen(a):
    return isinstance(a, int) and a == 10

print(Input("Number: ", int, isTen).get())

This will force the user to keep entering until the correct value is given, example output

Number: test
Number: 123
Number: 10.0
Number: 10
10
>>>

You can handle error messages in the check_against optional parameter, for example

def isTen(a):
    if isinstance(a, int) and a == 10:
        print("Good job!")
        return True
    print("Bad input, give me TEN")
    return False

If you want an error message when the type is incorrect, you can manually add that into the get function or make it a parameter in the class constructor.

Edit

This is how it might look in your code

yourCurrency = Input("Which currency do you have?: ", str, key_check).get()
yourMoney = Input("How much money do you have?: ", float).get()
exchangeCurrency = Input("Which currency would you like to buy?: ", str, key_check).get()
print(f"You have {yourMoney} {yourCurrency} and would like to buy {exchangeCurrency}")

Results in

Which currency do you have?: GBP
How much money do you have?: 650.30
Which currency would you like to buy?: USD
You have 650.3 GBP and would like to buy USD


问:
How Groove Music creates the multi-color shadow effect based on image colors?
How Groove Music UWP app creates the multi-color shadow effect based on image colors and how can I recreate this in XAML/C# (UWP), I know that I can use ColorThief (+ Win2D or WCT) library to get the color palette from an image but I don't know how I can benefit from it to recreate that effect

答: I have ended up using ColorShadow control from CompositionProToolkit</p>


问:
Exact representation of location in a legal text as string
Given a legal text as the EU-General Data Protection Regulation (GDPR) one wants to have reference to an exact location in that or another law.

In common written language one would write something like

Art. 13(1c) GDPR or
Section 41(1)(2), first sentence MyLaw.

How represent such text as a short string for storing in databases or querying results in a deterministic and exact way?

One could think of something such as GDPR-13-1-c or MyLaw-42-1-2-S1.

I am also comparing to ISO country or language codes such as ES for Spain or en-EN for the English language.

答:
It's always important to separate the concerns of data storage with data rendering.

Text such as Art. 13(1c) GDPR or Section 41(1)(2), first sentence MyLaw. is a rendering of multiple pieces of data. If you don't care about any of the pieces individually, then it could make sense to treat it as single value and store it in a single column.

However, you have raised checking the country code etc, so it's clear you do care about at least some of the individual pieces, so store them separately in separate columns.

This would enable you for example to have a country code table and create a foreign key constraint from that part of the data to the lookup table.


问:
How to have 'required' in my textarea without executing the 'onclick' function immediately?
I tried putting requiredin my textarea. But it won't work because my onclick="displayText()" function executes right away. How can I require my textarea get filled out first without executing the onclick right away? Here's my code:

HTML:

```<code><!DOCTYPE html>
<html>
  <head>
    <title>Word Counter</title>
  </head>
  <body>
    <div id="input-page">
      <h1>Word Counter</h1>
      <form action="">
        <textarea id="inputted-text" type="text" rows="22" cols="60"></textarea>
        <br />
      </form>
      <button onclick="displayText()">COUNT</button>
    </div>

    <div id="count-page" style="display: none;">
      <h1>Your Text:</h1>
      <p id=display-user-text></p>
      <div>
         <h1 id="word-count">Count: </h1>
      </div>
    </div>
  </body>
  <script src="app.js"></script>
</html>
</code>```

JavaScript:

```<code>const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  inputPage.style.display = "none";
  // get user's inputted text
  const inputtedText = document.getElementById("inputted-text");
  const inputtedTextValue = inputtedText.value;
  // diplay user's inputted text
  document.getElementById("display-user-text").innerText = inputtedTextValue;
  countPage.style.display = "block";
  console.log(countWords(inputtedTextValue));
};

const countWords = (str) => {
  return str.split(" ").length;
};

const renderWordCount = () => {
  document.getElementById("word-count") = wordCount;
};
</code>```

Bonus:
How can I display the count of my words besides the Count: header, instead of just having it on my console?

答:
you want the system to issue a warning when the text-area is empty. You can do this by adding If-else condition expressions to your codes.

const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  const inputtedText = document.getElementById("inputted-text");
  const inputtedTextValue = inputtedText.value;

  if (inputtedText.value !== "") { // normal flow will continue if the text-area is not empty
    inputPage.style.display = "none";
    document.getElementById("display-user-text").innerText = inputtedTextValue;
    countPage.style.display = "block";
  } else { // if the text-area is empty, it will issue a warning.
    alert("this area required")
  }

  console.log(countWords(inputtedTextValue));
};

const countWords = (str) => {
  return str.split(" ").length;
};

const renderWordCount = () => {
  document.getElementById("word-count") = wordCount;
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="input-page">
  <h1>Word Counter</h1>
  <form action="">
    <textarea id="inputted-text" type="text" rows="22" cols="60"></textarea>
    <br />
  </form>
  <button onclick="displayText()">COUNT</button>
</div>

<div id="count-page" style="display: none;">
  <h1>Your Text:</h1>
  <p id="display-user-text"></p>
  <div>
    <h1 id="word-count">Count: </h1>
  </div>
</div></code>```

Body:
I tried putting requiredin my textarea. But it won't work because my onclick="displayText()" function executes right away. How can I require my textarea get filled out first without executing the onclick right away? Here's my code:

HTML:

<!DOCTYPE html>

    <title>Word Counter</title>

Word Counter

      <form action="">
        <textarea id="inputted-text" type="text" rows="22" cols="60"></textarea>

      </form>
      <button onclick="displayText()">COUNT</button>

Your Text:

Count:

JavaScript:

const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  inputPage.style.display = "none";
  // get user's inputted text
  const inputtedText = document.getElementById("inputted-text");
  const inputtedTextValue = inputtedText.value;
  // diplay user's inputted text
  document.getElementById("display-user-text").innerText = inputtedTextValue;
  countPage.style.display = "block";
  console.log(countWords(inputtedTextValue));
};

const countWords = (str) => {
  return str.split(" ").length;
};

const renderWordCount = () => {
  document.getElementById("word-count") = wordCount;
};

Bonus:
How can I display the count of my words besides the Count: header, instead of just having it on my console?

Body:
you want the system to issue a warning when the text-area is empty. You can do this by adding If-else condition expressions to your codes.

const displayText = () => {
  const inputPage = document.getElementById("input-page");
  const countPage = document.getElementById("count-page");
  const inputtedText = document.getElementById("inputted-text");
  const inputtedTextValue = inputtedText.value;

  if (inputtedText.value !== "") { // normal flow will continue if the text-area is not empty
    inputPage.style.display = "none";
    document.getElementById("display-user-text").innerText = inputtedTextValue;
    countPage.style.display = "block";
  } else { // if the text-area is empty, it will issue a warning.
    alert("this area required")
  }

  console.log(countWords(inputtedTextValue));
};

const countWords = (str) => {
  return str.split(" ").length;
};

const renderWordCount = () => {
  document.getElementById("word-count") = wordCount;
};

<div id="input-page">
  <h1>Word Counter</h1>
  <form action="">
    <textarea id="inputted-text" type="text" rows="22" cols="60"></textarea>
    <br />
  </form>
  <button onclick="displayText()">COUNT</button>
</div>

<div id="count-page" style="display: none;">
  <h1>Your Text:</h1>
  <p id="display-user-text"></p>
  <div>
    <h1 id="word-count">Count: </h1>
  </div>
</div>


问:
Problem changing icon in Delphi 2007
I've been working with a program someone else has made and I wanted to change the icon.

The icon I have is 256x256. I used http://converticon.com/ to create the icon (from a bmp I think). I used the icon in Inno Setup to create an installer and it worked fine

So I go to Options -> Application and attempt to load it. However, Delphi 2007 gives me an error 'The parameter is incorrect.' with this info: http://i.stack.imgur.com/vRCgs.png

When I do the same thing in Delphi XE, it works and loads the icon and changes it on compile. I can't use XE right now because the program uses a math parser that has a problem with unicode (thats something to fix for later haha)

So, what I did was open the project in XE, change the icon, save it, delete the dproj and open it in 2007. This works, compiles and displays the correct icon, but when I go to the project options, it gives me the same 'The parameter is incorrect' error.

The workaround isn't a big deal, but I shouldn't need to do it. Does anyone know why I can't change the icon in Delphi 2007?

Edit: I just used that same converticon site to convert the 256x256 icon to 192x192 and smaller and now it works perfectly. Thanks for the answers

答:
Older versions of Delphi don't support 256px Vista icons. I believe that 2010 does not support them so I guess the limitation was fixed in XE.

When working with an older Delphi you'll need to keep the 256px icon out of the IDE. You can still build an executable with a 256px icon from the command line compiler - I used to do just this before upgrading from Delphi 6. But to do this requires the use of a competent resource compiler, for example the Microsoft one.

Title: Problem changing icon in Delphi 2007


问:
Can't use .value for Text Area in JavaScript
I'm trying to get the value of a text area after the submit button is pressed. However, when I try to use .value in my JS file to get the textarea, it doesn't work. Here is my code for my HTML text area and button:

```<code><form>
        <textarea type="text" id = "textArea" rows="5" cols="100"></textarea>
        <br>
        <input type="button" id="submitButton" value="Submit">
</form>
</code>```

And then this is my Javascript code for trying to get the value of the text area. I've set up a listener on the submit button.

```<code>var submit = document.getElementById("submitButton")
function buttonPressed(){
     var text = document.getElementById("textArea").value (this .value part doesn't show up)
     console.log(text);
     submit.addEventListener("click", buttonPressed())
}
</code>```

The .value part won't work and doesn't show up when I type it. The only thing that does show up is .nodeValue How would I get the value of this text area?

I'm a newb at Javascript so any help would be appreciated! Thank you.

答:
your problem is that your button doesn't have attached the event listener because the "addEventListener is inside the function (that is never invoked), I extracted this and the function is invoked now.

const submit = document.getElementById("submitButton");

submit.addEventListener("click", buttonPressed)

function buttonPressed(){
     const text = document.getElementById("textArea").value
     console.log(text);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form>
    <textarea type="text" id = "textArea" rows="5" cols="100"></textarea>
    <br>
    <input type="button" id="submitButton" value="Submit">
</form></code>```

Body:
I'm trying to get the value of a text area after the submit button is pressed. However, when I try to use .value in my JS file to get the textarea, it doesn't work. Here is my code for my HTML text area and button:

<form>
        <textarea type="text" id = "textArea" rows="5" cols="100"></textarea>

        <input type="button" id="submitButton" value="Submit">
</form>

And then this is my Javascript code for trying to get the value of the text area. I've set up a listener on the submit button.

var submit = document.getElementById("submitButton")
function buttonPressed(){
     var text = document.getElementById("textArea").value (this .value part doesn't show up)
     console.log(text);
     submit.addEventListener("click", buttonPressed())
}

The .value part won't work and doesn't show up when I type it. The only thing that does show up is .nodeValue How would I get the value of this text area?

I'm a newb at Javascript so any help would be appreciated! Thank you.

Body:
your problem is that your button doesn't have attached the event listener because the "addEventListener is inside the function (that is never invoked), I extracted this and the function is invoked now.

const submit = document.getElementById("submitButton");

submit.addEventListener("click", buttonPressed)

function buttonPressed(){
     const text = document.getElementById("textArea").value
     console.log(text);
}

<form>
    <textarea type="text" id = "textArea" rows="5" cols="100"></textarea>
    <br>
    <input type="button" id="submitButton" value="Submit">
</form>


问:
If else if shortening
I can see there are so many related questions to this. Could not find anything specific addressing my query. Here is my question:

How can i shorten the below if else condition:

```<code>If (condition1)
{
    If(condition2)
    {
        Logic A
    }
}
Else if (condition3)
{
    Logic A
}
</code>```

One way i could come up was as below:

```<code>If (condition1 && condition2  ||  !condition1 && condition3)
{
    Logic A
}
</code>```

Just wondering if there is a better way of doing it?

答:
sometimes its possible to simplify (note the use of the word 'simplify' instead of 'shorten') conditional logic by reversing it, or by delegating logic to other functions, or a combination of both:

given this:

```<code>function performLogic() {
  if (condition a) {
    if (condition b) {
      logic 1
    }
  } else {
    logic 1
  }
}
</code>```

let's try to think about this in reverse:

```<code>function performLogic() {
  if (!condition a) logic 1
  else if (conditoin b) logic 1
}
</code>```

keep in mind this kind of refactor will not always be possible, and i also advise you to write unit tests for the logic to ensure that the end result remains the same.

It can also sometimes be simplified further depending on the logic in the function. many times we can replace conditional logic with guard clauses like this:

```<code>function getSomeValue() {
  if (condition a) {
    if (condition b) {
      ... do some logic
      return someValue;
    }
  }
}
</code>```

this can be changed to

```<code>function getSomeValue() {
  if (!condition a) return;
  if (!condition b) return;

  ... do some logic
  return someValue;
}
</code>```

Title: If else if shortening

Body:
I can see there are so many related questions to this. Could not find anything specific addressing my query. Here is my question:

How can i shorten the below if else condition:

If (condition1)
{
    If(condition2)
    {
        Logic A
    }
}
Else if (condition3)
{
    Logic A
}

One way i could come up was as below:

If (condition1 && condition2  ||  !condition1 && condition3)
{
    Logic A
}

Just wondering if there is a better way of doing it?

Body:
sometimes its possible to simplify (note the use of the word 'simplify' instead of 'shorten') conditional logic by reversing it, or by delegating logic to other functions, or a combination of both:

given this:

function performLogic() {
  if (condition a) {
    if (condition b) {
      logic 1
    }
  } else {
    logic 1
  }
}

let's try to think about this in reverse:

function performLogic() {
  if (!condition a) logic 1
  else if (conditoin b) logic 1
}

keep in mind this kind of refactor will not always be possible, and i also advise you to write unit tests for the logic to ensure that the end result remains the same.

It can also sometimes be simplified further depending on the logic in the function. many times we can replace conditional logic with guard clauses like this:

function getSomeValue() {
  if (condition a) {
    if (condition b) {
      ... do some logic
      return someValue;
    }
  }
}

this can be changed to

function getSomeValue() {
  if (!condition a) return;
  if (!condition b) return;

  ... do some logic
  return someValue;
}


问:
Avoid Cookie Expiration (Web Scraping)
So I am using Python to make a web scraper for my school's gradebook website called Schoology. So far, it works great, but I was troubled to see that all of the cookies will expire in a few days. Is there a way to automatically get new cookies so that I dont have to replace them every few days? My school uses an "SSO" login where you have to login with your school google account which makes things sort of complicated. I used CURL to get the header/cookie information. If there is anything else that I can improve on in my code, let me know. Here is my code:</p>

```<code># Schoology Web Scraper

import requests
from bs4 import BeautifulSoup

grades = []

headers = {
    # A bunch of headers / cookies that will expire
}

response = requests.get('https://monongalia.schoology.com/grades/grades', headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

for item in soup.find_all('span', attrs={"class":"course-grade-value"}):
  grades.append(item.get_text())

print('\n'.join(grades))
</code>```

答:
you can have it go through the sign in and use credentials provided by the user you can use:

```<code>from bs4 import BeautifulSoup
import requests

##################

username=""
password=""
schoolID=""

##################

# ^ fill in these values ^

payload = {
"mail":username
"pass":password
"school_nid":
}

session = requests.Session()
response = session.post('https://monongalia.schoology.comlogin/ldap', data = payload)
# this will log you in using the credentials provided above

# continue with script below, all cookies will be saved without you needing to do
# anything

</code>```

send the username and password as a payload to the url, using Session() it will keep the
cookies throughout the script so you dont need to manually collect them

Title: Avoid Cookie Expiration (Web Scraping)

Body:
So I am using Python to make a web scraper for my school's gradebook website called Schoology. So far, it works great, but I was troubled to see that all of the cookies will expire in a few days. Is there a way to automatically get new cookies so that I dont have to replace them every few days? My school uses an "SSO" login where you have to login with your school google account which makes things sort of complicated. I used CURL to get the header/cookie information. If there is anything else that I can improve on in my code, let me know. Here is my code:

# Schoology Web Scraper

import requests
from bs4 import BeautifulSoup

grades = []

headers = {
    # A bunch of headers / cookies that will expire
}

response = requests.get('https://monongalia.schoology.com/grades/grades', headers=headers)
soup = BeautifulSoup(response.content, 'html.parser')

for item in soup.find_all('span', attrs={"class":"course-grade-value"}):
  grades.append(item.get_text())

print('\n'.join(grades))

Body:
you can have it go through the sign in and use credentials provided by the user you can use:

from bs4 import BeautifulSoup
import requests

##################

username=""
password=""
schoolID=""

##################

# ^ fill in these values ^

payload = {
"mail":username
"pass":password
"school_nid":
}

session = requests.Session()
response = session.post('https://monongalia.schoology.comlogin/ldap', data = payload)
# this will log you in using the credentials provided above

# continue with script below, all cookies will be saved without you needing to do
# anything

send the username and password as a payload to the url, using Session() it will keep the
cookies throughout the script so you dont need to manually collect them


问:
Java code works on eclipse but not on command prompt
I am writing a java program and it is properly running on Eclipse, there are no errors and the program gives accurate output. However when I compile it using command prompt it gives me 39 errors.

```<code>import java.util.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.*;

public class Main extends JFrame{

    public static void main (String args [])

    {

    JFrame frame = new JFrame (); // making a frame in which we will add all the
                                    // components
    FrameWork work = new FrameWork ();
    frame.setLayout(null);
    frame.setBounds (10,10,700,500);
    frame.setResizable(false); // making the frame non resizeable so that components are not misplaced
    frame.add (work);
    frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
    frame.setVisible (true);

    } // main ends here

} // main class ends here

class FrameWork extends JPanel
{
 // panel in which all the components are added
    JPanel panel = new JPanel ();

    JTextArea jarea = new JTextArea();
    JTextField jfield = new JTextField();
    // Buttons that can be used to switch between standard IO NIO and NIO2
    JButton IO   = new JButton ("Standard IO");
    JButton NIO  = new JButton ("New IO");
    JButton NIO2 = new JButton ("New IO2");
    JScrollPane scroll = new JScrollPane();

FrameWork ()

{

// setting the lay out null so that componenets can be places at respective postions
add(panel);
setLayout (null);
setBounds (0,0,700,500);
setBackground(Color.white);

add(jarea);
jarea.setBounds(5,85,670,360);
//setting border arround the JText area
jarea.setBorder(BorderFactory.createLineBorder(Color.black));
jarea.add(scroll);

add(jfield);
jfield.setBounds(10,10,650,25);

 // adding Standard IO button and Implemnting action listener
add(IO);
IO.setBounds (50,40,150,40);
IO.addMouseListener(new MouseListener(){

    @Override
    public void mouseClicked(MouseEvent ae)

    {
        try {
            FileReader reader = new FileReader("test.txt");
            BufferedReader buff = new BufferedReader(reader);
            jarea.read(buff,null);
            buff.close();

        }

        catch (IOException e) {

        }
    }

    @Override
    public void mouseEntered(MouseEvent ae) {

    }

    @Override
    public void mouseExited(MouseEvent ae) {

    }

    @Override
    public void mousePressed(MouseEvent ae) {

    }

    @Override
    public void mouseReleased(MouseEvent ae) {

    }});

// adding Standard NIO button and Implementing action listener

add(NIO);
NIO.setBounds (250,40,150,40);
NIO.addMouseListener(new MouseListener(){

    @Override
    public void mouseClicked(MouseEvent ae) {
// some part of this code from java docs

        Path file = Paths.get("test.txt");
        try (InputStream in = Files.newInputStream(file);
            BufferedReader reader =new BufferedReader(new InputStreamReader(in)))

        {
            String line = null;
            while ((line = reader.readLine()) != null) {
                jarea.read(reader,null);
            }

        } catch (IOException x) {
            System.err.println(x);
        }

    }

    @Override
    public void mouseEntered(MouseEvent ae) {

    }

    @Override
    public void mouseExited(MouseEvent ae) {

    }

    @Override
    public void mousePressed(MouseEvent ae) {

    }

    @Override
    public void mouseReleased(MouseEvent ae) {

    }});

// adding Standard NIO2 button and Implemnting action listener

add(NIO2);
NIO2.setBounds (450,40,150,40);
NIO2.addMouseListener(new MouseListener(){

    @Override
    public void mouseClicked(MouseEvent ae) {
        try
        {
        ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
        Path file = Paths.get("test.txt");
        ReadableByteChannel rbc = Files.newByteChannel(file);
        int counter =0;
        int flag = 0;
        int enter = 0;
        while(counter != -1)
        {
                buffer.rewind ();
                counter = rbc.read(buffer);
                buffer.rewind();
                flag++;
                for(enter =0 ; enter <= counter-1 ; enter++)
                {
                    byte by = buffer.get();
                    jarea.append(""+(char)by);
                }
        }

        }
        catch(Exception e){}

    }

    @Override
    public void mouseEntered(MouseEvent ae) {

    }

    @Override
    public void mouseExited(MouseEvent ae) {

    }

    @Override
    public void mousePressed(MouseEvent ae) {

    }

    @Override
    public void mouseReleased(MouseEvent ae) {

    }});

}   // constructor ends

}   //FrameWork Class ends
</code>```

Errors:

答: I ran into a similar issue today.  My program was working fine in the Eclipse debugger but misbehaving from the OS command line.  It finally turned out to be a CLASSPATH issue.  My code was incompatible with a JAR that I had included in my CLASSPATH environment variable for the OS shell.  This JAR was not even required for my program.  For Eclipse I had only linked the requisite JARs, so this problem did not manifest in the Eclipse debugger.  After excluding the offending JAR from my CLASSPATH, the problem disappeared.</p>

Body:
I am writing a java program and it is properly running on Eclipse, there are no errors and the program gives accurate output. However when I compile it using command prompt it gives me 39 errors.

import java.util.*;
import javax.swing.*;
import java.awt.Color;
import java.awt.event.*;
import java.io.*;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.*;

public class Main extends JFrame{

    public static void main (String args [])

    {

    JFrame frame = new JFrame (); // making a frame in which we will add all the
                                    // components
    FrameWork work = new FrameWork ();
    frame.setLayout(null);
    frame.setBounds (10,10,700,500);
    frame.setResizable(false); // making the frame non resizeable so that components are not misplaced
    frame.add (work);
    frame.setDefaultCloseOperation (EXIT_ON_CLOSE);
    frame.setVisible (true);

    } // main ends here

} // main class ends here

class FrameWork extends JPanel
{
 // panel in which all the components are added
    JPanel panel = new JPanel ();

    JTextArea jarea = new JTextArea();
    JTextField jfield = new JTextField();
    // Buttons that can be used to switch between standard IO NIO and NIO2
    JButton IO   = new JButton ("Standard IO");
    JButton NIO  = new JButton ("New IO");
    JButton NIO2 = new JButton ("New IO2");
    JScrollPane scroll = new JScrollPane();

FrameWork ()

{

// setting the lay out null so that componenets can be places at respective postions
add(panel);
setLayout (null);
setBounds (0,0,700,500);
setBackground(Color.white);

add(jarea);
jarea.setBounds(5,85,670,360);
//setting border arround the JText area
jarea.setBorder(BorderFactory.createLineBorder(Color.black));
jarea.add(scroll);

add(jfield);
jfield.setBounds(10,10,650,25);

 // adding Standard IO button and Implemnting action listener
add(IO);
IO.setBounds (50,40,150,40);
IO.addMouseListener(new MouseListener(){

    @Override
    public void mouseClicked(MouseEvent ae)

    {
        try {
            FileReader reader = new FileReader("test.txt");
            BufferedReader buff = new BufferedReader(reader);
            jarea.read(buff,null);
            buff.close();

        }

        catch (IOException e) {

        }
    }

    @Override
    public void mouseEntered(MouseEvent ae) {

    }

    @Override
    public void mouseExited(MouseEvent ae) {

    }

    @Override
    public void mousePressed(MouseEvent ae) {

    }

    @Override
    public void mouseReleased(MouseEvent ae) {

    }});

// adding Standard NIO button and Implementing action listener

add(NIO);
NIO.setBounds (250,40,150,40);
NIO.addMouseListener(new MouseListener(){

    @Override
    public void mouseClicked(MouseEvent ae) {
// some part of this code from java docs

        Path file = Paths.get("test.txt");
        try (InputStream in = Files.newInputStream(file);
            BufferedReader reader =new BufferedReader(new InputStreamReader(in)))

        {
            String line = null;
            while ((line = reader.readLine()) != null) {
                jarea.read(reader,null);
            }

        } catch (IOException x) {
            System.err.println(x);
        }

    }

    @Override
    public void mouseEntered(MouseEvent ae) {

    }

    @Override
    public void mouseExited(MouseEvent ae) {

    }

    @Override
    public void mousePressed(MouseEvent ae) {

    }

    @Override
    public void mouseReleased(MouseEvent ae) {

    }});

// adding Standard NIO2 button and Implemnting action listener

add(NIO2);
NIO2.setBounds (450,40,150,40);
NIO2.addMouseListener(new MouseListener(){

    @Override
    public void mouseClicked(MouseEvent ae) {
        try
        {
        ByteBuffer buffer = ByteBuffer.allocate(1024*1024);
        Path file = Paths.get("test.txt");
        ReadableByteChannel rbc = Files.newByteChannel(file);
        int counter =0;
        int flag = 0;
        int enter = 0;
        while(counter != -1)
        {
                buffer.rewind ();
                counter = rbc.read(buffer);
                buffer.rewind();
                flag++;
                for(enter =0 ; enter <= counter-1 ; enter++)
                {
                    byte by = buffer.get();
                    jarea.append(""+(char)by);
                }
        }

        }
        catch(Exception e){}

    }

    @Override
    public void mouseEntered(MouseEvent ae) {

    }

    @Override
    public void mouseExited(MouseEvent ae) {

    }

    @Override
    public void mousePressed(MouseEvent ae) {

    }

    @Override
    public void mouseReleased(MouseEvent ae) {

    }});

}   // constructor ends

}   //FrameWork Class ends

Errors:


问:
Why properties of an XMLHttpRequest object are only printable through console.log()?
```<code>var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)
</code>```

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

答:
I think this is the most practical way .It would help you

```<code>class User {
  //this is a private field
  #name
  get Name() {
    return this.#name
  }
  set Name(val) {
    this.#name = val
  }
}

var obj = new User()
obj.Name = 'test'

console.log('Object.keys():', Object.keys(obj))
console.log('Object.getOwnPropertyNames():', Object.getOwnPropertyNames(obj))
console.log('Object.entries():', Object.entries(obj))
console.log('JSON.stringify():', JSON.stringify(obj))

console.log('console.log:')
console.log(obj)
console.log(obj.Name)
</code>```

this is its compiled code

```<code>function _classPrivateFieldSet(receiver, privateMap, value) {
  var descriptor = privateMap.get(receiver)
  if (!descriptor) {
    throw new TypeError('attempted to set private field on non-instance')
  }
  if (descriptor.set) {
    descriptor.set.call(receiver, value)
  } else {
    if (!descriptor.writable) {
      throw new TypeError('attempted to set read only private field')
    }
    descriptor.value = value
  }
  return value
}
function _classPrivateFieldGet(receiver, privateMap) {
  var descriptor = privateMap.get(receiver)
  if (!descriptor) {
    throw new TypeError('attempted to get private field on non-instance')
  }
  if (descriptor.get) {
    return descriptor.get.call(receiver)
  }
  return descriptor.value
} // Try edit message
class User {
  constructor() {
    _name.set(this, { writable: true, value: void 0 })
  }
  get Name() {
    return _classPrivateFieldGet(this, _name)
  }
  set Name(val) {
    _classPrivateFieldSet(this, _name, val)
  }
}
var _name = new WeakMap()
var obj = new User()
obj.Name = 'test'
console.log('Object.keys():', Object.keys(obj))
console.log('Object.getOwnPropertyNames():', Object.getOwnPropertyNames(obj))
console.log('Object.entries():', Object.entries(obj))
console.log('JSON.stringify():', JSON.stringify(obj))
console.log('console.log:')
console.log(obj)
console.log(obj.Name)
</code>```

this the result of the compiled version on chromium

Body:
var obj = new XMLHttpRequest();
console.log("Object.keys():",Object.keys(obj));
console.log("Object.getOwnPropertyNames():",Object.getOwnPropertyNames(obj))
console.log("Object.entries():",Object.entries(obj))
console.log("JSON.stringify():",JSON.stringify(obj))

console.log("console.log:"); console.log(obj)

output:

Object.keys(): []

  Object.getOwnPropertyNames(): []

  Object.entries(): []

  JSON.stringify(): {}

  console.log:

  XMLHttpRequest {onreadystatechange: null, readyState: 0, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}

How can I create such an object in javascript, whose properties are only printed using console.log(obj), but not returned by any of the above functions?

I have already tried to create objects using constructor function, object.create() (with enumerable:false),  Object.assign(), using getters, instatiating from a class, instatiating from an extended class e.t.c

Body:
I think this is the most practical way .It would help you

class User {
  //this is a private field
  #name
  get Name() {
    return this.#name
  }
  set Name(val) {
    this.#name = val
  }
}

var obj = new User()
obj.Name = 'test'

console.log('Object.keys():', Object.keys(obj))
console.log('Object.getOwnPropertyNames():', Object.getOwnPropertyNames(obj))
console.log('Object.entries():', Object.entries(obj))
console.log('JSON.stringify():', JSON.stringify(obj))

console.log('console.log:')
console.log(obj)
console.log(obj.Name)

this is its compiled code

function _classPrivateFieldSet(receiver, privateMap, value) {
  var descriptor = privateMap.get(receiver)
  if (!descriptor) {
    throw new TypeError('attempted to set private field on non-instance')
  }
  if (descriptor.set) {
    descriptor.set.call(receiver, value)
  } else {
    if (!descriptor.writable) {
      throw new TypeError('attempted to set read only private field')
    }
    descriptor.value = value
  }
  return value
}
function _classPrivateFieldGet(receiver, privateMap) {
  var descriptor = privateMap.get(receiver)
  if (!descriptor) {
    throw new TypeError('attempted to get private field on non-instance')
  }
  if (descriptor.get) {
    return descriptor.get.call(receiver)
  }
  return descriptor.value
} // Try edit message
class User {
  constructor() {
    _name.set(this, { writable: true, value: void 0 })
  }
  get Name() {
    return _classPrivateFieldGet(this, _name)
  }
  set Name(val) {
    _classPrivateFieldSet(this, _name, val)
  }
}
var _name = new WeakMap()
var obj = new User()
obj.Name = 'test'
console.log('Object.keys():', Object.keys(obj))
console.log('Object.getOwnPropertyNames():', Object.getOwnPropertyNames(obj))
console.log('Object.entries():', Object.entries(obj))
console.log('JSON.stringify():', JSON.stringify(obj))
console.log('console.log:')
console.log(obj)
console.log(obj.Name)

this the result of the compiled version on chromium