问:
Accessing component's "key" prop
I want to update the Counter component to take onIncrement and onDecrement
callbacks as props and ensure they update the counter’s values
independently.

Each callback can only take a single integer as parameter
which tells the amount to increment the counter’s existing value.

I believe the best way to do this is to access the 'key' prop of the Counter component?

Sandbox: https://codesandbox.io/s/silly-sound-5ofef?from-embed
App.js

```<code>import Counter from './components/Counter'
import './App.css'

export class App extends Component {
  constructor(props, context) {
    super(props, context)
    this.state = {
      data: [
        { id: 1, value: 0 },
        { id: 2, value: 0 },
        { id: 3, value: 0 },
        { id: 4, value: 0 },
      ],
    }
  }

  onDecrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value -= e) }
      })
      return {
        data,
      }
    })
  }

  onIncrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value += e) }
      })
      return {
        data,
      }
    })
  }

  render() {
    return (
      <div>
        {this.state['data'].map(counter => (
          <Counter
            key={counter.id}
            value={counter.value}
            onIncrement={this.onIncrement}
            onDecrement={this.onDecrement}
          />
        ))}
      </div>
    )
  }
}

export default App
</code>```

Counter.js

```<code>
export class Counter extends Component {
  render() {
    const { value, onIncrement, onDecrement } = this.props
    return (
      <div className="counter test">
        <b>{value}</b>
        <div className="counter-controls">
          <button
            className="button btn-danger btn-sm"
            onClick={() => onDecrement(1)}
          >
            -
          </button>
          <button
            className="button btn-success btn-sm"
            onClick={() => onIncrement(1)}
          >
            +
          </button>
        </div>
      </div>
    )
  }
}

export default Counter
</code>```

答:
As I understand, you cant change Counter component. You can bind onIncrement and onDecrement in App.js, so props callbacks semantic will not change for Counter.

```<code>onDecrement = (id, e) => {
    this.setState(state => {
      const data = state.data.map(item => {
        if (item.id === id) {
          return { id: item.id, value: (item.value -= e) };
        }
        return item;
      });
      return {
        data
      };
    });
  };

  onIncrement = (id, e) => {
    this.setState(state => {
      const data = state.data.map(item => {
        if (item.id === id) {
          return { id: item.id, value: (item.value += e) };
        }
        return item;
      });
      return {
        data
      };
    });
  };

  render() {
    return (
      <div>
        {this.state["data"].map(counter => (
          <Counter
            key={counter.id}
            value={counter.value}
            onIncrement={this.onIncrement.bind(this, counter.id)}
            onDecrement={this.onDecrement.bind(this, counter.id)}
          />
        ))}
      </div>
    );
  }
</code>```

Title: Accessing component's "key" prop

Body:
I want to update the Counter component to take onIncrement and onDecrement
callbacks as props and ensure they update the counter’s values
independently.

Each callback can only take a single integer as parameter
which tells the amount to increment the counter’s existing value.

I believe the best way to do this is to access the 'key' prop of the Counter component?

Sandbox: https://codesandbox.io/s/silly-sound-5ofef?from-embed
App.js

import Counter from './components/Counter'
import './App.css'

export class App extends Component {
  constructor(props, context) {
    super(props, context)
    this.state = {
      data: [
        { id: 1, value: 0 },
        { id: 2, value: 0 },
        { id: 3, value: 0 },
        { id: 4, value: 0 },
      ],
    }
  }

  onDecrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value -= e) }
      })
      return {
        data,
      }
    })
  }

  onIncrement = e => {
    this.setState(state => {
      const data = state.data.map(item => {
        return { id: item.id, value: (item.value += e) }
      })
      return {
        data,
      }
    })
  }

  render() {
    return (

        {this.state['data'].map(counter => (
          <Counter
            key={counter.id}
            value={counter.value}
            onIncrement={this.onIncrement}
            onDecrement={this.onDecrement}
          />
        ))}

    )
  }
}

export default App

Counter.js

export class Counter extends Component {
  render() {
    const { value, onIncrement, onDecrement } = this.props
    return (

        {value}

          <button
            className="button btn-danger btn-sm"
            onClick={() => onDecrement(1)}
          >
            -
          </button>
          <button
            className="button btn-success btn-sm"
            onClick={() => onIncrement(1)}
          >
            +
          </button>

    )
  }
}

export default Counter

Body:
As I understand, you cant change Counter component. You can bind onIncrement and onDecrement in App.js, so props callbacks semantic will not change for Counter.

onDecrement = (id, e) => {
    this.setState(state => {
      const data = state.data.map(item => {
        if (item.id === id) {
          return { id: item.id, value: (item.value -= e) };
        }
        return item;
      });
      return {
        data
      };
    });
  };

  onIncrement = (id, e) => {
    this.setState(state => {
      const data = state.data.map(item => {
        if (item.id === id) {
          return { id: item.id, value: (item.value += e) };
        }
        return item;
      });
      return {
        data
      };
    });
  };

  render() {
    return (
      <div>
        {this.state["data"].map(counter => (
          <Counter
            key={counter.id}
            value={counter.value}
            onIncrement={this.onIncrement.bind(this, counter.id)}
            onDecrement={this.onDecrement.bind(this, counter.id)}
          />
        ))}
      </div>
    );
  }


来源: stackexchange

问:
Use undefined variables in Selenium IDE for if condition
I want to run a "child" test at the end of a "parent" test that clears the session cookie if the flag skipReset has not been set. Further, I'd like to run a "grandparent" test that calls the "parent" test and sets skipReset = true which should make the "child" test skip the reset and thus keep the session data (see print screen).

However if the "child" test was run from a parent which did not set the flag skipReset the test fails.

I'd like to do this so the "parent" test does not have to be copy pasted into the "grand parent" test excluding the session reset line. Is there a way to achieve this?

答:
```<code>if "${skipReset}" == "$" + "{skipReset}"
</code>```

<p>Just use string comparision, unset variable in IDE means that there weren't any substitution, so it just remains litterally as it was written ('${skipReset}'). </p>

ContentLicense: CC BY-SA 4.0

Body:
if "${skipReset}" == "$" + "{skipReset}"

Just use string comparision, unset variable in IDE means that there weren't any substitution, so it just remains litterally as it was written ('${skipReset}').


问:
AttributeError: module 'test' has no attribute 'randhiletter'
I am getting the error, in the title, even though there is a function randhiletter in the python file test.py. I am using this code in the file accessing test.py:

```<code>import test
print(test.randhiletter())
</code>```

The code in test.py basically uses randint to assign a variable a number. Based on that number it will return a letter. There are two functions in test.py. These are randhiletter and randlowletter which do the same thing but for lowercase and uppercase letters. I do not understand why I am getting the error.

答:
Credits to user2357112 supports Monica for this answer. He/she did not post one so I felt that I should to close the discussion or something:
The issue was that I could not use the name test for the file I was trying to import as that is apparently already a python library.</p>

Body:
I am getting the error, in the title, even though there is a function randhiletter in the python file test.py. I am using this code in the file accessing test.py:

import test
print(test.randhiletter())

The code in test.py basically uses randint to assign a variable a number. Based on that number it will return a letter. There are two functions in test.py. These are randhiletter and randlowletter which do the same thing but for lowercase and uppercase letters. I do not understand why I am getting the error.


问:
How to find JSON object in text with python
I'm trying to parse JSON object from text with python regex. I found this match:

```<code>'\{(?:[^{}]|(?R))*\}'
</code>```

but in python I get this error:

```<code>re.error: unknown extension ?R at position 12
</code>```

See the regex match in this regex101 example.

答:
If there is only one JSON in one line, you can use the index methods to find the first and the last bracket to select the JSON:</p>

```<code>firstValue = jsonString.index("{")
lastValue = len(jsonString) - jsonString[::-1].index("}")
jsonString = jsonStringEncoded[firstValue:lastValue]
</code>```

Body:
I'm trying to parse JSON object from text with python regex. I found this match:

'\{(?:[^{}]|(?R))*\}'

but in python I get this error:

re.error: unknown extension ?R at position 12

See the regex match in this regex101 example.

Body:
If there is only one JSON in one line, you can use the index methods to find the first and the last bracket to select the JSON:

firstValue = jsonString.index("{")
lastValue = len(jsonString) - jsonString[::-1].index("}")
jsonString = jsonStringEncoded[firstValue:lastValue]


问:
Check single elements in a list of dictionaries with python
You have a list of dictionaries like this one:

```<code>groups = {"1":["Susanne", "Laura", "Anna"],
    "2":["Kim", "Lisa", "Kevin"];
    "3": ["Donald", "Hans", "Jack"],
    }
</code>```

How can u check the single elements, like for example: How many of the names are starting with an "A"
I tried everything, but I always get errors...

答:
You can try this.</p>

```<code>sum(map(lambda x:x.startswith('A'),sum(groups.values(),[])))
#1
</code>```

Body:
You have a list of dictionaries like this one:

groups = {"1":["Susanne", "Laura", "Anna"],
    "2":["Kim", "Lisa", "Kevin"];
    "3": ["Donald", "Hans", "Jack"],
    }

How can u check the single elements, like for example: How many of the names are starting with an "A"
I tried everything, but I always get errors...

Body:
You can try this.

sum(map(lambda x:x.startswith('A'),sum(groups.values(),[])))
#1


问:
Error with Devise Gem when Signing up
I'm getting an error when signing up using Devise. I am switching from a session-based authentication system I previously set up to Devise.

I installed Devise and have this in my model:

```<code>devise :database_authenticatable,  :registerable, :confirmable,
       :recoverable, :rememberable, :trackable, :validatable
</code>```

This is my migration:

```<code>class AddDeviseUserTable < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      t.recoverable
      t.rememberable
      t.trackable
      t.confirmable
      t.encryptable

      t.timestamps
    end

    add_column :users, :name, :string

    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true
    # add_index :users, :confirmation_token,   :unique => true
    # add_index :users, :unlock_token,         :unique => true
    # add_index :users, :authentication_token, :unique => true
  end

  def self.down
    drop_table :users
  end
end
</code>```

I also have this in my routes:

```<code>root :to => "videos#index"
devise_for :users
resources :users do
  member do
    get :following, :followers
  end
end
</code>```

The error I get when signing up is:

```<code>NameError in Devise/registrationsController#create

undefined local variable or method `encrypt_new_password' for #<User:0x1032a8cb8>
</code>```

Here is the full trace:

```<code>activemodel (3.0.4) lib/active_model/attribute_methods.rb:364:in `method_missing'
activerecord (3.0.4) lib/active_record/attribute_methods.rb:46:in `method_missing'
activesupport (3.0.4) lib/active_support/callbacks.rb:419:in `_run_save_callbacks'
activerecord (3.0.4) lib/active_record/callbacks.rb:277:in `create_or_update'
activerecord (3.0.4) lib/active_record/persistence.rb:39:in `save'
activerecord (3.0.4) lib/active_record/validations.rb:43:in `save'
activerecord (3.0.4) lib/active_record/attribute_methods/dirty.rb:21:in `save'
activerecord (3.0.4) lib/active_record/transactions.rb:240:in `save'
activerecord (3.0.4) lib/active_record/transactions.rb:292:in `with_transaction_returning_status'
activerecord (3.0.4) lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction'
activerecord (3.0.4) lib/active_record/transactions.rb:207:in `transaction'
activerecord (3.0.4) lib/active_record/transactions.rb:290:in `with_transaction_returning_status'
activerecord (3.0.4) lib/active_record/transactions.rb:240:in `save'
activerecord (3.0.4) lib/active_record/transactions.rb:251:in `rollback_active_record_state!'
activerecord (3.0.4) lib/active_record/transactions.rb:239:in `save'
devise (1.3.4) app/controllers/devise/registrations_controller.rb:16:in `create'
actionpack (3.0.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.4) lib/abstract_controller/base.rb:150:in `process_action'
actionpack (3.0.4) lib/action_controller/metal/rendering.rb:11:in `process_action'
actionpack (3.0.4) lib/abstract_controller/callbacks.rb:18:in `process_action'
activesupport (3.0.4) lib/active_support/callbacks.rb:445:in `_run__1732029701__process_action__1623385099__callbacks'
activesupport (3.0.4) lib/active_support/callbacks.rb:409:in `send'
activesupport (3.0.4) lib/active_support/callbacks.rb:409:in `_run_process_action_callbacks'
activesupport (3.0.4) lib/active_support/callbacks.rb:93:in `send'
activesupport (3.0.4) lib/active_support/callbacks.rb:93:in `run_callbacks'
actionpack (3.0.4) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.0.4) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
activesupport (3.0.4) lib/active_support/notifications.rb:52:in `instrument'
activesupport (3.0.4) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.4) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.4) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.0.4) lib/action_controller/metal/rescue.rb:17:in `process_action'
actionpack (3.0.4) lib/abstract_controller/base.rb:119:in `process'
actionpack (3.0.4) lib/abstract_controller/rendering.rb:41:in `process'
actionpack (3.0.4) lib/action_controller/metal.rb:138:in `dispatch'
actionpack (3.0.4) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.0.4) lib/action_controller/metal.rb:178:in `action'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:62:in `call'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:27:in `call'
actionpack (3.0.4) lib/action_dispatch/routing/mapper.rb:35:in `call'
rack-mount (0.6.13) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.13) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.13) lib/rack/mount/code_generation.rb:89:in `optimized_each'
rack-mount (0.6.13) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.13) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:492:in `call'
warden (1.0.4) lib/warden/manager.rb:35:in `call'
warden (1.0.4) lib/warden/manager.rb:34:in `catch'
warden (1.0.4) lib/warden/manager.rb:34:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.1) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/cookies.rb:302:in `call'
activerecord (3.0.4) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.4) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.4) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.4) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.4) lib/active_support/callbacks.rb:415:in `_run_call_callbacks'
actionpack (3.0.4) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.1) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.0.4) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.1) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.4) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
</code>```

Why am I getting this error? How do I fix it?

答:
There is no encrypt_new_password method in the Devise source code so I suspect this method was left behind when you switched from your previous authentication system to Devise. I would search through your application code for the string encrypt_new_password and see what you can find.

Probably something in your User model that needs more cleanup. In particular look for any obsolete before and/or after callback in your User model since the failure occurs during a call to User#save.

ContentLicense: CC BY-SA 3.0

Title: Error with Devise Gem when Signing up

Body:
I'm getting an error when signing up using Devise. I am switching from a session-based authentication system I previously set up to Devise.

I installed Devise and have this in my model:

devise :database_authenticatable,  :registerable, :confirmable,
       :recoverable, :rememberable, :trackable, :validatable

This is my migration:

class AddDeviseUserTable < ActiveRecord::Migration
  def self.up
    create_table(:users) do |t|
      t.database_authenticatable :null => false
      t.recoverable
      t.rememberable
      t.trackable
      t.confirmable
      t.encryptable

      t.timestamps
    end

    add_column :users, :name, :string

    add_index :users, :email,                :unique => true
    add_index :users, :reset_password_token, :unique => true
    # add_index :users, :confirmation_token,   :unique => true
    # add_index :users, :unlock_token,         :unique => true
    # add_index :users, :authentication_token, :unique => true
  end

  def self.down
    drop_table :users
  end
end

I also have this in my routes:

root :to => "videos#index"
devise_for :users
resources :users do
  member do
    get :following, :followers
  end
end

The error I get when signing up is:

NameError in Devise/registrationsController#create

undefined local variable or method `encrypt_new_password' for #<User:0x1032a8cb8>

Here is the full trace:

activemodel (3.0.4) lib/active_model/attribute_methods.rb:364:in `method_missing'
activerecord (3.0.4) lib/active_record/attribute_methods.rb:46:in `method_missing'
activesupport (3.0.4) lib/active_support/callbacks.rb:419:in `_run_save_callbacks'
activerecord (3.0.4) lib/active_record/callbacks.rb:277:in `create_or_update'
activerecord (3.0.4) lib/active_record/persistence.rb:39:in `save'
activerecord (3.0.4) lib/active_record/validations.rb:43:in `save'
activerecord (3.0.4) lib/active_record/attribute_methods/dirty.rb:21:in `save'
activerecord (3.0.4) lib/active_record/transactions.rb:240:in `save'
activerecord (3.0.4) lib/active_record/transactions.rb:292:in `with_transaction_returning_status'
activerecord (3.0.4) lib/active_record/connection_adapters/abstract/database_statements.rb:139:in `transaction'
activerecord (3.0.4) lib/active_record/transactions.rb:207:in `transaction'
activerecord (3.0.4) lib/active_record/transactions.rb:290:in `with_transaction_returning_status'
activerecord (3.0.4) lib/active_record/transactions.rb:240:in `save'
activerecord (3.0.4) lib/active_record/transactions.rb:251:in `rollback_active_record_state!'
activerecord (3.0.4) lib/active_record/transactions.rb:239:in `save'
devise (1.3.4) app/controllers/devise/registrations_controller.rb:16:in `create'
actionpack (3.0.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.4) lib/action_controller/metal/implicit_render.rb:4:in `send_action'
actionpack (3.0.4) lib/abstract_controller/base.rb:150:in `process_action'
actionpack (3.0.4) lib/action_controller/metal/rendering.rb:11:in `process_action'
actionpack (3.0.4) lib/abstract_controller/callbacks.rb:18:in `process_action'
activesupport (3.0.4) lib/active_support/callbacks.rb:445:in `_run__1732029701__process_action__1623385099__callbacks'
activesupport (3.0.4) lib/active_support/callbacks.rb:409:in `send'
activesupport (3.0.4) lib/active_support/callbacks.rb:409:in `_run_process_action_callbacks'
activesupport (3.0.4) lib/active_support/callbacks.rb:93:in `send'
activesupport (3.0.4) lib/active_support/callbacks.rb:93:in `run_callbacks'
actionpack (3.0.4) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.0.4) lib/action_controller/metal/instrumentation.rb:30:in `process_action'
activesupport (3.0.4) lib/active_support/notifications.rb:52:in `instrument'
activesupport (3.0.4) lib/active_support/notifications/instrumenter.rb:21:in `instrument'
activesupport (3.0.4) lib/active_support/notifications.rb:52:in `instrument'
actionpack (3.0.4) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.0.4) lib/action_controller/metal/rescue.rb:17:in `process_action'
actionpack (3.0.4) lib/abstract_controller/base.rb:119:in `process'
actionpack (3.0.4) lib/abstract_controller/rendering.rb:41:in `process'
actionpack (3.0.4) lib/action_controller/metal.rb:138:in `dispatch'
actionpack (3.0.4) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.0.4) lib/action_controller/metal.rb:178:in `action'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:62:in `call'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:62:in `dispatch'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:27:in `call'
actionpack (3.0.4) lib/action_dispatch/routing/mapper.rb:35:in `call'
rack-mount (0.6.13) lib/rack/mount/route_set.rb:148:in `call'
rack-mount (0.6.13) lib/rack/mount/code_generation.rb:93:in `recognize'
rack-mount (0.6.13) lib/rack/mount/code_generation.rb:89:in `optimized_each'
rack-mount (0.6.13) lib/rack/mount/code_generation.rb:92:in `recognize'
rack-mount (0.6.13) lib/rack/mount/route_set.rb:139:in `call'
actionpack (3.0.4) lib/action_dispatch/routing/route_set.rb:492:in `call'
warden (1.0.4) lib/warden/manager.rb:35:in `call'
warden (1.0.4) lib/warden/manager.rb:34:in `catch'
warden (1.0.4) lib/warden/manager.rb:34:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/head.rb:14:in `call'
rack (1.2.1) lib/rack/methodoverride.rb:24:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/flash.rb:182:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/session/abstract_store.rb:149:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/cookies.rb:302:in `call'
activerecord (3.0.4) lib/active_record/query_cache.rb:32:in `call'
activerecord (3.0.4) lib/active_record/connection_adapters/abstract/query_cache.rb:28:in `cache'
activerecord (3.0.4) lib/active_record/query_cache.rb:12:in `cache'
activerecord (3.0.4) lib/active_record/query_cache.rb:31:in `call'
activerecord (3.0.4) lib/active_record/connection_adapters/abstract/connection_pool.rb:354:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/callbacks.rb:46:in `call'
activesupport (3.0.4) lib/active_support/callbacks.rb:415:in `_run_call_callbacks'
actionpack (3.0.4) lib/action_dispatch/middleware/callbacks.rb:44:in `call'
rack (1.2.1) lib/rack/sendfile.rb:107:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/remote_ip.rb:48:in `call'
actionpack (3.0.4) lib/action_dispatch/middleware/show_exceptions.rb:47:in `call'
railties (3.0.4) lib/rails/rack/logger.rb:13:in `call'
rack (1.2.1) lib/rack/runtime.rb:17:in `call'
activesupport (3.0.4) lib/active_support/cache/strategy/local_cache.rb:72:in `call'

Why am I getting this error? How do I fix it?


问:
Having multiple themes with custom colors for Angular Material and custom components
I'd like to have a few themes in my app, but along with Angular Material themes I also want to define custom colors that are used by specific components and elements that aren't part of Angular Material. Whenever I change a theme those custom colors should be changed as well.
Let's say I have a file that defines colors for each theme, then I'd like to import it in an arbitrary scss file and utilize the colors to style some elements

```<code>@import "custom-colors"

.my-elem {
 color: $textColor;
}
</code>```

Then, if I need to change a theme I would apply a specific class to the outer most container of the app, and after this I'd like $textColor to have another value, so that color of the .my-elem would change.

Is there any way of doing this without writing something like

```<code>.another-theme {
 .my-elem {
   color: $textColorOfAnotherTheme;
 }
}
</code>```

In every component that should be affected by theme changing?

答:
There are 2 ways to change themes

  1. Adding parent class to your root component

  2. Changing file name (As angular material done)

1. You can add css with parent class (Example below)

```<code>.light {
 mat-form-field {
  color: white;
 }
 my-custom-element {
 color: white;
 }
}
.dark {
 mat-form-field {
  color: black;
 }
 my-custom-element {
  color: black;
 }
}
</code>```

and when user change theme, you can change class on your root element <app-component class="light">

There are various ways to do it: Having global varible, Using Event Emitter

2. Changing file names, same file without parent class will be divided into light.css and dark.css

and upon user changing theme, you can replace <link ref="stylesheet" href="light.css">

Angular way of doing this is, using Rendere 2 Set Attribute

Body:
I'd like to have a few themes in my app, but along with Angular Material themes I also want to define custom colors that are used by specific components and elements that aren't part of Angular Material. Whenever I change a theme those custom colors should be changed as well.
Let's say I have a file that defines colors for each theme, then I'd like to import it in an arbitrary scss file and utilize the colors to style some elements

@import "custom-colors"

.my-elem {
 color: $textColor;
}

Then, if I need to change a theme I would apply a specific class to the outer most container of the app, and after this I'd like $textColor to have another value, so that color of the .my-elem would change.

Is there any way of doing this without writing something like

.another-theme {
 .my-elem {
   color: $textColorOfAnotherTheme;
 }
}

In every component that should be affected by theme changing?

Body:
There are 2 ways to change themes

  1. Adding parent class to your root component

  2. Changing file name (As angular material done)

1. You can add css with parent class (Example below)

.light {
 mat-form-field {
  color: white;
 }
 my-custom-element {
 color: white;
 }
}
.dark {
 mat-form-field {
  color: black;
 }
 my-custom-element {
  color: black;
 }
}

and when user change theme, you can change class on your root element <app-component class="light">

There are various ways to do it: Having global varible, Using Event Emitter

2. Changing file names, same file without parent class will be divided into light.css and dark.css

and upon user changing theme, you can replace <link ref="stylesheet" href="light.css">

Angular way of doing this is, using Rendere 2 Set Attribute


问:
Regular expression to discard "
I have the next regular expression: /i18n(-?).*="(.*)"/g for javascript.

I use https://www.regextester.com to check.

```<code><button i18n="@@user.button" data-test="download-confirmation_ok">
<a i18n-href="@@link.url" href="https://www.aaaa.es" target="_blank">
<div i18n="@@link.text">www.aaaa.es</div>
</code>```

I don't like data-test="download-confirmation_ok" and href="https://www.aaaa.es" target="_blank":
https://imgur.com/sQZQXzZ

I only want i18n or i18n-* text between "TEXT".

How can I discard rest of the tetx?

Thank.

答:
What about using simply:

```<code>/i18n\S+/g
</code>```

It appears you only want the substring untill next space character, check this. This would however discard the last closing > at the first two strings.

Or if you want to grab text untill second " then maybe this:

```<code>/i18n[^"]+"[^"]+"/g
</code>```

Title: Regular expression to discard "

Body:
I have the next regular expression: /i18n(-?).*="(.*)"/g for javascript.

I use https://www.regextester.com to check.

<button i18n="@@user.button" data-test="download-confirmation_ok">

www.aaaa.es

I don't like data-test="download-confirmation_ok" and href="https://www.aaaa.es" target="_blank":
https://imgur.com/sQZQXzZ

I only want i18n or i18n-* text between "TEXT".

How can I discard rest of the tetx?

Thank.

Body:
What about using simply:

/i18n\S+/g

It appears you only want the substring untill next space character, check this. This would however discard the last closing > at the first two strings.

Or if you want to grab text untill second " then maybe this:

/i18n[^"]+"[^"]+"/g


问:
Creating an instance from another instance?
I'm so confused that how could it be written like this... It creates an instance from another instance

st.new FirstLevel();

```<code>    public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);

        ShadowTest.FirstLevel mali = st.new FirstLevel();
    }
}
</code>```

答:
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.ref.javaOO_nested

As per java syntaxes, unless it's a private or static class you could initialize it in the following way

```<code>class OuterClass {
    ...
    class InnerClass {
        ...
    }
}
</code>```

Then a sample initialisation can be done so:

```<code>OuterClass.InnerClass innerObject = outerObject.new InnerClass();
</code>```

NOTE: I have referred the block to the oracle java docs. You can read more there

Body:
I'm so confused that how could it be written like this... It creates an instance from another instance

st.new FirstLevel();

    public class ShadowTest {

    public int x = 0;

    class FirstLevel {

        public int x = 1;

        void methodInFirstLevel(int x) {
            System.out.println("x = " + x);
            System.out.println("this.x = " + this.x);
            System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
        }
    }

    public static void main(String... args) {
        ShadowTest st = new ShadowTest();
        ShadowTest.FirstLevel fl = st.new FirstLevel();
        fl.methodInFirstLevel(23);

        ShadowTest.FirstLevel mali = st.new FirstLevel();
    }
}

Body:
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.ref.javaOO_nested

As per java syntaxes, unless it's a private or static class you could initialize it in the following way

class OuterClass {
    ...
    class InnerClass {
        ...
    }
}

Then a sample initialisation can be done so:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

NOTE: I have referred the block to the oracle java docs. You can read more there


问:
How to drive the DDS Compiler IP core from Xilinx
I completed Anton Potočniks' introductory guide to the red pitaya board and I am now able to send commands from the linux machine running on the SoC to its FPGA logic.

I would like to further modify the project so that I can control the phase of the signal that is being transmitted via the red pitayas' DAC. Some pins (from 7 down to 1) of the first GPIO port were still unused so I started setting them from within the OS and used the red pitaya's LEDs to confirm that they were being set without interfering with the functionality of Anton Potočnik's "high bandwidth averager".

I then set the DDS_compilers' to Phase Offset Programmability to "streaming" mode so that it can be configured on the fly using the bits that are currently controling the red pitaya's LEDs. I used some slices to connect my signals to the AXI4-Stream Constant IP core, which in turn drives the DDS compiler.

Unfortunately the DAC is just giving me a constant output of 500 mV.

I created a new project with a  testbench for the DDS compiler, because synthesis takes a long time and doesn't give me much insight into what is happening.

Unfortunately all the output signals of the DDS compiler are undefined.

My question:

What am I doing wrong and how can I proceed to control DACs' phase?

EDIT1; here is my test bench

The IP core is configured as follows, so many of the control signals that I provided should not be required:

EDIT2; I changed declarations of the form m_axis_data_tready => '0' to m_axis_phase_tready => m_axis_phase_tready_signal. I also took a look at the wrapper file called dds_compiler_0.vhd and saw that it treats both m_axis_phase_tready and m_axis_data_tready as inputs.

My simulation results remained unchanged...

My new test bench can be found here.

EDIT3: Vivado was just giving me the old simulation results - creating a new testbench, deleting the file under <project_name>.sim/sim_1/behav/xsim/simulate.log and restarting vivado solved this problem.

I noticed that the wrapper file (dds_compiler_0.vhd) only has five ports:

aclk (in)

s_axis_phase_tvalid (in)

s_axis_phase_tdata (in)

m_axis_data_tvalid (out)

and m_axis_data_tdata (out)

So I removed all the unnecessary control signals and got a new simulation result, but I am still not recieving any useful output from the dds_compiler:

The corresponding testbench can be found here.

I also don't get any valid output when I include the control signals.

The corresponding testbench can be found here.

答: Looks like m_axis_data_tready is not connected. No data will come out unless that's asserted.</p>


问:
Loop over columns of dataframe in R
How can I loop to perform the same test over columns with similar names in R?

for example I have three columns, named col30, col126, col145. I was thinking something like:

```<code>x <- c(30, 126, 145)

for (i in x) {

  wilcox.test(col(i) ~ level)

}
</code>```

is not working and provide the following error:

Error in eval(predvars, data, env) : attempt to apply non-function

答:
You can use apply function instead of a for loop and iterate the same test for the selected columns:

apply(df[, c(col30, col126, col145)], 2, wilcox.test ~ level)

Title: Loop over columns of dataframe in R

Body:
How can I loop to perform the same test over columns with similar names in R?

for example I have three columns, named col30, col126, col145. I was thinking something like:

x <- c(30, 126, 145)

for (i in x) {

  wilcox.test(col(i) ~ level)

}

is not working and provide the following error:

Error in eval(predvars, data, env) : attempt to apply non-function


问:
WSO2 ESB get all transport headers
I want to get all transport headers in a sequence. I can get specific headers that I know the their names, but I want to get all of them including the ones that I do not know header names.

I find this question same, but there is no solution for our problem.
WSO2 ESB print all TRANSPORT_HEADERS

I tried also logging this

```<code><property name="TRANSPORT_HEADERS" action="set" scope="axis2"/>
</code>```

but I got nothing in WSO2 logs.

WSO2 version 6.4.0

Thanks for any idea!

答:
I have enabled wire logs in log4j.properties and restarted the server and It works fine for me.
I am using esb 4.9 version.

```<code>log4j.logger.org.apache.synapse.transport.http.headers=DEBUG
log4j.logger.org.apache.synapse.transport.http.wire=DEBUG
</code>```

Title: WSO2 ESB get all transport headers

Body:
I want to get all transport headers in a sequence. I can get specific headers that I know the their names, but I want to get all of them including the ones that I do not know header names.

I find this question same, but there is no solution for our problem.
WSO2 ESB print all TRANSPORT_HEADERS

I tried also logging this

<property name="TRANSPORT_HEADERS" action="set" scope="axis2"/>

but I got nothing in WSO2 logs.

WSO2 version 6.4.0

Thanks for any idea!

Body:
I have enabled wire logs in log4j.properties and restarted the server and It works fine for me.
I am using esb 4.9 version.

log4j.logger.org.apache.synapse.transport.http.headers=DEBUG
log4j.logger.org.apache.synapse.transport.http.wire=DEBUG


问:
Pystache without escaping (unescaped)
I'm using pystache to render the templates. I'm getting & in the output when I render context variables having &. How can get rid of & where I need & .
Same thing is happening with django templating as well

```<code>>>> pystache.render('The URL {{URL}}', {'URL': 'http://google.com?a=3&b=3'})
u'The URL http://google.com?a=3&b=3'
</code>```

答:
A long time ago they've got such suggestion.

There is auxillary escape option of Renderer class initializer. This option accepts function that operates on strings. Default is cgi.escape(s, quote=True).

So when you write:

```<code>import pystache
rend = pystache.Rendered(escape=lambda s: s)
rend.render(your_obj)
</code>```

you've got unascaped values without tripple braces in template.

See docs on Rendered class

Title: Pystache without escaping (unescaped)

Body:
I'm using pystache to render the templates. I'm getting & in the output when I render context variables having &. How can get rid of & where I need & .
Same thing is happening with django templating as well

>>> pystache.render('The URL {{URL}}', {'URL': 'http://google.com?a=3&b=3'})
u'The URL http://google.com?a=3&b=3'

Body:
A long time ago they've got such suggestion.

There is auxillary escape option of Renderer class initializer. This option accepts function that operates on strings. Default is cgi.escape(s, quote=True).

So when you write:

import pystache
rend = pystache.Rendered(escape=lambda s: s)
rend.render(your_obj)

you've got unascaped values without tripple braces in template.

See docs on Rendered class


问:
CSS Flip effect with different heights
I've created a book slider where ech side takes 50% of width. For mobile the direction of the pages changes so that they are above eachother instead of next to each other. I need different heights for the pages. Images should be 30-40% and the content about 60-70% in height. The Flip effect crashes at this point. I guess it's because the height is changing as soon as the class is given. However it looks kind of weird. Could anybody help me to make it look like a page that actually flips down?

```<code>class BookSlider extends React.Component {
 constructor(props) {
  super(props);
  this.state = {slideCount: 0, slider: []};
  this.handleClick = this.handleClick.bind(this);
  this.resolveClassNames = this.resolveClassNames.bind(this);
}

componentDidMount() {
  let _this = this;
  let count = this.state.slideCount;
  // create slider elements
  const slider = [];
  let initialContent = [];

  this.props.content.map((obj) => {
   if (obj.slideNo === 1) {
    initialContent.push(obj);
   }
 })
 slider.push({content: initialContent, slideNo: 1});

this.props.images.map((img) => {
  let contents = [];
  this.props.content.map((obj) => {
    if (img.slideNo + 1 === obj.slideNo) {
      contents.push(obj);
    }
  })
    const slide = {
      img: img.img,
      slideNo: img.slideNo,
      content: contents
    }
    slider.push(slide)
  })
  this.setState({slider})
}

handleClick(type) {
  if (type === 'next') {
    $(`#slide-${this.state.slideCount}`).next().addClass("flipped");
    $(`#slide-${this.state.slideCount + 2}`).addClass("active");
    $('.active').next().addClass('active-mute');
    this.setState({slideCount:  this.state.slideCount < (this.props.images.length - 1) ?
    this.state.slideCount + 1 : 0});
  }
  if (type === 'prev') {
   $(`#slide-${this.state.slideCount - 1}`).next().removeClass("flipped");
   this.setState({slideCount: this.state.slideCount - 1 >= 0 ? this.state.slideCount - 1 :
   this.props.images.length - 1});
  }
}

resolveClassNames(slideNo) {
  const { slideCount, slider } = this.state;
  if (slideCount === slideNo - 1) {
    return 'page active'
  }
  else if (slideCount - 1 === slideNo) {
    return 'page flipped active-mute';
  }
  else if (slideCount - 1 <= 0 && slideNo === (slider.length -1 )) {
    return 'page flipped active-mute';
  }
  else if (slideCount === slideNo && (slideCount < slider.length || slideCount === 0 && slideNo ===
  slideCount)) {
  return 'page flipped active';
}
else if (slideCount - 1 === slideNo && slideCount - 1 < 0 && (slideNo === (slider.length - 1))) {
  return 'page flipped active';
}
else if (slideCount + 2 === slideNo && slideCount + 2 <= (slider.length - 1)) {
  return 'page active-mute';
}
else if (slideCount + 2 > slideNo && (slideCount + 2) - (slider.length) === slideNo) {
  return 'page active-mute';
}
else {
  return 'page';
}
}

render() {
const { slider } = this.state;
return (
  <section
    className="partial-book-slider"
    >
    <div className="container-fluid">
      <div className="row">
        <div className="col-12 col-md-10 offset-md-1">
          <div
            className='partial-book'
            data-aos="fade-up"
            data-aos-once="true"
            >
            <div className="book-bg-left bg-primary">
              <div className="content-wrap">
                <div className='content h-100 d-flex justify-content-around flex-column'>
                  {slider[slider.length - 2] && slider[slider.length - 2].content && slider[slider.length - 2].content.map((obj, i) => {
                    const k = `slide_content_${i}`;
                    return (
                      <div  key={k} className="container-fluid">
                        <div className="row">
                          <div className="col-2 pr-0">
                            <div>
                              <img className="mw-100 text-white" src={obj.media.url}/>
                            </div>
                          </div>
                          <div className="col-10">
                            <div className="text-white font-weight-bold">{obj.title}</div>
                            <p>{obj.description}</p>
                          </div>
                        </div>
                      </div>
                    )
                  })}
                </div>
              </div>
            </div>
            {slider[1] && slider[1].img && (
              <div className="book-bg-right">
                <div className="img-wrap" style={{'background-image': `url("${slider[1].img.url}")`}} />
              </div>
            )}
            {slider.map((slide, index) => {
              const key = `slide-${index}`;
              return (
                <div key={key} id={key} className={this.resolveClassNames(index)}>
                  <div className="content-wrap">
                    <div className='content h-100 d-flex justify-content-around flex-column'>
                      {slide.content && slide.content.map((obj, i) => {
                        const k = `slide_${index}_content_${i}`;
                        return (
                          <div  key={k} className="container-fluid">
                            <div className="row">
                              <div className="col-2 pr-0">
                                <div>
                                  <img className="mw-100 text-white" src={`${obj.media.url}`}/>
                                </div>
                              </div>
                              <div className="col-10">
                                <div className="text-white font-weight-bold">{obj.title}</div>
                                <p>{obj.description}</p>
                              </div>
                            </div>
                          </div>
                        )
                      })}
                    </div>
                  </div>
                  {slide.img && (
                    <div className="img-wrap" style={{'background-image': `url("${slide.img.url}")`}} />
                  )}
                </div>
              )
            })}
          </div>
          <div className="text-center my-4 slider-controls">
            <button id="prev" onClick={(e) => this.handleClick('prev')}>
              PREV
            </button>
            <button id="next" onClick={(e) => this.handleClick('next')}>
              NEXT
            </button>
          </div>
        </div>
      </div>
    </div>
  </section>
);
</code>```

}
}

Here's my CodePen look at < 600px (mobile).

https://codepen.io/mblmarlon/pen/poJoVzx?editors=0110

答: Found a solution -> remove "transform-style: preserve-3d;"</p>

Title: CSS Flip effect with different heights

Body:
I've created a book slider where ech side takes 50% of width. For mobile the direction of the pages changes so that they are above eachother instead of next to each other. I need different heights for the pages. Images should be 30-40% and the content about 60-70% in height. The Flip effect crashes at this point. I guess it's because the height is changing as soon as the class is given. However it looks kind of weird. Could anybody help me to make it look like a page that actually flips down?

class BookSlider extends React.Component {
 constructor(props) {
  super(props);
  this.state = {slideCount: 0, slider: []};
  this.handleClick = this.handleClick.bind(this);
  this.resolveClassNames = this.resolveClassNames.bind(this);
}

componentDidMount() {
  let _this = this;
  let count = this.state.slideCount;
  // create slider elements
  const slider = [];
  let initialContent = [];

  this.props.content.map((obj) => {
   if (obj.slideNo === 1) {
    initialContent.push(obj);
   }
 })
 slider.push({content: initialContent, slideNo: 1});

this.props.images.map((img) => {
  let contents = [];
  this.props.content.map((obj) => {
    if (img.slideNo + 1 === obj.slideNo) {
      contents.push(obj);
    }
  })
    const slide = {
      img: img.img,
      slideNo: img.slideNo,
      content: contents
    }
    slider.push(slide)
  })
  this.setState({slider})
}

handleClick(type) {
  if (type === 'next') {
    $(`#slide-${this.state.slideCount}`).next().addClass("flipped");
    $(`#slide-${this.state.slideCount + 2}`).addClass("active");
    $('.active').next().addClass('active-mute');
    this.setState({slideCount:  this.state.slideCount < (this.props.images.length - 1) ?
    this.state.slideCount + 1 : 0});
  }
  if (type === 'prev') {
   $(`#slide-${this.state.slideCount - 1}`).next().removeClass("flipped");
   this.setState({slideCount: this.state.slideCount - 1 >= 0 ? this.state.slideCount - 1 :
   this.props.images.length - 1});
  }
}

resolveClassNames(slideNo) {
  const { slideCount, slider } = this.state;
  if (slideCount === slideNo - 1) {
    return 'page active'
  }
  else if (slideCount - 1 === slideNo) {
    return 'page flipped active-mute';
  }
  else if (slideCount - 1 <= 0 && slideNo === (slider.length -1 )) {
    return 'page flipped active-mute';
  }
  else if (slideCount === slideNo && (slideCount < slider.length || slideCount === 0 && slideNo ===
  slideCount)) {
  return 'page flipped active';
}
else if (slideCount - 1 === slideNo && slideCount - 1 < 0 && (slideNo === (slider.length - 1))) {
  return 'page flipped active';
}
else if (slideCount + 2 === slideNo && slideCount + 2 <= (slider.length - 1)) {
  return 'page active-mute';
}
else if (slideCount + 2 > slideNo && (slideCount + 2) - (slider.length) === slideNo) {
  return 'page active-mute';
}
else {
  return 'page';
}
}

render() {
const { slider } = this.state;
return (

                  {slider[slider.length - 2] && slider[slider.length - 2].content && slider[slider.length - 2].content.map((obj, i) => {
                    const k = `slide_content_${i}`;
                    return (

{obj.title}

{obj.description}

                    )
                  })}

            {slider[1] && slider[1].img && (

                <div className="img-wrap" style={{'background-image': `url("${slider[1].img.url}")`}} />

            )}
            {slider.map((slide, index) => {
              const key = `slide-${index}`;
              return (

                      {slide.content && slide.content.map((obj, i) => {
                        const k = `slide_${index}_content_${i}`;
                        return (

                                  <img className="mw-100 text-white" src={`${obj.media.url}`}/>

{obj.title}

{obj.description}

                        )
                      })}

                  {slide.img && (
                    <div className="img-wrap" style={{'background-image': `url("${slide.img.url}")`}} />
                  )}

              )
            })}

            <button id="prev" onClick={(e) => this.handleClick('prev')}>
              PREV
            </button>
            <button id="next" onClick={(e) => this.handleClick('next')}>
              NEXT
            </button>

);

}
}

Here's my CodePen look at < 600px (mobile).

https://codepen.io/mblmarlon/pen/poJoVzx?editors=0110


问:
reactjs service worker update
I have a PWA made by create-react-app.
I have service worker enabled as by default.

```<code>import registerServiceWorker from './registerServiceWorker'
import App from './App'
ReactDOM.render(
  <App />
  , document.getElementById('root'))
registerServiceWorker()
</code>```

On every publish I change package version, but my service-worker doesn't update.

I have tried with function

```<code>import { unregister } from './registerServiceWorker';
unregister()
</code>```

as described here https://github.com/facebook/create-react-app

And this

```<code>navigator.serviceWorker.getRegistrations()
  .then(registrationsArray => {
    if (registrationsArray.length > 0) {
        registrationsArray[0].update()
    }
  })
</code>```

It doesn't work, what is my mistake? What is wrong?
Thanks

答:
Update to react-scripts ^3.2.0.  Verify that you have the new version of serviceWorker.ts or .js.  The old one was called registerServiceWorker.ts and the register function did not accept a configuration object.  Here is the new one:  https://github.com/facebook/create-react-app/blob/3190e4f4a99b8c54acb0993d92fec8a859889a28/packages/cra-template/template/src/serviceWorker.js
Note that this solution only works well if you are Not lazy-loading.

then in index.tsx:

```<code>  serviceWorker.register({
    onUpdate: registration => {
      alert('New version available!  Ready to update?');
      if (registration && registration.waiting) {
        registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      }
      window.location.reload();
    }
  });
</code>```

The latest version of the ServiceWorker.ts register()function accepts a config object with a callback function where we can handle upgrading.  If we post a message SKIP_WAITING this tells the service worker to stop waiting and to go ahead and load the new content after the next refresh.  In this example I am using a javascript alert to inform the user.  Please replace this with a custom toast.

The reason this postMessage function works is because under the hood CRA is using workbox-webpack-plugin which includes a SKIP_WAITING listener.

More About Service Workers

good guide: https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68

CRA issue discussing service worker cache:  https://github.com/facebook/create-react-app/issues/5316

If you are not using CRA, you can use workbox directly: https://developers.google.com/web/tools/workbox

Title: reactjs service worker update

Body:
I have a PWA made by create-react-app.
I have service worker enabled as by default.

import registerServiceWorker from './registerServiceWorker'
import App from './App'
ReactDOM.render(
  <App />
  , document.getElementById('root'))
registerServiceWorker()

On every publish I change package version, but my service-worker doesn't update.

I have tried with function

import { unregister } from './registerServiceWorker';
unregister()

as described here https://github.com/facebook/create-react-app

And this

navigator.serviceWorker.getRegistrations()
  .then(registrationsArray => {
    if (registrationsArray.length > 0) {
        registrationsArray[0].update()
    }
  })

It doesn't work, what is my mistake? What is wrong?
Thanks

Body:
Update to react-scripts ^3.2.0.  Verify that you have the new version of serviceWorker.ts or .js.  The old one was called registerServiceWorker.ts and the register function did not accept a configuration object.  Here is the new one:  https://github.com/facebook/create-react-app/blob/3190e4f4a99b8c54acb0993d92fec8a859889a28/packages/cra-template/template/src/serviceWorker.js
Note that this solution only works well if you are Not lazy-loading.

then in index.tsx:

  serviceWorker.register({
    onUpdate: registration => {
      alert('New version available!  Ready to update?');
      if (registration && registration.waiting) {
        registration.waiting.postMessage({ type: 'SKIP_WAITING' });
      }
      window.location.reload();
    }
  });

The latest version of the ServiceWorker.ts register()function accepts a config object with a callback function where we can handle upgrading.  If we post a message SKIP_WAITING this tells the service worker to stop waiting and to go ahead and load the new content after the next refresh.  In this example I am using a javascript alert to inform the user.  Please replace this with a custom toast.

The reason this postMessage function works is because under the hood CRA is using workbox-webpack-plugin which includes a SKIP_WAITING listener.

More About Service Workers

good guide: https://redfin.engineering/how-to-fix-the-refresh-button-when-using-service-workers-a8e27af6df68

CRA issue discussing service worker cache:  https://github.com/facebook/create-react-app/issues/5316

If you are not using CRA, you can use workbox directly: https://developers.google.com/web/tools/workbox


问:
C++, entering strings or chars in int arrays outputs 0 instead of ascii or error
I have been testing this piece of code on visual studio c++.

Curiously the output if I enter any character first, the program stops and outputs 0, I was expecting the ASCII code or an error but I 0 instead. What is the reason for that?

```<code>int x[10];  int s;
    cin >> s;

    for (int i = 0; i < s; i++){
        cin >> x[i];
    }
    cout << x[0];
</code>```

答:
You should check if the read was successful:</p>

```<code>int x[10];  int s;
if (!(cin >> s)) {
    cout << "Read failed\n";
    return;
}

int i = 0;
for (; i < s && cin >> x[i]; i++){
}
cout << "successful reads: " << i << '\n';
if (i > 0) {
    cout << x[0];
}
</code>```

Body:
I have been testing this piece of code on visual studio c++.

Curiously the output if I enter any character first, the program stops and outputs 0, I was expecting the ASCII code or an error but I 0 instead. What is the reason for that?

int x[10];  int s;
    cin >> s;

    for (int i = 0; i < s; i++){
        cin >> x[i];
    }
    cout << x[0];

Body:
You should check if the read was successful:

int x[10];  int s;
if (!(cin >> s)) {
    cout << "Read failed\n";
    return;
}

int i = 0;
for (; i < s && cin >> x[i]; i++){
}
cout << "successful reads: " << i << '\n';
if (i > 0) {
    cout << x[0];
}


答:
Here, FirstLevel is a so-called inner class – that's because it is defined inside another class. Both relations (the 'outer' and the 'inner') are plain jane classes (and not interfaces, enums, or records). In this case, unless the inner class has the modifier static on it (and, in your code, it doesn't), then you get an instance inner class.

Such classes have a hidden field of the outer type associated with them. It is as if your FirstLevel class has this field:

```<code>private final ShadowTest outerInstance;
</code>```

And each and every constructor of ShadowTest has a parameter for this field, but, it is hidden and a bit special.

Because this secret field exists, you can do things like invoke non-static methods from ShadowTest from within FirstLevel.

If you type new FirstLevel(), that just works... but only within non-static contexts inside ShadowTest. Anywhere else and the compiler will tell you that it doesn't know what instance of ShadowTest to pass along for that secret field. You can explicitly define which instance of ShadowTest. But not with new FirstLevel(shadowTestInstance), but with the somewhat weird-looking syntax shadowTestInstance.new FirstLevel(). But, it's the same thing: A parameter being passed to a constructor.

I generally advise that you do not use instance inner classes unless you really know they are the best fit for the case; this hidden field tends to cause confusion and surprises. I'd go so far as to say that you should never have instance inner classes; if you must hold a reference to an instance of the outer class, make it explicit (add an actual field, and make an actual parameter in your constructor). That way you avoid the surprises and confusion, at least. In other words, mark your FirstLevel class as static. By making your outer reference explicit, the shadowing thing also goes away; now you just have x or this.x referring to the x field in FirstLevel, and outerInstance.x for the outer field:

```<code>static class FirstLevel {
    final ShadowTest shadow;
    int x;

    public FirstLevel(ShadowTest shadow) { this.shadow = shadow; }
}
</code>```

Title: Creating an instance from another instance?

Body:
Here, FirstLevel is a so-called inner class – that's because it is defined inside another class. Both relations (the 'outer' and the 'inner') are plain jane classes (and not interfaces, enums, or records). In this case, unless the inner class has the modifier static on it (and, in your code, it doesn't), then you get an instance inner class.

Such classes have a hidden field of the outer type associated with them. It is as if your FirstLevel class has this field:

private final ShadowTest outerInstance;

And each and every constructor of ShadowTest has a parameter for this field, but, it is hidden and a bit special.

Because this secret field exists, you can do things like invoke non-static methods from ShadowTest from within FirstLevel.

If you type new FirstLevel(), that just works... but only within non-static contexts inside ShadowTest. Anywhere else and the compiler will tell you that it doesn't know what instance of ShadowTest to pass along for that secret field. You can explicitly define which instance of ShadowTest. But not with new FirstLevel(shadowTestInstance), but with the somewhat weird-looking syntax shadowTestInstance.new FirstLevel(). But, it's the same thing: A parameter being passed to a constructor.

I generally advise that you do not use instance inner classes unless you really know they are the best fit for the case; this hidden field tends to cause confusion and surprises. I'd go so far as to say that you should never have instance inner classes; if you must hold a reference to an instance of the outer class, make it explicit (add an actual field, and make an actual parameter in your constructor). That way you avoid the surprises and confusion, at least. In other words, mark your FirstLevel class as static. By making your outer reference explicit, the shadowing thing also goes away; now you just have x or this.x referring to the x field in FirstLevel, and outerInstance.x for the outer field:

static class FirstLevel {
    final ShadowTest shadow;
    int x;

    public FirstLevel(ShadowTest shadow) { this.shadow = shadow; }
}


问:
Send keys in selenium webdriver with javascript
I can't seem to get the sendKeys function to work. I am using selenium webdriver, and js to send keys. any help would be appreciated.

```<code>it("Apply text input", async function() {
await dashboardPage.run();

let inputs = await dashboardPage.componentsByClass('ace-content');
// identify the Element to put text into

for (let i in inputs){
  console.log(await results[i].sendKeys("https://www.google.com",Key.RETURN);    }
  await driver.sleep(4000);
});
</code>```

答:
Remove console.log. Send Keys  two times.

```<code>element.sendKeys("https://www.google.com")
element.sendKeys(driver.Key.ENTER)
</code>```

Body:
I can't seem to get the sendKeys function to work. I am using selenium webdriver, and js to send keys. any help would be appreciated.

it("Apply text input", async function() {
await dashboardPage.run();

let inputs = await dashboardPage.componentsByClass('ace-content');
// identify the Element to put text into

for (let i in inputs){
  console.log(await results[i].sendKeys("https://www.google.com",Key.RETURN);    }
  await driver.sleep(4000);
});

Body:
Remove console.log. Send Keys  two times.

element.sendKeys("https://www.google.com")
element.sendKeys(driver.Key.ENTER)


问:
Using Linq to iterate groups and change property with condition
I want to iterate through each group and set "IsQualified= true" for only first student whose "University= OPQ". (Example: Emity in Group 2, Jacob in Group 3, White in Group 5)

What I tried

```<code>        var results= StudentsList
            .GroupBy(x => x.GroupID)
            .Where(x => x.Any(y => y.University == "OPQ"))
            .FirstOrDefault
            .ToList();

      results.ForEach(x => x.IsQualified = true);

      foreach(var item in results){if (item.IsQualified== true){
      Console.WriteLine("Group " + item.GroupID + " , " + item.Student);}}
</code>```

This does completely the opposite. I change "IsQualified=True" for all items in the 1st group! That's not what I want.

My Code:

```<code>List<StudentInfo> StudentsList = new List<StudentInfo>();

// Group 1
StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="John", University="abc", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="Jack", University="def", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Peter", University="abc", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", GroupID = 1, IsQualified=false} );

// Group 2
StudentsList.Add( new StudentInfo { Student="Donald", University="def", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", GroupID = 2, IsQualified=false} );

// Group 3
StudentsList.Add( new StudentInfo { Student="Adam", University="yub", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Saint", University="abc", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", GroupID = 3, IsQualified=false} );

// Group 4
StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", GroupID = 4, IsQualified=false} );

// Group 5
StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", GroupID = 5, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="White", University="OPQ", GroupID = 5, IsQualified=false} );
</code>```

答:
Demo on dotnet fiddle

You should adjust Where clause to filter before grouping.

You can get the first item for each group by using First() instead of FirstOrDefault(). Simply because the Where clause has already filtered to make sure that each group will have at least one item.

In terms of Performance, According to @Çöđěxěŕ's comment, Instead of iterating through the LINQ results (to update), You just update records on the fly as part of the query. It means no need for this code results.ForEach(x => x.IsQualified = true); anymore.

```<code>    var results = StudentsList
            .Where(x => x.University == "OPQ")
            .GroupBy(x => x.GroupID)
            .Select(g =>
                    {
                        var firstItem = g.First();
                        firstItem.IsQualified = true;

                        return firstItem;
                    }).ToList();
</code>```

Body:
I want to iterate through each group and set "IsQualified= true" for only first student whose "University= OPQ". (Example: Emity in Group 2, Jacob in Group 3, White in Group 5)

What I tried

        var results= StudentsList
            .GroupBy(x => x.GroupID)
            .Where(x => x.Any(y => y.University == "OPQ"))
            .FirstOrDefault
            .ToList();

      results.ForEach(x => x.IsQualified = true);

      foreach(var item in results){if (item.IsQualified== true){
      Console.WriteLine("Group " + item.GroupID + " , " + item.Student);}}

This does completely the opposite. I change "IsQualified=True" for all items in the 1st group! That's not what I want.

My Code:

List<StudentInfo> StudentsList = new List<StudentInfo>();

// Group 1
StudentsList.Add( new StudentInfo { Student="Gungun", University="cdf", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="John", University="abc", GroupID = 1, IsQualified=false});
StudentsList.Add( new StudentInfo { Student="Jack", University="def", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Peter", University="abc", GroupID = 1, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Lemity", University="abc", GroupID = 1, IsQualified=false} );

// Group 2
StudentsList.Add( new StudentInfo { Student="Donald", University="def", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Olivia", University="ggh", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emity", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Emma", University="OPQ", GroupID = 2, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alan", University="OPQ", GroupID = 2, IsQualified=false} );

// Group 3
StudentsList.Add( new StudentInfo { Student="Adam", University="yub", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Jacob", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Matthew", University="OPQ", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Saint", University="abc", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Joshua", University="qer", GroupID = 3, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Aubrey", University="fef", GroupID = 3, IsQualified=false} );

// Group 4
StudentsList.Add( new StudentInfo { Student="Caleb", University="DEF", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Anna", University="ABC", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Chill", University="GHI", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Alexis", University="JKL", GroupID = 4, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="Zoe", University="MNO", GroupID = 4, IsQualified=false} );

// Group 5
StudentsList.Add( new StudentInfo { Student="Dylan", University="PQR", GroupID = 5, IsQualified=false} );
StudentsList.Add( new StudentInfo { Student="White", University="OPQ", GroupID = 5, IsQualified=false} );

Body:
Demo on dotnet fiddle

You should adjust Where clause to filter before grouping.

You can get the first item for each group by using First() instead of FirstOrDefault(). Simply because the Where clause has already filtered to make sure that each group will have at least one item.

In terms of Performance, According to @Çöđěxěŕ's comment, Instead of iterating through the LINQ results (to update), You just update records on the fly as part of the query. It means no need for this code results.ForEach(x => x.IsQualified = true); anymore.

    var results = StudentsList
            .Where(x => x.University == "OPQ")
            .GroupBy(x => x.GroupID)
            .Select(g =>
                    {
                        var firstItem = g.First();
                        firstItem.IsQualified = true;

                        return firstItem;
                    }).ToList();


问:
How do I fix CORS issue when using Ionicons from CDN?
I have set up a very basic web project with the following files:

index.html

styles.css

scripts.js

I have included the following line in the head of my html file:

```<code><link href="https://unpkg.com/ionicons@4.5.10-0/dist/css/ionicons.min.css" rel="stylesheet">
</code>```

I am using the icons like so in my html file:

```<code><i class="icon ion-md-menu"></i>
</code>```

The icon was displaying properly but now i am receiving a CORS error when previewing the project.

Access to font at 'https://unpkg.com/ionicons@4.5.10-0/dist/fonts/ionicons.woff2?v=4.5.9-1' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Not sure why i am receiving the error now when it was working just fine before.  Any ideas how to fix this issue?  Thanks.

答: it seems to be unpkg issue to inject those url so when I moved to cloudfare cdn that resolve the issue, https://cdnjs.com/libraries/ionicons</p>

Body:
I have set up a very basic web project with the following files:

index.html

styles.css

scripts.js

I have included the following line in the head of my html file:

<link href="https://unpkg.com/ionicons@4.5.10-0/dist/css/ionicons.min.css" rel="stylesheet">

I am using the icons like so in my html file:

The icon was displaying properly but now i am receiving a CORS error when previewing the project.

Access to font at 'https://unpkg.com/ionicons@4.5.10-0/dist/fonts/ionicons.woff2?v=4.5.9-1' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Not sure why i am receiving the error now when it was working just fine before.  Any ideas how to fix this issue?  Thanks.


问:
How to negate specific word in regex?
I know that I can negate group of chars as in [^bar] but I need a regular expression where negation applies to the specific word - so in my example how do I negate an actual bar, and not "any chars in bar"?

答:
If it's truly a word, bar that you don't want to match, then:

```<code>^(?!.*\bbar\b).*$
</code>```

The above will match any string that does not contain bar that is on a word boundary, that is to say, separated from non-word characters. However, the period/dot (.) used in the above pattern will not match newline characters unless the correct regex flag is used:

```<code>^(?s)(?!.*\bbar\b).*$
</code>```

Alternatively:

```<code>^(?!.*\bbar\b)[\s\S]*$
</code>```

Instead of using any special flag, we are looking for any character that is either white space or non-white space. That should cover every character.

But what if we would like to match words that might contain bar, but just not the specific word bar?

```<code>(?!\bbar\b)\b\[A-Za-z-]*bar[a-z-]*\b
</code>```

(?!\bbar\b) Assert that the next input is not bar on a word boundary.

\b\[A-Za-z-]*bar[a-z-]*\b Matches any word on a word boundary that contains bar.

See Regex Demo

Title: How to negate specific word in regex?

Body:
If it's truly a word, bar that you don't want to match, then:

^(?!.*\bbar\b).*$

The above will match any string that does not contain bar that is on a word boundary, that is to say, separated from non-word characters. However, the period/dot (.) used in the above pattern will not match newline characters unless the correct regex flag is used:

^(?s)(?!.*\bbar\b).*$

Alternatively:

^(?!.*\bbar\b)[\s\S]*$

Instead of using any special flag, we are looking for any character that is either white space or non-white space. That should cover every character.

But what if we would like to match words that might contain bar, but just not the specific word bar?

(?!\bbar\b)\b\[A-Za-z-]*bar[a-z-]*\b

(?!\bbar\b) Assert that the next input is not bar on a word boundary.

\b\[A-Za-z-]*bar[a-z-]*\b Matches any word on a word boundary that contains bar.

See Regex Demo


问:
Check how many of the same chars line op in list
I have a python list,

```<code>l=[0,1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
</code>```

for example,
I want to check if the list contain at least 7 1's next to each other.

I'm not sure how to check this.

to clarify:

```<code>a=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ] #should return True
b=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 ] #should return False
</code>```

Any ideas?

答:
A very simple way is concatenating the list into a string and check if the 1... are there like this:

l_true = [0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ] #should return True
l_false = [0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 ] #should return False

check = lambda x: '1'*7 in ''.join(str(num) for num in x)

print(check(l_true))
>>> True
print(check(l_false))
>>> False
```

Body:
I have a python list,

l=[0,1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]

for example,
I want to check if the list contain at least 7 1's next to each other.

I'm not sure how to check this.

to clarify:

a=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0 ] #should return True
b=[0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0 ] #should return False

Any ideas?


问:
Alternatives to std::array for objects of different types in C++11
I am looking for better solutions on how to organize and access my data.
My data is a set of structures (_array_10 and _array_20 in the example below) that contain std::array of different sizes (see my_data below).
Ideally, I would like to access it as it was an array of structs with different lengths, but this is not allowed, since different lengths are different types.
The solution I have below works, but I find it extremely ugly (specially the array of void *).

Q1. Any ideas on how to have a safer, more efficient/portable, or at least less ugly solution?

Q2. Is the proposed solution without templates portable? It relies on the fact that the length is stored before the rest of the data, since casting the pointer to an object with wrong length would mess the access to all fields that come after the first field of variable length.

My limitations include:

C++11

standard libraries

no std::vector

memory usage prevents me from being able to simply allocate an array of my_data with the maximum possible length

the bulk of the data (_array_10, _array_20, etc) will be placed in a memory area reserved specially for it

Using data_view and template require knowledge of the length of the arrays in build time. It would be great if we could avoid it.

Question edited to include the solution proposed by Guillaume Racicot

```<code>#include <iostream>
#include <array>

std::array<void *, 2> _ptrs;

template <int length>
struct my_data
{
    int                     array_length;
    std::array<int, length> something;
    std::array<int, length> data;
    my_data()
    {
        array_length = length;
    }
};

struct my_data_view
{
    int         array_length;
    const int * something;
    const int * data;

    template <int length>
    my_data_view(my_data<length> const & data_in) :
        array_length(length),
        something(data_in.something.data()),
        data(data_in.data.data())
    {}
};

template <int length>
void
print_element(int array_idx, int element)
{
    my_data<length> * ptr = reinterpret_cast<my_data<length> *>(_ptrs[array_idx]);

    std::cout << "array " << length << ", data[" << element << "] = " << ptr->data[element] << ".\n";
}

void
print_element(int array_idx, int element)
{
    my_data<1> * ptr    = reinterpret_cast<my_data<1> *>(_ptrs[array_idx]);
    int          length = ptr->array_length;

    int data_to_print = 0;
    switch (length)
    {
        case 10:
        {
            data_to_print = reinterpret_cast<my_data<10> *>(_ptrs[array_idx])->data[element];
            break;
        }
        case 20:
        {
            data_to_print = reinterpret_cast<my_data<20> *>(_ptrs[array_idx])->data[element];
            break;
        }
    }
    std::cout << "array " << length << ", data[" << element << "] = " << data_to_print << ".\n";
}

void
print_element(my_data_view view, int element)
{
    int length        = view.array_length;
    int data_to_print = view.data[element];

    std::cout << "array " << length << ", data[" << element << "] = " << data_to_print << ".\n";
}

int
main()
{
    my_data<10> _array_10;
    my_data<20> _array_20;

    _ptrs[0] = static_cast<void *>(&_array_10);
    _ptrs[1] = static_cast<void *>(&_array_20);

    _array_10.data[5] = 11;
    _array_20.data[5] = 22;

    std::cout << "using template\n";
    print_element<10>(0, 5);
    print_element<20>(1, 5);

    std::cout << "\nwithout template\n";
    print_element(0, 5);
    print_element(1, 5);

    std::cout << "\nusing data_view\n";
    print_element(my_data_view(_array_10), 5);
    print_element(my_data_view(_array_20), 5);
}
</code>```

答:
You could create a dynamic view class that don't allocate:

```<code>struct my_data_view
{
    int array_length;
    std::span<int> something;
    std::span<int> data;

    template<int length>
    my_data_view(my_data<length> const& data) :
        array_length{length}, something{data.something}, data{data.data}
    {}
};
</code>```

Spans simply are a pointer and a size. If you don't have access to std::span (which is from C++20) you can simply replace those member with int* and use array_length for the size.

This my_data_view type is used like that:

```<code>void
print_element(my_data_view view, int element)
{
    int length = view.array_length;
    int data_to_print = view.data[element];

    std::cout << "array " << length << ", data[" << element << "] = " << data_to_print << ".\n";
}
</code>```

This is the code that will work both with std::span and simple int*.

Body:
I am looking for better solutions on how to organize and access my data.
My data is a set of structures (_array_10 and _array_20 in the example below) that contain std::array of different sizes (see my_data below).
Ideally, I would like to access it as it was an array of structs with different lengths, but this is not allowed, since different lengths are different types.
The solution I have below works, but I find it extremely ugly (specially the array of void *).

Q1. Any ideas on how to have a safer, more efficient/portable, or at least less ugly solution?

Q2. Is the proposed solution without templates portable? It relies on the fact that the length is stored before the rest of the data, since casting the pointer to an object with wrong length would mess the access to all fields that come after the first field of variable length.

My limitations include:

C++11

standard libraries

no std::vector

memory usage prevents me from being able to simply allocate an array of my_data with the maximum possible length

the bulk of the data (_array_10, _array_20, etc) will be placed in a memory area reserved specially for it

Using data_view and template require knowledge of the length of the arrays in build time. It would be great if we could avoid it.

Question edited to include the solution proposed by Guillaume Racicot

#include <iostream>
#include <array>

std::array<void *, 2> _ptrs;

template <int length>
struct my_data
{
    int                     array_length;
    std::array<int, length> something;
    std::array<int, length> data;
    my_data()
    {
        array_length = length;
    }
};

struct my_data_view
{
    int         array_length;
    const int * something;
    const int * data;

    template <int length>
    my_data_view(my_data<length> const & data_in) :
        array_length(length),
        something(data_in.something.data()),
        data(data_in.data.data())
    {}
};

template <int length>
void
print_element(int array_idx, int element)
{
    my_data<length> * ptr = reinterpret_cast<my_data<length> *>(_ptrs[array_idx]);

    std::cout << "array " << length << ", data[" << element << "] = " << ptr->data[element] << ".\n";
}

void
print_element(int array_idx, int element)
{
    my_data<1> * ptr    = reinterpret_cast<my_data<1> *>(_ptrs[array_idx]);
    int          length = ptr->array_length;

    int data_to_print = 0;
    switch (length)
    {
        case 10:
        {
            data_to_print = reinterpret_cast<my_data<10> *>(_ptrs[array_idx])->data[element];
            break;
        }
        case 20:
        {
            data_to_print = reinterpret_cast<my_data<20> *>(_ptrs[array_idx])->data[element];
            break;
        }
    }
    std::cout << "array " << length << ", data[" << element << "] = " << data_to_print << ".\n";
}

void
print_element(my_data_view view, int element)
{
    int length        = view.array_length;
    int data_to_print = view.data[element];

    std::cout << "array " << length << ", data[" << element << "] = " << data_to_print << ".\n";
}

int
main()
{
    my_data<10> _array_10;
    my_data<20> _array_20;

    _ptrs[0] = static_cast<void *>(&_array_10);
    _ptrs[1] = static_cast<void *>(&_array_20);

    _array_10.data[5] = 11;
    _array_20.data[5] = 22;

    std::cout << "using template\n";
    print_element<10>(0, 5);
    print_element<20>(1, 5);

    std::cout << "\nwithout template\n";
    print_element(0, 5);
    print_element(1, 5);

    std::cout << "\nusing data_view\n";
    print_element(my_data_view(_array_10), 5);
    print_element(my_data_view(_array_20), 5);
}

Body:
You could create a dynamic view class that don't allocate:

struct my_data_view
{
    int array_length;
    std::span<int> something;
    std::span<int> data;

    template<int length>
    my_data_view(my_data<length> const& data) :
        array_length{length}, something{data.something}, data{data.data}
    {}
};

Spans simply are a pointer and a size. If you don't have access to std::span (which is from C++20) you can simply replace those member with int* and use array_length for the size.

This my_data_view type is used like that:

void
print_element(my_data_view view, int element)
{
    int length = view.array_length;
    int data_to_print = view.data[element];

    std::cout << "array " << length << ", data[" << element << "] = " << data_to_print << ".\n";
}

This is the code that will work both with std::span and simple int*.


问:
What is the following C++ code used for -> "#define idiv(a, b) (((a) + (b) / 2) / (b))"?
I'm working with the code that frequently uses some nontrivial optimizations.
What is the

#define idiv(a, b) (((a) + (b) / 2) / (b))
```

<p>used for? Why not simply</p>

<pre class="lang-c prettyprint-override"><code>#define idiv(a, b) ((a)/(b) + 0.5)
</code>```

Is it integer division overflow protection or something else?

答:
Your suggested modification is not equivalent, because a/b is integer division when the parameters are integers. You should cast parameters to floating point first.

The first macro avoids conversion to floating point, which might be faster. Additionally, converting values to floating point and back to integer might lose precision, because not all integers can be represented exactly as floats.

Body:
I'm working with the code that frequently uses some nontrivial optimizations.
What is the

#define idiv(a, b) (((a) + (b) / 2) / (b))

used for? Why not simply

#define idiv(a, b) ((a)/(b) + 0.5)

Is it integer division overflow protection or something else?


答:
```<code>var firstPerGroup = StudentsList
                .Where(s => s.University == "OPQ")
                .GroupBy(s => s.GroupID)
                .Select(g => g.First())
                .ToList();
</code>```

Title: Using Linq to iterate groups and change property with condition


问:
Can I make a snappables snapchat game with lens studio?
I have searched through Snap Chats website and have not found info regarding publishing Snappable games.

Can I create and publish a Snappable game with Snap Chat Lens Studio?

答:
Late answer, but I saw several Snapchat team people who say no, it's not available.

For the moment we can use the Highscore template, or play with local Storage to create game experience with Text (like quiz) or 3d models.


问:
Reactive forms conditional custom validation
I'm using reactive form validation in angular, and I'm trying to add different messages for different

 in-validities, for example if I have a score field that should be between 1-100, I want to have a message when the user enters a letter and a different message if he enters a number bigger than 100.

Is there a way to do it by creating an interface:

```<code>interface error {
     condition: boolean,
     message: string
}
</code>```

using ngFor and iterating over a collection of errors, checking wether a condition is met?

The problem I have is that the condition is linked to function() : boolean, and ngFor does not renders itself again when the user enters an invalid input, since there is no change in the collection but in the value that the condition function will return.

答:
when you create a customValidator you return an object if an error happens. This object can be different acording your requeriments.

```<code>  customError() {
    return (control: AbstractControl) => {
      if (isNaN(control.value)) return { error: "it's not a number" };
      if (+control.value > 100) return { error: "it's greater than 100" };
      return null;
    };
  }

   <div *ngIf="myform.get('control').errors">
         {{myform.get('control').errors.error}}
   </div>
</code>```

You can also return an object with diferents property,e.g. errorNaN and errorGt

```<code>  customError() {
    return (control: AbstractControl) => {
      if (isNaN(control.value)) return { errorNaN : "it's not a number" };
      if (+control.value > 100) return { errorGt: "it's greater than 100" };
      return null;
    };
  }

   <div *ngIf="myform.get('control').errors?.errorNaN">
      It's not a number
   </div>
   <div *ngIf="myform.get('control').errors?.errorGt">
      it's greater than 100
   </div>
</code>```

a simple example stackblitz

Body:
I'm using reactive form validation in angular, and I'm trying to add different messages for different

 in-validities, for example if I have a score field that should be between 1-100, I want to have a message when the user enters a letter and a different message if he enters a number bigger than 100.

Is there a way to do it by creating an interface:

interface error {
     condition: boolean,
     message: string
}

using ngFor and iterating over a collection of errors, checking wether a condition is met?

The problem I have is that the condition is linked to function() : boolean, and ngFor does not renders itself again when the user enters an invalid input, since there is no change in the collection but in the value that the condition function will return.

Body:
when you create a customValidator you return an object if an error happens. This object can be different acording your requeriments.

  customError() {
    return (control: AbstractControl) => {
      if (isNaN(control.value)) return { error: "it's not a number" };
      if (+control.value > 100) return { error: "it's greater than 100" };
      return null;
    };
  }

   <div *ngIf="myform.get('control').errors">
         {{myform.get('control').errors.error}}
   </div>

You can also return an object with diferents property,e.g. errorNaN and errorGt

  customError() {
    return (control: AbstractControl) => {
      if (isNaN(control.value)) return { errorNaN : "it's not a number" };
      if (+control.value > 100) return { errorGt: "it's greater than 100" };
      return null;
    };
  }

   <div *ngIf="myform.get('control').errors?.errorNaN">
      It's not a number
   </div>
   <div *ngIf="myform.get('control').errors?.errorGt">
      it's greater than 100
   </div>

a simple example stackblitz