问:
Currency field constraint check done before rounding off
HI All
i was unit testing my currency field and i found this issue that can be considered as a bug.

```<code><xforms:bind id="amount" nodeset="instance('form')/data/amount"
constraint="if(.!='') then number(.) >0 and string-length(.)<20 else ."/>
...
<fr:currency bind="amount" xxforms:maxlength="50" incremental="true">
   <xforms:alert>Value should be below $ 9,999,999,999,999,999,999.99</xforms:alert>
</fr:currency>
</code>```

The condition that i am trying to achieve in the above case is, to put a max value check < "9999999,999999999.99" this has 19 characters total. (i had tried constraint="if(.='') then true() else number(.)<10000000000000000"  also instead of length check, but later seeing some bug in that number check switched to this string-length check)

now the issue in this case of string length is
if i enter "9,999,999,999,999,999.991" the following happens
1. the constraint check is performed. which returns 'false' as "9999999999999999.991" = 20 length
2. the currency amount is rounded off.

so my constraint check fails. But if i click the field and click outside the field, the constraint check returns true

can anyone suggest a better way to do it or how to solve the above issue.

答:
A few things to note:

xxforms:maxlength does not work on fr:currency or any other fr: control

Numbers are evaluated against other numbers as a double-precision 64-bit floating point type.  Take this into account when numbers are being evaluated.  Basically what this means is large numbers get rounded.  it is possible that problems you experience with large number evaluations is not a bug but rather just math.

For example, the numbers between 9999999999999998976.00  and 10000000000000001023.99 all evaluate to 1.0E19

Body:
HI All
i was unit testing my currency field and i found this issue that can be considered as a bug.

<xforms:bind id="amount" nodeset="instance('form')/data/amount"
constraint="if(.!='') then number(.) >0 and string-length(.)<20 else ."/>
...
<fr:currency bind="amount" xxforms:maxlength="50" incremental="true">
   <xforms:alert>Value should be below $ 9,999,999,999,999,999,999.99</xforms:alert>
</fr:currency>

The condition that i am trying to achieve in the above case is, to put a max value check < "9999999,999999999.99" this has 19 characters total. (i had tried constraint="if(.='') then true() else number(.)<10000000000000000"  also instead of length check, but later seeing some bug in that number check switched to this string-length check)

now the issue in this case of string length is
if i enter "9,999,999,999,999,999.991" the following happens
1. the constraint check is performed. which returns 'false' as "9999999999999999.991" = 20 length
2. the currency amount is rounded off.

so my constraint check fails. But if i click the field and click outside the field, the constraint check returns true

can anyone suggest a better way to do it or how to solve the above issue.


来源: stackexchange

问:
How to insert a random string into the sed 's//' replace string for each line actioned?
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

```<code>$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590
</code>```

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

答:
Depends on your version of sed, but -

```<code>$: cat x
a
b
c
d
e

$: sed 's/.*/printf "%05d\n" $RANDOM/e' x
30181
30514
24742
28555
26267
</code>```

The e means execute, and spawns a subshell, so be wary of the cost.

addendum

You can format output. printf "%07.7s\n" $(($RANDOM%10000))$(($RANDOM%10000)) will always print 7 digits with leading zero pad, and ameliorate the constraints from the default range, which makes 10000 numbers that starts with 1, 10000 numbers that start with 2, and 2,767 that start with 3 out of a total of 32,767 aside from those in the normal 0-9999 range - not an ideal distribution. You might also just use awk for better random numbers.

ContentLicense: CC BY-SA 4.0

Body:
This:

echo "    " | tr ' ' '\n' | sed "s|.*|$RANDOM|"

Or this:

echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"

Will print a list of 5 numbers (space is replaced by newline, sed replaces each line with $RANDOM), and those 5 numbers will all be the same:

$ echo "    " | tr ' ' '\n' | sed "s|.*|$(echo $RANDOM)|"
21590
21590
21590
21590
21590

This is because the replace of $RANDOM to a random value happens only once.

What is the easiest and shortest way, preferably by only using sed, to actually print a different random number for each line. i.e. to provide some "secondary input stream" which differs for each line that sed handles?

I could do it with xargs, but I wonder if there is a way to do it with sed only.

Body:
Depends on your version of sed, but -

$: cat x
a
b
c
d
e

$: sed 's/.*/printf "%05d\n" $RANDOM/e' x
30181
30514
24742
28555
26267

The e means execute, and spawns a subshell, so be wary of the cost.

addendum

You can format output. printf "%07.7s\n" $(($RANDOM%10000))$(($RANDOM%10000)) will always print 7 digits with leading zero pad, and ameliorate the constraints from the default range, which makes 10000 numbers that starts with 1, 10000 numbers that start with 2, and 2,767 that start with 3 out of a total of 32,767 aside from those in the normal 0-9999 range - not an ideal distribution. You might also just use awk for better random numbers.


问:
Using font-awesome in python django application
I'm trying to load a local copy of font awesome icons in my python django app.

My template base.html contains:

```<code>{% load static %}
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'appointments/css/all.css' %}" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
    <title>{% block title %}Hello, world!{% endblock %}</title>
</head>
</code>```

as adapted from https://docs.djangoproject.com/en/2.0/howto/static-files/

The directory structure of my app is:

```<code>joel@hp:~/myappointments$ tree
.
├── appointments
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   ├── models.py
│   ├── static
│   │   └── appointments
│   │       ├── css
│   │       │   ├── all.css
│   │       └── webfonts
│   │           ├── fa-brands-400.eot
│   │           ├── fa-brands-400.svg
│   │           ├── fa-brands-400.ttf
│   │           ├── fa-brands-400.woff
│   │           ├── fa-brands-400.woff2
│   │           ├── fa-regular-400.eot
│   │           ├── fa-regular-400.svg
│   │           ├── fa-regular-400.ttf
│   │           ├── fa-regular-400.woff
│   │           ├── fa-regular-400.woff2
│   │           ├── fa-solid-900.eot
│   │           ├── fa-solid-900.svg
│   │           ├── fa-solid-900.ttf
│   │           ├── fa-solid-900.woff
│   │           └── fa-solid-900.woff2
│   ├── templates
│   │   └── appointments
│   │       ├── base.html
│   │       ├── createappointment.html
│   │       ├── doctor.html
│   │       ├── doctors.html
│   │       ├── home.html
│   │       ├── index.html
│   │       ├── navbar.html
│   │       ├── patient.html
│   │       └── patients.html
│   ├── tests.py
│   ├── urls.py
│   ├── using shell.txt
│   └── views.py
├── appointments.ipynb
├── db.sqlite3
├── manage.py
├── myappointments
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
</code>```

However these icons are not being served. It works if I use the following:

```<code><link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
</code>```

答:
I just had this problem,
wanted to comment it to say  someone posted on pypi :
https://pypi.org/project/django-static-fontawesome/
a "clean" css with good "url" link,

without ron g i would have never figured why it wouldn't work

Body:
I'm trying to load a local copy of font awesome icons in my python django app.

My template base.html contains:

{% load static %}
<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <link rel="stylesheet" href="{% static 'appointments/css/all.css' %}" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">
    <title>{% block title %}Hello, world!{% endblock %}</title>

as adapted from https://docs.djangoproject.com/en/2.0/howto/static-files/

The directory structure of my app is:

joel@hp:~/myappointments$ tree
.
├── appointments
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   ├── __init__.py
│   ├── models.py
│   ├── static
│   │   └── appointments
│   │       ├── css
│   │       │   ├── all.css
│   │       └── webfonts
│   │           ├── fa-brands-400.eot
│   │           ├── fa-brands-400.svg
│   │           ├── fa-brands-400.ttf
│   │           ├── fa-brands-400.woff
│   │           ├── fa-brands-400.woff2
│   │           ├── fa-regular-400.eot
│   │           ├── fa-regular-400.svg
│   │           ├── fa-regular-400.ttf
│   │           ├── fa-regular-400.woff
│   │           ├── fa-regular-400.woff2
│   │           ├── fa-solid-900.eot
│   │           ├── fa-solid-900.svg
│   │           ├── fa-solid-900.ttf
│   │           ├── fa-solid-900.woff
│   │           └── fa-solid-900.woff2
│   ├── templates
│   │   └── appointments
│   │       ├── base.html
│   │       ├── createappointment.html
│   │       ├── doctor.html
│   │       ├── doctors.html
│   │       ├── home.html
│   │       ├── index.html
│   │       ├── navbar.html
│   │       ├── patient.html
│   │       └── patients.html
│   ├── tests.py
│   ├── urls.py
│   ├── using shell.txt
│   └── views.py
├── appointments.ipynb
├── db.sqlite3
├── manage.py
├── myappointments
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py

However these icons are not being served. It works if I use the following:

<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">


问:
Storing module names inside map in database
I am creating a notification service for an IOT app using Elixir/Ecto/Phoenix.
A sensor in this app can have multiple values e.g.

```<code>temperature: ["temp"],
accelerometer: ["ax", "ay", "az"]
</code>```

To create a generic notification policy I have to store the module name with the sensor which will implement the logic for handling eligibility rule. Also, since each sensor can have multiple values associated with it accelerometer -> ax, ay, az the module can be different for different values.

```<code>  schema("acqdat_sensor_notifications") do
    field(:rule_values, :map)
    field(:alarm_status, :boolean, default: false)
    belongs_to(:sensor, Sensor, on_replace: :delete)

    timestamps()
  end
</code>```

The rule values column will store data in the following format e.g. for accelerometer sensor.

```<code>%{
  "ax" => %{
    module: "NotificationPolicyA",
    module_preferences: {"prefA": valuea, "prefb": valueb}
  },
  "ay" => %{
    module: "NotificationPolicyB",
    module_preferences: {"pref1": value1, "pref2": value2}
  },
}
</code>```

The problem here is storing the module name which will handle the logic. I can not use enumeration library like ecto_enum as the values are stored in a jsonb map which is not constant(can not use embeds here). It keeps changing with the sensor name and the module used for processing it.

At present I am handling it by using a map

```<code>%{
  NotificationPolicyA: 0,
  NotificationPolicyA: 1
  .
  .
  .
}
</code>```

and then storing the integers in the db so that if the module name is modified only the map is changed.

```<code>"ax" => %{
    module: 0,
    module_preferences: {"prefA": valuea, "prefb": valueb}
  }
</code>```

What could be alternate approach to handle this kind of scenario with ecto?

答:
You can store the module name as string on the database, use String.to_existing_atom/1 to convert it and Kernel.apply/3 to run any function that you need.

Example:

```<code>iex(2)> apply(String.to_existing_atom("Elixir.MyApp.Version"), :run, [1])
0.29.1
</code>```

Body:
I am creating a notification service for an IOT app using Elixir/Ecto/Phoenix.
A sensor in this app can have multiple values e.g.

temperature: ["temp"],
accelerometer: ["ax", "ay", "az"]

To create a generic notification policy I have to store the module name with the sensor which will implement the logic for handling eligibility rule. Also, since each sensor can have multiple values associated with it accelerometer -> ax, ay, az the module can be different for different values.

  schema("acqdat_sensor_notifications") do
    field(:rule_values, :map)
    field(:alarm_status, :boolean, default: false)
    belongs_to(:sensor, Sensor, on_replace: :delete)

    timestamps()
  end

The rule values column will store data in the following format e.g. for accelerometer sensor.

%{
  "ax" => %{
    module: "NotificationPolicyA",
    module_preferences: {"prefA": valuea, "prefb": valueb}
  },
  "ay" => %{
    module: "NotificationPolicyB",
    module_preferences: {"pref1": value1, "pref2": value2}
  },
}

The problem here is storing the module name which will handle the logic. I can not use enumeration library like ecto_enum as the values are stored in a jsonb map which is not constant(can not use embeds here). It keeps changing with the sensor name and the module used for processing it.

At present I am handling it by using a map

%{
  NotificationPolicyA: 0,
  NotificationPolicyA: 1
  .
  .
  .
}

and then storing the integers in the db so that if the module name is modified only the map is changed.

"ax" => %{
    module: 0,
    module_preferences: {"prefA": valuea, "prefb": valueb}
  }

What could be alternate approach to handle this kind of scenario with ecto?

Body:
You can store the module name as string on the database, use String.to_existing_atom/1 to convert it and Kernel.apply/3 to run any function that you need.

Example:

iex(2)> apply(String.to_existing_atom("Elixir.MyApp.Version"), :run, [1])
0.29.1


问:
Unable to cancel Twisted Deferred chain (AlreadyCalledError)
I'm trying to cancel a Deferred chain (main) whenever some chained deferred (child) raises an error.
But I'm getting an AlreadyCalledError and the chain continues its work.

Here's the code:

from twisted.internet import defer

def asyncText(s, okCallback, errCallback):
  deferred = defer.Deferred()
  deferred.addCallbacks(okCallback, errCallback)
  if s.find('STOP')>=0:
    deferred.errback(ValueError('You are trying to print the unprintable :('))
  else:
    deferred.callback(s)
  return deferred

def asyncChain():
  texts = ['Hello StackOverflow,',
           'this is an example of Twisted.chainDeferred()',
           'which is raising an AlreadyCalledError',
           'when I try to cancel() it.',
           'STOP => I will raise error and should stop the main deferred',
           'Best regards'
           ]

  mainDeferred= defer.Deferred()

  for text in texts:
    def onSuccess(res):
      print('>> {}'.format(res))

    def onError(err):
      print('Error!! {}'.format(err))
      mainDeferred.cancel()

    d = asyncText(text, onSuccess, onError)
    mainDeferred.chainDeferred(d)
```

<p>And here's the output:</p>

```>>> asyncChain()
- Hello StackOverflow,
- this is an example of Twisted.chainDeferred()
- which is raising an AlreadyCalledError
- when I try to cancel() it.
Error!! [Failure instance: Traceback (failure with no frames): <class 'ValueError'>: You are trying to print the unprintable :(
]
- Best regards
Unhandled error in Deferred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../test.py", line 1, in asyncChain
    mainDeferred.chainDeferred(d)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 435, in chainDeferred
    return self.addCallbacks(d.callback, d.errback)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 311, in addCallbacks
    self._runCallbacks()
--- <exception caught here> ---
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 501, in errback
    self._startRunCallbacks(fail)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 561, in _startRunCallbacks
    raise AlreadyCalledError
twisted.internet.defer.AlreadyCalledError:
```

<p>I also tried to use a <code>canceller</code>, like so:</p>

<pre class="lang-py prettyprint-override"><code>def asyncOnCancel(d):
  print('------ cancel() called ------')
  d.errback(ValueError('chain seems to be cancelled!'))
def asyncChainOnError(err):
  print('------ ERROR ON Chain {} ------'.format(err))

...
  mainDeferred= defer.Deferred(canceller= asyncOnCancel)
  mainDeferred.addErrback(asyncChainOnError)
...
</code>```

But result is the same.

I also tried delaying child .callback(s) calls, or calling them after the .chainDeferred(). But I get always the same behaviour.

Is it really possible to cancel a chained Deferred (and getting chained child deferreds to get cancelled too)?

Why I'm getting this AlreadyCalledError?

I'm using python 3.6.6 and Twisted 18.9.0.

Thanks!

******* EDIT *******

After Jean-Paul answer, and noticing that .chainDeferred() is not what I need, I'll put here in a clearer way what I want (and how I finnally did it).

What I want was quite simpler: to run several Deferred, in a "synchronous" way (they have to wait for the previous one to have finished), although they don't need to share their results. If one fails, the rest of them is not executed.

Turns out is quite easy to do it with @defer.inlineCallbacks and yield. Here an example:

def asyncText(s):
  deferred = defer.Deferred()
  if s.find('STOP') >= 0:
    deferred.callback(True)
  else:
    deferred.callback(False)
  return deferred

@defer.inlineCallbacks
def asyncChain():
  texts = ['Hello StackOverflow,',
           'this is a simpler way to explain the question.',
           'I need no chainDeferred(). I need no .cancel().',
           'I just need inlineCallbacks decorator.',
           'STOP',
           'Yeah I will not be printed'
           ]
  for text in texts:
    stopHere = yield asyncText(text)
    if stopHere:
      break
    print('- {}'.format(text))

deferred= asyncChain()
```

```>>> asyncChain()
- Hello StackOverflow,
- this is a simpler way to explain the question.
- I need no chainDeferred(). I need no .cancel().
- I just need inlineCallbacks decorator.
```

答:
It's not clear what you're actually trying to do but I think your chain is backwards from what you expect:

```<code>    d = asyncText(text, onSuccess, onError)
    mainDeferred.chainDeferred(d)
</code>```

d has already fired when asyncText returns.  But mainDeferred.chainDeferred(d) means "when mainDeferred fires, pass its result to d".  Since d has already fired, this is invalid.  A Deferred can only fire once.

Perhaps you meant d.chainDeferred(mainDeferred) instead.  Then "when d fires, pass its result to mainDeferred".

However, the there is still a problem since if you chain d to mainDeferred then it doesn't make sense to cancel mainDeferred in a callback on d.  The result will propagate from d to mainDeferred because they're chained.  Cancellation is not necessary or useful.

Body:
I'm trying to cancel a Deferred chain (main) whenever some chained deferred (child) raises an error.
But I'm getting an AlreadyCalledError and the chain continues its work.

Here's the code:

from twisted.internet import defer

def asyncText(s, okCallback, errCallback):
  deferred = defer.Deferred()
  deferred.addCallbacks(okCallback, errCallback)
  if s.find('STOP')>=0:
    deferred.errback(ValueError('You are trying to print the unprintable :('))
  else:
    deferred.callback(s)
  return deferred

def asyncChain():
  texts = ['Hello StackOverflow,',
           'this is an example of Twisted.chainDeferred()',
           'which is raising an AlreadyCalledError',
           'when I try to cancel() it.',
           'STOP => I will raise error and should stop the main deferred',
           'Best regards'
           ]

  mainDeferred= defer.Deferred()

  for text in texts:
    def onSuccess(res):
      print('>> {}'.format(res))

    def onError(err):
      print('Error!! {}'.format(err))
      mainDeferred.cancel()

    d = asyncText(text, onSuccess, onError)
    mainDeferred.chainDeferred(d)

And here's the output:

>>> asyncChain()
- Hello StackOverflow,
- this is an example of Twisted.chainDeferred()
- which is raising an AlreadyCalledError
- when I try to cancel() it.
Error!! [Failure instance: Traceback (failure with no frames): <class 'ValueError'>: You are trying to print the unprintable :(
]
- Best regards
Unhandled error in Deferred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File ".../test.py", line 1, in asyncChain
    mainDeferred.chainDeferred(d)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 435, in chainDeferred
    return self.addCallbacks(d.callback, d.errback)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 311, in addCallbacks
    self._runCallbacks()
--- <exception caught here> ---
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 654, in _runCallbacks
    current.result = callback(current.result, *args, **kw)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 501, in errback
    self._startRunCallbacks(fail)
  File ".../.venvs/p3/lib/python3.6/site-packages/twisted/internet/defer.py", line 561, in _startRunCallbacks
    raise AlreadyCalledError
twisted.internet.defer.AlreadyCalledError:

I also tried to use a canceller, like so:

def asyncOnCancel(d):
  print('------ cancel() called ------')
  d.errback(ValueError('chain seems to be cancelled!'))
def asyncChainOnError(err):
  print('------ ERROR ON Chain {} ------'.format(err))

...
  mainDeferred= defer.Deferred(canceller= asyncOnCancel)
  mainDeferred.addErrback(asyncChainOnError)
...

But result is the same.

I also tried delaying child .callback(s) calls, or calling them after the .chainDeferred(). But I get always the same behaviour.

Is it really possible to cancel a chained Deferred (and getting chained child deferreds to get cancelled too)?

Why I'm getting this AlreadyCalledError?

I'm using python 3.6.6 and Twisted 18.9.0.

Thanks!

******* EDIT *******

After Jean-Paul answer, and noticing that .chainDeferred() is not what I need, I'll put here in a clearer way what I want (and how I finnally did it).

What I want was quite simpler: to run several Deferred, in a "synchronous" way (they have to wait for the previous one to have finished), although they don't need to share their results. If one fails, the rest of them is not executed.

Turns out is quite easy to do it with @defer.inlineCallbacks and yield. Here an example:

def asyncText(s):
  deferred = defer.Deferred()
  if s.find('STOP') >= 0:
    deferred.callback(True)
  else:
    deferred.callback(False)
  return deferred

@defer.inlineCallbacks
def asyncChain():
  texts = ['Hello StackOverflow,',
           'this is a simpler way to explain the question.',
           'I need no chainDeferred(). I need no .cancel().',
           'I just need inlineCallbacks decorator.',
           'STOP',
           'Yeah I will not be printed'
           ]
  for text in texts:
    stopHere = yield asyncText(text)
    if stopHere:
      break
    print('- {}'.format(text))

deferred= asyncChain()

>>> asyncChain()
- Hello StackOverflow,
- this is a simpler way to explain the question.
- I need no chainDeferred(). I need no .cancel().
- I just need inlineCallbacks decorator.

Body:
It's not clear what you're actually trying to do but I think your chain is backwards from what you expect:

    d = asyncText(text, onSuccess, onError)
    mainDeferred.chainDeferred(d)

d has already fired when asyncText returns.  But mainDeferred.chainDeferred(d) means "when mainDeferred fires, pass its result to d".  Since d has already fired, this is invalid.  A Deferred can only fire once.

Perhaps you meant d.chainDeferred(mainDeferred) instead.  Then "when d fires, pass its result to mainDeferred".

However, the there is still a problem since if you chain d to mainDeferred then it doesn't make sense to cancel mainDeferred in a callback on d.  The result will propagate from d to mainDeferred because they're chained.  Cancellation is not necessary or useful.


问:
WPF style for Grid with defined columns and rows?
In my application I have a lot of grids like this:

```<code><Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="20"/>
        <ColumnDefinition Width="40"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <!-- ... -->
</Grid>
</code>```

They have 4 columns and 3 rows and column widths are set to some value.

Can I create style or some other kind of template to simplify my window that uses 20 grids like this?

I know, that I can create styles for column definitions one by one to avoid Width="10" everywhere, but is it possible to do something like this?

```<code><Grid Style="{StaticResource GridWith4ColumnsAnd3Rows}">
    <!-- ... -->
</Grid>
</code>```

答:
You can't set the RowDefinitions or ColumnDefinitions properties in a Style because they are not dependency properties.

But you could create a custom class that inherits from Grid and adds the ColumnDefinitions and RowDefinition in the constructor:

```<code>public class CustomGrid : Grid
{
    public CustomGrid()
    {
        ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(10) });
        //...
        ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
    }
}
</code>```

Usage:

```<code><local:CustomGrid>...</local:CustomGrid>
</code>```

Alternatively, you could define an attached behaviour that creates the RowDefinitions and ColumnDefinitions.

Body:
In my application I have a lot of grids like this:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="10"/>
        <ColumnDefinition Width="20"/>
        <ColumnDefinition Width="40"/>
        <ColumnDefinition Width="Auto"/>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>

</Grid>

They have 4 columns and 3 rows and column widths are set to some value.

Can I create style or some other kind of template to simplify my window that uses 20 grids like this?

I know, that I can create styles for column definitions one by one to avoid Width="10" everywhere, but is it possible to do something like this?

<Grid Style="{StaticResource GridWith4ColumnsAnd3Rows}">

</Grid>

Body:
You can't set the RowDefinitions or ColumnDefinitions properties in a Style because they are not dependency properties.

But you could create a custom class that inherits from Grid and adds the ColumnDefinitions and RowDefinition in the constructor:

public class CustomGrid : Grid
{
    public CustomGrid()
    {
        ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(10) });
        //...
        ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
    }
}

Usage:

<local:CustomGrid>...</local:CustomGrid>

Alternatively, you could define an attached behaviour that creates the RowDefinitions and ColumnDefinitions.


问:
Can anybody write the select query for this issue?
I havetwo Tables namely mit_follow & mit_tweets

In mit_follow table structure :

```<code>Id    UserName            followers          Following

1     dobriyalji          manish             Sachin
2     dobriyalji          karthik            parul
</code>```

In mit_tweets table structure :

```<code>Id        UserName          tweets

1         dobriyalji        hi everybody
2         manish            hello all m karthik
</code>```

i wanna write the select query for this ..

if i login using username dobriyalji .... and post tweets in mit_tweets table then dobriyalji and all of his followers can view their msgs and all the followers msgs will be viewed by dobriyalji...i m displaying the mit_tweets table using gridview in webform....

and if any new member login to their account and  post tweets then in gridview only new member msg will display ...

can any body write the select query for this ?

答:
I'm not sure about your mit_follow table. Your followers and Following columns don't really make sense. Surely the table should look more like:

```<code>id user            user_followed
** *************** ******************
1  dobriyalji      Sachin
2  dobriyalji      parul
3  manish          dobriyalji
4  karthik         dobriyalji
</code>```

This would be much easier to query

ContentLicense: CC BY-SA 3.0

Body:
I havetwo Tables namely mit_follow & mit_tweets

In mit_follow table structure :

Id    UserName            followers          Following

1     dobriyalji          manish             Sachin
2     dobriyalji          karthik            parul

In mit_tweets table structure :

Id        UserName          tweets

1         dobriyalji        hi everybody
2         manish            hello all m karthik

i wanna write the select query for this ..

if i login using username dobriyalji .... and post tweets in mit_tweets table then dobriyalji and all of his followers can view their msgs and all the followers msgs will be viewed by dobriyalji...i m displaying the mit_tweets table using gridview in webform....

and if any new member login to their account and  post tweets then in gridview only new member msg will display ...

can any body write the select query for this ?

Body:
I'm not sure about your mit_follow table. Your followers and Following columns don't really make sense. Surely the table should look more like:

id user            user_followed
** *************** ******************
1  dobriyalji      Sachin
2  dobriyalji      parul
3  manish          dobriyalji
4  karthik         dobriyalji

This would be much easier to query


问:
Using single ngOnDestroy in parent component
In our application we have some components that inherit from a BaseComponent.

The base component implements OnDestroy interface and emits with a Subject to notify the children to unsubscribe from eventual open streams.

Is this an acceptable approach or rather every single component should have its own ngOnDestroy implementation? From this article I read that Lifecycle hooks are not inherited.

BaseComponent

```<code>export abstract class ComponentBase implements OnDestroy {
  protected destroy$ = new Subject<boolean>();

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}
</code>```

ChildComponent

```<code>export class ChildComponent extends ComponentBase implements OnInit {

 ngOnInit() {
    this.service
      .getById(userId)
      .pipe(takeUntil(this.destroy$)) // this is emitted by the parent
      .subscribe(user => { ...}
 }
}
</code>```

答:
UPDATE 9th of Sept 2020:

We've released a library at work that is safe to use with Ivy and that gives you access to all the component lifecycles as observables: https://github.com/cloudnc/ngx-observable-lifecycle

That said, the PR which was supposed to fix this upstream in Angular itself has been merged and released recently (can't remember the release but have a look!)

UPDATE 18th of May 2020:

The following doesn't work anymore with Ivy as explained here: https://github.com/angular/angular/issues/36776

There's a PR to restore that behavior here: https://github.com/angular/angular/pull/35464

Even though it's not as flexible, in the meantime you can use this: https://github.com/ngneat/until-destroy

If you're using the ComponentBase to only give you access to destroy$ I'd say it's a bit overkill. You might need extending another class and Typescript doesn't support multiple inheritance so try to avoid that unless it's really necessary.

That said, if you're simply looking for a method to easily unsubscribe in a reactive way, please look at the following:

```<code>/**
 * Easily unsubscribe from an observable stream by appending `takeUntilDestroyed(this)` to the observable pipe.
 * If the component already has a `ngOnDestroy` method defined, it will call this first.
 * Note that the component *must* implement OnDestroy for this to work (the typings will enforce this anyway)
 */
export function takeUntilDestroyed<T>(component: OnDestroy): (source: Observable<T>) => Observable<T> {
  return (source: Observable<T>): Observable<T> => {
    const onDestroy = new Subject();
    const previousOnDestroy = component.ngOnDestroy;

     component.ngOnDestroy = () => {
      if (previousOnDestroy) {
        previousOnDestroy.apply(component);
      }

       onDestroy.next();
      onDestroy.complete();
    };

     return source.pipe(takeUntil(onDestroy));
  };
}
</code>```

And then from your component just do this.myObs$.pipe(takeUntilDestroyed(this))

You can find that function and a demo usage in this PR too:

https://github.com/cloudnc/ngx-sub-form/pull/41/files#diff-5796510f30fdd5bede9d709ce53ef225R45

Body:
In our application we have some components that inherit from a BaseComponent.

The base component implements OnDestroy interface and emits with a Subject to notify the children to unsubscribe from eventual open streams.

Is this an acceptable approach or rather every single component should have its own ngOnDestroy implementation? From this article I read that Lifecycle hooks are not inherited.

BaseComponent

export abstract class ComponentBase implements OnDestroy {
  protected destroy$ = new Subject<boolean>();

  ngOnDestroy() {
    this.destroy$.next(true);
  }
}

ChildComponent

export class ChildComponent extends ComponentBase implements OnInit {

 ngOnInit() {
    this.service
      .getById(userId)
      .pipe(takeUntil(this.destroy$)) // this is emitted by the parent
      .subscribe(user => { ...}
 }
}

Body:
UPDATE 9th of Sept 2020:

We've released a library at work that is safe to use with Ivy and that gives you access to all the component lifecycles as observables: https://github.com/cloudnc/ngx-observable-lifecycle

That said, the PR which was supposed to fix this upstream in Angular itself has been merged and released recently (can't remember the release but have a look!)

UPDATE 18th of May 2020:

The following doesn't work anymore with Ivy as explained here: https://github.com/angular/angular/issues/36776

There's a PR to restore that behavior here: https://github.com/angular/angular/pull/35464

Even though it's not as flexible, in the meantime you can use this: https://github.com/ngneat/until-destroy

If you're using the ComponentBase to only give you access to destroy$ I'd say it's a bit overkill. You might need extending another class and Typescript doesn't support multiple inheritance so try to avoid that unless it's really necessary.

That said, if you're simply looking for a method to easily unsubscribe in a reactive way, please look at the following:

/**
 * Easily unsubscribe from an observable stream by appending `takeUntilDestroyed(this)` to the observable pipe.
 * If the component already has a `ngOnDestroy` method defined, it will call this first.
 * Note that the component *must* implement OnDestroy for this to work (the typings will enforce this anyway)
 */
export function takeUntilDestroyed<T>(component: OnDestroy): (source: Observable<T>) => Observable<T> {
  return (source: Observable<T>): Observable<T> => {
    const onDestroy = new Subject();
    const previousOnDestroy = component.ngOnDestroy;

     component.ngOnDestroy = () => {
      if (previousOnDestroy) {
        previousOnDestroy.apply(component);
      }

       onDestroy.next();
      onDestroy.complete();
    };

     return source.pipe(takeUntil(onDestroy));
  };
}

And then from your component just do this.myObs$.pipe(takeUntilDestroyed(this))

You can find that function and a demo usage in this PR too:

https://github.com/cloudnc/ngx-sub-form/pull/41/files#diff-5796510f30fdd5bede9d709ce53ef225R45


问:
Php cannot run procedure on Proxysql
I made my "Laravel" project connected to "Proxysql". Every query works fine (select, insert, update, func etc.) but if I add a SELECT query without INTO the procedure does not answer to php.

If I connect to "Proxysql" via Mysql WorkBench and call the procedure that works.

I tried to disabled all of the rules and also added a rule about CALL but it doesn't work.

Any idea?

Edit: I talkted to Rene from Proxysql, We understand the problem is coming from Laravel but i still didn't fix the problem, what kind of data should i share about it?

Proxysql issue

答:
Set in PDO constructor attribute PDO::ATTR_EMULATE_PREPARES to TRUE.
It solves the problem.

Title: Php cannot run procedure on Proxysql


问:
Generate object from list
I have an array like this: [1, 2, 3, 4, 5] and I want to obtain from it an object like this:

```<code>[
  { product_id: 1 },
  { product_id: 2 },
  { product_id: 3 },
  { product_id: 4 },
  { product_id: 5 }
]
</code>```

What is an ES6ish way to obtain this?

答:
Problem is in understanding how ES6 .map() return works.

Add round brackets to map, because you want to return that statement. Curly brackets just opens body with no return value. (you have to add it on your own e.g. { return {product_id: item }})

const inputArr = [1, 2, 3, 4, 5];
const newArr = inputArr.map(item => ({ product_id: item }));
console.log('arrayLog', newArr);
```

Title: Generate object from list

Body:
I have an array like this: [1, 2, 3, 4, 5] and I want to obtain from it an object like this:

[
  { product_id: 1 },
  { product_id: 2 },
  { product_id: 3 },
  { product_id: 4 },
  { product_id: 5 }
]

What is an ES6ish way to obtain this?


问:
Custom storage path per model
I'm implementing an email handling system where I want to save the original email and all its attachments to a path. For example - mail-data/123456/5

Where 123456 is the parent ID and 5 is the child ID.

In filesystems.php I've created a custom disk called mail-data

```<code>'mail-data' => [
    'driver' => 'local',
    'root' => storage_path('app/public/mail-data'),
    'visibility' => 'private',
],
</code>```

This works great as far as setting a prefix for the storage path, visibility etc. However, what I want to be able to do is on a per model basis, call a storage property and it return the mail-data driver set to the exact path. This way, all of my logic can simply be:

```<code>$model->storage->put($file->getFilename(), $file->stream());
</code>```

rather than:

```<code>$path = Storage::disk('mail-data')->put($model->parent_id . '/' . $model->id . '/' . $file->getFilename(), $file->getStream())
</code>```

I think the best way to do this by creating an accessor on the model, and I've been able to update the adapter, I just don't know how to update that on the Filesystem instance and return it?

```<code>public function getStorageAttribute()
{
    $storage = Storage::disk('mail-data');

    $adapter = $storage->getAdapter();

    $adapter->setPathPrefix($adapter->getPathPrefix() . $this->parent_id . '/' . $this->id);

    // what to do here to return our modified storage instance?
}
</code>```

答:
Right, I was a bit stupid here... it turns out that when you run setPathPrefix on the adapter, it's all by reference so the code above actually had the desired effect. For anyone Googling in the future, here is the final code -

On the model -

```<code>/**
 * Get our storage disk for this model
 *
 * @return \Illuminate\Contracts\Filesystem\Filesystem
 */
public function getStorageAttribute()
{
    $storage = Storage::disk('mail-data');

    $adapter = $storage->getAdapter();
    $adapter->setPathPrefix($adapter->getPathPrefix() . $this->ticket_id . '/' . $this->id);

    return $storage;
}
</code>```

I can then access my models storage at the absolute storage path simply using $model->storage. So my now much cleaner code for saving my mail data looks like this (no more calculating paths and having to worry about calculating paths anywhere else in my logic) -

```<code>$storage = $model->storage;

$storage->put('email.eml', $mail->message()->getStream());

/** @var MimePart $attachment */
foreach ($mail->attachments() as $attachment) {
    $storage->put($attachment->getFilename(), $attachment->getStream());
}
</code>```

Very happy with that solution and I hope it comes in handy for someone else in the future :)

Title: Custom storage path per model

Body:
I'm implementing an email handling system where I want to save the original email and all its attachments to a path. For example - mail-data/123456/5

Where 123456 is the parent ID and 5 is the child ID.

In filesystems.php I've created a custom disk called mail-data

'mail-data' => [
    'driver' => 'local',
    'root' => storage_path('app/public/mail-data'),
    'visibility' => 'private',
],

This works great as far as setting a prefix for the storage path, visibility etc. However, what I want to be able to do is on a per model basis, call a storage property and it return the mail-data driver set to the exact path. This way, all of my logic can simply be:

$model->storage->put($file->getFilename(), $file->stream());

rather than:

$path = Storage::disk('mail-data')->put($model->parent_id . '/' . $model->id . '/' . $file->getFilename(), $file->getStream())

I think the best way to do this by creating an accessor on the model, and I've been able to update the adapter, I just don't know how to update that on the Filesystem instance and return it?

public function getStorageAttribute()
{
    $storage = Storage::disk('mail-data');

    $adapter = $storage->getAdapter();

    $adapter->setPathPrefix($adapter->getPathPrefix() . $this->parent_id . '/' . $this->id);

    // what to do here to return our modified storage instance?
}

Body:
Right, I was a bit stupid here... it turns out that when you run setPathPrefix on the adapter, it's all by reference so the code above actually had the desired effect. For anyone Googling in the future, here is the final code -

On the model -

/**
 * Get our storage disk for this model
 *
 * @return \Illuminate\Contracts\Filesystem\Filesystem
 */
public function getStorageAttribute()
{
    $storage = Storage::disk('mail-data');

    $adapter = $storage->getAdapter();
    $adapter->setPathPrefix($adapter->getPathPrefix() . $this->ticket_id . '/' . $this->id);

    return $storage;
}

I can then access my models storage at the absolute storage path simply using $model->storage. So my now much cleaner code for saving my mail data looks like this (no more calculating paths and having to worry about calculating paths anywhere else in my logic) -

$storage = $model->storage;

$storage->put('email.eml', $mail->message()->getStream());

/** @var MimePart $attachment */
foreach ($mail->attachments() as $attachment) {
    $storage->put($attachment->getFilename(), $attachment->getStream());
}

Very happy with that solution and I hope it comes in handy for someone else in the future :)


问:
Colour the x-values and show in legend instead of as ticks, in matplotlib (or seaborn)
I have a large df which I've grouped to plot in a bar chart.
I made this mock df to show what I mean. (And I had way too much fun creating it...)

```<code>my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my
</code>```

And then I grouped and plotted it: my.groupby('tv-show').sum().plot(kind='bar', stacked = True)

What I would like is a plot where the names of the tv-shows are in a legend instead of under the x-axis and where the shows have different colours (of course).

答:
Try this with sns:

```<code>new_df = my.groupby('tv-show').sum().reset_index()

sns.barplot(x='tv-show', y='episodes',
            hue='tv-show', data=new_df)
</code>```

Output:

Body:
I have a large df which I've grouped to plot in a bar chart.
I made this mock df to show what I mean. (And I had way too much fun creating it...)

my = pd.DataFrame(
{'names': ['Andrea', 'Donna', 'Kelly', 'Brenda', 'Allison', 'Jo', 'Amanda', 'Jane', 'Kerry', 'Abby', 'Elizabeth', 'Haleh'],
'episodes': [ 147, 292, 292, 111, 160, 111, 199, 172, 250, 189, 160,184 ],
'tv-show' : ['Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210', 'Beverly Hills, 90210',
'Melrose place', 'Melrose place', 'Melrose place', 'Melrose place',
'ER', 'ER', 'ER', 'ER']})
my

And then I grouped and plotted it: my.groupby('tv-show').sum().plot(kind='bar', stacked = True)

What I would like is a plot where the names of the tv-shows are in a legend instead of under the x-axis and where the shows have different colours (of course).

Body:
Try this with sns:

new_df = my.groupby('tv-show').sum().reset_index()

sns.barplot(x='tv-show', y='episodes',
            hue='tv-show', data=new_df)

Output:


问:
convert date into format 2019-05-31T12:08:04Z momentjs
How to convert date into format 2019-05-31T12:08:04Z using momentjs? And which format it is?

答:
You can use something like this:

```<code>moment().format('YYYY-MM-DDTHH:mm:ss[Z]');
</code>```

Or

```<code>moment().format(moment.ISO_8601());
</code>```

The second way you'll have the timezone

Body:
You can use something like this:

moment().format('YYYY-MM-DDTHH:mm:ss[Z]');

Or

moment().format(moment.ISO_8601());

The second way you'll have the timezone


问:
How to scrape dynamic review content from steam using beautifulsoup and python
I am trying to scrape reviews from steam for a particular game. But steam has infinite scrolling mechanism, means reviews are generated dynamically as you scroll. Due to this I am able to scrape only one page, which has 10 reviews. But i need to scrape all the pages. Is there any way to do it using beautiful soup?

I have written code which is scraping the first page and showing results. But can't get further that. I've also tried looking for AJAX request and JS in the network panel, but found nothing which I can use.

```<code>def getHTML(url):
    response = requests.get(url)
    return BeautifulSoup(response.content,'html.parser')

html = getHTML('https://steamcommunity.com/app/44350/reviews/?
browsefilter=toprated&snr=1_5_100010_#scrollTop=0')

for div in html.find_all('div',{'class','apphub_CardTextContent'}):
    print(div.text.strip())
    print("\n\n")
</code>```

答:
I found something in AJAX request and JS in the network panel. You'll have to deal with how to know you've reached the end.

```<code>import requests
import bs4
import re

url = 'https://steamcommunity.com/app/44350/homecontent/'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}

regex = re.compile('apphub_CardContentAuthorName')

for x in range(1, 99):
    offset = (x*10) - 10

    payload = {
    'userreviewsoffset': offset,
    'p': x,
    'workshopitemspage': x,
    'readytouseitemspage': x,
    'mtxitemspage': x,
    'itemspage': x,
    'screenshotspage': x,
    'videospage': x,
    'artpage': x,
    'allguidepage': x,
    'webguidepage': x,
    'integratedguidepage': x,
    'discussionspage': x,
    'numperpage': '10',
    'browsefilter': 'toprated',
    'browsefilter': 'toprated',
    'l': 'english',
    'appHubSubSection': '10',
    'filterLanguage': 'default',
    'searchText': '',
    'forceanon': '1'}

    response = requests.get(url, headers=headers, params=payload)
    soup = bs4.BeautifulSoup(response.text, 'html.parser')

    cards = soup.find_all('div',{'class':'apphub_Card modalContentLink interactable'})
    for card in cards:
        title = card.find('div',{'class':'title'}).text
        hours = card.find('div',{'class':'hours'}).text
        content = card.find('div',{'class':'apphub_CardTextContent'}).text.strip()
        author = card.find('div',{'class':regex}).text

        print(title + '\n' + hours + '\n' + content + '\n\n' + 'Author: ' + author + '\n' + '#'*50)
</code>```

Output:

```<code>Recommended
101.0 hrs on record
Posted: February 5, 2014
                                                                                I really like GRID 2 and I think it's the best racing game on Steam. Just keep in mind that it's not a racing simulator like GRID. It's Need for Speed: Greatest Hits. I can see huge chunks of various NFS games put into the game nicely like Touge on the California Dixon track at night is a canyon race from Carbon, sponsor decals, body and performance mods are from Underground, circuit races strongly remind me of ProStreet. Cote d'Azur track alone reminds me of Porsche Unleashed and brings a smile to my face. Codemasters made a great arcade racing game.The graphics are gorgeous, physics is awesome in terms of car behavior, online matchmaking is great and single player campaign is fun to play and interesting to progress. AI can be easily adjusted to a desired difficulty.After some hours in-game assistant's voice became rather annoying and I turned it off along with generic soundtrack. I wish there were several assistants to choose from. DLCs certainly crippled the game. Extra tracks and cars just don't fit in properly, e. g. you can't use Ford Sierra RS500 online and nobody races on Bathurst unless you create a custom lobby and invite friends to play it. The lack of cockpit view is unfortunate. Also I wish there were Ferraris, Lamborghinis and Porsches but don't get me wrong, the game is great fun and there's a lot of cars to choose from.

Author: camXmile
##################################################
Recommended
318.7 hrs on record
Posted: June 10, 2017
                                                                                I played this game first from a friend who shared their games to me, I just had a go at it since my favourite game is Grid Autosport thought its worth a go.My first impression was terrible I thought I will never play this game again, it was lagging and i was slow as well.But I continued on and honestly it become one of my favourites and then later on when it was on a lower price i bought it and then continued on with the dlc-s slowly, sadly there wasnt a season pass like grid autosportThis game is waay different from grid autosport, but in order to break it down to points lets go and start with the positives.Positives:- Drifting. I love drifting on this game I'm very good at it, In online sessions I beat level 99 players Im very happy with the drifting of this game- Music - Awesome music and soundtracks, i have them downloaded and on my phone- Just like Autosport in this game we have a lot of cars to race on which are collected in different tiers, from tier 1 to tier 4, and indycar and demolition derby.- Lot of Games modes more than Grid Autosport! It has modes like Touge (i cant pronounce that yet by the way :D) Overtake, and face off.Now personally Touge is my favourite and prefer it over faceoff because u dont need to complete the full race if u pull away 5 seconds or drop back 5 seconds behind ur rival of course if u drop u lose lol. Touge is usually on tight tracks around cliffs same with faceoff.....Overtake events are when u have to go against very slow ai cars which aren't racing, the point is to overtake as many of them and meanwhile score points, the points at the top are going up after an overtake and always getting smaller and smaller if ur not overtaking, a scale from 100 to 1000. if u crash or leave track it goes down automaticly to 100..Also an event type called liveroutes which are mostly on street tracks and that means the track layout keeps changing and u have to adapt, there are arrows to help you- Followers! On grid online, this is a feature which autosport doesn't have, here u can compare ur score of followers to other players, u get followers based on global challange or beating ur rival or completing an objective.- Rivals. You can race against weekly and social rivals and over 1 week perioud. whoever gets more xp will get more grid followers- Career mode. with cutscenes, Fans, (a number going up, and u will have more than 20 milion followers after 5 seasons) I think this career mode is better than Grid Autosports career, the better u perform along with ur objectives and results the  more fans u will get, and more fans unlock new tracks. I like that ur in a paddock it gives more to the feel.-Global challanges. You get 9 challanges per week more than Autosport which gives 5!! usually they are tough and annoying and require a lot of effort but its worth it. Also with the friends leaderboards u can see how u stand with ur other friends doing the challange and becoming first will give u a lot of xp.- Just like in Autosport u can edit liveries however here u can edit them in single player too.Now lets go to the meh. before the negatives.Handling.. Not realistic obviously its an arcade handling ur literally flying through corners drifting the rear end like ur doing doughnuts. its faster to drift also, its a disadvantage if u have a front wheel or 4wd, except a few ones.Custom event is connected with career. u can't drive with cars u havent unlocked in career. it meh cause on grid u can drive any car in gp mode.Now Negatives.-The most annoying and ridicolous thing for me is the CAR SELECTION ONLINE. It makes me angry. You only get 20 seconds to choose your car right before the race and the bloddy timer goes so fast... unlike ANY other game i played here ur under pressure to select ur car because for some reason you CANT SELECT IT from the menu before the raceNOW 2ND thing is connected to this which is EVEN MORE ANNOYING. When u join a custom event and ur the middle of championship lets say its event 2 and you're waiting for event 3... What's wrong?? It puts you straight into the event WITHOUT GIVING YOU ANY CHOICE OF CAR SELECTION. YES REALLY. THIS IS BEYOND ME. WTF IS THIS CRAP. 7-AI - They ai in general is,ok, sort of but the AI DURING THE OVERTAKE EVENTS is a disgrace I cant stand them at all, they turn into you, they squize you like mad and then you get a collison and that removes your points, hate them with a passion, its a constant battle in global challanges.- Global challange always gives bloddy impossible things like. yeah overtake with tier 4 around a track tighter than my a$$ im not even kidding. like it just annoys me. then when i wanna pass the ai guess what? they turn into me. many restarts, many angry moments.- Sprint tracks? I don't know the name, those cliff tracks where 1 wrong moment and u literally fall into your death.. I hate those tracks.. tracks like Hong Kong or Okutama. u know...u make a small mistake and u get flipped over and flipped off. Also they're so damn long some are 10 kilometers and take 3 or 4 minutes come on I hate that, after a while just by pure boredom I lose concentration and bang. regardless even with tier1 cars I hate those tracks.. its not flipping dirt rally come on. put these tracks there.. i know its tarmac but still..- There a lot of useless cars which are rarely used.. mostly because they aren't drifty or they're crappy in general I dont see how I will use those cars unless there will be a global event which stricts it down to that 1 car. example. mclaren's in tier 3 and 4. i won't name them. This might invalidate my previous point that Im happy that there are a lot of cars but oh well..- Moneywh0ring and level limits.. In order for u to have full achivements like in other games u will need almost all dlc's, in order to unlock all cars for example online u need a dlcs. in order to play 1 track and get 2 or 3 cars  u need to spend like 7 euros. it might not be a lot but come on why couldnt u just put it in the full game?  Level limits. So just because ur not a level 25 or something u cant upgrade a car  from like tier 3 to 4. so until then everyone else will use caterham in tier 4 for overtake events for example meanwhile u have to use something else, why cant u just make it more expensive why need to level up that much for that.. now this might sound a bit like crying but its unfair kind of, but its debateable it might not be. anyway that's my thoughts- small thing, Indycar is slower than Pagani Zonda Revolucion??? indycar can do 452 in grid autosport but here its slower than 370 and u can't even upgrade it, and why is Zonda 376 with 7 gears when its 6 gears on autosport?- no upgrades for DLC veichles.. -no driving line or assists- No time trial,- NO global leaderboards on racenet ingame, u have to go out there manually to codies site all the time, and u cant go through the list of people only ones who are near you.Overall I would give this 8/10 and Autosport 9/10I personally prefer Autosport but this game the way it is, is fun too except the annoying things. Why autosport? 3 reasons. handling, multiplayer and smoother fps.To all friends who have autosport, go and try Grid 2 as well pls. thanks for reading. Goodbye.

Author: LuckyRacer99
##################################################
Recommended
3.2 hrs on record
Posted: March 14
Product received for free
Free on Humble Bundle![www.humblebundle.com]

Author: Makk0
##################################################
Recommended
1.4 hrs on record
Posted: April 23
Product received for free
                                                                                Got it free, and it runs on my Intel HD2500 graphics PC. So, if you're looking for a racing game that runs decently on a piece of trash computer, this one is probably it.

Author: Aaron

....
</code>```

Body:
I am trying to scrape reviews from steam for a particular game. But steam has infinite scrolling mechanism, means reviews are generated dynamically as you scroll. Due to this I am able to scrape only one page, which has 10 reviews. But i need to scrape all the pages. Is there any way to do it using beautiful soup?

I have written code which is scraping the first page and showing results. But can't get further that. I've also tried looking for AJAX request and JS in the network panel, but found nothing which I can use.

def getHTML(url):
    response = requests.get(url)
    return BeautifulSoup(response.content,'html.parser')

html = getHTML('https://steamcommunity.com/app/44350/reviews/?
browsefilter=toprated&snr=1_5_100010_#scrollTop=0')

for div in html.find_all('div',{'class','apphub_CardTextContent'}):
    print(div.text.strip())
    print("\n\n")

Body:
I found something in AJAX request and JS in the network panel. You'll have to deal with how to know you've reached the end.

import requests
import bs4
import re

url = 'https://steamcommunity.com/app/44350/homecontent/'

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'}

regex = re.compile('apphub_CardContentAuthorName')

for x in range(1, 99):
    offset = (x*10) - 10

    payload = {
    'userreviewsoffset': offset,
    'p': x,
    'workshopitemspage': x,
    'readytouseitemspage': x,
    'mtxitemspage': x,
    'itemspage': x,
    'screenshotspage': x,
    'videospage': x,
    'artpage': x,
    'allguidepage': x,
    'webguidepage': x,
    'integratedguidepage': x,
    'discussionspage': x,
    'numperpage': '10',
    'browsefilter': 'toprated',
    'browsefilter': 'toprated',
    'l': 'english',
    'appHubSubSection': '10',
    'filterLanguage': 'default',
    'searchText': '',
    'forceanon': '1'}

    response = requests.get(url, headers=headers, params=payload)
    soup = bs4.BeautifulSoup(response.text, 'html.parser')

    cards = soup.find_all('div',{'class':'apphub_Card modalContentLink interactable'})
    for card in cards:
        title = card.find('div',{'class':'title'}).text
        hours = card.find('div',{'class':'hours'}).text
        content = card.find('div',{'class':'apphub_CardTextContent'}).text.strip()
        author = card.find('div',{'class':regex}).text

        print(title + '\n' + hours + '\n' + content + '\n\n' + 'Author: ' + author + '\n' + '#'*50)

Output:

Recommended
101.0 hrs on record
Posted: February 5, 2014
                                                                                I really like GRID 2 and I think it's the best racing game on Steam. Just keep in mind that it's not a racing simulator like GRID. It's Need for Speed: Greatest Hits. I can see huge chunks of various NFS games put into the game nicely like Touge on the California Dixon track at night is a canyon race from Carbon, sponsor decals, body and performance mods are from Underground, circuit races strongly remind me of ProStreet. Cote d'Azur track alone reminds me of Porsche Unleashed and brings a smile to my face. Codemasters made a great arcade racing game.The graphics are gorgeous, physics is awesome in terms of car behavior, online matchmaking is great and single player campaign is fun to play and interesting to progress. AI can be easily adjusted to a desired difficulty.After some hours in-game assistant's voice became rather annoying and I turned it off along with generic soundtrack. I wish there were several assistants to choose from. DLCs certainly crippled the game. Extra tracks and cars just don't fit in properly, e. g. you can't use Ford Sierra RS500 online and nobody races on Bathurst unless you create a custom lobby and invite friends to play it. The lack of cockpit view is unfortunate. Also I wish there were Ferraris, Lamborghinis and Porsches but don't get me wrong, the game is great fun and there's a lot of cars to choose from.

Author: camXmile
##################################################
Recommended
318.7 hrs on record
Posted: June 10, 2017
                                                                                I played this game first from a friend who shared their games to me, I just had a go at it since my favourite game is Grid Autosport thought its worth a go.My first impression was terrible I thought I will never play this game again, it was lagging and i was slow as well.But I continued on and honestly it become one of my favourites and then later on when it was on a lower price i bought it and then continued on with the dlc-s slowly, sadly there wasnt a season pass like grid autosportThis game is waay different from grid autosport, but in order to break it down to points lets go and start with the positives.Positives:- Drifting. I love drifting on this game I'm very good at it, In online sessions I beat level 99 players Im very happy with the drifting of this game- Music - Awesome music and soundtracks, i have them downloaded and on my phone- Just like Autosport in this game we have a lot of cars to race on which are collected in different tiers, from tier 1 to tier 4, and indycar and demolition derby.- Lot of Games modes more than Grid Autosport! It has modes like Touge (i cant pronounce that yet by the way :D) Overtake, and face off.Now personally Touge is my favourite and prefer it over faceoff because u dont need to complete the full race if u pull away 5 seconds or drop back 5 seconds behind ur rival of course if u drop u lose lol. Touge is usually on tight tracks around cliffs same with faceoff.....Overtake events are when u have to go against very slow ai cars which aren't racing, the point is to overtake as many of them and meanwhile score points, the points at the top are going up after an overtake and always getting smaller and smaller if ur not overtaking, a scale from 100 to 1000. if u crash or leave track it goes down automaticly to 100..Also an event type called liveroutes which are mostly on street tracks and that means the track layout keeps changing and u have to adapt, there are arrows to help you- Followers! On grid online, this is a feature which autosport doesn't have, here u can compare ur score of followers to other players, u get followers based on global challange or beating ur rival or completing an objective.- Rivals. You can race against weekly and social rivals and over 1 week perioud. whoever gets more xp will get more grid followers- Career mode. with cutscenes, Fans, (a number going up, and u will have more than 20 milion followers after 5 seasons) I think this career mode is better than Grid Autosports career, the better u perform along with ur objectives and results the  more fans u will get, and more fans unlock new tracks. I like that ur in a paddock it gives more to the feel.-Global challanges. You get 9 challanges per week more than Autosport which gives 5!! usually they are tough and annoying and require a lot of effort but its worth it. Also with the friends leaderboards u can see how u stand with ur other friends doing the challange and becoming first will give u a lot of xp.- Just like in Autosport u can edit liveries however here u can edit them in single player too.Now lets go to the meh. before the negatives.Handling.. Not realistic obviously its an arcade handling ur literally flying through corners drifting the rear end like ur doing doughnuts. its faster to drift also, its a disadvantage if u have a front wheel or 4wd, except a few ones.Custom event is connected with career. u can't drive with cars u havent unlocked in career. it meh cause on grid u can drive any car in gp mode.Now Negatives.-The most annoying and ridicolous thing for me is the CAR SELECTION ONLINE. It makes me angry. You only get 20 seconds to choose your car right before the race and the bloddy timer goes so fast... unlike ANY other game i played here ur under pressure to select ur car because for some reason you CANT SELECT IT from the menu before the raceNOW 2ND thing is connected to this which is EVEN MORE ANNOYING. When u join a custom event and ur the middle of championship lets say its event 2 and you're waiting for event 3... What's wrong?? It puts you straight into the event WITHOUT GIVING YOU ANY CHOICE OF CAR SELECTION. YES REALLY. THIS IS BEYOND ME. WTF IS THIS CRAP. 7-AI - They ai in general is,ok, sort of but the AI DURING THE OVERTAKE EVENTS is a disgrace I cant stand them at all, they turn into you, they squize you like mad and then you get a collison and that removes your points, hate them with a passion, its a constant battle in global challanges.- Global challange always gives bloddy impossible things like. yeah overtake with tier 4 around a track tighter than my a$$ im not even kidding. like it just annoys me. then when i wanna pass the ai guess what? they turn into me. many restarts, many angry moments.- Sprint tracks? I don't know the name, those cliff tracks where 1 wrong moment and u literally fall into your death.. I hate those tracks.. tracks like Hong Kong or Okutama. u know...u make a small mistake and u get flipped over and flipped off. Also they're so damn long some are 10 kilometers and take 3 or 4 minutes come on I hate that, after a while just by pure boredom I lose concentration and bang. regardless even with tier1 cars I hate those tracks.. its not flipping dirt rally come on. put these tracks there.. i know its tarmac but still..- There a lot of useless cars which are rarely used.. mostly because they aren't drifty or they're crappy in general I dont see how I will use those cars unless there will be a global event which stricts it down to that 1 car. example. mclaren's in tier 3 and 4. i won't name them. This might invalidate my previous point that Im happy that there are a lot of cars but oh well..- Moneywh0ring and level limits.. In order for u to have full achivements like in other games u will need almost all dlc's, in order to unlock all cars for example online u need a dlcs. in order to play 1 track and get 2 or 3 cars  u need to spend like 7 euros. it might not be a lot but come on why couldnt u just put it in the full game?  Level limits. So just because ur not a level 25 or something u cant upgrade a car  from like tier 3 to 4. so until then everyone else will use caterham in tier 4 for overtake events for example meanwhile u have to use something else, why cant u just make it more expensive why need to level up that much for that.. now this might sound a bit like crying but its unfair kind of, but its debateable it might not be. anyway that's my thoughts- small thing, Indycar is slower than Pagani Zonda Revolucion??? indycar can do 452 in grid autosport but here its slower than 370 and u can't even upgrade it, and why is Zonda 376 with 7 gears when its 6 gears on autosport?- no upgrades for DLC veichles.. -no driving line or assists- No time trial,- NO global leaderboards on racenet ingame, u have to go out there manually to codies site all the time, and u cant go through the list of people only ones who are near you.Overall I would give this 8/10 and Autosport 9/10I personally prefer Autosport but this game the way it is, is fun too except the annoying things. Why autosport? 3 reasons. handling, multiplayer and smoother fps.To all friends who have autosport, go and try Grid 2 as well pls. thanks for reading. Goodbye.

Author: LuckyRacer99
##################################################
Recommended
3.2 hrs on record
Posted: March 14
Product received for free
Free on Humble Bundle![www.humblebundle.com]

Author: Makk0
##################################################
Recommended
1.4 hrs on record
Posted: April 23
Product received for free
                                                                                Got it free, and it runs on my Intel HD2500 graphics PC. So, if you're looking for a racing game that runs decently on a piece of trash computer, this one is probably it.

Author: Aaron

....


问:
How to update a column in one dataframe based on another dataframe?
I am needing to see how to update one column in a data frame where the employeeID matches that of another data frame.

For example:

```<code>df1 >

empID     salary
1         10000
2         15000
3         0

df2 >

empID     salary2
1         10000
2         15000
3         20000
</code>```

I am needing to see how to update it where df1$salary = 0, then update it where df1$empID = df2$empID.

I tried this but received "No such column: salary2" error :

```<code>df1$salary <- ifelse(df1$salary == 0,sqldf("UPDATE df1 SET salary = salary2 WHERE df1.empID = df2.empID"),df1$salary)
</code>```

答:
Here is another option with merge,

```<code>transform(merge(df1, df2, by = 'empID'),
               salary = replace(salary, salary == 0, salary2[salary == 0]),
               salary2 = NULL)

#  empID salary
#1     1  10000
#2     2  15000
#3     3  20000
</code>```

You can also use ifelse instead of replace for salary, i.e.

```<code>salary = ifelse(salary == 0, salary2, salary)
</code>```

Body:
I am needing to see how to update one column in a data frame where the employeeID matches that of another data frame.

For example:

df1 >

empID     salary
1         10000
2         15000
3         0

df2 >

empID     salary2
1         10000
2         15000
3         20000

I am needing to see how to update it where df1$salary = 0, then update it where df1$empID = df2$empID.

I tried this but received "No such column: salary2" error :

df1$salary <- ifelse(df1$salary == 0,sqldf("UPDATE df1 SET salary = salary2 WHERE df1.empID = df2.empID"),df1$salary)

Body:
Here is another option with merge,

transform(merge(df1, df2, by = 'empID'),
               salary = replace(salary, salary == 0, salary2[salary == 0]),
               salary2 = NULL)

#  empID salary
#1     1  10000
#2     2  15000
#3     3  20000

You can also use ifelse instead of replace for salary, i.e.

salary = ifelse(salary == 0, salary2, salary)


问:
Initializing inner struct in emplace_back()
I have struct which contains array of inner struct. I want to use method emplace_back() of vector<my_struct>. But I cannot figure how could I initialize this struct correctly:

```<code>struct my_struct
{
    struct
    {
        float x, y, z;
    } point[3];
};

std::vector<my_struct> v;

v.emplace_back(
    {0, 0, 0},
    {0, 0, 0},
    {0, 0, 0}
);
</code>```

This gives compilation error error: no matching function for call to ‘std::vector::emplace_back(<brace-enclosed initializer list>, <brace-enclosed initializer list>, <brace-enclosed initializer list>)

Is it possible to emplace_back this struct (I'm using C++17)? Should I write custom constructor?

Body:
I have struct which contains array of inner struct. I want to use method emplace_back() of vector<my_struct>. But I cannot figure how could I initialize this struct correctly:

struct my_struct
{
    struct
    {
        float x, y, z;
    } point[3];
};

std::vector<my_struct> v;

v.emplace_back(
    {0, 0, 0},
    {0, 0, 0},
    {0, 0, 0}
);

This gives compilation error error: no matching function for call to ‘std::vector::emplace_back(<brace-enclosed initializer list>, <brace-enclosed initializer list>, <brace-enclosed initializer list>)

Is it possible to emplace_back this struct (I'm using C++17)? Should I write custom constructor?

Body:
how about this:

v.push_back(my_struct{{{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}});


问:
Why do I get, and how do I solve this "String to object of type <objecttype>" error
I am (being an absolute beginner), trying to create a simple tool, that creates some objects and links them.
The objects are:
Customers
Licenses (2 types, extends class)

The idea is to use (one of) the customer company name when creating a license, so the license is linked to a customer.
I use ArrayLists to store the data.

I tried to use the getter for Customer cCompany, but when I try to actually create a new license object, I get errors about incompatible types (String to object of type customer)

How can I fix that error?

Any help is highly appreciated, but please explain well, me being an absolute beginner. I probably overcomplicate stuff....

Some code extracts:

From Main:

```<code>public class Main {

    public static void main(String[] args) {
        //Create customers
        List <Customer> customers = new ArrayList <> (10);
        customers.add(new Customer("TestCompany","John Doe",1234567890,"John@testcompany.com"));

....

//Create Elvis licenses (based on superclass License)
List <ElvisLicense> ellicenses = new ArrayList <> (10);
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
</code>```

Class: Customer:

```<code>class Customer {
    String cCompany;
    private String cName;
    private int cPhone;
    private String cEmail;

    public Customer( String cCompany, String cName,int cPhone, String cEmail)
    {
    this.cCompany = cCompany;
    this.cName = cName;
    this.cPhone = cPhone;
    this.cEmail = cEmail;
    }

    //This getter should be used to link the license to the customer (Done in License.java)
    public String getcCompany() {
        return cCompany;
    }
</code>```

Class License (Superclass)

```<code>class License {
// Used no modifier to set access for Class/Package and Subclass inside the package
Customer licenseCompany;
String lVendor;
int lContractNumber;
String lCertificateNumber;
String lProductName;
String lLicenseKey;
int lNumberOfSeats;

    public License(Customer cCompany, String lVendor, int lContractNumber, String lCertificateNumber,
            String lProductName, String lLicenseKey, int lNumberOfSeats)
    {
    licenseCompany = cCompany;
    this.lVendor = lVendor;
    this.lVendor = lVendor;
    this.lContractNumber = lContractNumber;
    this.lCertificateNumber = lCertificateNumber;
    this.lProductName = lProductName;
    this.lLicenseKey = lLicenseKey;
    this.lNumberOfSeats = lNumberOfSeats;
    }

    public Customer getLicenseCompany() {
        return licenseCompany;
    }

    public void setLicenseCompany(Customer licenseCompany) {
        this.licenseCompany = licenseCompany;
    }

//preparations to allow for example printing the content of an arraylist element
    @Override
    public String toString(){
    return "Customer name " + getLicenseCompany()  + "\n" + "Vendor name " + getlVendor()  + "\n" + "Contract number: " + getlContractNumber() + "\n"
               + "Certificate number: " + getlCertificateNumber() + "\n" +
                "Product name " + getlProductName()  + "\n" + "Licence key: " + getlLicenseKey() + "\n"
               + "Number of seats: " + getlNumberOfSeats();
}

}
</code>```

And the extended class:

```<code>public class ElvisLicense extends License{

private boolean elIsBundle;
private boolean elIsSubscription;

public ElvisLicense(
        Customer licenseCompany,
        String lVendor,
        int lContractNumber,
        String lCertificateNumber,
        String lProductName,
        String lLicenseKey,
        int lNumberOfSeats,
        boolean elIsBundle,
        boolean elIsSubscription
        )

    {
    super(
            licenseCompany,
            lVendor,
            lContractNumber,
            lCertificateNumber,
            lProductName,
            lLicenseKey,
            lNumberOfSeats);

    this.elIsBundle = elIsBundle;
    this.elIsSubscription = elIsSubscription;
    }

.....

@Override
public String toString(){
    return "Customer name " + licenseCompany  + "\n"
            + "Vendor name " + lVendor  + "\n"
            + "Contract number: " + lContractNumber + "\n"
            + "Certificate number: " + lCertificateNumber + "\n"
            + "Product name " + lProductName  + "\n"
            + "Licence key: " + lLicenseKey + "\n"
            + "Number of seats: " + lNumberOfSeats + "\n"
            + "Number of seats: " + elIsBundle + "\n"
            + "Number of seats: " + elIsSubscription;
}

}
</code>```

I expect that the Customername is used when creating a new license.

答:
Below line is wrong.

ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
```

<p>As license need customer object an parameter. Instead, you should create customer object first.</p>

<pre class="lang-java prettyprint-override"><code>ellicenses.add(new ElvisLicense(new Customer("TestCompany","VendorA",1234,"1234-A"),"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));
</code>```

for reusing that customer list to avoid create company.

for(Customer customer : customers){
   // here you need some way to offer other parameters except customer parameter.
   License license = new new ElvisLicense(customer,"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true);
   ellicenses.add(license);
}
```

Body:
I am (being an absolute beginner), trying to create a simple tool, that creates some objects and links them.
The objects are:
Customers
Licenses (2 types, extends class)

The idea is to use (one of) the customer company name when creating a license, so the license is linked to a customer.
I use ArrayLists to store the data.

I tried to use the getter for Customer cCompany, but when I try to actually create a new license object, I get errors about incompatible types (String to object of type customer)

How can I fix that error?

Any help is highly appreciated, but please explain well, me being an absolute beginner. I probably overcomplicate stuff....

Some code extracts:

From Main:

public class Main {

    public static void main(String[] args) {
        //Create customers
        List <Customer> customers = new ArrayList <> (10);
        customers.add(new Customer("TestCompany","John Doe",1234567890,"John@testcompany.com"));

....

//Create Elvis licenses (based on superclass License)
List <ElvisLicense> ellicenses = new ArrayList <> (10);
ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));

Class: Customer:

class Customer {
    String cCompany;
    private String cName;
    private int cPhone;
    private String cEmail;

    public Customer( String cCompany, String cName,int cPhone, String cEmail)
    {
    this.cCompany = cCompany;
    this.cName = cName;
    this.cPhone = cPhone;
    this.cEmail = cEmail;
    }

    //This getter should be used to link the license to the customer (Done in License.java)
    public String getcCompany() {
        return cCompany;
    }

Class License (Superclass)

class License {
// Used no modifier to set access for Class/Package and Subclass inside the package
Customer licenseCompany;
String lVendor;
int lContractNumber;
String lCertificateNumber;
String lProductName;
String lLicenseKey;
int lNumberOfSeats;

    public License(Customer cCompany, String lVendor, int lContractNumber, String lCertificateNumber,
            String lProductName, String lLicenseKey, int lNumberOfSeats)
    {
    licenseCompany = cCompany;
    this.lVendor = lVendor;
    this.lVendor = lVendor;
    this.lContractNumber = lContractNumber;
    this.lCertificateNumber = lCertificateNumber;
    this.lProductName = lProductName;
    this.lLicenseKey = lLicenseKey;
    this.lNumberOfSeats = lNumberOfSeats;
    }

    public Customer getLicenseCompany() {
        return licenseCompany;
    }

    public void setLicenseCompany(Customer licenseCompany) {
        this.licenseCompany = licenseCompany;
    }

//preparations to allow for example printing the content of an arraylist element
    @Override
    public String toString(){
    return "Customer name " + getLicenseCompany()  + "\n" + "Vendor name " + getlVendor()  + "\n" + "Contract number: " + getlContractNumber() + "\n"
               + "Certificate number: " + getlCertificateNumber() + "\n" +
                "Product name " + getlProductName()  + "\n" + "Licence key: " + getlLicenseKey() + "\n"
               + "Number of seats: " + getlNumberOfSeats();
}

}

And the extended class:

public class ElvisLicense extends License{

private boolean elIsBundle;
private boolean elIsSubscription;

public ElvisLicense(
        Customer licenseCompany,
        String lVendor,
        int lContractNumber,
        String lCertificateNumber,
        String lProductName,
        String lLicenseKey,
        int lNumberOfSeats,
        boolean elIsBundle,
        boolean elIsSubscription
        )

    {
    super(
            licenseCompany,
            lVendor,
            lContractNumber,
            lCertificateNumber,
            lProductName,
            lLicenseKey,
            lNumberOfSeats);

    this.elIsBundle = elIsBundle;
    this.elIsSubscription = elIsSubscription;
    }

.....

@Override
public String toString(){
    return "Customer name " + licenseCompany  + "\n"
            + "Vendor name " + lVendor  + "\n"
            + "Contract number: " + lContractNumber + "\n"
            + "Certificate number: " + lCertificateNumber + "\n"
            + "Product name " + lProductName  + "\n"
            + "Licence key: " + lLicenseKey + "\n"
            + "Number of seats: " + lNumberOfSeats + "\n"
            + "Number of seats: " + elIsBundle + "\n"
            + "Number of seats: " + elIsSubscription;
}

}

I expect that the Customername is used when creating a new license.

Body:
Below line is wrong.

ellicenses.add(new ElvisLicense("TestCompany","VendorA",1234,"1234-A","Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));

As license need customer object an parameter. Instead, you should create customer object first.

ellicenses.add(new ElvisLicense(new Customer("TestCompany","VendorA",1234,"1234-A"),"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true));

for reusing that customer list to avoid create company.

for(Customer customer : customers){
   // here you need some way to offer other parameters except customer parameter.
   License license = new new ElvisLicense(customer,"Solutions Server gold","1234-dtbk-87654-nlof",10, true , true);
   ellicenses.add(license);
}


问:
Center align li with equal height and fixed width
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">83</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4><span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">65k</h4><span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">37k</h4><span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">£250m</h4><span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div></code>```

JS Fiddle Link

答:
Use Flexbox:

* {
  box-sizing: border-box;
}
.box-outer {
  display: flex;
  justify-content: center;
  align-items: stretch;
  background-color: #333;
}
.boxes {
  flex: 0 0 20%;
  vertical-align: middle;
  border: 1px dotted red;
  padding: 4px 6px;
  margin-bottom: 0;
}
.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: "hurme_geometric_sans_4regular", sans-serif;
}
.field-text {
  padding-top: 10px;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">67</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4>
    <span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">6k</h4>
    <span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7k</h4>
    <span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">775m</h4>
    <span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div></code>```

Body:
Under an ul, there are 5 li's. wanted to have all the li with same height with fixed width(20% for each li is 100%). i have achieved that with the below code.But my problem is, if i have only 3 or 4 li's i want to display the li's with same height and width but in center. Right now if i have 3 or 4, the width is adjusting and occupying the whole ul container.

Even if its 3 li or 4 li, the li should have fixed width with aligned in the center.

.box-outer {
  text-align: center;
  display: table;
  table-layout: fixed;
  background-color: #333;
}

.boxes {
  vertical-align: middle;
  width: 10% !important;
  margin-right: 1% !important;
  background: #fff;
  border-radius: 6px;
  text-align: center;
  padding: 32px 29px;
  display: table-cell;
}

.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: sans-serif;
}

.field-text {
  padding-top: 10px;
  color: #333;
}

83

    Lorem ipsum dolor sit amet, consectetur adipiscing elit,

7,800
mod tempor incididunt ut labor

65k
ut aliquip

37k
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

£250m
veniam, quis nostrud exercitation ullamco

JS Fiddle Link

Body:
Use Flexbox:

* {
  box-sizing: border-box;
}
.box-outer {
  display: flex;
  justify-content: center;
  align-items: stretch;
  background-color: #333;
}
.boxes {
  flex: 0 0 20%;
  vertical-align: middle;
  border: 1px dotted red;
  padding: 4px 6px;
  margin-bottom: 0;
}
.field-number {
  color: #de008d;
  font-size: 48px;
  font-family: "hurme_geometric_sans_4regular", sans-serif;
}
.field-text {
  padding-top: 10px;
  color: #fff;
}

<div class="box-outer">
  <div class="boxes">
    <h4 class="field-number">67</h4>
    <span class="field-text">Lorem ipsum dolor sit amet, consectetur adipiscing elit,</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7,800</h4>
    <span class="field-text">mod tempor incididunt ut labor</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">6k</h4>
    <span class="field-text">ut aliquip</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">7k</h4>
    <span class="field-text">Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
  </div>
  <div class="boxes">
    <h4 class="field-number">775m</h4>
    <span class="field-text">veniam, quis nostrud exercitation ullamco</span>
  </div>
</div>


问:
How i can save div text for use in another place?
I need save div text value and after it assert in another place?</p>

```<code>cy.get('div').should(($div) => {
    const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)
</code>```

答:
Cypress is asynchronous. What this means is that if you do something like this:

cy.get('div').should(($div) => {
  const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)
```

<p>...your test will always fail. <code>const myText = $div.innerText</code> will be executed <em>after</em> the <code>.should('have.text', myText)</code> is evaluated.</p>

<p>If you want to use <code>myText</code> in this way, just use the Promise returned by <code>cy.get()</code>:</p>

<pre class="lang-js prettyprint-override"><code>cy.get('div')
.then($div => {
  const myText = $div.text()
  // write the rest of your test here
  cy.get('.value').should('have.text', myText)
})
</code>```

Body:
I need save div text value and after it assert in another place?

cy.get('div').should(($div) => {
    const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)

Body:
Cypress is asynchronous. What this means is that if you do something like this:

cy.get('div').should(($div) => {
  const myText = $div.innerText
})
cy.get('.value').should('have.text', myText)

...your test will always fail. const myText = $div.innerText will be executed after the .should('have.text', myText) is evaluated.

If you want to use myText in this way, just use the Promise returned by cy.get():

cy.get('div')
.then($div => {
  const myText = $div.text()
  // write the rest of your test here
  cy.get('.value').should('have.text', myText)
})


问:
Why NUMPY correlate and corrcoef return different values and how to "normalize" a correlate in "full" mode?
I'm trying to use some Time Series Analysis in Python, using Numpy.

I have two somewhat medium-sized series, with 20k values each and I want to check the sliding correlation.

The corrcoef gives me as output a Matrix of auto-correlation/correlation coefficients. Nothing useful by itself in my case, as one of the series contains a lag.

The correlate function (in mode="full") returns a 40k elements list that DO look like the kind of result I'm aiming for (the peak value is as far from the center of the list as the Lag would indicate), but the values are all weird - up to 500, when I was expecting something from -1 to 1.

I can't just divide it all by the max value; I know the max correlation isn't 1.

How could I normalize the "cross-correlation" (correlation in "full" mode) so the return values would be the correlation on each lag step instead those very large, strange values?

答:
You are looking for normalized cross-correlation. This option isn't available yet in Numpy, but a patch is waiting for review that does just what you want. It shouldn't be too hard to apply it I would think. Most of the patch is just doc string stuff. The only lines of code that it adds are

```<code>if normalize:
    a = (a - mean(a)) / (std(a) * len(a))
    v = (v - mean(v)) /  std(v)
</code>```

where a and v are the inputted numpy arrays of which you are finding the cross-correlation. It shouldn't be hard to either add them into your own distribution of Numpy or just make a copy of the correlate function and add the lines there. I would do the latter personally if I chose to go this route.

Another, quite possibly better, alternative is to just do the normalization to the input vectors before you send it to correlate. It's up to you which way you would like to do it.

By the way, this does appear to be the correct normalization as per the Wikipedia page on cross-correlation except for dividing by len(a) rather than (len(a)-1). I feel that the discrepancy is akin to the standard deviation of the sample vs. sample standard deviation and really won't make much of a difference in my opinion.

Body:
You are looking for normalized cross-correlation. This option isn't available yet in Numpy, but a patch is waiting for review that does just what you want. It shouldn't be too hard to apply it I would think. Most of the patch is just doc string stuff. The only lines of code that it adds are

if normalize:
    a = (a - mean(a)) / (std(a) * len(a))
    v = (v - mean(v)) /  std(v)

where a and v are the inputted numpy arrays of which you are finding the cross-correlation. It shouldn't be hard to either add them into your own distribution of Numpy or just make a copy of the correlate function and add the lines there. I would do the latter personally if I chose to go this route.

Another, quite possibly better, alternative is to just do the normalization to the input vectors before you send it to correlate. It's up to you which way you would like to do it.

By the way, this does appear to be the correct normalization as per the Wikipedia page on cross-correlation except for dividing by len(a) rather than (len(a)-1). I feel that the discrepancy is akin to the standard deviation of the sample vs. sample standard deviation and really won't make much of a difference in my opinion.


问:
Minio bucket size
I want to calculate bucket size of minio.
is it possible to calculate storage quota using MinioClient?
 or is there any best way to calculate bucket size of minio storage.

thanks in advance

答:
You can do something like this:

mc ls -r --json your_bucket_path | awk '{ FS=","; print $4 }' | awk '{ FS=":"; n+=$2 } END{ print n }'
```

Title: Minio bucket size