问:
context.EnsureCreated() throwing exception - already a table named
Creating unit tests with Sqlite InMemory is giving exceptions with and without EnsureCreated().  I'm testing on the MS Northwind database.

If I call ensureCreated() is throws an exception "Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'there is already a table named Region'."

My understanding is that EnsureCreated() will only attempt to create the database if it is not already created.

It looked like it had therefore already created the DB, so I tried removing that call which resulted in an exception later because the tables didn't exist. So, I get exceptions with EnsureCreated() and no tables without it.

I have already checked the context.OnModelCreating and the table 'Region' is only defined once.

Note that this works fine running on an existing SQL database and also allowing EFCore to create a new SQL database. The problem only exists with sqlite in-memory mode.

```<code>public async Task UpdateCategoryWithCorrectEtag(Category expectedCategory)
{
       var connection = new SqliteConnection("DataSource=:memory:");
       connection.Open();
       var builder = new DbContextOptionsBuilder<NorthwindContext>().UseSqlite(connection);
       var context = new NorthwindContext(builder.Options);

       try
       {
           context.Database.EnsureCreated();
           var x = context.Categories.Count();
       }
       finally
       {
           context.Database.EnsureDeleted();
           connection.Close();
       }
}
</code>```

EDIT:
The 'Region' entity defined as follows. I also note that this seems to be the only table where the Entity name already matches the table name.

```<code>modelBuilder.Entity<Region>(entity =>
{
    entity.ToTable("Region");
    entity.HasKey(e => e.RegionId)
        .ForSqlServerIsClustered(false);

    entity.Property(e => e.RegionId)
        .HasColumnName("RegionID")
        .ValueGeneratedNever();

    entity.Property(e => e.RegionDescription)
        .IsRequired()
        .HasMaxLength(50);
});
</code>```

UPDATE:
I already tried removing the line entity.ToTable("Region");  to see if that was causing the table to be created twice, however, this still has the same problem.
Currently I've removed all tables except for the 2 I absolutely need to run the test and it works. Putting them back in one by one to see what breaks. Will report back.

答:
I have the answer after spending more time removing all tables and then adding items until the problem returned.

The problem was caused by indexes on tables being the same as indexes on other tables, or as a table name. With SQL Server and EF Core in-memory, this was OK because it saw them as indexes on the table. But, with Sqlite, it wasn't happy about different objects having the same name, regardless of their apparent scope.

The solution was to ensure that all objects' names were unique so nothing clashed at all. In this case, the name 'Region' was the name of a table and the name of an index on a different table.

Body:
Creating unit tests with Sqlite InMemory is giving exceptions with and without EnsureCreated().  I'm testing on the MS Northwind database.

If I call ensureCreated() is throws an exception "Microsoft.Data.Sqlite.SqliteException : SQLite Error 1: 'there is already a table named Region'."

My understanding is that EnsureCreated() will only attempt to create the database if it is not already created.

It looked like it had therefore already created the DB, so I tried removing that call which resulted in an exception later because the tables didn't exist. So, I get exceptions with EnsureCreated() and no tables without it.

I have already checked the context.OnModelCreating and the table 'Region' is only defined once.

Note that this works fine running on an existing SQL database and also allowing EFCore to create a new SQL database. The problem only exists with sqlite in-memory mode.

public async Task UpdateCategoryWithCorrectEtag(Category expectedCategory)
{
       var connection = new SqliteConnection("DataSource=:memory:");
       connection.Open();
       var builder = new DbContextOptionsBuilder<NorthwindContext>().UseSqlite(connection);
       var context = new NorthwindContext(builder.Options);

       try
       {
           context.Database.EnsureCreated();
           var x = context.Categories.Count();
       }
       finally
       {
           context.Database.EnsureDeleted();
           connection.Close();
       }
}

EDIT:
The 'Region' entity defined as follows. I also note that this seems to be the only table where the Entity name already matches the table name.

modelBuilder.Entity<Region>(entity =>
{
    entity.ToTable("Region");
    entity.HasKey(e => e.RegionId)
        .ForSqlServerIsClustered(false);

    entity.Property(e => e.RegionId)
        .HasColumnName("RegionID")
        .ValueGeneratedNever();

    entity.Property(e => e.RegionDescription)
        .IsRequired()
        .HasMaxLength(50);
});

UPDATE:
I already tried removing the line entity.ToTable("Region");  to see if that was causing the table to be created twice, however, this still has the same problem.
Currently I've removed all tables except for the 2 I absolutely need to run the test and it works. Putting them back in one by one to see what breaks. Will report back.


来源: stackexchange

问:
How to display data read from a file using Electron and React?
My goal is simply to display data (using React) from a file stored locally with my Electron app. I've gotten halfway there in actually reading and processing the data, I just can't figure out how to display it.

Here's what I have for my file read:

```<code>export function read() {
  let values = [];

  fs.readFile(
    path.resolve(__dirname, './files/test.txt'),
    'utf-8',
    (err, data) => {
      if (err) throw err;
      values = data.toString().split('\n');

      const listItems = values.map(val => <p>{val}</p>);
      return listItems;
    }
  );
}
</code>```

This works correctly, and I've console logged all the correct values.

The part that's confusing me is when I want to display it. Here's my react component:

```<code>// @flow
import React, { Component } from 'react';
import styles from './ReadFile.css';
import { read } from '../actions/fileread';

type Props = {};

export default class ReadFile extends Component<Props> {
  props: Props;

  render() {
    const result = read();

    return (
      <div className={styles.container} data-tid="container">
        <p>Read from File</p>
        {result}
      </div>
    );
  }
}
</code>```

What I would expect this to do is call the read function, store it in result and then print the results with {result}. What it does instead is display nothing. It also gives no errors.

I have a feeling this has to do with some odd server/client relationship between the react frontend and the node.js "backend" reading the file. I'm not sure how to create a simple interface between these two components to get them to work.

答:
As mentioned in my comment your code is async and your read() method is not returning anything. You should have something close to this:

```<code>export default class ReadFile extends Component<Props> {
  props: Props;
  constructor(props) {
    super(props);
    this.state = {};
  }
  componentDidMount() {
    read((result) => {
      this.setState({
        result,
      });
    });
  }

  render() {
    return (
      <div className={styles.container} data-tid="container">
        <p>Read from File</p>
        {this.state.result}
      </div>
    );
  }
}
</code>```

And for read() this:

```<code>export function read(callback) {
  let values = [];

  fs.readFile(
    path.resolve(__dirname, './files/test.txt'),
    'utf-8',
    (err, data) => {
      if (err) throw err;
      values = data.toString().split('\n');

      const listItems = values.map(val => <p>{val}</p>);
      return callback(listItems);
    }
  );
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My goal is simply to display data (using React) from a file stored locally with my Electron app. I've gotten halfway there in actually reading and processing the data, I just can't figure out how to display it.

Here's what I have for my file read:

export function read() {
  let values = [];

  fs.readFile(
    path.resolve(__dirname, './files/test.txt'),
    'utf-8',
    (err, data) => {
      if (err) throw err;
      values = data.toString().split('\n');

      const listItems = values.map(val =>
{val}
);
      return listItems;
    }
  );
}

This works correctly, and I've console logged all the correct values.

The part that's confusing me is when I want to display it. Here's my react component:

// @flow
import React, { Component } from 'react';
import styles from './ReadFile.css';
import { read } from '../actions/fileread';

type Props = {};

export default class ReadFile extends Component<Props> {
  props: Props;

  render() {
    const result = read();

    return (

Read from File

        {result}

    );
  }
}

What I would expect this to do is call the read function, store it in result and then print the results with {result}. What it does instead is display nothing. It also gives no errors.

I have a feeling this has to do with some odd server/client relationship between the react frontend and the node.js "backend" reading the file. I'm not sure how to create a simple interface between these two components to get them to work.

Body:
As mentioned in my comment your code is async and your read() method is not returning anything. You should have something close to this:

export default class ReadFile extends Component<Props> {
  props: Props;
  constructor(props) {
    super(props);
    this.state = {};
  }
  componentDidMount() {
    read((result) => {
      this.setState({
        result,
      });
    });
  }

  render() {
    return (
      <div className={styles.container} data-tid="container">
        <p>Read from File</p>
        {this.state.result}
      </div>
    );
  }
}

And for read() this:

export function read(callback) {
  let values = [];

  fs.readFile(
    path.resolve(__dirname, './files/test.txt'),
    'utf-8',
    (err, data) => {
      if (err) throw err;
      values = data.toString().split('\n');

      const listItems = values.map(val => <p>{val}</p>);
      return callback(listItems);
    }
  );
}


问:
How subscribe in an RabbitMQ queue with MQTT Paho
I am trying to connect from my Android app to one queue called "messages".

The producer (one webservices under AMQP protocol) is already connected, it can be check through RabbitMQ admin panel.

To connect from my Android device I am coding like this.

```<code>private void connect() throws Exception {

    this.sampleClient = new MqttClient(this.broker, this.clientId);

    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName("user");
    connOpts.setPassword("user".toCharArray());
    /*connOpts.setConnectionTimeout(60 * 10);
    connOpts.setKeepAliveInterval(60 * 5);*/
    connOpts.setCleanSession(true);

    this.sampleClient.connect(connOpts);

    this.sampleClient.setCallback(this);

    this.sampleClient.subscribe("messages");

    if(!this.sampleClient.isConnected()){

        System.out.println("Not Connected");
        return;
    }

    System.out.println("Connected");
}
</code>```

I have tried with "amq.topic", "amq.topic.*", "amq.topic.messages", etc... But when I look in  the RabbitMQ queue section "messages" is with 0 consumers, and have been set one new queue called "mqtt-subscription-Sampleqos1" automatically.

What's happening? How can I susbscribe to "messages" queue?

答:
First, make sure MQTT plugin is enabled: rabbitmq-plugins enable rabbitmq_mqtt

From the client side (here is you Android app), you need subscriber to a topic, lets say, topic my/android/app/messages

```<code>this.sampleClient.subscribe("my/android/app/messages");
</code>```

Then, from the server side, because of RabbitMQ's implementation, you need send the message to a special exchange 'amq.topic' with appropriate route key my.android.app.messages (notice the mapping between '/' and '.', MQTT use / and AMQP use .). For example if you publish by pika AMQP Python lib, the code will looks like following:

```<code>channel.basic_publish(
    exchange='amq.topic',
    routing_key='my.android.app.messages',
    body='hello world'
)
</code>```

In your case, you want to receive message from queue "messages", basically there is no way to directly subscriber message from that AMQP queue on your MQTT client. The work around is create a service running on your server side, work as AMQP subscriber, receive message from "messages" queue, and transparent forward message to exchange amq.topic with proper routing key.

Hope my answer helpful.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to connect from my Android app to one queue called "messages".

The producer (one webservices under AMQP protocol) is already connected, it can be check through RabbitMQ admin panel.

To connect from my Android device I am coding like this.

private void connect() throws Exception {

    this.sampleClient = new MqttClient(this.broker, this.clientId);

    MqttConnectOptions connOpts = new MqttConnectOptions();
    connOpts.setUserName("user");
    connOpts.setPassword("user".toCharArray());
    /*connOpts.setConnectionTimeout(60 * 10);
    connOpts.setKeepAliveInterval(60 * 5);*/
    connOpts.setCleanSession(true);

    this.sampleClient.connect(connOpts);

    this.sampleClient.setCallback(this);

    this.sampleClient.subscribe("messages");

    if(!this.sampleClient.isConnected()){

        System.out.println("Not Connected");
        return;
    }

    System.out.println("Connected");
}

I have tried with "amq.topic", "amq.topic.*", "amq.topic.messages", etc... But when I look in  the RabbitMQ queue section "messages" is with 0 consumers, and have been set one new queue called "mqtt-subscription-Sampleqos1" automatically.

What's happening? How can I susbscribe to "messages" queue?

Body:
First, make sure MQTT plugin is enabled: rabbitmq-plugins enable rabbitmq_mqtt

From the client side (here is you Android app), you need subscriber to a topic, lets say, topic my/android/app/messages

this.sampleClient.subscribe("my/android/app/messages");

Then, from the server side, because of RabbitMQ's implementation, you need send the message to a special exchange 'amq.topic' with appropriate route key my.android.app.messages (notice the mapping between '/' and '.', MQTT use / and AMQP use .). For example if you publish by pika AMQP Python lib, the code will looks like following:

channel.basic_publish(
    exchange='amq.topic',
    routing_key='my.android.app.messages',
    body='hello world'
)

In your case, you want to receive message from queue "messages", basically there is no way to directly subscriber message from that AMQP queue on your MQTT client. The work around is create a service running on your server side, work as AMQP subscriber, receive message from "messages" queue, and transparent forward message to exchange amq.topic with proper routing key.

Hope my answer helpful.


问:
Angular 2 resolver with loading indicator
I use resolvers to load the data into the components, but until the data is not returned from the server the component does not load.
I would like to know if there is a way to render a load indicator before the server responds.</p>

答:
Another solution I came up with is using Observable<Observable<...>> in your resolvers:

// data-resolver.service.ts

// ...

export class DataResolverService implements Resolve<Observable<Data>> {

// ...

  resolve(route: ActivatedRouteSnapshot): Observable<Observable<Data>> {
    return of(this.client.get(...));
  }
}
```

<p>Notice the usage of <em>rxjs</em>'s <code>of</code> operator to construct an immediately completing <code>Observable</code> from your source <code>Observable</code>. Now you can easily handle your loading indicator in the component:</p>

<pre class="lang-js prettyprint-override"><code>export class DashboardComponent {
  loading = true;
  error = false;

  data$: Observable<Data>;

  constructor(private activatedRoute: ActivatedRoute) {
    this.data$ = this.activatedRoute.data.pipe(switchMap((data) => data.data$));
    this.data$.subscribe(() => this.loading = false, () => this.error = true);
  }
}
</code>```

See my in-depth medium story about this here. This is a real life example coming from my shift scheduling application tift.

Body:
Another solution I came up with is using Observable<Observable<...>> in your resolvers:

// data-resolver.service.ts

// ...

export class DataResolverService implements Resolve<Observable<Data>> {

// ...

  resolve(route: ActivatedRouteSnapshot): Observable<Observable<Data>> {
    return of(this.client.get(...));
  }
}

Notice the usage of rxjs's of operator to construct an immediately completing Observable from your source Observable. Now you can easily handle your loading indicator in the component:

export class DashboardComponent {
  loading = true;
  error = false;

  data$: Observable<Data>;

  constructor(private activatedRoute: ActivatedRoute) {
    this.data$ = this.activatedRoute.data.pipe(switchMap((data) => data.data$));
    this.data$.subscribe(() => this.loading = false, () => this.error = true);
  }
}

See my in-depth medium story about this here. This is a real life example coming from my shift scheduling application tift.


问:
How to make a percentage appear in the other input bar?
I'm trying to add JaveScript to my html input bars, what I want is for when someone enters a certain amount of money in one an equivalent amount of percentage will automatically appear in the other. For instants: typing 6000 in one box will cause the other to show 6%.

const btnOne = document.querySelector('.btn1');

const btnTwo = document.querySelector('.btn2');

```<code>object.addEventListener("click", myScript);

function myScript(e) {
    e.preventDefault();
    if(btnOne.nodeValue === '6000') {
    btnTwo.innerHTML = '<h1>6%</h1>';
    }
}

  <!--goal window-->  <!--html-->
    <div class="goal-window">
<div class="goal-window-container">
    <div class="goal-status-and-text">
    <h2 class="goal-text">goal <br> 6,000 = 6%</h2></div>
    <h4><a><br>pledged of 14,000.00 = 14%</a></h4>
    <div class="pledge"><h2>pledge the amount relitive
     to the percentage<br>you would like to purchase.</h2></div>
        <form action="/action_page.php">
      <div class="pay-section">
      <input class="btn1" type="text" placeholder="$" name="lname">
      <h2 class="equal-sign">=</h2>
      <input class="btn2" type="text" placeholder="%" name="lname"><br>
      </div>
 <button class="invest-button">invest</button>
</form>
</div>
    </div>

    <hr />
    </div>
  </div>
</div>

/* ### goal window ### */ /*###CSS###*/

.goal-window {
    width: 96%;
    height: 40rem;
    border-radius: 40px;
    margin-top: 2rem;
    background-color: rgb(255, 255, 255);
    box-shadow: 5px 10px #888888;
    border: 4px solid rgb(187, 183, 183);
    display: flex;
    align-items: center;
    flex-direction: column;
}

.goal-window-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 2.5rem;
}

.goal-text {
    font-size: 4rem;
    text-align: center;
}

.goal-status-and-text {
   display: flex;
   height: 4rem;
   align-items: center;
   margin-top: 2rem;
}

.goal-number {
    height: 4rem;
    border: 4px solid rgb(187, 183, 183);
}

.pledge {
    text-align: center;
}

input {
    border: 4px solid black;
    height: 2rem;
}

.equal-sign {
    padding: 0 8px;
}

.pay-section {
    display: flex;
    align-items: center;
}
/* ### invest botton ### */

.invest-button {
    width: 100%;
    height: 10rem;
    border-radius: 30px;
    font-size: 6rem;
    margin-top: 4rem;
}

hr {
    width: 100%;
    background-color: black;
    border: 2px solid black;
    margin-top: 6rem;
}
</code>```

答:
You're literally just hardcoding a specific value into the view. What you need to do is get what the user typed in, convert it to its percent value, and update the view with the new percent. Here is an example

document.getElementById('num-input').addEventListener('input', function(e) {
 let val = e.target.value;
 let percent = parseFloat(val / 1000);
 document.getElementById('percent').value = percent;
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input id="num-input" type="number" placeholder="enter a number">
<input id="percent" disabled>
<span>%</span></code>```

Body:
I'm trying to add JaveScript to my html input bars, what I want is for when someone enters a certain amount of money in one an equivalent amount of percentage will automatically appear in the other. For instants: typing 6000 in one box will cause the other to show 6%.

const btnOne = document.querySelector('.btn1');

const btnTwo = document.querySelector('.btn2');

object.addEventListener("click", myScript);

function myScript(e) {
    e.preventDefault();
    if(btnOne.nodeValue === '6000') {
    btnTwo.innerHTML = '
6%
';
    }
}

goal
 6,000 = 6%

pledged of 14,000.00 = 14%

pledge the amount relitive
     to the percentage
you would like to purchase.

        <form action="/action_page.php">

      <input class="btn1" type="text" placeholder="$" name="lname">

=

      <input class="btn2" type="text" placeholder="%" name="lname">

 <button class="invest-button">invest</button>
</form>

/* ### goal window ### */ /*###CSS###*/

.goal-window {
    width: 96%;
    height: 40rem;
    border-radius: 40px;
    margin-top: 2rem;
    background-color: rgb(255, 255, 255);
    box-shadow: 5px 10px #888888;
    border: 4px solid rgb(187, 183, 183);
    display: flex;
    align-items: center;
    flex-direction: column;
}

.goal-window-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 2.5rem;
}

.goal-text {
    font-size: 4rem;
    text-align: center;
}

.goal-status-and-text {
   display: flex;
   height: 4rem;
   align-items: center;
   margin-top: 2rem;
}

.goal-number {
    height: 4rem;
    border: 4px solid rgb(187, 183, 183);
}

.pledge {
    text-align: center;
}

input {
    border: 4px solid black;
    height: 2rem;
}

.equal-sign {
    padding: 0 8px;
}

.pay-section {
    display: flex;
    align-items: center;
}
/* ### invest botton ### */

.invest-button {
    width: 100%;
    height: 10rem;
    border-radius: 30px;
    font-size: 6rem;
    margin-top: 4rem;
}

hr {
    width: 100%;
    background-color: black;
    border: 2px solid black;
    margin-top: 6rem;
}

Body:
You're literally just hardcoding a specific value into the view. What you need to do is get what the user typed in, convert it to its percent value, and update the view with the new percent. Here is an example

document.getElementById('num-input').addEventListener('input', function(e) {
 let val = e.target.value;
 let percent = parseFloat(val / 1000);
 document.getElementById('percent').value = percent;
})

<input id="num-input" type="number" placeholder="enter a number">
<input id="percent" disabled>
<span>%</span>


问:
Ho to use FunctionScoreQuery with text fields?
In Lucene 6.6.0, index-time boosting is deprecated. Moreover, also CustomQueryScore is deprecated. So, Lucene developers advice is to use FunctionScoreQuery. However, I can't understand how to boost text field with FunctionScoreQuery, since it takes as input DoubleValuesSource, which helps to boost just numerical fields (fromIntField, fromDoubleField etc...)</p>

答:
It might be too late, but check the discussions here: http://lucene.472066.n3.nabble.com/any-example-on-FunctionScoreQuery-since-Field-setBoost-is-deprecated-with-Lucene-6-6-0-td4400355.html, and some copy and paste of how to use the FunctionScoreQuery class:

Example that sorts based on an expression:

```<code>// compile an expression:
Expression expr = JavascriptCompiler.compile("sqrt(_score) + ln(popularity)");

// SimpleBindings just maps variables to SortField instances
SimpleBindings bindings = new SimpleBindings();
bindings.add(new SortField("_score", SortField.Type.SCORE));
bindings.add(new SortField("popularity", SortField.Type.INT));

// create a sort field and sort by it (reverse order)
Sort sort = new Sort(expr.getSortField(bindings, true));
Query query = new TermQuery(new Term("body", "contents"));
searcher.search(query, 10, sort);
</code>```

Example that modifies the scores produced by the query:

```<code>// compile an expression:
Expression expr = JavascriptCompiler.compile("sqrt(_score) + ln(popularity)");

// SimpleBindings just maps variables to SortField instances
SimpleBindings bindings = new SimpleBindings();
bindings.add(new SortField("_score", SortField.Type.SCORE));
bindings.add(new SortField("popularity", SortField.Type.INT));

// create a query that matches based on body:contents but
// scores using expr
Query query = new FunctionScoreQuery(
    new TermQuery(new Term("body", "contents")),
    expr.getDoubleValuesSource(bindings));
searcher.search(query, 10);
</code>```

The Lucene Expression class accepts Javascript expressions:
(https://lucene.apache.org/core/7_7_2/expressions/org/apache/lucene/expressions/js/package-summary.html)

"A Javascript expression is a numeric expression specified using an expression syntax that's based on JavaScript expressions. You can construct expressions using:

Integer, floating point, hex and octal literals

Arithmetic operators: + - * / %

Bitwise operators: | & ^ ~ << >> >>>

Boolean operators (including the ternary operator): && || ! ?:

Comparison operators: < <= == >= >

Common mathematic functions: abs ceil exp floor ln log10 logn max min sqrt pow

Trigonometric library functions: acosh acos asinh asin atanh atan atan2 cosh cos sinh sin tanh tan

Distance functions: haversin

Miscellaneous functions: min, max

Arbitrary external variables" - see the above Bindings examples

Body:
It might be too late, but check the discussions here: http://lucene.472066.n3.nabble.com/any-example-on-FunctionScoreQuery-since-Field-setBoost-is-deprecated-with-Lucene-6-6-0-td4400355.html, and some copy and paste of how to use the FunctionScoreQuery class:

Example that sorts based on an expression:

// compile an expression:
Expression expr = JavascriptCompiler.compile("sqrt(_score) + ln(popularity)");

// SimpleBindings just maps variables to SortField instances
SimpleBindings bindings = new SimpleBindings();
bindings.add(new SortField("_score", SortField.Type.SCORE));
bindings.add(new SortField("popularity", SortField.Type.INT));

// create a sort field and sort by it (reverse order)
Sort sort = new Sort(expr.getSortField(bindings, true));
Query query = new TermQuery(new Term("body", "contents"));
searcher.search(query, 10, sort);

Example that modifies the scores produced by the query:

// compile an expression:
Expression expr = JavascriptCompiler.compile("sqrt(_score) + ln(popularity)");

// SimpleBindings just maps variables to SortField instances
SimpleBindings bindings = new SimpleBindings();
bindings.add(new SortField("_score", SortField.Type.SCORE));
bindings.add(new SortField("popularity", SortField.Type.INT));

// create a query that matches based on body:contents but
// scores using expr
Query query = new FunctionScoreQuery(
    new TermQuery(new Term("body", "contents")),
    expr.getDoubleValuesSource(bindings));
searcher.search(query, 10);

The Lucene Expression class accepts Javascript expressions:
(https://lucene.apache.org/core/7_7_2/expressions/org/apache/lucene/expressions/js/package-summary.html)

"A Javascript expression is a numeric expression specified using an expression syntax that's based on JavaScript expressions. You can construct expressions using:

Integer, floating point, hex and octal literals

Arithmetic operators: + - * / %

Bitwise operators: | & ^ ~ << >> >>>

Boolean operators (including the ternary operator): && || ! ?:

Comparison operators: < <= == >= >

Common mathematic functions: abs ceil exp floor ln log10 logn max min sqrt pow

Trigonometric library functions: acosh acos asinh asin atanh atan atan2 cosh cos sinh sin tanh tan

Distance functions: haversin

Miscellaneous functions: min, max

Arbitrary external variables" - see the above Bindings examples


问:
Size-limited queue that holds last N elements in Java
A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

Of course, it's trivial to implement it manually:

```<code>import java.util.LinkedList;

public class LimitedQueue<E> extends LinkedList<E> {
    private int limit;

    public LimitedQueue(int limit) {
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        super.add(o);
        while (size() > limit) { super.remove(); }
        return true;
    }
}
</code>```

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?

答:
Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

```<code>    import java.util.Queue;
    import org.apache.commons.collections4.queue.CircularFifoQueue;

    Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
    fifo.add(1);
    fifo.add(2);
    fifo.add(3);
    System.out.println(fifo);

    // Observe the result:
    // [2, 3]
</code>```

If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.

Update: updated answer following release of commons collections version 4 that supports generics.

Body:
A very simple & quick question on Java libraries: is there a ready-made class that implements a Queue with a fixed maximum size - i.e. it always allows addition of elements, but it will silently remove head elements to accomodate space for newly added elements.

Of course, it's trivial to implement it manually:

import java.util.LinkedList;

public class LimitedQueue<E> extends LinkedList<E> {
    private int limit;

    public LimitedQueue(int limit) {
        this.limit = limit;
    }

    @Override
    public boolean add(E o) {
        super.add(o);
        while (size() > limit) { super.remove(); }
        return true;
    }
}

As far as I see, there's no standard implementation in Java stdlibs, but may be there's one in Apache Commons or something like that?

Body:
Apache commons collections 4 has a CircularFifoQueue<> which is what you are looking for. Quoting the javadoc:

CircularFifoQueue is a first-in first-out queue with a fixed size that replaces its oldest element if full.

    import java.util.Queue;
    import org.apache.commons.collections4.queue.CircularFifoQueue;

    Queue<Integer> fifo = new CircularFifoQueue<Integer>(2);
    fifo.add(1);
    fifo.add(2);
    fifo.add(3);
    System.out.println(fifo);

    // Observe the result:
    // [2, 3]

If you are using an older version of the Apache commons collections (3.x), you can use the CircularFifoBuffer which is basically the same thing without generics.

Update: updated answer following release of commons collections version 4 that supports generics.


问:
PHP: How to sort the characters in a string?
I have a set of strings containing characters in a PHP script, I need to sort those characters in each string.

For example:

```<code>"bac" -> "abc"
"abc" -> "abc"
"" -> ""
"poeh" -> "ehop"
</code>```

These characters don't have accents and are all lower case. How can I perform this in PHP?

答:
Keep in mind that str_split() does not support multibyte strings. In case you have to deal with e.g. UTF-8 strings, preg_split() should be used instead:</p>
```<code>$string = 'bac';
$stringParts = preg_split('//u', $string);
sort($stringParts);
echo implode($stringParts); // abc
</code>```

Body:
I have a set of strings containing characters in a PHP script, I need to sort those characters in each string.

For example:

"bac" -> "abc"
"abc" -> "abc"
"" -> ""
"poeh" -> "ehop"

These characters don't have accents and are all lower case. How can I perform this in PHP?

Body:
Keep in mind that str_split() does not support multibyte strings. In case you have to deal with e.g. UTF-8 strings, preg_split() should be used instead:

$string = 'bac';
$stringParts = preg_split('//u', $string);
sort($stringParts);
echo implode($stringParts); // abc


问:
How to represent a checkbox with data from two different arrays?
I am trying to render some check boxes with data from two arrays which are the id and name in one array and the count/length in the other array. Ex:

```<code>const count = [[{"1":"91"}],[{"1":"1"}],[{"1":"0"}]]
const type = [{id: "1", name: "iPhone"}, {id: "2",name: "Samsung"}, {id: "3",name: "Huawei"}]
</code>```

I tried to use a map function inside another map function.

```<code>var text=type.map(function(itm,i){
   return [<label key={itm.id}><input type="checkbox" key={itm.id} value={itm.id} name="search"/>{itm.name}</label>, (count && count.length > 0 && count.map( item =>
                      item.length > 0 && item.map( el =>
                          Object.keys(el).length > 0 &&
                          Object.keys(el).map(val => <p>{el[val]}</p>)
                      )
                  )[i])];
}).join(' ');
</code>```

this is how should be represented. [] is the checkbox.

```<code>[] Iphone (91)
[] samsung (1)
[] huawei (0)
</code>```

the link of the example https://stackblitz.com/edit/react-6naael

答:
You can loop through the count array and add a new property to type array which holds the total, number of item in count array base on id.

```

Body:
I am trying to render some check boxes with data from two arrays which are the id and name in one array and the count/length in the other array. Ex:

const count = [[{"1":"91"}],[{"1":"1"}],[{"1":"0"}]]
const type = [{id: "1", name: "iPhone"}, {id: "2",name: "Samsung"}, {id: "3",name: "Huawei"}]

I tried to use a map function inside another map function.

var text=type.map(function(itm,i){
   return [<input type="checkbox" key={itm.id} value={itm.id} name="search"/>{itm.name}, (count && count.length > 0 && count.map( item =>
                      item.length > 0 && item.map( el =>
                          Object.keys(el).length > 0 &&
                          Object.keys(el).map(val =>
{el[val]}
)
                      )
                  )[i])];
}).join(' ');

this is how should be represented. [] is the checkbox.

[] Iphone (91)
[] samsung (1)
[] huawei (0)

the link of the example https://stackblitz.com/edit/react-6naael

Body:
You can loop through the count array and add a new property to type array which holds the total, number of item in count array base on id.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">
const count = [[{ "1": "91" }], [{ "1": "1" }], [{ "1": "0" }]]
let type = [{ id: "1", name: "iPhone" }, { id: "2", name: "Samsung" }, { id: "3", name: "Huawei" }]

for (let i = 0; i < count.length; i++) {
  Object.keys(count[i][0]).forEach(key => {
    const index = type.findIndex(x => x.id === key);

    const total = parseInt(count[i][0][key], 10);

    type[index].total ? type[index].total += total : type[index].total = total;
  })
}

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  render() {

    const check = type.map(item => {
      return (
        <div>
        <input type="checkbox" id="check3"/> {`${item.name} (${item.total ? item.total : 0})`}
        </div>
      )
    })
    return (
      <div>
        {check}
      </div>
    );
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
</script>


问:
Can (endless) CSS keyframe animations be stopped at certain time point or a defined keyframe?
I am trying to find out if CSS today offers enough tools to have animations run until an event tells them to stop?

Yes this is possible see snippet, however:

This animation will jump to the end if stopped in between. I was wondering if it can be stopped at any certain point of the computed keyframes. So basically like a wheel of fortune keep spinning the DIV until it's stopped and when stopped while upside down remain upside down until maybe restarted?

snippet:

#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: 0;
  animation-timing-function: linear;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id='wrap'>
  <div id='left-eye'>

  </div>
  <div id='right-eye'>

  </div>
  <div id='mouth'>

  </div>
</div>
<input type='button' value='start' onClick="document.getElementById('wrap').style.animationIterationCount = 'infinite';">
<input type='button' value='stop' onClick="document.getElementById('wrap').style.animationIterationCount = '0';"></code>```

答:
You can pause and resume CSS animations using animation-play-state and toggling a class:

CSS:

```<code>.paused {
  animation-play-state: paused;
  -webkit-animation-play-state: paused;
}
</code>```

Snippet:

function pause() {
    wrap.classList.add("paused");
}

function play() {
    wrap.classList.remove("paused");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.paused {
  animation-play-state: paused;
  -webkit-animation-play-state: paused;
}

#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}</code>```

<input type = "button" value = "start" onClick = "play()">
<input type = "button" value = "stop" onClick = "pause()">```

Body:
I am trying to find out if CSS today offers enough tools to have animations run until an event tells them to stop?

Yes this is possible see snippet, however:

This animation will jump to the end if stopped in between. I was wondering if it can be stopped at any certain point of the computed keyframes. So basically like a wheel of fortune keep spinning the DIV until it's stopped and when stopped while upside down remain upside down until maybe restarted?

snippet:

#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: 0;
  animation-timing-function: linear;
}

<input type='button' value='start' onClick="document.getElementById('wrap').style.animationIterationCount = 'infinite';">
<input type='button' value='stop' onClick="document.getElementById('wrap').style.animationIterationCount = '0';">

Body:
You can pause and resume CSS animations using animation-play-state and toggling a class:

CSS:

.paused {
  animation-play-state: paused;
  -webkit-animation-play-state: paused;
}

Snippet:

function pause() {
    wrap.classList.add("paused");
}

function play() {
    wrap.classList.remove("paused");
}

.paused {
  animation-play-state: paused;
  -webkit-animation-play-state: paused;
}

#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}

<div id = "wrap" class = "paused">
  <div id = "left-eye">&nbsp;</div>
  <div id = "right-eye">&nbsp;</div>
  <div id = "mouth">&nbsp;</div>
</div>
<input type = "button" value = "start" onClick = "play()">
<input type = "button" value = "stop" onClick = "pause()">


答:
You may want to consider adjusting the animation play state rather than the iteration count. This will allow you to stop the animation at your desired point, but not reset it to the beginning.

function play() {
  let target = document.getElementById('wrap')
  target.style.animationPlayState = 'running'
  let styles = getComputedStyle(target)
  console.log(styles.getPropertyValue('animation-play-state'))
}

function pause() {
  let target = document.getElementById('wrap')
  target.style.animationPlayState = 'paused'
  let styles = getComputedStyle(target)
  console.log(styles.getPropertyValue('animation-play-state'))
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: 0;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  animation-play-state: paused;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}</code>```

<input type='button' value='start' onClick="play()">
<input type='button' value='stop' onClick="pause()">```

Edit:

If you want to access information regarding a component's computed styles, you can use the getComputedStyle function. This will provide information within Javascript about all of an element's computed styles. The returned value from getComputedStyle can be used with the getPropertyValue function to provide information regarding a specific property.

Title: Can (endless) CSS keyframe animations be stopped at certain time point or a defined keyframe?

Body:
You may want to consider adjusting the animation play state rather than the iteration count. This will allow you to stop the animation at your desired point, but not reset it to the beginning.

function play() {
  let target = document.getElementById('wrap')
  target.style.animationPlayState = 'running'
  let styles = getComputedStyle(target)
  console.log(styles.getPropertyValue('animation-play-state'))
}

function pause() {
  let target = document.getElementById('wrap')
  target.style.animationPlayState = 'paused'
  let styles = getComputedStyle(target)
  console.log(styles.getPropertyValue('animation-play-state'))
}

#wrap {
  background-color: yellow;
  position: relative;
  top: 0px;
  width: 100px;
  height: 100px;
  border-radius: 50px;
  box-sizing: border-box;
  transition: 700ms linear;
  animation-iteration-count: infinite;
}

#wrap:hover {
  background-color: orange;
}

#mouth {
  background-color: transparent;
  position: absolute;
  border-left: 4px solid black;
  border-right: 4px solid black;
  border-bottom: 4px solid black;
  border-radius: 0 0 60px 60px;
  height: 30px;
  width: 60px;
  top: 52px;
  left: 20px;
  box-sizing: border-box;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#left-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  left: 30px;
  top: 25px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#right-eye {
  position: absolute;
  background-color: black;
  border-radius: 50%;
  width: 8px;
  height: 16px;
  box-sizing: border-box;
  top: 25px;
  right: 30px;
  display: inline-block;
  overflow: hidden;
  padding: 0;
}

#wrap {
  animation-duration: 1200ms;
  animation-name: rotateDiv;
  animation-iteration-count: 0;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  animation-play-state: paused;
}

@keyframes rotateDiv {
  from {
  -ms-transform: rotate(0deg); /* IE 9 */
  -webkit-transform: rotate(0deg); /* Safari */
  transform: rotate(0deg);
  }

  to {
  -ms-transform: rotate(360deg); /* IE 9 */
  -webkit-transform: rotate(360deg); /* Safari */
  transform: rotate(360deg);
  }
}

<div id='wrap'>
  <div id='left-eye'>
    &nbsp;
  </div>
  <div id='right-eye'>
    &nbsp;
  </div>
  <div id='mouth'>
    &nbsp;
  </div>
</div>
<input type='button' value='start' onClick="play()">
<input type='button' value='stop' onClick="pause()">

Edit:

If you want to access information regarding a component's computed styles, you can use the getComputedStyle function. This will provide information within Javascript about all of an element's computed styles. The returned value from getComputedStyle can be used with the getPropertyValue function to provide information regarding a specific property.


问:
Git strategy for when you need to work on several features at a time
Let's say I am working on a few front-end features concurrently that all are in different branches (e.g. login branch, reset password branch, update settings branch, etc.). In our current workflow, it's up to me in which order or manner I finish all these features as long as I do them within the set deadline (e.g. 2 weeks time).

To pace myself better, I'd create a branch for each of these features and work on them concurrently, integrating the functionalities first (the hard parts so to speak) and work on the styles and nitty-gritty details towards the end. (Analogy would be like building a house; you don't really complete each part of the house one by one. You build all the foundation first, scaffolding and all, before you do all the decorative stuff towards the end.)

Now this is fine if all of these features are totally isolated from one another. However, there are functionalities or even general styles that I've done on e.g. login branch that I can actually use in reset password branch. (Example, both are forms hence should have the same general form styling and will make use of the same validation functions).

However, since all of them are WIP all at once, I cannot do a PR for login before I continue working on reset pw (e.g. login is at 90% and reset pw at 80% but I need something from login to get reset pw to 90% completion also). Even if I complete login, PR reviews may take time.

I also cannot also e.g. merge/rebase to login from reset pw because 1. that would mix the 2 different features and 2. login feature is not even approved yet.

What is the best strategy for this kind of scenario? I am in a dilemma because the best way to actually avoid this is to finish one feature after another. But at the same time, I work better if I do it in the manner I just mentioned (in parallel).

答:
This is opinion based but I would work on all these three features on a single branch. e.g. I should be able to login. That doesn't require reset pw. Once the login feature is done, I push that for code review or whatever. After that, I add the password reset functionality as a different set of commits and send that for review.

The general point is that if the features are coupled, the split is artificial and it's better to treat them as a single branch. If the features are coupled, it's usually still possible to sort them in order of dependency and implement them in order.


问:
How to fix CONSTRAINTS stopping me from copying table schema?
I have a table that consists of rows to make case barcodes.  I need EXACTLY the same schema now for pallet barcodes.  However, trying to just SHOW CREATE of the caselabels table, changing the name and a few column names, does not work.

Here is the CREATE script -

```<code>SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[caselabels](
    [idx] [int] IDENTITY(42,1) NOT NULL,
    [imageFile] [nvarchar](50) NULL,
    [jobId] [nvarchar](50) NULL CONSTRAINT [DF__caselabel__workO__47DBAE45]  DEFAULT (NULL),
    [triggerStatus] [nvarchar](5) NULL CONSTRAINT [DF__caselabel__trigg__48CFD27E]  DEFAULT (NULL),
    [workOrder] [nvarchar](30) NULL,
    [t_stamp] [datetime2](0) NULL CONSTRAINT [DF__caselabel__t_sta__49C3F6B7]  DEFAULT (getdate()),
    [lotCode] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__lotCo__4AB81AF0]  DEFAULT (NULL),
    [expDate] [nvarchar](20) NULL CONSTRAINT [DF__caselabel__expDa__4BAC3F29]  DEFAULT (NULL),
    [qty] [int] NULL CONSTRAINT [DF__caselabels__qty__4CA06362]  DEFAULT (NULL),
    [gtinUL] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__gtinU__4D94879B]  DEFAULT (NULL),
    [gtinUC] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__gtinU__4E88ABD4]  DEFAULT (NULL),
    [prodNumber] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodN__4F7CD00D]  DEFAULT (NULL),
    [prodDesc] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodD__5070F446]  DEFAULT (NULL),
    [prodBrand] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodB__5165187F]  DEFAULT (NULL),
    [prodSKU] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodS__52593CB8]  DEFAULT (NULL),
    [prodSize] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodS__5441852A]  DEFAULT (NULL),
    [dataMatrix] [nvarchar](50) NULL,
    [startingADCaseCount] [int] NULL,
    [address] [nvarchar](50) NULL,
 CONSTRAINT [PK_palletlabels_idx] PRIMARY KEY CLUSTERED
(
    [idx] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
</code>```

I am just trying to change the name of the table to palletlabels, and the column startingADCaseCount to startingADPalletCount.  Note I already changed the CONSTRAINT[PL_caselabels_idx] PRIMARY KEY CLUSTERED to CONSTRAINT [PK_palletlabels_idx] PRIMARY KEY CLUSTERED

However, I still get these errors -

```<code>Msg 2714, Level 16, State 5, Line 11
There is already an object named 'DF__caselabel__workO__47DBAE45' in the database.
Msg 1750, Level 16, State 0, Line 11
Could not create constraint or index. See previous errors.
Msg 15233, Level 16, State 1, Procedure sp_addextendedproperty, Line 74
Property cannot be added. Property 'MS_SSMA_SOURCE' already exists for 'dbo.caselabels'.
</code>```

I look at the first constraint [DF_caselabel_workO-47DBAE45] under caselabels and I see this

```<code>USE [AntiDiversion]
GO

ALTER TABLE [dbo].[caselabels] ADD  CONSTRAINT [DF__caselabel__workO__47DBAE45]  DEFAULT (NULL) FOR [jobId]
GO
</code>```

which seems to just be the same as the DEFAULT (NULL) in the table creation already.  Every rows constraint is like this.  Is it ok to just get rid of the CONSTRAINT [DF_caselabel_....] sections?

Given the second error is based on the first, I think solving this constraint issue will solve the second error message as well, but what of the third?  I am clueless on that.

Using SQL SERVER 2014.

答:
Based on your table definition, you should be okay removing the explicit names and just have FieldName Null, FieldName2 Not Null.

I typically don't name my Null / Not Null constraints.

Body:
I have a table that consists of rows to make case barcodes.  I need EXACTLY the same schema now for pallet barcodes.  However, trying to just SHOW CREATE of the caselabels table, changing the name and a few column names, does not work.

Here is the CREATE script -

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[caselabels](
    [idx] [int] IDENTITY(42,1) NOT NULL,
    [imageFile] [nvarchar](50) NULL,
    [jobId] [nvarchar](50) NULL CONSTRAINT [DF__caselabel__workO__47DBAE45]  DEFAULT (NULL),
    [triggerStatus] [nvarchar](5) NULL CONSTRAINT [DF__caselabel__trigg__48CFD27E]  DEFAULT (NULL),
    [workOrder] [nvarchar](30) NULL,
    [t_stamp] [datetime2](0) NULL CONSTRAINT [DF__caselabel__t_sta__49C3F6B7]  DEFAULT (getdate()),
    [lotCode] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__lotCo__4AB81AF0]  DEFAULT (NULL),
    [expDate] [nvarchar](20) NULL CONSTRAINT [DF__caselabel__expDa__4BAC3F29]  DEFAULT (NULL),
    [qty] [int] NULL CONSTRAINT [DF__caselabels__qty__4CA06362]  DEFAULT (NULL),
    [gtinUL] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__gtinU__4D94879B]  DEFAULT (NULL),
    [gtinUC] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__gtinU__4E88ABD4]  DEFAULT (NULL),
    [prodNumber] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodN__4F7CD00D]  DEFAULT (NULL),
    [prodDesc] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodD__5070F446]  DEFAULT (NULL),
    [prodBrand] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodB__5165187F]  DEFAULT (NULL),
    [prodSKU] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodS__52593CB8]  DEFAULT (NULL),
    [prodSize] [nvarchar](45) NULL CONSTRAINT [DF__caselabel__prodS__5441852A]  DEFAULT (NULL),
    [dataMatrix] [nvarchar](50) NULL,
    [startingADCaseCount] [int] NULL,
    [address] [nvarchar](50) NULL,
 CONSTRAINT [PK_palletlabels_idx] PRIMARY KEY CLUSTERED
(
    [idx] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

I am just trying to change the name of the table to palletlabels, and the column startingADCaseCount to startingADPalletCount.  Note I already changed the CONSTRAINT[PL_caselabels_idx] PRIMARY KEY CLUSTERED to CONSTRAINT [PK_palletlabels_idx] PRIMARY KEY CLUSTERED

However, I still get these errors -

Msg 2714, Level 16, State 5, Line 11
There is already an object named 'DF__caselabel__workO__47DBAE45' in the database.
Msg 1750, Level 16, State 0, Line 11
Could not create constraint or index. See previous errors.
Msg 15233, Level 16, State 1, Procedure sp_addextendedproperty, Line 74
Property cannot be added. Property 'MS_SSMA_SOURCE' already exists for 'dbo.caselabels'.

I look at the first constraint [DF_caselabel_workO-47DBAE45] under caselabels and I see this

USE [AntiDiversion]
GO

ALTER TABLE [dbo].[caselabels] ADD  CONSTRAINT [DF__caselabel__workO__47DBAE45]  DEFAULT (NULL) FOR [jobId]
GO

which seems to just be the same as the DEFAULT (NULL) in the table creation already.  Every rows constraint is like this.  Is it ok to just get rid of the CONSTRAINT [DF_caselabel_....] sections?

Given the second error is based on the first, I think solving this constraint issue will solve the second error message as well, but what of the third?  I am clueless on that.

Using SQL SERVER 2014.


问:
4 simple toggle switches! What am I doing wrong?
I got this code from a youtube video but, it doesn't work. So, I put it into jsfiddle and fixed everything it said was wrong but, EEERRRRRR.... it still doesn't work. There should be four sliding on/off switches. Yet I only have this one giant blob that doesn't do anything but, sit there and laugh at me. Any help out there?

http://jsfiddle.net/p2bxkyv8/

```<code>    <html>
    <head>
     <title>Toggle Switch</title>
     <link href="style.css" rel="stylesheet" type="text/css">
    </head>

    <body>
    <div class="container">
     <h1>Toggle Switch</h1>
     <lable class="switch">
     <input type="checkbox">
     <span class="slider"></span>
     </lable>

     <lable class="switch">
     <input type="checkbox" checked>
     <span class="slider"></span>
     </lable>

     <lable class="switch">
     <input type="checkbox">
     <span class="slider"></span>
     </lable>

     <lable class="switch">
     <input type="checkbox" checked>
     <span class="slider"></span>
     </lable>
    </div>
    </body>
    </html>
</code>```

css

```<code>  * {
    margin: 0;
    padding: 0;
    }

  .container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    }

  h1 {
    margin-bottom: 40px;
    font-family: sans-serif;
    }

  .switch {
    position: relitive;
    display: inline-block;
    width: 110px;
    height: 60px;
    margin: 0 10px;
    }

  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.4s;
    border-radius: 34px;
    }

  .switch input { display: none; }

  .slider::before {
    position: absolute;
    content: "";
    height: 50px;
    width: 50px;
    left: 5px;
    bottom: 5px;
    background-color: white;
    transition: 0.4s;
    border-radius: 50px;
    }

  input:checked + .slider {
    background-color: #ff278c;
    }

  input:checked + .slider::before {
    transform: translateX(50px);
    }
</code>```

答:
you have a typo, position: relitive; is wrong:

```<code>.switch {
  position: relative;
  display: inline-block;
  width: 110px;
  height: 60px;
  margin: 0 10px;
  }
</code>```

and lable should be label

Body:
I got this code from a youtube video but, it doesn't work. So, I put it into jsfiddle and fixed everything it said was wrong but, EEERRRRRR.... it still doesn't work. There should be four sliding on/off switches. Yet I only have this one giant blob that doesn't do anything but, sit there and laugh at me. Any help out there?

http://jsfiddle.net/p2bxkyv8/

     <title>Toggle Switch</title>
     <link href="style.css" rel="stylesheet" type="text/css">

Toggle Switch

     <lable class="switch">
     <input type="checkbox">

     </lable>

     <lable class="switch">
     <input type="checkbox" checked>

     </lable>

     <lable class="switch">
     <input type="checkbox">

     </lable>

     <lable class="switch">
     <input type="checkbox" checked>

     </lable>

css

  * {
    margin: 0;
    padding: 0;
    }

  .container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    text-align: center;
    }

  h1 {
    margin-bottom: 40px;
    font-family: sans-serif;
    }

  .switch {
    position: relitive;
    display: inline-block;
    width: 110px;
    height: 60px;
    margin: 0 10px;
    }

  .slider {
    position: absolute;
    cursor: pointer;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #ccc;
    transition: 0.4s;
    border-radius: 34px;
    }

  .switch input { display: none; }

  .slider::before {
    position: absolute;
    content: "";
    height: 50px;
    width: 50px;
    left: 5px;
    bottom: 5px;
    background-color: white;
    transition: 0.4s;
    border-radius: 50px;
    }

  input:checked + .slider {
    background-color: #ff278c;
    }

  input:checked + .slider::before {
    transform: translateX(50px);
    }

Body:
you have a typo, position: relitive; is wrong:

.switch {
  position: relative;
  display: inline-block;
  width: 110px;
  height: 60px;
  margin: 0 10px;
  }

and lable should be label


问:
If Statement for Error Checking is not working
I need to do some error checking so a user knows they have missed some information before sending the form.

I have a table which is controlled by a Data Validation list dropdown box. This box has numbers 1 to 15, and will show/hide rows associated to the number selected i.e. 3 selected, so rows 1 to 3 are displayed, 4 to 15 or hidden. What the error checking code is supposed to do is, check the list number selected, then check a cell in each row to see if it is empty or not, if empty display the error message, if not then do nothing. I need this error message to display for each row which is displayed and not for the hidden rows. I have a cell at the top of the page with tells the user how many errors they have, so I don't want the hidden rows adding to this count. I can get it working for numbers zero and 1, but for 2 to 15 it is not working. Code below only shows numbers 0 to 3, I can alter the code for the other rows once working.

Correct outcome when nbr 3 is selected
D63 is empty so error msg in A63, D64:65 not empty so no error msg

Actual outcome when Nbr 3 is selected
D63:65 are empty so A63:65 should display the error msg

```<code>Sub Check_SRU_Table()

    ' SRU 0 ** WORKING **
    If Range("SRUAdd").Value = "0" Then
        Range("Sig_1").Value = "Signature Release 1"
        Range("Sig_2").Value = "Signature Release 2"
        Range("Sig_3").Value = "Signature Release 3"
    ' 4 TO 15 OMITTED
    End If

    ' SRU 1 ** WORKING **
    If Range("SRUAdd").Value = "1" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
        End If
    End If

    ' SRU 2 ** NOT WORKING **
    If Range("SRUAdd").Value = "2" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
        End If
    End If

    ' SRU 3 ** NOT WORKING **
    If Range("SRUAdd").Value = "3" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        ElseIf Range("SRUName3").Value = "" Then
            Range("Sig_3").Value = "Signature Release 3 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
            Range("Sig_3").Value = "Signature Release 3"
        End If
    End If
    End Sub

    Private Sub BtnCheck_Click()
        Check_SRU_Table
    End Sub
</code>```

Any help to figure out where I'm going wrong would be much appreciated.

答:
Only one condition of your If...ElseIf...Else block will be met.  Sounds like you want to check all conditions.  Therefore, you'd need to rewrite to something like this:

```<code>If Range("SRUAdd").Value = "3" Then
    If Range("SRUName1").Value = "" Then
        Range("Sig_1").Value = "Signature Release 1 - ERROR"
    End If
    If Range("SRUName2").Value = "" Then
        Range("Sig_2").Value = "Signature Release 2 - ERROR"
    End If
    If Range("SRUName3").Value = "" Then
        Range("Sig_3").Value = "Signature Release 3 - ERROR"
    End If
    If Range("SRUName3").Value <> "" And Range("SRUName2").Value <> "" And Range("SRUName1").Value <> "" Then
        Range("Sig_1").Value = "Signature Release 1"
        Range("Sig_2").Value = "Signature Release 2"
        Range("Sig_3").Value = "Signature Release 3"
    End If
End If
</code>```

I'm sure there's a more elegant way to do it, but this version requires the least rewrite of how you've chosen to approach it.

Body:
I need to do some error checking so a user knows they have missed some information before sending the form.

I have a table which is controlled by a Data Validation list dropdown box. This box has numbers 1 to 15, and will show/hide rows associated to the number selected i.e. 3 selected, so rows 1 to 3 are displayed, 4 to 15 or hidden. What the error checking code is supposed to do is, check the list number selected, then check a cell in each row to see if it is empty or not, if empty display the error message, if not then do nothing. I need this error message to display for each row which is displayed and not for the hidden rows. I have a cell at the top of the page with tells the user how many errors they have, so I don't want the hidden rows adding to this count. I can get it working for numbers zero and 1, but for 2 to 15 it is not working. Code below only shows numbers 0 to 3, I can alter the code for the other rows once working.

Correct outcome when nbr 3 is selected
D63 is empty so error msg in A63, D64:65 not empty so no error msg

Actual outcome when Nbr 3 is selected
D63:65 are empty so A63:65 should display the error msg

Sub Check_SRU_Table()

    ' SRU 0 ** WORKING **
    If Range("SRUAdd").Value = "0" Then
        Range("Sig_1").Value = "Signature Release 1"
        Range("Sig_2").Value = "Signature Release 2"
        Range("Sig_3").Value = "Signature Release 3"
    ' 4 TO 15 OMITTED
    End If

    ' SRU 1 ** WORKING **
    If Range("SRUAdd").Value = "1" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
        End If
    End If

    ' SRU 2 ** NOT WORKING **
    If Range("SRUAdd").Value = "2" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
        End If
    End If

    ' SRU 3 ** NOT WORKING **
    If Range("SRUAdd").Value = "3" Then
        If Range("SRUName1").Value = "" Then
            Range("Sig_1").Value = "Signature Release 1 - ERROR"
        ElseIf Range("SRUName2").Value = "" Then
            Range("Sig_2").Value = "Signature Release 2 - ERROR"
        ElseIf Range("SRUName3").Value = "" Then
            Range("Sig_3").Value = "Signature Release 3 - ERROR"
        Else
            Range("Sig_1").Value = "Signature Release 1"
            Range("Sig_2").Value = "Signature Release 2"
            Range("Sig_3").Value = "Signature Release 3"
        End If
    End If
    End Sub

    Private Sub BtnCheck_Click()
        Check_SRU_Table
    End Sub

Any help to figure out where I'm going wrong would be much appreciated.

Body:
Only one condition of your If...ElseIf...Else block will be met.  Sounds like you want to check all conditions.  Therefore, you'd need to rewrite to something like this:

If Range("SRUAdd").Value = "3" Then
    If Range("SRUName1").Value = "" Then
        Range("Sig_1").Value = "Signature Release 1 - ERROR"
    End If
    If Range("SRUName2").Value = "" Then
        Range("Sig_2").Value = "Signature Release 2 - ERROR"
    End If
    If Range("SRUName3").Value = "" Then
        Range("Sig_3").Value = "Signature Release 3 - ERROR"
    End If
    If Range("SRUName3").Value <> "" And Range("SRUName2").Value <> "" And Range("SRUName1").Value <> "" Then
        Range("Sig_1").Value = "Signature Release 1"
        Range("Sig_2").Value = "Signature Release 2"
        Range("Sig_3").Value = "Signature Release 3"
    End If
End If

I'm sure there's a more elegant way to do it, but this version requires the least rewrite of how you've chosen to approach it.


问:
C can I open a directory's files using open dir in an alphabetical order?
In windows when you are opening files using open dir and dirent it will give you the files in an alphabetical order but in linux it does not is there any way to get the files sorted too in linux?</p>

答: No, readdir() returns directory entries in an arbitrary order, generally the order that they exist in the filesystem. If you want them ordered by some criteria, sort them yourself.


问:
HTML Forwarding
So I've been playing around with some simple HTML forwarding with c++. Haven't accomplished much and I have some questions on the backbone.

First: Do I need to use any special libraries other than socket libraries to simply forward HTML data and connections?

Second: When a client connects to an HTML server, is the TCP connection kept open? Or is it closed once data is sent?

Third: When I forward data, from a client to the server, the packet includes the destination address. I should technically be able to read this address and connect to the server via port 80, keep it open, and send and receive on that newly opened port right? Is there anything I have to do? Any time constraints? If I directly forward every single packet directly between the client and server the website should show up correctly on the client, correct?

I would prefer to keep any external libs to a minimum. But if necessary I can expand the program to include any required libraries.

So far I've gotten data to and from both parties, however the website does not function.

[platform] :: windows.primary && posix_compliant.secondary

答:
After doing quite a bit of research, the greatest help I've had in my endeavors has been this website.

This one also helped quite a bit.

LibCURL is certainly the way to go. It's kind of dated, and everything is in C, but it's much easier than redoing everything..

quote from second site:

Like most network protocols, HTTP uses the client-server model: An HTTP client opens a connection and sends a request message to an HTTP server; the server then returns a response message, usually containing the resource that was requested. After delivering the response, the server closes the connection (making HTTP a stateless protocol, i.e. not maintaining any connection information between transactions).

Title: HTML Forwarding


问:
WSO2 ESB startup error - H2 database unable to delete row
WSO2 ESB goes into error state on startup.

During startup, the following H2 database error is thrown.

org.h2.jdbc.JdbcSQLException: Row not found when trying to delete from
  index

Due to some data corruption, the following error occurs. Restarts didnt help.

答:
We need more information... ¿What do you need? , restart and recover all the resources in your install or just restart and keep working.

1.- Make a backup copy of all databases files in $CARBON_HOME/databases/ folder
2.- Restart a clean instances removing the corrupted database, remove all the H2 files in $CARBON_HOME/databases/ folder. If you have all your artifacts in $CARBON_HOME/deployment it should rebuild all.


问:
How to add a TextField object in list?
I tried to add a TextField object in a list but i have a error "The argument type 'PlayerItem' can't be assigned to the parameter type 'TextField'.

I created a TextField list (_playerList):

```<code>List<TextField> _playerList = new List();
</code>```

I created a class to create TextField object:

```<code>class PlayerItem extends StatelessWidget {

  //constructor
  PlayerItem();

  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: InputDecoration(
        prefixIcon: const Icon(Icons.person),
        hintText: "Player",
        counterText: "",
      ),
    );
  }
}
</code>```

When i tried to add a item in list i have a error:

```<code> _playerList.add(new PlayerItem()),
</code>```

答:
This is an expected type error.

You declared your list as List<TextField> and try to insert PlayerItem.

The consequence of this is that you should type your list using PlayerItem:

List<PlayerItem> _playerList = <PlayerItem>[];
```

<p>Alternatively, you could also use a more generic type, i.e. a super type of both <code>TextField</code> and <code>PlayerItem</code> which could be <code>Widget</code> for example:</p>

<pre class="lang-dart prettyprint-override"><code>List<Widget> _playerList = <Widget>[];
</code>```

Title: How to add a TextField object in list?

Body:
I tried to add a TextField object in a list but i have a error "The argument type 'PlayerItem' can't be assigned to the parameter type 'TextField'.

I created a TextField list (_playerList):

List<TextField> _playerList = new List();

I created a class to create TextField object:

class PlayerItem extends StatelessWidget {

  //constructor
  PlayerItem();

  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: InputDecoration(
        prefixIcon: const Icon(Icons.person),
        hintText: "Player",
        counterText: "",
      ),
    );
  }
}

When i tried to add a item in list i have a error:

 _playerList.add(new PlayerItem()),

Body:
This is an expected type error.

You declared your list as List<TextField> and try to insert PlayerItem.

The consequence of this is that you should type your list using PlayerItem:

List<PlayerItem> _playerList = <PlayerItem>[];

Alternatively, you could also use a more generic type, i.e. a super type of both TextField and PlayerItem which could be Widget for example:

List<Widget> _playerList = <Widget>[];


问:
How to Add changable text on splash screen?
Hi i want to add text on the splash image on splash screen. i have added single text on image but i want to change the text every time the app opens.how to do that please tell me .

i have added single textview in splash.xml it is displaying . But i want to display all the item in the list.xml one-by-one every time app opens.

```<code><TextView
    android:id="@+id/quote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your limitation—it's only your imagination."
    android:textColor="#ffffff"
    android:textSize="36sp"
   android:layout_centerInParent="true"/>
</code>```

in list.xml

```<code><string-array name="quote_array">
    <item>Your limitation—it's only your imagination.</item>
    <item>Great things never come from comfort zones.</item>
    <item>The harder you work for something, the greater you’ll feel when you achieve it.</item>
</string-array>
</code>```

答:
You can do the following:

You create a class that extends from AsyncTask:

```<code>public class MyAsyncTask extends AsyncTask<Void, String, Void> {
    private String[] stringArray;
    private TextView myTextView;
    private long delay;

    MyAsyncTask(String[] stringArray, long delay, TextView myTextView) {
        this.stringArray = stringArray;
        this.delay = delay;
        this.myTextView = myTextView;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
             for (String value : stringArray) {
                Thread.sleep(delay);
                publishProgress(value);
             }
        } catch (InterruptedException ex) {
            // Handle interrupted exception
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(String... value) {
        myTextView.setText(value[0]);
    }
}
</code>```

This allows you to edit the textview as the code is executed within your thread.

Run the asynctask from the activity, passing it by parameters the list of strings, the time in milliseconds you want between text changes and the textview that you want to be modified:

```<code>TextView myTextView = findViewById(R.id.myTextView);

new MyAsyncTask(
        getResources().getStringArray(R.array.quote_array),
        5000,
        myTextView).execute();
</code>```

I hope it has been helpful for you.

Body:
Hi i want to add text on the splash image on splash screen. i have added single text on image but i want to change the text every time the app opens.how to do that please tell me .

i have added single textview in splash.xml it is displaying . But i want to display all the item in the list.xml one-by-one every time app opens.

<TextView
    android:id="@+id/quote"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your limitation—it's only your imagination."
    android:textColor="#ffffff"
    android:textSize="36sp"
   android:layout_centerInParent="true"/>

in list.xml

<string-array name="quote_array">
    <item>Your limitation—it's only your imagination.</item>
    <item>Great things never come from comfort zones.</item>
    <item>The harder you work for something, the greater you’ll feel when you achieve it.</item>
</string-array>

Body:
You can do the following:

You create a class that extends from AsyncTask:

public class MyAsyncTask extends AsyncTask<Void, String, Void> {
    private String[] stringArray;
    private TextView myTextView;
    private long delay;

    MyAsyncTask(String[] stringArray, long delay, TextView myTextView) {
        this.stringArray = stringArray;
        this.delay = delay;
        this.myTextView = myTextView;
    }

    @Override
    protected Void doInBackground(Void... voids) {
        try {
             for (String value : stringArray) {
                Thread.sleep(delay);
                publishProgress(value);
             }
        } catch (InterruptedException ex) {
            // Handle interrupted exception
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(String... value) {
        myTextView.setText(value[0]);
    }
}

This allows you to edit the textview as the code is executed within your thread.

Run the asynctask from the activity, passing it by parameters the list of strings, the time in milliseconds you want between text changes and the textview that you want to be modified:

TextView myTextView = findViewById(R.id.myTextView);

new MyAsyncTask(
        getResources().getStringArray(R.array.quote_array),
        5000,
        myTextView).execute();

I hope it has been helpful for you.


问:
How would you explain the following: [position*-1] in Python? The * is throwing me off
I’m practicing reading and writing explanations of Python code so I better understand what in the world I’m reading. I came across the below:

```<code>orderLog = [ ]
N = 5
def get_last(position):

    if position <= N and position <= len(orderLog):
     return orderLog[position * -1]
</code>```

There is more code following but I need some assistance understanding the last line starting with return. Am I multiplying the parameter ‘position’ by -1 and if so.. why?    Also, further down I see:

```<code>Choice = -1
</code>```

Again this -1 is puzzling me.

答:
Negative list indexes count from the back. Consider this hypothetical list:

# positive indexes
#  0    1    2    3    4    5    6
 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# -7   -6   -5   -4   -3   -2   -1
# negative indexes
```

Multiplying by negative one simply inverts the sign of your value. I'll assume that position is usually positive, so this code reads:

If position is less than or equal to N, and position is less than or equal to the length of orderLog, then return the element that is position spaces from the end.

Body:
I’m practicing reading and writing explanations of Python code so I better understand what in the world I’m reading. I came across the below:

orderLog = [ ]
N = 5
def get_last(position):

    if position <= N and position <= len(orderLog):
     return orderLog[position * -1]

There is more code following but I need some assistance understanding the last line starting with return. Am I multiplying the parameter ‘position’ by -1 and if so.. why?    Also, further down I see:

Choice = -1

Again this -1 is puzzling me.

Body:
Negative list indexes count from the back. Consider this hypothetical list:

# positive indexes
#  0    1    2    3    4    5    6
 ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# -7   -6   -5   -4   -3   -2   -1
# negative indexes

Multiplying by negative one simply inverts the sign of your value. I'll assume that position is usually positive, so this code reads:

If position is less than or equal to N, and position is less than or equal to the length of orderLog, then return the element that is position spaces from the end.


问:
How to validate type 'java.lang.Boolean' in Spring boot
I have a boolean field which I want to validate to have only "true" or "false" as value(without quotes). But this field is also allowing "true" or "false" as value(with quotes) which I want to restrict.

I tried to use @Pattern annotation to match these values.
But I have the following error:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Boolean'. Check configuration for 'restartable'

My code is:

```<code>@Pattern(regexp = "^(true|false)$", message = "restartable field allowed input: true or false")
private Boolean restartable;
</code>```

What should i do? Is there some other way to overcome this issue? Thanks in advance.

答:
Why are you using a text validation on a boolean field? that's what the error is stating.

I think it would make more sense to check if it's null or not (use @NotNull); if it's non-null then surely it's a valid boolean, by definition it can't have any other value besides true or false. On the other hand, if it's null then that's probably the error that you want to detect.

Body:
I have a boolean field which I want to validate to have only "true" or "false" as value(without quotes). But this field is also allowing "true" or "false" as value(with quotes) which I want to restrict.

I tried to use @Pattern annotation to match these values.
But I have the following error:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Boolean'. Check configuration for 'restartable'

My code is:

@Pattern(regexp = "^(true|false)$", message = "restartable field allowed input: true or false")
private Boolean restartable;

What should i do? Is there some other way to overcome this issue? Thanks in advance.


问:
How do I display multiple divs (and their child elements) as Inline?
I am attempting to display 4 div sections side by side by setting the parent div to:

```<code>.parent {
    display: inline;
}
</code>```

```<code><div class="parent">
        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>

        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>

        <div class="child">
            <ul>
                <li>test1</li>
                <li>test1</li>
                <li>test1</li>
            </ul>
        </div>
</code>```

The 4 divs (with child elements nested) remain stacked as block elements:

```<code>test1
test1
test1
test1
test1
test1
test1
test1
test1
</code>```

But I want them side by side like this - test1 test1 test1

答:
Like this:</p>

```<code>.parent .child {
    display: inline-block;
}
</code>```

Body:
I am attempting to display 4 div sections side by side by setting the parent div to:

.parent {
    display: inline;
}

test1

test1

test1

test1

test1

test1

test1

test1

test1

The 4 divs (with child elements nested) remain stacked as block elements:

test1
test1
test1
test1
test1
test1
test1
test1
test1

But I want them side by side like this - test1 test1 test1

Body:
Like this:

.parent .child {
    display: inline-block;
}


问:
Method to determine whether a binary contains Bitcode no longer seems to work
In my search for a method to determine if a iOS binary was build with Bitcode, I found the following post:

How to check if a framework is BITCODE supported for Xcode7

Here, the following method was suggested to determine if bitcode is present in a binary:

```<code>$ otool -l libName.o | grep __LLVM
</code>```

However, I have tried this on several binaries with no success. One of them is a library I know has bitcode since after I changed the flag on its project a build error went away. Another one of them is a binary for a file extension, build using Archive. And another is for apple watch.

I believe all of the above binaries should have Bitcode, and yet I always get no results from the above command.

Does anyone know any other method that works with the latest binaries?

I'm using XCode 7.2 and 10.10.5 in case it matters.

UPDATE: Here is an example of a file which is supposed to have bitcode but the above command doesn't return anything. It is a binary from a test File Provider. I generated it via Archive and Deploy as Ad Hoc, and made sure the setting for bitcode was on for the target.

https://www.dropbox.com/s/eyuzs5j1t7nsq6t/CustomDocumentProviderFileProvider?dl=0

答:
As of today, the technique which works for me is the one mentioned in this answer from another SO thread. Specifically, for a (dynamic) framework named MyLib and containing those two device architectures:

otool -arch armv7 MyLib.framework/MyLib | grep LLVM
otool -arch arm64 MyLib.framework/MyLib | grep LLVM
```

Body:
In my search for a method to determine if a iOS binary was build with Bitcode, I found the following post:

How to check if a framework is BITCODE supported for Xcode7

Here, the following method was suggested to determine if bitcode is present in a binary:

$ otool -l libName.o | grep __LLVM

However, I have tried this on several binaries with no success. One of them is a library I know has bitcode since after I changed the flag on its project a build error went away. Another one of them is a binary for a file extension, build using Archive. And another is for apple watch.

I believe all of the above binaries should have Bitcode, and yet I always get no results from the above command.

Does anyone know any other method that works with the latest binaries?

I'm using XCode 7.2 and 10.10.5 in case it matters.

UPDATE: Here is an example of a file which is supposed to have bitcode but the above command doesn't return anything. It is a binary from a test File Provider. I generated it via Archive and Deploy as Ad Hoc, and made sure the setting for bitcode was on for the target.

https://www.dropbox.com/s/eyuzs5j1t7nsq6t/CustomDocumentProviderFileProvider?dl=0


问:
VisualState storyboard not activating on path 'MouseOver' state
I'm trying to change the colour of a Path control on mouseover where the path data is always changing through a data binding.  It should change from yellow to red, but There is no colour change on the path as I move my mouse over it, it remains yellow.

my view:

MainWindow.xaml

```<code><reactiveui:ReactiveWindow
    x:Class="TestWpfAnim.MainWindow"
    x:TypeArguments="local:MainViewModel"

    xmlns:reactiveui="http://reactiveui.net"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestWpfAnim"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>

    <local:PointsToPathNormalConv x:Key="MyConv" />

</Window.Resources>
<Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualStateGroup.Transitions>
                    <!--Take one half second to transition to the MouseOver state.-->
                    <VisualTransition To="MouseOver" GeneratedDuration="0:0:0.5" />
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="MyAnimatedBrush" Storyboard.TargetProperty="Color" To="Red" Duration="0:0:0.5"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    <Path
        x:Name="MainPath" StrokeThickness="4"
        Data="{Binding Poly, Converter={StaticResource MyConv}}">
        <Path.Stroke>
            <SolidColorBrush Color="Yellow" x:Name="MyAnimatedBrush" />
        </Path.Stroke>
    </Path>
</Grid>
</code>```

MainWindow.xaml.cs

```<code>public partial class MainWindow : ReactiveWindow<MainViewModel>
{
    public MainWindow()
    {
        InitializeComponent();
        ViewModel = new MainViewModel();
        DataContext = ViewModel;

        var timer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher.CurrentDispatcher)
        {
            Interval = TimeSpan.FromSeconds(2)
        };
        int x = 100;
        int y = 100;

        timer.Tick += (o, e) =>
        {
            ViewModel.Add(x++, y++ * 2);
        };

        timer.Start();

    }
}
</code>```

The converter

```<code>[ValueConversion(typeof(IEnumerable<System.Windows.Point>), typeof(Geometry))]
public class PointsToPathNormalConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is IEnumerable<System.Windows.Point> points && points.Any())
        {
            List<LineSegment> segments = new List<LineSegment>();

            foreach (var p in points)
            {
                segments.Add(new LineSegment(p, true));
            }

            PathFigure figure = new PathFigure(points.First(), segments, false); //true if closed
            PathGeometry geometry = new PathGeometry();
            geometry.Figures.Add(figure);

            return geometry;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

my viewmodel:
MainViewModel.cs

```<code>public class MainViewModel : AbstractNotifyPropertyChanged, IDisposable
{
    public MainViewModel()
    {
        Poly = new ObservableCollection<System.Windows.Point>();
    }

    public void Add(int x, int y)
    {
        var newlist = Poly.ToList();
        newlist.Add(new System.Windows.Point(x, y));
        Poly = new ObservableCollection<System.Windows.Point>(newlist);
    }

    public void Dispose()
    {
    }
    private ObservableCollection<System.Windows.Point> _poly;

    public ObservableCollection<System.Windows.Point> Poly
    {
        get => _poly;
        set => this.SetAndRaise(ref _poly, value);
    }
}
</code>```

答: According to the documentation, a VisualTransition by itself cannot fire just because the name is "MouseOver".  It still requires an eventhandler of some kind to perform the transition.  You would have to add an eventhandler for the MouseOver event fired by the Path.</p>

Body:
I'm trying to change the colour of a Path control on mouseover where the path data is always changing through a data binding.  It should change from yellow to red, but There is no colour change on the path as I move my mouse over it, it remains yellow.

my view:

MainWindow.xaml

<reactiveui:ReactiveWindow
    x:Class="TestWpfAnim.MainWindow"
    x:TypeArguments="local:MainViewModel"

    xmlns:reactiveui="http://reactiveui.net"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestWpfAnim"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.Resources>

    <local:PointsToPathNormalConv x:Key="MyConv" />

</Window.Resources>
<Grid>
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualStateGroup.Transitions>

                    <VisualTransition To="MouseOver" GeneratedDuration="0:0:0.5" />
                </VisualStateGroup.Transitions>
                <VisualState x:Name="Normal"/>
                <VisualState x:Name="MouseOver">
                    <Storyboard>
                        <ColorAnimation Storyboard.TargetName="MyAnimatedBrush" Storyboard.TargetProperty="Color" To="Red" Duration="0:0:0.5"/>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
    <Path
        x:Name="MainPath" StrokeThickness="4"
        Data="{Binding Poly, Converter={StaticResource MyConv}}">
        <Path.Stroke>
            <SolidColorBrush Color="Yellow" x:Name="MyAnimatedBrush" />
        </Path.Stroke>
    </Path>
</Grid>

MainWindow.xaml.cs

public partial class MainWindow : ReactiveWindow<MainViewModel>
{
    public MainWindow()
    {
        InitializeComponent();
        ViewModel = new MainViewModel();
        DataContext = ViewModel;

        var timer = new DispatcherTimer(DispatcherPriority.Normal, Dispatcher.CurrentDispatcher)
        {
            Interval = TimeSpan.FromSeconds(2)
        };
        int x = 100;
        int y = 100;

        timer.Tick += (o, e) =>
        {
            ViewModel.Add(x++, y++ * 2);
        };

        timer.Start();

    }
}

The converter

[ValueConversion(typeof(IEnumerable<System.Windows.Point>), typeof(Geometry))]
public class PointsToPathNormalConv : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is IEnumerable<System.Windows.Point> points && points.Any())
        {
            List<LineSegment> segments = new List<LineSegment>();

            foreach (var p in points)
            {
                segments.Add(new LineSegment(p, true));
            }

            PathFigure figure = new PathFigure(points.First(), segments, false); //true if closed
            PathGeometry geometry = new PathGeometry();
            geometry.Figures.Add(figure);

            return geometry;
        }

        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

my viewmodel:
MainViewModel.cs

public class MainViewModel : AbstractNotifyPropertyChanged, IDisposable
{
    public MainViewModel()
    {
        Poly = new ObservableCollection<System.Windows.Point>();
    }

    public void Add(int x, int y)
    {
        var newlist = Poly.ToList();
        newlist.Add(new System.Windows.Point(x, y));
        Poly = new ObservableCollection<System.Windows.Point>(newlist);
    }

    public void Dispose()
    {
    }
    private ObservableCollection<System.Windows.Point> _poly;

    public ObservableCollection<System.Windows.Point> Poly
    {
        get => _poly;
        set => this.SetAndRaise(ref _poly, value);
    }
}