问:
Update the value of JSON elements in Postgresql
I have table with following table structure:

```<code>create table instances(
                       id               bigint,
                       createdate       timestamp,
                       createdby        bigint,
                       lastmodifieddate timestamp,
                       lastmodifiedby   bigint,
                       context          text
                       )
</code>```

Field context contains a JSON data i.e.

```<code>insert into instances values
(1, '2020-06-01 22:10:04', 20112,'2020-06-01 22:10:04',20112,
    '{"id":1,"details":[{"binduserid":90182}]}')
</code>```

I need to replace all values of JSON element binduserid with value 90182 using postgres query.

I have achieved this by using REPLACE function:

```<code>update instances
   set context = replace(context, '"binduserid":90182','"binduserid":1000619')
</code>```

Is there any other way to do this by using Postgres JSON Functions

答:
Firstly, let's consider storing the column as JSON or JSONB those are already defined to hold the data properly and use in a productive manner such as no needed conversions among types like holding a DATE value in DATE format rather than a STRING.

In this case I consider context column in JSONB data type.

You can use JSONB_SET() function in order to get the desired result where the first argument(target) might be in array format through use of JSONB_BUILD_ARRAY() function with indexes (as 0 in '{0,details}' for this case ) to manipulate easily by the below DML Statement :

```<code>UPDATE instances
   SET context =
          JSONB_SET(JSONB_BUILD_ARRAY(context), '{0,details}','[{"binduserid":1000619}]')
</code>```

Demo

Body:
I have table with following table structure:

create table instances(
                       id               bigint,
                       createdate       timestamp,
                       createdby        bigint,
                       lastmodifieddate timestamp,
                       lastmodifiedby   bigint,
                       context          text
                       )

Field context contains a JSON data i.e.

insert into instances values
(1, '2020-06-01 22:10:04', 20112,'2020-06-01 22:10:04',20112,
    '{"id":1,"details":[{"binduserid":90182}]}')

I need to replace all values of JSON element binduserid with value 90182 using postgres query.

I have achieved this by using REPLACE function:

update instances
   set context = replace(context, '"binduserid":90182','"binduserid":1000619')

Is there any other way to do this by using Postgres JSON Functions

Body:
Firstly, let's consider storing the column as JSON or JSONB those are already defined to hold the data properly and use in a productive manner such as no needed conversions among types like holding a DATE value in DATE format rather than a STRING.

In this case I consider context column in JSONB data type.

You can use JSONB_SET() function in order to get the desired result where the first argument(target) might be in array format through use of JSONB_BUILD_ARRAY() function with indexes (as 0 in '{0,details}' for this case ) to manipulate easily by the below DML Statement :

UPDATE instances
   SET context =
          JSONB_SET(JSONB_BUILD_ARRAY(context), '{0,details}','[{"binduserid":1000619}]')

Demo


来源: stackexchange

问:
fork with map function in Redux Saga
I am a beginner at redux-sagas and I am confused with the following situation. I have an items array and I want to fork the same method for each item. So I am using this line of code:

```<code>yield items.map(item => fork(loadItemDetails, item));
</code>```

With the above-mentioned code, loadItemDetails is never invoked. On the contrary, if I call fork individually on each item, as shown below, then it works as intended.

```<code>yield fork(loadItemDetails, items[0]);
yield fork(loadItemDetails, items[1]);
yield fork(loadItemDetails, items[2]);
</code>```

This is confusing me and I can't figure out the reason why the map won't work.

答:
I came across the same issue.

```<code>items.forEach(item => yield fork(loadItemDetails, item));
</code>```

won't work, as you will get the following error:

A 'yield' expression is only allowed in a generator body.

In order to resolve it, I used yield all

```<code>export function* itemDetailsSage() {
  const { items } = yield take(SET_CART_ITEMS);
  yield all(items.map(item => fork(loadItemDetails, item)));
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: fork with map function in Redux Saga

Body:
I am a beginner at redux-sagas and I am confused with the following situation. I have an items array and I want to fork the same method for each item. So I am using this line of code:

yield items.map(item => fork(loadItemDetails, item));

With the above-mentioned code, loadItemDetails is never invoked. On the contrary, if I call fork individually on each item, as shown below, then it works as intended.

yield fork(loadItemDetails, items[0]);
yield fork(loadItemDetails, items[1]);
yield fork(loadItemDetails, items[2]);

This is confusing me and I can't figure out the reason why the map won't work.

Body:
I came across the same issue.

items.forEach(item => yield fork(loadItemDetails, item));

won't work, as you will get the following error:

A 'yield' expression is only allowed in a generator body.

In order to resolve it, I used yield all

export function* itemDetailsSage() {
  const { items } = yield take(SET_CART_ITEMS);
  yield all(items.map(item => fork(loadItemDetails, item)));
}


问:
Learning curves for RandomForest
I'm using a RandomForestClassifier for a binary classification problem.
I plotted the following learning curve. Can I say that more training data would benefit this model?
image:
Learning curve for RandomForest Classifier

答: From the training curve, it is clear accuracy will not improve by adding more instances. </p>

Title: Learning curves for RandomForest


问:
Trying to make an HP bar for a game using HTML/JavaScript
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}</code>```

      100hp

    Health
    Damage

```

Also, if anyone has any ideas to improve the design I'm all ears!

答:
Change the JS to:

```<code>let width=100;

function add() {
    let addHealth = document.getElementById('health')
    width +=1;

    if (addHealth) {
        addHealth.style.width = width + '%';
        addHealth.innerHTML = width * 1  + 'hp';
    }
}

function remove() {
    let damage = document.getElementById('health')
    width-=1;

    if(damage) {
        damage.style.width = width + '%';
        damage.innerHTML = width - 1  + 'hp';
    }
}
</code>```

You had to make the variable width a global variable. And actually add and subtract from that variable.

Body:
I'm trying to make a health bar for a game where I have 2 buttons linked to the bar, one adds damage and the other adds health. I have it all designed the way I want it but am having trouble with the JavaScript part. The buttons are linked but when I click to add damage or health it only adjusts the amount of HP by one in either direction but no more than that. I also can't figure out how to make the width of the bar move with the number associated with the amount of health. I think I'm close but just need a little help. I'll add the CSS code too so there is some more context.

function add() {
  let addHealth = document.getElementById('health')
  let width = 100;
  addHealth.width += 1;

  if (addHealth) {
    addHealth.style.width = width + '%';
    addHealth.innerHTML = width * 1 + 'hp';
  }
}

function remove() {
  let damage = document.getElementById('health')
  let width = 100;
  damage.width -= 1;

  if (damage) {
    damage.style.width = width + '%';
    damage.innerHTML = width - 1 + 'hp';
  }
}

.hp {
  text-align: center;
  padding-bottom: 50px;
}

.gage {
  display: inline-block;
  width: 500px;
  padding-bottom: 30px;
}

.bar {
  height: 60px;
  position: relative;
  background: #555;
  -moz-border-radius: 25px;
  -webkit-border-radius: 25px;
  border-radius: 25px;
  padding: 10px;
  box-shadow: inset 0 -1px 1px rgba(255, 255, 255, 0.3);
}

.bar>span {
  display: block;
  height: 100%;
  border-top-right-radius: 8px;
  border-bottom-right-radius: 8px;
  border-top-left-radius: 20px;
  border-bottom-left-radius: 20px;
  background-color: rgb(43, 194, 83);
  background-image: linear-gradient( center bottom, rgb(43, 194, 83) 37%, rgb(84, 240, 84) 69%);
  box-shadow: inset 0 2px 9px rgba(255, 255, 255, 0.3), inset 0 -2px 6px rgba(0, 0, 0, 0.4);
  position: relative;
  overflow: hidden;
}

.lvl {
  background-color: #078a25;
  background-image: linear-gradient(to bottom, #078a25, #f36d0a);
}

#health {
  font-size: 20px;
  color: white;
  font-weight: bold;
  text-align: right;
}

.btn-3d {
  position: relative;
  display: inline-block;
  font-size: 22px;
  padding: 20px 60px;
  color: white;
  margin: 20px 10px 10px;
  border-radius: 6px;
  text-align: center;
  transition: top .01s linear;
  text-shadow: 0 1px 0 rgba(0, 0, 0, 0.15);
  cursor: pointer;
}

.btn-3d.green:hover {
  background-color: #80C49D;
}

.btn-3d:active {
  top: 9px;
}

.btn-3d.green {
  background-color: #82c8a0;
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 rgba(126, 194, 155, .7), 0 8px 0 1px rgba(0, 0, 0, .4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.green:active {
  box-shadow: 0 0 0 1px #82c8a0 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

.btn-3d.red:hover {
  background-color: #e74c3c;
}

.btn-3d.red {
  background-color: #e74c3c;
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 8px 0 0 #C24032, 0 8px 0 1px rgba(0, 0, 0, 0.4), 0 8px 8px 1px rgba(0, 0, 0, 0.5);
}

.btn-3d.red:active {
  box-shadow: 0 0 0 1px #c63702 inset, 0 0 0 2px rgba(255, 255, 255, 0.15) inset, 0 0 0 1px rgba(0, 0, 0, 0.4);
}

      100hp

    Health
    Damage

Also, if anyone has any ideas to improve the design I'm all ears!

Body:
Change the JS to:

let width=100;

function add() {
    let addHealth = document.getElementById('health')
    width +=1;

    if (addHealth) {
        addHealth.style.width = width + '%';
        addHealth.innerHTML = width * 1  + 'hp';
    }
}

function remove() {
    let damage = document.getElementById('health')
    width-=1;

    if(damage) {
        damage.style.width = width + '%';
        damage.innerHTML = width - 1  + 'hp';
    }
}

You had to make the variable width a global variable. And actually add and subtract from that variable.


问:
How to omit if variable is empty in Ansibe?
I'm going through ansible example for Docker.

And I need to publish a port just like in the example but with an if statement if port else omit. Like this:

```<code>docker_container:
name: myapplication
...
ports:
 - "{{ if port else omit }}" # the {{ port }} variable is set from the default task.
...
</code>```

But each time I run this, the Docker daemon tells me:

```<code>template error while templating string: expected token 'end of print statement', got 'port'. String: {{ if port else omit }}"
</code>```

How do I omit setting the port if the variable {{ port }} is empty?

Thanks kindly for your help in advance.

答:
You can use when for conditional plays. Define your container first:

```<code>docker_container:
  name: myapplication
  ...
</code>```

If port is defined expose it:

```<code>docker_container:
  name: myapplication
  ports:
   - "{{ port }}"
  when: port is defined
</code>```

Body:
I'm going through ansible example for Docker.

And I need to publish a port just like in the example but with an if statement if port else omit. Like this:

docker_container:
name: myapplication
...
ports:
 - "{{ if port else omit }}" # the {{ port }} variable is set from the default task.
...

But each time I run this, the Docker daemon tells me:

template error while templating string: expected token 'end of print statement', got 'port'. String: {{ if port else omit }}"

How do I omit setting the port if the variable {{ port }} is empty?

Thanks kindly for your help in advance.

Body:
You can use when for conditional plays. Define your container first:

docker_container:
  name: myapplication
  ...

If port is defined expose it:

docker_container:
  name: myapplication
  ports:
   - "{{ port }}"
  when: port is defined


问:
Flask-SocketIO making sure socket disconnects from client correctly
I added the Flask-SocketIO library to my Flask application to handle live connections and testing it with cookies being sent to the backend after the user completes a specific action. This is in case the user closes their browser or the webpage before issuing another HTTP request to the URL. I found that the browser won't save the cookie being set with document.cookie in javascript until it receives the cookie back from the server in response. Since adding the WebSocket and testing it in the development environment, the socket does emit the cookie correctly. However when I attempt to use ctrl-C in the terminal, it won't fire the signal, and even after I close the terminal and the browser/webpage, localhost is still listening on the port. I know how to manually kill the process with taskkill but my concern is that the socket connection with the client is left open after they had already closed the webpage/browser. I'm assuming this can be bad for performance on the backend and possibly cause some security risks, though I'm not sure. This might be because I'm not handling the socket connection and emitted message on the backend correctly but that's because the example code in the documentation was difficult to follow. Here is the documentation: https://flask-socketio.readthedocs.io/en/latest/.

Can someone please answer this question?

__init__.py:

```<code>from flask import Flask, url_for, current_app
from flask_socketio import SocketIO

csp = {
    "default-src": [
        "'self'",
        'https://www.youtube.com'
    ],
    'script-src': [ "'self'",
                    'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js',
                    'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js',
                    'https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'],
    'style-src': ["'self'",
                  'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css'],
    'img-src': ["'self'",
                'data:',
                'https://i.ytimg.com' ],
    'font-src': ['data:']
}

config = {
    "CACHE_TYPE": "simple",
    "DEBUG": True,
    "SQLALCHEMY_DATABASE_URI": "sqlite:///site.db",
    "SQLALCHEMY_TRACK_MODIFICATIONS": False,
    "SQLALCHEMY_ECHO": False
}
socketio = SocketIO()
def create_app():
    app = Flask(__name__)
    app.config.from_mapping(config)
    socketio.init_app(app)

    from flask_app.main.routes import main
    app.register_blueprint(main)
    with app.app_context():
        db.create_all()
        socketio.run(current_app)

    return app
</code>```

main/routes.py:

```<code>from flask import render_template, session, request, current_app, Blueprint, redirect, url_for, json, make_response
from flask_app import cache
import os

main = Blueprint("main", __name__)

@main.route("/")
def index():
    return render_template("index.html", title="Home")

@main.context_processor
def inject_template_scope():
    injections = dict()

    # Use this method to check if the client has consented to the use of cookies.
    def cookies_check():
        value = request.cookies.get('consent')
        return value != None
    injections.update(cookies_check=cookies_check)
    return injections
</code>```

run.py:

```<code>from flask_app import create_app
</code>```

base.html:

```<code><html>
 <body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"
    integrity="sha256-yr4fRk/GU1ehYJPAs8P4JlTgu0Hdsp4ZKrx8bDEDC3I="
    crossorigin="anonymous"></script>
 </body>
</html>
</code>```

base.js:

```<code>$(window).on('load', function() {
 function cookieConsent() {
   var socket = io();
   const now = new Date();
   document.cookie = "consent=consented:true,dateTime:" + now + ",lang:" + navigator.language;
   socket.on('connect', function() {
       socket.emit('consent cookie', {consent_cookie: document.cookie});
   });
 }
}
</code>```

Project Hierarchy:

```<code>project/
|_ flask_app/
   |_ main/
      |_ routes.py
   |_ templates/
      |_ base.html
   |_ static/
      |_ js/
         |_ base.js
   |_ __init__.py
|_ run.py
</code>```

Environment Variables:

```<code>FLASK_APP : run.py
FLASK_ENV : development
</code>```

答:
socketio.run(app) start a development server at the port 5000.

So when you execute flask run flask calls function create_app() and expects an app. Your function however doesn't actually return app because socketio.run(app) is blocking. When you press CTRL+C it stops this line.

Body:
I added the Flask-SocketIO library to my Flask application to handle live connections and testing it with cookies being sent to the backend after the user completes a specific action. This is in case the user closes their browser or the webpage before issuing another HTTP request to the URL. I found that the browser won't save the cookie being set with document.cookie in javascript until it receives the cookie back from the server in response. Since adding the WebSocket and testing it in the development environment, the socket does emit the cookie correctly. However when I attempt to use ctrl-C in the terminal, it won't fire the signal, and even after I close the terminal and the browser/webpage, localhost is still listening on the port. I know how to manually kill the process with taskkill but my concern is that the socket connection with the client is left open after they had already closed the webpage/browser. I'm assuming this can be bad for performance on the backend and possibly cause some security risks, though I'm not sure. This might be because I'm not handling the socket connection and emitted message on the backend correctly but that's because the example code in the documentation was difficult to follow. Here is the documentation: https://flask-socketio.readthedocs.io/en/latest/.

Can someone please answer this question?

__init__.py:

from flask import Flask, url_for, current_app
from flask_socketio import SocketIO

csp = {
    "default-src": [
        "'self'",
        'https://www.youtube.com'
    ],
    'script-src': [ "'self'",
                    'https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js',
                    'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js',
                    'https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js'],
    'style-src': ["'self'",
                  'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css'],
    'img-src': ["'self'",
                'data:',
                'https://i.ytimg.com' ],
    'font-src': ['data:']
}

config = {
    "CACHE_TYPE": "simple",
    "DEBUG": True,
    "SQLALCHEMY_DATABASE_URI": "sqlite:///site.db",
    "SQLALCHEMY_TRACK_MODIFICATIONS": False,
    "SQLALCHEMY_ECHO": False
}
socketio = SocketIO()
def create_app():
    app = Flask(__name__)
    app.config.from_mapping(config)
    socketio.init_app(app)

    from flask_app.main.routes import main
    app.register_blueprint(main)
    with app.app_context():
        db.create_all()
        socketio.run(current_app)

    return app

main/routes.py:

from flask import render_template, session, request, current_app, Blueprint, redirect, url_for, json, make_response
from flask_app import cache
import os

main = Blueprint("main", __name__)

@main.route("/")
def index():
    return render_template("index.html", title="Home")

@main.context_processor
def inject_template_scope():
    injections = dict()

    # Use this method to check if the client has consented to the use of cookies.
    def cookies_check():
        value = request.cookies.get('consent')
        return value != None
    injections.update(cookies_check=cookies_check)
    return injections

run.py:

from flask_app import create_app

base.html:

base.js:

$(window).on('load', function() {
 function cookieConsent() {
   var socket = io();
   const now = new Date();
   document.cookie = "consent=consented:true,dateTime:" + now + ",lang:" + navigator.language;
   socket.on('connect', function() {
       socket.emit('consent cookie', {consent_cookie: document.cookie});
   });
 }
}

Project Hierarchy:

project/
|_ flask_app/
   |_ main/
      |_ routes.py
   |_ templates/
      |_ base.html
   |_ static/
      |_ js/
         |_ base.js
   |_ __init__.py
|_ run.py

Environment Variables:

FLASK_APP : run.py
FLASK_ENV : development


答:
You should use the default filter with the omit variable for that.

- docker_container:
    name: myapplication
    ports: "{{ port|default(omit) if port is not defined else [port] }}"
```

<p>Mind that you want to use this exact syntax and not the array notation like</p>

<pre class="lang-yaml prettyprint-override"><code>- docker_container:
    name: myapplication
    ports:
      - "{{ port|default(omit) }}"
</code>```

Otherwise you will end up with an array in the attribute ports, still, that would have some odd value like

```<code>"__omit_place_holder__ad3616ee8afa39aa187d7fc6ac7ad36f3e7691c0"
</code>```

Title: How to omit if variable is empty in Ansibe?

Body:
You should use the default filter with the omit variable for that.

- docker_container:
    name: myapplication
    ports: "{{ port|default(omit) if port is not defined else [port] }}"

Mind that you want to use this exact syntax and not the array notation like

- docker_container:
    name: myapplication
    ports:
      - "{{ port|default(omit) }}"

Otherwise you will end up with an array in the attribute ports, still, that would have some odd value like

"__omit_place_holder__ad3616ee8afa39aa187d7fc6ac7ad36f3e7691c0"


问:
What is the "some" keyword in Swift(UI)?
The new SwiftUI tutorial has the following code:

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}
```

The second line the word some, and on their site is highlighted as if it were a keyword.

Swift 5.1 does not appear to have some as a keyword, and I don't see what else the word some could be doing there, since it goes where the type usually goes. Is there a new, unannounced version of Swift? Is it a function that's being used on a type in a way I didn't know about?

What does the keyword some do?

答:
For those who were dizzy by the subject, here a very decrypting and step by step article thanks to Vadim Bulavin.

https://www.vadimbulavin.com/opaque-return-types-and-the-some-keyword-in-swift/

Body:
The new SwiftUI tutorial has the following code:

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

The second line the word some, and on their site is highlighted as if it were a keyword.

Swift 5.1 does not appear to have some as a keyword, and I don't see what else the word some could be doing there, since it goes where the type usually goes. Is there a new, unannounced version of Swift? Is it a function that's being used on a type in a way I didn't know about?

What does the keyword some do?


问:
including specific header files with same names in different directories
Here is a sample of my directory structure:

```<code>TopDir
|-Makefile
|-Dir1
   |- A.c
   |- A.h
   |- Config.h
|-Dir2
   |- B.c
   |- B.h
   |- Config.h
</code>```

This is my straight forward code (Every sub directory follows the same pattern):

```<code>In file Config.h
# SomeConfig

in file A.h
#include "Config.h"

in file A.c
#include "A.h"
</code>```

And here is my Makefile:

```<code>CC = gcc
INC_DIR = -IDir1 \
          -IDir2
CFLAGS = -Wall -Wextra -pedantic $(INC_DIR)
AExe: A.c
    $(CC) $(CFLAGS) -o $@ $
BExe: A.c B.c
    $(CC) $(CFLAGS) -o $@ $
</code>```

When I compile, i just call:

```<code>$make AExe
</code>```

or

```<code>$make BExe
</code>```

My problem here is I am unable to include/build a Config specific to its own directory because of -I rule which just blindly picks the first Config.h it finds. AExe builds fine including its own Config. However BExe first finds the Config.h in Dir1 and ignores the Config.h in Dir2. If i reverse the INC_DIR order to include Dir2 first then B.h gets the right Config. In my case I have more directories with similar structure and they all could have dependencies on other directories header files only. Configs are meant for the specific directory. How do I instruct in Makefile to tell A.h to make using its own Config.h and B.h to use its own Config.h.

答:
One solutions is to change:

```<code>INC_DIR=-I$(CURDIR)
</code>```

And then if you need to include a header from another directory do:

```<code>#include <AnotherDir/Header.h>
</code>```

To include a header from the same directory do:

```<code>#include "Header.h"
</code>```

It looks for Header.h in the same directory first.

So that if:

```<code>// Dir1/A.h
#include "Config.h"
</code>```

and then:

```<code>// Dir2/B.h
#include <Dir1/A.h>
</code>```

B.h includes <Dir1/A.h> and <Dir1/Config.h> as expected.

Body:
Here is a sample of my directory structure:

TopDir
|-Makefile
|-Dir1
   |- A.c
   |- A.h
   |- Config.h
|-Dir2
   |- B.c
   |- B.h
   |- Config.h

This is my straight forward code (Every sub directory follows the same pattern):

In file Config.h
# SomeConfig

in file A.h
#include "Config.h"

in file A.c
#include "A.h"

And here is my Makefile:

CC = gcc
INC_DIR = -IDir1 \
          -IDir2
CFLAGS = -Wall -Wextra -pedantic $(INC_DIR)
AExe: A.c
    $(CC) $(CFLAGS) -o $@ $
BExe: A.c B.c
    $(CC) $(CFLAGS) -o $@ $

When I compile, i just call:

$make AExe

or

$make BExe

My problem here is I am unable to include/build a Config specific to its own directory because of -I rule which just blindly picks the first Config.h it finds. AExe builds fine including its own Config. However BExe first finds the Config.h in Dir1 and ignores the Config.h in Dir2. If i reverse the INC_DIR order to include Dir2 first then B.h gets the right Config. In my case I have more directories with similar structure and they all could have dependencies on other directories header files only. Configs are meant for the specific directory. How do I instruct in Makefile to tell A.h to make using its own Config.h and B.h to use its own Config.h.

Body:
One solutions is to change:

INC_DIR=-I$(CURDIR)

And then if you need to include a header from another directory do:

#include <AnotherDir/Header.h>

To include a header from the same directory do:

#include "Header.h"

It looks for Header.h in the same directory first.

So that if:

// Dir1/A.h
#include "Config.h"

and then:

// Dir2/B.h
#include <Dir1/A.h>

B.h includes <Dir1/A.h> and <Dir1/Config.h> as expected.


问:
How to remove response headers when sending a json response in php?
I am making an ajax request to a php page e.g page1.php. In page1.php I have a header("Location:page2.php?password=1234") code which redirects to page2.php with the password as a GET parameter. page2.php gives a json response.
The problem is that when I do inspect element and check the resources in Safari browser, I am able to see the location page2.php?password=1234" in the response header part.
This is a security issue. Please suggest how can I remove the response headers when sending the json response? I am using PHP 5.2.6.

答:
as a poor man defense, you could use some kind of crypt functions (md5, sha1, crc32) to generate hash from password and transfer it instead of password. Though, it is better to redo whole system to avoid it.

This workaround does not answer your question, though.

ContentLicense: CC BY-SA 3.0


问:
What is the meaning of the last letter "a", "b", or "s" in Azure DevOps' C:\agent\_work\1\a? Anyone know what that last letter stands for?
What is the meaning of the last letter "a", "b", or "s" in Azure DevOps' directory structure:

C:\agent_work\1\a
C:\agent_work\1\b
C:\agent_work\1\s

Anyone know what that last letter stands for?

Extra credit: what's the "1" represent too?

答:
Check out the predefined variables:

\a likely stands for "artifacts"

Build.ArtifactStagingDirectory - The local path on the agent where any artifacts are copied to before being pushed to their destination. For example: c:\agent_work\1\a

\b likely stands for "binaries"

Build.BinariesDirectory - The local path on the agent you can use as an output folder for compiled binaries.  For example: c:\agent_work\1\b.

\s likely stands for "sources"

Build.Repository.LocalPath - The local path on the agent where your source code files are downloaded. For example: c:\agent_work\1\s.  This variable is synonymous with Build.SourcesDirectory.

On Hosted build agents "1" seems to be static, on a self hosted agent I have noticed this number is unique per pipeline.


问:
Python -- Pandas can't find file but numpy can
I am at a complete loss here.  I am trying to open a txt file in pandas, I have tried multiple different approaches, but I receive the same error message every time.  'no such file'...

What is strange is that this...

```<code>import numpy as np
import matplotlib.pyplot as plt
from   matplotlib.ticker import PercentFormatter

full_file = np.loadtxt('2_Feature_Test.txt', delimiter=',')
</code>```

...works completely fine, however this...

```<code>import pandas as pd
import matplotlib.pyplot as plt
from   matplotlib.ticker import PercentFormatter

full_file = pd.read_csv('2_Feature_Test.txt', sep=',')
</code>```

...does not.

Doesn't matter full path, doesn't matter backslashes or forward slashes or prefixing with r for raw string.  Is the problem something to do with pandas and numpy being in different locations?  I have no clue.  Please, if you have any ideas I am all ears and would love nothing more than to get to the bottom of this.  Thanks everyone.

If it helps, this is the full error message I receive...

```<code>Traceback (most recent call last):
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\workbench.py", line 1449, in event_generate
    handler(event)
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 138, in handle_toplevel_response
    self._explain_exception(msg["user_exception"])
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 178, in _explain_exception
    + _error_helper_classes["*"]
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 176, in <listcomp>
    for helper_class in (
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\plugins\stdlib_error_helpers.py", line 555, in __init__
    super().__init__(error_info)
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 478, in __init__
    self.last_frame_module_source = read_source(self.last_frame.filename)
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\common.py", line 252, in read_source
    with tokenize.open(filename) as fp:
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\tokenize.py", line 447, in open
    buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'pandas\\_libs\\index.pyx'
</code>```

UPDATE: due to a more patient man than I actually reading the error message, I realize the issue is most likely with the pandas installation.  Install of pandas via conda install pandas failed saying 'the specified procedure could not be found'.  Might this have something to do with the issue?  Anybody seen this before?

答:
As the comments have said, clearly the missing file is one of pandas', not the file you are trying to read.

Try forcing the reinstall of pandas

```<code>pip install -I pandas
</code>```

or, if using Anaconda

```<code>conda install pandas --force-reinstall
</code>```

Body:
I am at a complete loss here.  I am trying to open a txt file in pandas, I have tried multiple different approaches, but I receive the same error message every time.  'no such file'...

What is strange is that this...

import numpy as np
import matplotlib.pyplot as plt
from   matplotlib.ticker import PercentFormatter

full_file = np.loadtxt('2_Feature_Test.txt', delimiter=',')

...works completely fine, however this...

import pandas as pd
import matplotlib.pyplot as plt
from   matplotlib.ticker import PercentFormatter

full_file = pd.read_csv('2_Feature_Test.txt', sep=',')

...does not.

Doesn't matter full path, doesn't matter backslashes or forward slashes or prefixing with r for raw string.  Is the problem something to do with pandas and numpy being in different locations?  I have no clue.  Please, if you have any ideas I am all ears and would love nothing more than to get to the bottom of this.  Thanks everyone.

If it helps, this is the full error message I receive...

Traceback (most recent call last):
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\workbench.py", line 1449, in event_generate
    handler(event)
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 138, in handle_toplevel_response
    self._explain_exception(msg["user_exception"])
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 178, in _explain_exception
    + _error_helper_classes["*"]
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 176, in <listcomp>
    for helper_class in (
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\plugins\stdlib_error_helpers.py", line 555, in __init__
    super().__init__(error_info)
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\assistance.py", line 478, in __init__
    self.last_frame_module_source = read_source(self.last_frame.filename)
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\site-packages\thonny\common.py", line 252, in read_source
    with tokenize.open(filename) as fp:
  File "C:\Users\Pat Oaks\Documents\txt_files\Thonny\lib\tokenize.py", line 447, in open
    buffer = _builtin_open(filename, 'rb')
FileNotFoundError: [Errno 2] No such file or directory: 'pandas\\_libs\\index.pyx'

UPDATE: due to a more patient man than I actually reading the error message, I realize the issue is most likely with the pandas installation.  Install of pandas via conda install pandas failed saying 'the specified procedure could not be found'.  Might this have something to do with the issue?  Anybody seen this before?

Body:
As the comments have said, clearly the missing file is one of pandas', not the file you are trying to read.

Try forcing the reinstall of pandas

pip install -I pandas

or, if using Anaconda

conda install pandas --force-reinstall


问:
scrapy limit amount of requests for domain
```<code>import scrapy
from urllib.parse import urljoin

class MyCrawlSpider(scrapy.Spider):
    LIMIT_OF_DOMAIN = 100

    def start_requests(self):
        with open('links.txt', 'r') as f:
            urls = f.read().split('\n')
        #urls=['https://www.google.com/search?q=hello+world','https://yahoo.com']
        for url in urls:
            # remove empty links
            if not url:
                continue
            sub_item = {'main_url': url, 'index_of_domain': 0}
            yield scrapy.Request(url, callback=self.parse, meta=sub_item,)

    def parse(self,response):
        main_url = response.meta['main_url']
        index_of_domain = response.meta['index_of_domain']
        for url in response.xpath('//a[@href] | //article[@href]'):
            href = url.xpath('@href').extract_first()
            url = urljoin(main_url, href.strip())
            if index_of_domain >= self.LIMIT_OF_DOMAIN:
                break
            index_of_domain += 1
            sub_item = {'main_url': main_url, 'index_of_domain': index_of_domain}
            yield scrapy.Request(url, callback=self.parse, meta=sub_item, )
</code>```

currently my limitLIMIT_OF_DOMAIN is not working as I wanted, somehow it keeps crawling much after my 100 limit. I have searched the scrapy docs but couldn't find limit for domain, How can I fix this?

Ideally what I want for each link in starting_requests to get 100 request

答:
```<code>class CurrentValue(object):
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1
class YourSpider(scrapy.Spider):
    def start_requets(self):
        obj = CurrentValue()
        #your code
        sub_item = {'current_url': url, 'main_url': url, 'index_of_domain': obj}

    def parse(self,response):
        obj = response.meta['index_of_domain']
        for url in urls:
            obj.increment()
</code>```

you simply need another class to store value for each starting link

Body:
import scrapy
from urllib.parse import urljoin

class MyCrawlSpider(scrapy.Spider):
    LIMIT_OF_DOMAIN = 100

    def start_requests(self):
        with open('links.txt', 'r') as f:
            urls = f.read().split('\n')
        #urls=['https://www.google.com/search?q=hello+world','https://yahoo.com']
        for url in urls:
            # remove empty links
            if not url:
                continue
            sub_item = {'main_url': url, 'index_of_domain': 0}
            yield scrapy.Request(url, callback=self.parse, meta=sub_item,)

    def parse(self,response):
        main_url = response.meta['main_url']
        index_of_domain = response.meta['index_of_domain']
        for url in response.xpath('//a[@href] | //article[@href]'):
            href = url.xpath('@href').extract_first()
            url = urljoin(main_url, href.strip())
            if index_of_domain >= self.LIMIT_OF_DOMAIN:
                break
            index_of_domain += 1
            sub_item = {'main_url': main_url, 'index_of_domain': index_of_domain}
            yield scrapy.Request(url, callback=self.parse, meta=sub_item, )

currently my limitLIMIT_OF_DOMAIN is not working as I wanted, somehow it keeps crawling much after my 100 limit. I have searched the scrapy docs but couldn't find limit for domain, How can I fix this?

Ideally what I want for each link in starting_requests to get 100 request

Body:
class CurrentValue(object):
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1
class YourSpider(scrapy.Spider):
    def start_requets(self):
        obj = CurrentValue()
        #your code
        sub_item = {'current_url': url, 'main_url': url, 'index_of_domain': obj}

    def parse(self,response):
        obj = response.meta['index_of_domain']
        for url in urls:
            obj.increment()

you simply need another class to store value for each starting link


问:
update object in hashmap by java 8 lambda
I created an item named player as follows:

```<code>import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class player implements Comparable <player> {

 int PlayerId ;
 String name ;
 double salary;

public player(int PlayerId) {
    this.PlayerId = PlayerId;
}

public void setPlayerId(int PlayerId) {
    this.PlayerId = PlayerId;
}

public void setName(String name) {
    this.name = name;
}

public void setSalary(double salary) {
    this.salary = salary;
}

public int getID() {
    return PlayerId;
}

public String getName() {
    return name;
}

public double getSalary() {
    return salary;
}

  @Override
   public int hashCode() {

    int key = 2;

    return key=2*key+PlayerId;
   }

   @Override
   public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final player other = (player) obj;
    if (this.PlayerId != other.PlayerId) {
        return false;
    }
    return true;
   }

   @Override
    public String toString(){

   return hashCode()+" "+getID() +" "+getName()+" "+getSalary();

  }

  // generic method StoreplayerDetails
  public <T> void StoreplayerDetails( HashMap<Integer,T> inputMap ) {
  // save elements into text file

  PrintWriter pw = null;
     try {
         pw = new PrintWriter(new FileOutputStream("OutPut.txt"));
         for(T  element : inputMap.values())
             pw.println(element);
         pw.close();
     } catch (FileNotFoundException ex) {
         Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
     } finally {
         pw.close();
     }
 }

@Override
public int compareTo(player other) {
    if(this.salary>other.salary)
    return 1;
else
    if(this.salary<other.salary)
        return -1;
return 0;
}

 public interface Update  {

 public <T> void updateSalaries( HashMap<Integer,player> inputMap);

}

}
</code>```

create an interface named update in the player class ,create a generic method named updateSalaries in the interface that takes a HashMap as input and returns a Queue of player objects after updating the salaries of players by adding 500 to each one's salary .
in the mainprogram class implement the method updatesalaries as a lamdba expression .in the mainprogram class,print the elements in the returned queue .

I tried it as follows but it did not work out:

```<code>@Override
public <T> void updateSalaries(HashMap<Integer, player> map) {

 map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;

  System.out.println("new map"+map);

}
</code>```

This is the full code in the main class

```<code> import java.util.HashMap;
 import player.player.Update;

 public class MainProgram implements Update{

public static void main(String[] args) {

 HashMap< Integer,player> Keys = new HashMap<>();

 player p1 =new player(1);
 p1.setName("Ali");
 p1.setSalary(5000);

 player p2 =new player(2);
 p2.setName("Sayed");
 p2.setSalary(7000);

 player p3 =new player(3);
 p3.setName("soha");
 p3.setSalary(3000);

 Keys.put(1, p1);
 Keys.put(2, p2);
 Keys.put(3, p3);

  // p1.StoreplayerDetails(Keys);
   MainProgram m = new MainProgram();

   m.updateSalaries(Keys);

}

@Override
public <T> void updateSalaries(HashMap<Integer, player> map) {

 map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;

  System.out.println("new map"+map);

}

}
</code>```

Is there any help in solving this?

答:
In your code snippet you have the following line of code:

```<code>map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;
</code>```

Let's take this apart piece by piece:

map.replaceAll This method lets you replace all the values in a map.  I believe you want to manipulate the values that are already there, instead.

(k,player.getSalary()) This is where you name the variables that the lambda will dump values into.  You aren't supposed to supply numbers here, you are supposed to be receiving numbers.  You likely want (k, p), where k will be set to the key (an Integer) and p will be set to the value (a player).

player.getSalary()+500 This returns an int.  The replaceAll method requires that you return the value type, which in this case is player.

You forgot to include a close parenthesis at the end.

I believe you want to use this line of code instead, which mitigates all of the above errors:

```<code>map.forEach((k, p) -> p.setSalary(p.getSalary() + 500));
</code>```

Body:
I created an item named player as follows:

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

public class player implements Comparable <player> {

 int PlayerId ;
 String name ;
 double salary;

public player(int PlayerId) {
    this.PlayerId = PlayerId;
}

public void setPlayerId(int PlayerId) {
    this.PlayerId = PlayerId;
}

public void setName(String name) {
    this.name = name;
}

public void setSalary(double salary) {
    this.salary = salary;
}

public int getID() {
    return PlayerId;
}

public String getName() {
    return name;
}

public double getSalary() {
    return salary;
}

  @Override
   public int hashCode() {

    int key = 2;

    return key=2*key+PlayerId;
   }

   @Override
   public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    }
    if (getClass() != obj.getClass()) {
        return false;
    }
    final player other = (player) obj;
    if (this.PlayerId != other.PlayerId) {
        return false;
    }
    return true;
   }

   @Override
    public String toString(){

   return hashCode()+" "+getID() +" "+getName()+" "+getSalary();

  }

  // generic method StoreplayerDetails
  public <T> void StoreplayerDetails( HashMap<Integer,T> inputMap ) {
  // save elements into text file

  PrintWriter pw = null;
     try {
         pw = new PrintWriter(new FileOutputStream("OutPut.txt"));
         for(T  element : inputMap.values())
             pw.println(element);
         pw.close();
     } catch (FileNotFoundException ex) {
         Logger.getLogger(MainProgram.class.getName()).log(Level.SEVERE, null, ex);
     } finally {
         pw.close();
     }
 }

@Override
public int compareTo(player other) {
    if(this.salary>other.salary)
    return 1;
else
    if(this.salary<other.salary)
        return -1;
return 0;
}

 public interface Update  {

 public <T> void updateSalaries( HashMap<Integer,player> inputMap);

}

}

create an interface named update in the player class ,create a generic method named updateSalaries in the interface that takes a HashMap as input and returns a Queue of player objects after updating the salaries of players by adding 500 to each one's salary .
in the mainprogram class implement the method updatesalaries as a lamdba expression .in the mainprogram class,print the elements in the returned queue .

I tried it as follows but it did not work out:

@Override
public <T> void updateSalaries(HashMap<Integer, player> map) {

 map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;

  System.out.println("new map"+map);

}

This is the full code in the main class

 import java.util.HashMap;
 import player.player.Update;

 public class MainProgram implements Update{

public static void main(String[] args) {

 HashMap< Integer,player> Keys = new HashMap<>();

 player p1 =new player(1);
 p1.setName("Ali");
 p1.setSalary(5000);

 player p2 =new player(2);
 p2.setName("Sayed");
 p2.setSalary(7000);

 player p3 =new player(3);
 p3.setName("soha");
 p3.setSalary(3000);

 Keys.put(1, p1);
 Keys.put(2, p2);
 Keys.put(3, p3);

  // p1.StoreplayerDetails(Keys);
   MainProgram m = new MainProgram();

   m.updateSalaries(Keys);

}

@Override
public <T> void updateSalaries(HashMap<Integer, player> map) {

 map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;

  System.out.println("new map"+map);

}

}

Is there any help in solving this?

Body:
In your code snippet you have the following line of code:

map.replaceAll((k,player.getSalary()) -> player.getSalary()+500;

Let's take this apart piece by piece:

map.replaceAll This method lets you replace all the values in a map.  I believe you want to manipulate the values that are already there, instead.

(k,player.getSalary()) This is where you name the variables that the lambda will dump values into.  You aren't supposed to supply numbers here, you are supposed to be receiving numbers.  You likely want (k, p), where k will be set to the key (an Integer) and p will be set to the value (a player).

player.getSalary()+500 This returns an int.  The replaceAll method requires that you return the value type, which in this case is player.

You forgot to include a close parenthesis at the end.

I believe you want to use this line of code instead, which mitigates all of the above errors:

map.forEach((k, p) -> p.setSalary(p.getSalary() + 500));


问:
accessing sqlite file in android
I have a sqlite file. I want to use it in my application.
Can anyone share proper example as how I can do that.

I was not sure if .sqlite file can be used so I have also made .db file.

答:
Android databases are sqlite files, so you can just use the standard Android database API.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html

http://www.screaming-penguin.com/node/7742

Title: accessing sqlite file in android


问:
discord bot that checks if the transfer is completed
I'm having an issue with my js code. I built a bot that makes a file to play in my server with the name of  who joins, but it's too fast so I want to put something that stops the code until it finishes to make the file</p>

```<code>        client.on('voiceStateUpdate', async(oldState, newState) => {
      if (!oldState || !newState) return;
      const oldChannel = oldState.channel ? oldState.channel.id : null;
      const newChannel = newState.channel ? newState.channel.id : null;
       const user = await client.users.fetch(newState.id)
       let nome = user.username;
       let messaggio = 'E\' entrato '+nome;
       say.export(messaggio , 'Cellos', 1, 'output.wav', (err) => {
        if (err) {
          return console.error(err)
        }
      })
        online(newChannel, newState, nome);
      });

function online(newChannel, newState, nome) {
  if(newChannel === universoVoice && newState.id !== Botid){
    console.log('entrata');
    const voiceChannel = client.channels.cache.get(universoVoice);
    if (!voiceChannel) return console.error("The channel does not exist!");
    voiceChannel.join().then(connection => {
        console.log("Connesso");
        connection.play('out.mp3');
        client.leaveVoiceChannel;
    }).catch(e => {
        console.error(e);
    });
  }else{

    console.log('uscita');
  }
}
</code>```

答: Try using await online(newChannel, newState, nome); in order to wait until the say.export function is completed

Body:
I'm having an issue with my js code. I built a bot that makes a file to play in my server with the name of  who joins, but it's too fast so I want to put something that stops the code until it finishes to make the file

        client.on('voiceStateUpdate', async(oldState, newState) => {
      if (!oldState || !newState) return;
      const oldChannel = oldState.channel ? oldState.channel.id : null;
      const newChannel = newState.channel ? newState.channel.id : null;
       const user = await client.users.fetch(newState.id)
       let nome = user.username;
       let messaggio = 'E\' entrato '+nome;
       say.export(messaggio , 'Cellos', 1, 'output.wav', (err) => {
        if (err) {
          return console.error(err)
        }
      })
        online(newChannel, newState, nome);
      });

function online(newChannel, newState, nome) {
  if(newChannel === universoVoice && newState.id !== Botid){
    console.log('entrata');
    const voiceChannel = client.channels.cache.get(universoVoice);
    if (!voiceChannel) return console.error("The channel does not exist!");
    voiceChannel.join().then(connection => {
        console.log("Connesso");
        connection.play('out.mp3');
        client.leaveVoiceChannel;
    }).catch(e => {
        console.error(e);
    });
  }else{

    console.log('uscita');
  }
}


问:
How to subscribe to User Defined fields in Acumatica
I've added on Acumatica User defined field:

How can I add to those fields CommitChanges="true" and how it's possible to add RowUpdated, FieldUpdated functionality for those fields?

答:
The UDF fields are rendered as regular fields, so the Commit Changes can be turned on from JavaScript by setting the onValueChange to 1.

The tricky part is with capturing the event. Unfortunately, the event is not triggered on the UDF field itself. But from the way the field is rendered it is bound to the main Form of the page. For example, on SO301000 - Sales orders it is bound to the Header form - primary view. Which means that it will trigger SO Order row level events.

From JavaScript side you can access this fields by the following way:

```<code>px_all.ctl00_phF_form_t1_AttributeBURDEN
</code>```

you just need to set the onValueChange to 1 to get the Commit Changes working

```<code>px_all.ctl00_phF_form_t1_AttributeBURDEN.onValueChange=1;
</code>```

As I have already explained in my this answer the UDF's are handled via KvExt tables and to access them we need to create additional DAC.

```<code>[PXCacheName("SO Order Attributes")]
[Serializable]
public class SOOrderKvExt : IBqlTable
{
    public abstract class recordID : BqlGuid.Field<recordID> { }
    [PXDBGuid(IsKey = true)]
    public Guid? RecordID { get; set; }

    public abstract class fieldName : BqlString.Field<fieldName> { }
    [PXDBString(50, IsKey = true)]
    [PXUIField(DisplayName = "Name")]
    public string FieldName { get; set; }

    public abstract class valueNumeric : BqlDecimal.Field<valueNumeric> { }
    [PXDBDecimal(8)]
    [PXUIField(DisplayName = "Value Numeric")]
    public decimal? ValueNumeric { get; set; }

    public abstract class valueDate : BqlDateTime.Field<valueDate> { }
    [PXDBDate]
    [PXUIField(DisplayName = "Value Date")]
    public DateTime? ValueDate { get; set; }

    public abstract class valueString : BqlString.Field<valueString> { }
    [PXDBString(256)]
    [PXUIField(DisplayName = "Value String")]
    public string ValueString { get; set; }

    public abstract class valueText : BqlString.Field<valueText> { }
    [PXDBString]
    [PXUIField(DisplayName = "Value Text")]
    public string ValueText { get; set; }
}
</code>```

After this we can catch the event in the SOOrder_RowUpdated handler like below:

```<code>protected virtual void SOOrder_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
{
    if(e.Row is SOOrder row)
    {
        PXResultset<SOOrder> orderWithUDFs = PXSelectJoin<SOOrder,
            LeftJoin<SOOrderKvExt, On<SOOrder.noteID, Equal<SOOrderKvExt.recordID>>,
            LeftJoin<PX.CS.CSAttribute, On<SOOrderKvExt.fieldName, Contains<PX.CS.CSAttribute.attributeID>>>>,
            Where<SOOrder.orderNbr, Equal<Required<SOOrder.orderNbr>>,
            And<SOOrder.orderType,Equal<Required<SOOrder.orderType>>>>>.Select(this.Base, row.OrderNbr,row.OrderType);
        foreach (PXResult<SOOrder,SOOrderKvExt,PX.CS.CSAttribute> orderWithUDF in orderWithUDFs)
        {
            var udfValue = (SOOrderKvExt)orderWithUDF;
            var attributeDef = (PX.CS.CSAttribute)orderWithUDF;
            if(attributeDef.FieldName=="BURDEN")
            {
                //do something
                var value = udfValue.ValueText;//depending on the Attribute.
            }
        }
    }
}
</code>```

So the same way you can work with other Row level events.
Unfortunately, I don't see any way to work with the field directly in the way we all used to do.

Body:
The UDF fields are rendered as regular fields, so the Commit Changes can be turned on from JavaScript by setting the onValueChange to 1.

The tricky part is with capturing the event. Unfortunately, the event is not triggered on the UDF field itself. But from the way the field is rendered it is bound to the main Form of the page. For example, on SO301000 - Sales orders it is bound to the Header form - primary view. Which means that it will trigger SO Order row level events.

From JavaScript side you can access this fields by the following way:

px_all.ctl00_phF_form_t1_AttributeBURDEN

you just need to set the onValueChange to 1 to get the Commit Changes working

px_all.ctl00_phF_form_t1_AttributeBURDEN.onValueChange=1;

As I have already explained in my this answer the UDF's are handled via KvExt tables and to access them we need to create additional DAC.

[PXCacheName("SO Order Attributes")]
[Serializable]
public class SOOrderKvExt : IBqlTable
{
    public abstract class recordID : BqlGuid.Field<recordID> { }
    [PXDBGuid(IsKey = true)]
    public Guid? RecordID { get; set; }

    public abstract class fieldName : BqlString.Field<fieldName> { }
    [PXDBString(50, IsKey = true)]
    [PXUIField(DisplayName = "Name")]
    public string FieldName { get; set; }

    public abstract class valueNumeric : BqlDecimal.Field<valueNumeric> { }
    [PXDBDecimal(8)]
    [PXUIField(DisplayName = "Value Numeric")]
    public decimal? ValueNumeric { get; set; }

    public abstract class valueDate : BqlDateTime.Field<valueDate> { }
    [PXDBDate]
    [PXUIField(DisplayName = "Value Date")]
    public DateTime? ValueDate { get; set; }

    public abstract class valueString : BqlString.Field<valueString> { }
    [PXDBString(256)]
    [PXUIField(DisplayName = "Value String")]
    public string ValueString { get; set; }

    public abstract class valueText : BqlString.Field<valueText> { }
    [PXDBString]
    [PXUIField(DisplayName = "Value Text")]
    public string ValueText { get; set; }
}

After this we can catch the event in the SOOrder_RowUpdated handler like below:

protected virtual void SOOrder_RowUpdated(PXCache sender, PXRowUpdatedEventArgs e)
{
    if(e.Row is SOOrder row)
    {
        PXResultset<SOOrder> orderWithUDFs = PXSelectJoin<SOOrder,
            LeftJoin<SOOrderKvExt, On<SOOrder.noteID, Equal<SOOrderKvExt.recordID>>,
            LeftJoin<PX.CS.CSAttribute, On<SOOrderKvExt.fieldName, Contains<PX.CS.CSAttribute.attributeID>>>>,
            Where<SOOrder.orderNbr, Equal<Required<SOOrder.orderNbr>>,
            And<SOOrder.orderType,Equal<Required<SOOrder.orderType>>>>>.Select(this.Base, row.OrderNbr,row.OrderType);
        foreach (PXResult<SOOrder,SOOrderKvExt,PX.CS.CSAttribute> orderWithUDF in orderWithUDFs)
        {
            var udfValue = (SOOrderKvExt)orderWithUDF;
            var attributeDef = (PX.CS.CSAttribute)orderWithUDF;
            if(attributeDef.FieldName=="BURDEN")
            {
                //do something
                var value = udfValue.ValueText;//depending on the Attribute.
            }
        }
    }
}

So the same way you can work with other Row level events.
Unfortunately, I don't see any way to work with the field directly in the way we all used to do.


问:
Finding Cross Product to find points above/below a line in MatplotLib
I am trying to draw a line in MatPlotLib , and find all points above or below the line depending on the slope.

After reading this post, and reading about Cross Product, I believe this is the best approach for me to check the points.

I am unsure what would be the most optimal way to implement this in python.

```<code>v1 = {x2-x1, y2-y1}   # Vector 1
v2 = {x2-xA, y2-yA}   # Vector 2
xp = v1.x*v2.y - v1.y*v2.x  # Cross product
</code>```

Has anyone tried implementing something similar ?

Is there some other way for me to find if points on the plot are above or below a line in MatPlotLib ?

答:
A dirty way - use the method for left/right with cross product (How to tell whether a point is to the right or left side of a line), then evaluate the slope of the line.  If slope is negative, then any point left of the line is above the line, and if slope is positive any point left of the line is below the line.  If the point is to the right, these are reversed.  (Obviously the answer depends on the orientation of the y-axis, for my example up is negative and down is positive.)  This method requires programming the special cases for vertical and horizontal lines.  For horizontal lines, the cross product method will give you the point's position above the line.  For vertical lines, there is no real answer, but we point to isLeftOfLine instead.

C++ code:

```<code>bool Point::isLeftOfLine(Line cmp)
{
    return ((cmp.p2.x - cmp.p1.x) * (y - cmp.p1.y) > (cmp.p2.y - cmp.p1.y) * (x - cmp.p1.x));
}

bool Point::isTopOfLine(Line cmp)
{
    if(cmp.p1.x == cmp.p2.x || cmp.p1.y == cmp.p2.y)
    {
        return isLeftOfLine(cmp);
    }
return isLeftOfLine(cmp) == cmp.slope() < 0;
}

double Line::slope()
{
    return (p2.y - p1.y) / (p2.x - p1.x);
}
</code>```

Body:
I am trying to draw a line in MatPlotLib , and find all points above or below the line depending on the slope.

After reading this post, and reading about Cross Product, I believe this is the best approach for me to check the points.

I am unsure what would be the most optimal way to implement this in python.

v1 = {x2-x1, y2-y1}   # Vector 1
v2 = {x2-xA, y2-yA}   # Vector 2
xp = v1.x*v2.y - v1.y*v2.x  # Cross product

Has anyone tried implementing something similar ?

Is there some other way for me to find if points on the plot are above or below a line in MatPlotLib ?

Body:
A dirty way - use the method for left/right with cross product (How to tell whether a point is to the right or left side of a line), then evaluate the slope of the line.  If slope is negative, then any point left of the line is above the line, and if slope is positive any point left of the line is below the line.  If the point is to the right, these are reversed.  (Obviously the answer depends on the orientation of the y-axis, for my example up is negative and down is positive.)  This method requires programming the special cases for vertical and horizontal lines.  For horizontal lines, the cross product method will give you the point's position above the line.  For vertical lines, there is no real answer, but we point to isLeftOfLine instead.

C++ code:

bool Point::isLeftOfLine(Line cmp)
{
    return ((cmp.p2.x - cmp.p1.x) * (y - cmp.p1.y) > (cmp.p2.y - cmp.p1.y) * (x - cmp.p1.x));
}

bool Point::isTopOfLine(Line cmp)
{
    if(cmp.p1.x == cmp.p2.x || cmp.p1.y == cmp.p2.y)
    {
        return isLeftOfLine(cmp);
    }
return isLeftOfLine(cmp) == cmp.slope() < 0;
}

double Line::slope()
{
    return (p2.y - p1.y) / (p2.x - p1.x);
}


问:
Why my FlatList in React-Native doesn't update, even after adding extradata?
For the last couple of hours I am trying to make simple list, that you can expand by typing something into text field and pressing button. But it doesn't update my FlatList, even after changing content of extra data. What am I doing wrong?
Please don't mind hard coded ID on updateTask, it is only for debugging. </p>

```<code>import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet, FlatList } from 'react-native'

const DATA = [
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
];

function Item({ title }) {
  return (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );
}

class Inputs extends Component {
   state = {
      task: '',
   }
   handleTask = (text) => {
      this.setState({ task: text })
   }
   updateTask = (task) => {
      DATA.push({
        id: '4',
        title: task
      })
      alert(DATA.length + task);
   }
   render() {
      return (
         <View style = {styles.container}>

          <FlatList
             data={DATA}
             renderItem={({ item }) => <Item title={item.title} />}
             keyExtractor={item => item.id}
             extraData={DATA.length}
          />

            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Task"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handleTask}/>

            <TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () => this.updateTask(this.state.task)
               }>
               <Text style = {styles.submitButtonText}> Submit </Text>
            </TouchableOpacity>
         </View>
      )
   }
}
export default Inputs

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   },
   item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
})
</code>```

答:
change

```<code>extraData={DATA.length}
</code>```

to

```<code>extraData={this.state}
</code>```

Hope it help.

Body:
For the last couple of hours I am trying to make simple list, that you can expand by typing something into text field and pressing button. But it doesn't update my FlatList, even after changing content of extra data. What am I doing wrong?
Please don't mind hard coded ID on updateTask, it is only for debugging.

import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet, FlatList } from 'react-native'

const DATA = [
  {
    id: '1',
    title: 'First Item',
  },
  {
    id: '2',
    title: 'Second Item',
  },
  {
    id: '3',
    title: 'Third Item',
  },
];

function Item({ title }) {
  return (
    <View style={styles.item}>
      <Text style={styles.title}>{title}</Text>
    </View>
  );
}

class Inputs extends Component {
   state = {
      task: '',
   }
   handleTask = (text) => {
      this.setState({ task: text })
   }
   updateTask = (task) => {
      DATA.push({
        id: '4',
        title: task
      })
      alert(DATA.length + task);
   }
   render() {
      return (
         <View style = {styles.container}>

          <FlatList
             data={DATA}
             renderItem={({ item }) => <Item title={item.title} />}
             keyExtractor={item => item.id}
             extraData={DATA.length}
          />

            <TextInput style = {styles.input}
               underlineColorAndroid = "transparent"
               placeholder = "Task"
               placeholderTextColor = "#9a73ef"
               autoCapitalize = "none"
               onChangeText = {this.handleTask}/>

            <TouchableOpacity
               style = {styles.submitButton}
               onPress = {
                  () => this.updateTask(this.state.task)
               }>
               <Text style = {styles.submitButtonText}> Submit </Text>
            </TouchableOpacity>
         </View>
      )
   }
}
export default Inputs

const styles = StyleSheet.create({
   container: {
      paddingTop: 23
   },
   input: {
      margin: 15,
      height: 40,
      borderColor: '#7a42f4',
      borderWidth: 1
   },
   submitButton: {
      backgroundColor: '#7a42f4',
      padding: 10,
      margin: 15,
      height: 40,
   },
   submitButtonText:{
      color: 'white'
   },
   item: {
    backgroundColor: '#f9c2ff',
    padding: 20,
    marginVertical: 8,
    marginHorizontal: 16,
  },
  title: {
    fontSize: 32,
  },
})

Body:
change

extraData={DATA.length}

to

extraData={this.state}

Hope it help.


问:
HTML / VUE - Allow user to select/activate multiple <input> elements and type in them at the same time
I have a HTML table with 2 columns that looks like this:

```<code>Item       Amount
Icecream   $3
Hotdog     $5
Hamburger  $10
</code>```

The "amount" column consists of <input> elements that live in a

The user should be able to select the $3 field, (hold down control?) and then also select the $5 field, then type in $6 , causing the $3 and the $5 to be changed to $6.

I understand this is kind of 2 questions. I think once i know how to let the user select multiple inputs I will be able to figure out the typing part. I'm using Vue in case that helps

答:
You must do a few things to achieve that:

Listen to on click event, which is fairly easy in vuejs

<element @click="firstWay"/> // this will pass only the `$event` as an argument
<element @click="$event => secondWay($event, someOtherProperty)"/> // and this way, you can define your own arguments
```

<pre class="lang-js prettyprint-override"><code>methods: {
  firstWay ($event) { },
  secondWay ($event, someOtherProperty) {}
}
</code>```

Know when ctrl key is pressed (event.ctrlKey is there for you)

Keep track of selected items - using your data object.

Example

Template

        <input
          type="number"
          :value="item.price"
          step="0.01"
          :selected="item.selected"
          @click="$event => onClick($event, item)"
          @input="$event => onInput($event, item)"
        />

```

<h3>JavaScript</h3>

<pre class="lang-js prettyprint-override"><code>  data: {
    items: [
        { name: 'Icecream',     price: 3.14, selected: false },
        { name: 'Hotdog',       price: 6.00, selected: false },
        { name: 'Hamburger',    price: 2.00, selected: false }
    ]
  },
  methods: {
    onClick (event, item) {
      if (event.ctrlKey) {
        item.selected = !item.selected
      }
    },

    onInput (event, item) {
      const value = event.target.value
      item.price = value

      if (!item.selected) return

      this.items
        .filter(it => it.selected)
        .forEach(it => {
            it.price = value
        })
    }
  }
</code>```

Styles

input[selected] {
  outline: 1px solid red;
}
```

Here you play with working demo

Body:
I have a HTML table with 2 columns that looks like this:

Item       Amount
Icecream   $3
Hotdog     $5
Hamburger  $10

The "amount" column consists of <input> elements that live in a

The user should be able to select the $3 field, (hold down control?) and then also select the $5 field, then type in $6 , causing the $3 and the $5 to be changed to $6.

I understand this is kind of 2 questions. I think once i know how to let the user select multiple inputs I will be able to figure out the typing part. I'm using Vue in case that helps

Body:
You must do a few things to achieve that:

Listen to on click event, which is fairly easy in vuejs

<element @click="firstWay"/> // this will pass only the `$event` as an argument
<element @click="$event => secondWay($event, someOtherProperty)"/> // and this way, you can define your own arguments

methods: {
  firstWay ($event) { },
  secondWay ($event, someOtherProperty) {}
}

Know when ctrl key is pressed (event.ctrlKey is there for you)

Keep track of selected items - using your data object.

Example

Template

    <tr
      v-for="(item, idx) in items"
      :key="idx"
    >
      <td v-text="item.name"/>
      <td>
        <input
          type="number"
          :value="item.price"
          step="0.01"
          :selected="item.selected"
          @click="$event => onClick($event, item)"
          @input="$event => onInput($event, item)"
        />
      </td>
    </tr>

JavaScript

  data: {
    items: [
        { name: 'Icecream',     price: 3.14, selected: false },
        { name: 'Hotdog',       price: 6.00, selected: false },
        { name: 'Hamburger',    price: 2.00, selected: false }
    ]
  },
  methods: {
    onClick (event, item) {
      if (event.ctrlKey) {
        item.selected = !item.selected
      }
    },

    onInput (event, item) {
      const value = event.target.value
      item.price = value

      if (!item.selected) return

      this.items
        .filter(it => it.selected)
        .forEach(it => {
            it.price = value
        })
    }
  }

Styles

input[selected] {
  outline: 1px solid red;
}

Here you play with working demo


问:
How connect socket in different port in PHP?
This code is working fine.
I am successfully tested socket connection in my system in port:80 but not able to connect in different port .

```<code><?php
echo "```";
error_reporting(E_ALL);

echo "
TCP/IP Connection
\n";

/* Get the port for the WWW service. */
$service_port = 8000;

/* Get the IP address for the target host. */
$address = gethostbyname('localhost');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";

?>
```

<p>Output:</p>

```Attempting to connect to '127.0.0.1' on port '8000'...socket_connect() failed.
Reason: () Connection refused
Closing socket...OK.
```

I need to connect in port different than 80, so please any Idea?
Thank You

答: You can't connect to a generic port if there isn't a server socket opened there.</p>

Body:
This code is working fine.
I am successfully tested socket connection in my system in port:80 but not able to connect in different port .

<?php
echo "
";
error_reporting(E_ALL);

echo "
TCP/IP Connection
\n";

/* Get the port for the WWW service. */
$service_port = 8000;

/* Get the IP address for the target host. */
$address = gethostbyname('localhost');

/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
    echo "OK.\n";
}

echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
    echo "OK.\n";
}

echo "Closing socket...";
socket_close($socket);
echo "OK.\n\n";

?>

Output:

Attempting to connect to '127.0.0.1' on port '8000'...socket_connect() failed.
Reason: () Connection refused
Closing socket...OK.

I need to connect in port different than 80, so please any Idea?
Thank You


问:
Trouble understanding Maven Surefire plugin's parallel parameters
Quoting from maven.apache.org:

... the parallel parameter. The possible values depend on the test
  provider used. For JUnit 4.7 and onwards, this may be methods,
  classes, both, suites, suitesAndClasses, suitesAndMethods,
  classesAndMethods or all

I just want to execute Cucumber feature files in parallel. What do these parameters--main, methods, classes, etc.-- mean in this context?  Here's an excerpt from my pom.xml file:

```<code><build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>
            <configuration>
                **<parallel>methods</parallel>**
                <useUnlimitedThreads>true</useUnlimitedThreads>
            </configuration>
        </plugin>
    </plugins>
</build>
</code>```

I just put 'methods' in the parallel tag because the guide on Cucumber's Parallel Execution page used this configuration. I have no idea why they chose to configure it this way. Why didn't they choose other options like 'classes' or 'classesAndMethods'?

答:
This is a really good question! I am one of the implementer of support for parallel execution in Cucumber and it actually took me quite a while to work this all out.

JUnit, Surefire and Cucumber have evolved together. So certain concepts were initially introduced with a narrow focus that was later generalized but not renamed. As a result you run into these rather odd mismatches.

So JUnit represents tests as a simple tree:

```<code>Example1Test.class
 |- method1()
 |- method2()
 |- method3()
Example2Test.class
 |- method1()
 |- method2()
 |- method3()
</code>```

Because JUnit initially didn't have parallel execution this was handled by surefire. Surefire would start multiple instances of JUnit and divide the classes that should be tested between them.

JUnit added support for parallel execution down to method level by adding setScheduler(RunnerScheduler scheduler) to test executors. Once this was present, surefire had to distinguish between using its own parallel execution method, junits parallel execution method or both. Hence the different options and their names.

At some point in time JUnit also added support for implementing custom runners. Cucumber uses this implements a custom runner. And to JUnit this looks like this:

```<code>@RunWith(Cucumber.class)
RunCucumberTest.class
|- Feature1
|  |- scenario1()
|- Feature2
|  |- scenario1()
|  |- scenario2()
</code>```

To execute features in parallel JUnit has to use setScheduler(scheduler) method on the executor (Cucumber.class). To do this JUnit has to be instructed by Surefire to use a parallel scheduler. And the way we do this is by telling Surefire to use the methods option.

Now this is a rather high level explanation and you can zoom in much more by looking at the source code:

https://github.com/cucumber/cucumber-jvm/blob/master/junit/src/main/java/io/cucumber/junit/Cucumber.java

https://github.com/apache/maven-surefire/blob/master/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreProvider.java

https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runner/JUnitCore.java

https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/ParentRunner.java

Body:
Quoting from maven.apache.org:

... the parallel parameter. The possible values depend on the test
  provider used. For JUnit 4.7 and onwards, this may be methods,
  classes, both, suites, suitesAndClasses, suitesAndMethods,
  classesAndMethods or all

I just want to execute Cucumber feature files in parallel. What do these parameters--main, methods, classes, etc.-- mean in this context?  Here's an excerpt from my pom.xml file:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>3.0.0-M4</version>
            <configuration>
                **<parallel>methods</parallel>**
                <useUnlimitedThreads>true</useUnlimitedThreads>
            </configuration>
        </plugin>
    </plugins>
</build>

I just put 'methods' in the parallel tag because the guide on Cucumber's Parallel Execution page used this configuration. I have no idea why they chose to configure it this way. Why didn't they choose other options like 'classes' or 'classesAndMethods'?

Body:
This is a really good question! I am one of the implementer of support for parallel execution in Cucumber and it actually took me quite a while to work this all out.

JUnit, Surefire and Cucumber have evolved together. So certain concepts were initially introduced with a narrow focus that was later generalized but not renamed. As a result you run into these rather odd mismatches.

So JUnit represents tests as a simple tree:

Example1Test.class
 |- method1()
 |- method2()
 |- method3()
Example2Test.class
 |- method1()
 |- method2()
 |- method3()

Because JUnit initially didn't have parallel execution this was handled by surefire. Surefire would start multiple instances of JUnit and divide the classes that should be tested between them.

JUnit added support for parallel execution down to method level by adding setScheduler(RunnerScheduler scheduler) to test executors. Once this was present, surefire had to distinguish between using its own parallel execution method, junits parallel execution method or both. Hence the different options and their names.

At some point in time JUnit also added support for implementing custom runners. Cucumber uses this implements a custom runner. And to JUnit this looks like this:

@RunWith(Cucumber.class)
RunCucumberTest.class
|- Feature1
|  |- scenario1()
|- Feature2
|  |- scenario1()
|  |- scenario2()

To execute features in parallel JUnit has to use setScheduler(scheduler) method on the executor (Cucumber.class). To do this JUnit has to be instructed by Surefire to use a parallel scheduler. And the way we do this is by telling Surefire to use the methods option.

Now this is a rather high level explanation and you can zoom in much more by looking at the source code:

https://github.com/cucumber/cucumber-jvm/blob/master/junit/src/main/java/io/cucumber/junit/Cucumber.java

https://github.com/apache/maven-surefire/blob/master/surefire-providers/surefire-junit47/src/main/java/org/apache/maven/surefire/junitcore/JUnitCoreProvider.java

https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runner/JUnitCore.java

https://github.com/junit-team/junit4/blob/master/src/main/java/org/junit/runners/ParentRunner.java


问:
LinkedIn v2 share api not fetching og:image tags
I am making a call to the linkedin v2 api to share a link (an article) and it works fine in the post inspector (image thumbnail is shown) but when I use the api the thumbnail is not displayed.

The documentation says LinkedIn will automatically fetch the thumbnail from the meta og:image tag....which I have.

https://learn.microsoft.com/en-us/linkedin/marketing/integrations/community-management/shares/share-api#controlling-how-share-content-is-displayed

Controlling How Share Content is Displayed If you're unable to provide
  a complete share with all metadata, LinkedIn fetches the content
  directly from the page. To best facilitate this, set [Open Graph
  tags][http://ogp.me/] if you have control over the published content
  that's being shared.

TABLE 11 Tag  Description og:title    Set the title tag to control how
  your web page's title displays on LinkedIn. og:description    Set the
  description tag to control how the shared link is described on
  LinkedIn. og:image    Set the image tag to control which image is
  displayed on LinkedIn. og:url The URL tag is recommended to provide
  the best URL link for LinkedIn to use to point to your web page. If
  you're unable to set Open Graph tags within the page that's being
  shared, LinkedIn attempts to fetch the content automatically by
  determining the title, description, thumbnail image, etc.

Does anyone know how to get the thumbnail to show up via the v2 share api?

答:
If you have the og: tag working, then it definitely should be working.  Source: Official LinkedIn Shareable Documentation.

They state some limitations, but, I don't see your image, so, I'm not sure how to point out anything specific, but generally, according to the linked docs above...

Max file size: 5 MB

Minimum image dimensions: 1200 (w) x 627 (h) pixels

Recommended ratio: 1.91:1

If you're not sure, check out the LinkedIn Post Inspector with the URL you are trying to share.  I have found that there is actually other meta data that LinkedIn considers sometimes more important: for instance, I have seen it looking at oEmbed data, which few people are aware is installed on their servers.

I know for a fact it works for me.  Tested just today:

Hope this helps!


问:
CERTIFICATE_VERIFY_FAILED: certificate has expired on all flutter apps
I am getting CERTIFICATE_VERIFY_FAILED: certificate has expired in all network calls (including Network_image calls) - all my flutter apps even the old ones.

All apps were working fine but I don't know what caused this error. Other apps are working fine (Chrome , facebook , ..)

I also checked phone Date & time.
My flutter version is Flutter 1.12.13+hotfix.5 • channel stable •

答:
I assume you are making requests to a server you manage?

Try testing your server with this tool: https://www.ionos.com/tools/ssl-checker and see if it says that it is "not installed correctly".

If you find that it has been working historically but recently stopped, you likely have an invalid chain of trust. Recently, a common root CA certificate expired. Your server may be using this and sending it as part of it's chain of certificates it sends to clients. If that is the case, and it is this recently-expired root CA, your fix will  most likely look like removing that root certificate from your bundle. So you'd include the intermediate certificates still, but exclude the root. You can then use these tools to revalidate if things are setup correctly.

You can also see the chain and some of the validity information using this tool: https://www.sslshopper.com/ssl-checker.html


问:
Aggregating results from multiple go routines with common channel
I have the following program which serves as a proof of concept. I'm attempting to aggregate the results from chann, that is, too merge each instance of chann in to a common slice. Is this possible with my approach?

So my output for the following example would be a slice containing the following (in any order): []int{0,1,2}, thanks.

```<code> func DoStuff(i int, chann chan[]int,  wg *sync.WaitGroup) {
    defer wg.Done()
    chann <-[]int{i}
 }

func main() {
    var wg sync.WaitGroup
    chann := make(chan int[], 3)
    defer close(chann)

    for i := 0; i < count; 3 {
        wg.Add(1)
        go DoStuff(i, chann, &wg)
    }

    wg.Wait()

    for {
        select {
        case result := <-chann:
            fmt.Println(result)
            os.Exit(1)
        }
    }

    return nil
}
</code>```

答:
what you want to do is possible, but your program will not run because you are reading from the channel after wg.Wait(), so all goroutines will stop waiting to write, because you will never read from the channel.

You can read from the channel in a goroutine:

```<code>for i := 0; i < count; 3 {
        wg.Add(1)
        go DoStuff(i, chann, &wg)
    }
}
go func() {
   for data:=range chann {
      // Process data
   }
}()
wg.Wait()
// Close here, so the reading goroutine can terminate
close(chann)
</code>```

Body:
I have the following program which serves as a proof of concept. I'm attempting to aggregate the results from chann, that is, too merge each instance of chann in to a common slice. Is this possible with my approach?

So my output for the following example would be a slice containing the following (in any order): []int{0,1,2}, thanks.

 func DoStuff(i int, chann chan[]int,  wg *sync.WaitGroup) {
    defer wg.Done()
    chann <-[]int{i}
 }

func main() {
    var wg sync.WaitGroup
    chann := make(chan int[], 3)
    defer close(chann)

    for i := 0; i < count; 3 {
        wg.Add(1)
        go DoStuff(i, chann, &wg)
    }

    wg.Wait()

    for {
        select {
        case result := <-chann:
            fmt.Println(result)
            os.Exit(1)
        }
    }

    return nil
}

Body:
what you want to do is possible, but your program will not run because you are reading from the channel after wg.Wait(), so all goroutines will stop waiting to write, because you will never read from the channel.

You can read from the channel in a goroutine:

for i := 0; i < count; 3 {
        wg.Add(1)
        go DoStuff(i, chann, &wg)
    }
}
go func() {
   for data:=range chann {
      // Process data
   }
}()
wg.Wait()
// Close here, so the reading goroutine can terminate
close(chann)


问:
Dependency missing when running AzureML Estimator in docker environment

Scenario description

I'm trying to submit a training script to AzureML (want to use AmlCompute, but I'm starting/testing locally first, for debugging purposes).

The train.py script I have uses a custom package (arcus.ml) and I believe I have specified the right settings and dependencies, but still I get the error:

User program failed with ModuleNotFoundError: No module named 'arcus.ml'

Code and reproduction

This the python code I have:

name='test'
script_params = {
    '--test-par': 0.2
}

est = Estimator(source_directory='./' + name,
                   script_params=script_params,
                   compute_target='local',
                   entry_script='train.py',
                   pip_requirements_file='requirements.txt',
                   conda_packages=['scikit-learn','tensorflow', 'keras'])

run = exp.submit(est)
print(run.get_portal_url())
```

<p>This is the (fully simplified) train.py script in the <code>test</code>directory:</p>

<pre class="lang-py prettyprint-override"><code>from arcus.ml import dataframes as adf
from azureml.core import Workspace, Dataset, Datastore, Experiment, Run

# get hold of the current run
run = Run.get_context()
ws = run.get_environment()

print('training finished')
</code>```

And this is my requirements.txt file

```<code>arcus-azureml
arcus-ml
numpy
pandas
azureml-core
tqdm
joblib
scikit-learn
matplotlib
tensorflow
keras
</code>```

Logs

In the logs file of the run, I can see this section, sot it seems the external module is being installed anyhow.

```<code>Collecting arcus-azureml
  Downloading arcus_azureml-1.0.3-py3-none-any.whl (3.1 kB)
Collecting arcus-ml
  Downloading arcus_ml-1.0.6-py3-none-any.whl (2.1 kB)
</code>```

答: It could be there's an issue with arcus-ml 1.0.6 wheel installable, like Anders pointed out it doesn't seem to have any code. Could you try with earlier version arcus-ml==1.0.5 ? </p>

Body:
Scenario description

I'm trying to submit a training script to AzureML (want to use AmlCompute, but I'm starting/testing locally first, for debugging purposes).

The train.py script I have uses a custom package (arcus.ml) and I believe I have specified the right settings and dependencies, but still I get the error:

User program failed with ModuleNotFoundError: No module named 'arcus.ml'

Code and reproduction

This the python code I have:

name='test'
script_params = {
    '--test-par': 0.2
}

est = Estimator(source_directory='./' + name,
                   script_params=script_params,
                   compute_target='local',
                   entry_script='train.py',
                   pip_requirements_file='requirements.txt',
                   conda_packages=['scikit-learn','tensorflow', 'keras'])

run = exp.submit(est)
print(run.get_portal_url())

This is the (fully simplified) train.py script in the testdirectory:

from arcus.ml import dataframes as adf
from azureml.core import Workspace, Dataset, Datastore, Experiment, Run

# get hold of the current run
run = Run.get_context()
ws = run.get_environment()

print('training finished')

And this is my requirements.txt file

arcus-azureml
arcus-ml
numpy
pandas
azureml-core
tqdm
joblib
scikit-learn
matplotlib
tensorflow
keras

Logs

In the logs file of the run, I can see this section, sot it seems the external module is being installed anyhow.

Collecting arcus-azureml
  Downloading arcus_azureml-1.0.3-py3-none-any.whl (3.1 kB)
Collecting arcus-ml
  Downloading arcus_ml-1.0.6-py3-none-any.whl (2.1 kB)


问:
How to eliminate elements with certain characters or phrases from a list in python?
I have a list of plant names from an excel spreadsheet that I have extracted with pandas. After removing duplicates and making the entire list lower-case, I wanted to remove characters like parenthesis, apostrophes, dashes, and phrases like "A" and "The" to further eliminate any possible duplicates so that in a list like: ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin") only "Pumpkin" would remain. Note I don't want to remove just the characters from the string, but the entire string from the list.

```<code>def checkSyntax(str):
    boolean = None

    regexes = ["a ", "the ", "^\W"]
    combined = "(" + ")|(".join(regexes) + ")"
    match = re.match('combined', str)
    if match == None:
        boolean = True

    return boolean

def elimInvalidNames(names):
    new_names = [s for s in names if checkSyntax(s)]
    return new_names

test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
test_list = list(map(lambda x: x.lower(), test_list))
test_list = elimInvalidNames(test_list)
print(test_list)
</code>```

For some reason this gets rid of "the" and "a" but not parenthesis, dashes, or apostrophes.

答:
If regex is not mandatory be used, try it:

names = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
def checkSyntax(s):
    regexes = ["a ", "the ",'"', "'", '\\', '.', ',', ')', '(', '-']
    return not any(letra in s.lower() for letra in regexes)

def eIn(names):
    new_names = [s for s in names if checkSyntax(s)]
    return new_names
```

Body:
I have a list of plant names from an excel spreadsheet that I have extracted with pandas. After removing duplicates and making the entire list lower-case, I wanted to remove characters like parenthesis, apostrophes, dashes, and phrases like "A" and "The" to further eliminate any possible duplicates so that in a list like: ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin") only "Pumpkin" would remain. Note I don't want to remove just the characters from the string, but the entire string from the list.

def checkSyntax(str):
    boolean = None

    regexes = ["a ", "the ", "^\W"]
    combined = "(" + ")|(".join(regexes) + ")"
    match = re.match('combined', str)
    if match == None:
        boolean = True

    return boolean

def elimInvalidNames(names):
    new_names = [s for s in names if checkSyntax(s)]
    return new_names

test_list = ("A Pumpkin", "Pumpkin", "The Pumpkin", "Pump-kin", "(European) Pumpkin", "Pumpkin (Orange)", "Farmer's Pumpkin")
test_list = list(map(lambda x: x.lower(), test_list))
test_list = elimInvalidNames(test_list)
print(test_list)

For some reason this gets rid of "the" and "a" but not parenthesis, dashes, or apostrophes.