问:
How to link tables with MYSQL JOIN?
There are 4 tables. I want to link all tables with the current ID. If there is no value in the last table in my query, the data does not return. I want to access the data in all tables. How should I proceed for this?

MY CODE: (Partially Working)

```<code>SELECT
    U.id AS id,
    U.amount AS amount,
    A.commission AS commission,
    I.power AS item_power
FROM affiliate AS A
     INNER JOIN users AS U
ON A.owner_id = U.id
     INNER JOIN users_booster AS B
ON U.id = B.userid
     INNER JOIN auction_item AS I
ON B.item_id = I.id
    WHERE
A.partner_id = '1947' AND
I.type = 'reference_booster' AND
B.end_time >= NOW()
GROUP BY I.type
</code>```

答:
Use left join.  And no group by is needed:

```<code>SELECT U.id AS id, U.amount AS amount, A.commission AS commission,
      I.power AS item_power
FROM affiliate A JOIN
     users U
     ON A.owner_id = U.id JOIN
     users_booster B
     ON U.id = B.userid LEFT JOIN
     auction_item I
     ON B.item_id = I.id AND I.type = 'reference_booster'
WHERE A.partner_id = 1947 AND
      B.end_time >= NOW();
</code>```

Notes:

Use LEFT JOIN whenever you want to keep rows, even if there is no match.

The condition on the second table in the LEFT JOIN needs to be in the ON clause.

I imagine that partner_id is a number, so don't compare it to a string.  Use 1947 instead of '1947'.  Of course, if it is a string, keep the single quotes.

GROUP BY rarely makes sense with no aggregation functions.

Title: How to link tables with MYSQL JOIN?

Body:
There are 4 tables. I want to link all tables with the current ID. If there is no value in the last table in my query, the data does not return. I want to access the data in all tables. How should I proceed for this?

MY CODE: (Partially Working)

SELECT
    U.id AS id,
    U.amount AS amount,
    A.commission AS commission,
    I.power AS item_power
FROM affiliate AS A
     INNER JOIN users AS U
ON A.owner_id = U.id
     INNER JOIN users_booster AS B
ON U.id = B.userid
     INNER JOIN auction_item AS I
ON B.item_id = I.id
    WHERE
A.partner_id = '1947' AND
I.type = 'reference_booster' AND
B.end_time >= NOW()
GROUP BY I.type

Body:
Use left join.  And no group by is needed:

SELECT U.id AS id, U.amount AS amount, A.commission AS commission,
      I.power AS item_power
FROM affiliate A JOIN
     users U
     ON A.owner_id = U.id JOIN
     users_booster B
     ON U.id = B.userid LEFT JOIN
     auction_item I
     ON B.item_id = I.id AND I.type = 'reference_booster'
WHERE A.partner_id = 1947 AND
      B.end_time >= NOW();

Notes:

Use LEFT JOIN whenever you want to keep rows, even if there is no match.

The condition on the second table in the LEFT JOIN needs to be in the ON clause.

I imagine that partner_id is a number, so don't compare it to a string.  Use 1947 instead of '1947'.  Of course, if it is a string, keep the single quotes.

GROUP BY rarely makes sense with no aggregation functions.


来源: stackexchange

问:
How to upload a large file in Azure blob storage from angular app directly
I have the connection string and container name of azure storage. I want to upload a large file from my angular app to azure storage directly. I also want to show the uploading progress. How can I do that? </p>

答:
According to my test, if you want to upload file to Azure blob, please refer to the following steps

Create an angular web app

```<code>ng new <appname>
</code>```

install Azure storage SDk

```<code>npm install @azure/storage-blob
</code>```

Update app.component.html File

```<code><div class="form-group">
  <label for="file">Choose File</label>
  <input type="file"
         id="file"
         (change)="onFileChange($event)">
</div>

</code>```

Update Environment.ts

```<code>export const environment = {
  production: false,
  accountName : "<account name>",
  containerName:"",
   key:""
};
</code>```

Add the following code in polyfills.ts

```<code>(window as any).global = window;
(window as any).process = require( 'process' );
(window as any).Buffer = require( 'buffer' ).Buffer;
</code>```

Add the following code in app.component.ts

```<code>import { Component } from '@angular/core';
import {BlobServiceClient,AnonymousCredential,newPipeline } from '@azure/storage-blob';
import { environment } from './../environments/environment';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'web1';
  currentFile : File =null;
  onFileChange(event) {
    this.currentFile = event.target.files[0];
    this.upload();
 }

 async upload(){
// generate account sas token
  const accountName =environment.accountName;
  const key=environment.key;
  const start = new Date(new Date().getTime() - (15 * 60 * 1000));
  const end = new Date(new Date().getTime() + (30 * 60 * 1000));
const signedpermissions = 'rwdlac';
  const signedservice = 'b';
  const signedresourcetype = 'sco';
  const signedexpiry = end.toISOString().substring(0, end.toISOString().lastIndexOf('.')) + 'Z';
  const signedProtocol = 'https';
  const signedversion = '2018-03-28';

  const StringToSign =
      accountName+ '\n' +
      signedpermissions + '\n' +
      signedservice + '\n' +
      signedresourcetype + '\n' +
       '\n' +
      signedexpiry + '\n' +
       '\n' +
      signedProtocol + '\n' +
signedversion + '\n';
  const crypto =require('crypto')
   const sig = crypto.createHmac('sha256', Buffer.from(key, 'base64')).update(StringToSign, 'utf8').digest('base64');
  const sasToken =`sv=${(signedversion)}&ss=${(signedservice)}&srt=${(signedresourcetype)}&sp=${(signedpermissions)}&se=${encodeURIComponent(signedexpiry)}&spr=${(signedProtocol)}&sig=${encodeURIComponent(sig)}`;
  const containerName=environment.containerName;

            const pipeline =newPipeline (new AnonymousCredential(),{
            retryOptions: { maxTries: 4 }, // Retry options
            userAgentOptions: { userAgentPrefix: "AdvancedSample V1.0.0" }, // Customized telemetry string
            keepAliveOptions: {
                // Keep alive is enabled by default, disable keep alive by setting false
                enable: false
            }
            });

            const blobServiceClient =new BlobServiceClient(`https://${accountname}.blob.core.windows.net?${sasToken}`,
                                                             pipeline  )
            const containerClient =blobServiceClient.getContainerClient(containerName)
            if(!containerClient.exists()){
            console.log("the container does not exit")
            await containerClient.create()

            }
            const client = containerClient.getBlockBlobClient(this.currentFile.name)
           const response = await client.uploadBrowserData(this.currentFile,{
                  blockSize: 4 * 1024 * 1024, // 4MB block size
                  concurrency: 20, // 20 concurrency
                  onProgress: (ev) => console.log(ev),
                  blobHTTPHeaders :{blobContentType:this.currentFile.type}
                  })
    console.log(response._response.status)
 }
}

</code>```

7 Test. I upload a 1.3 GB video.

ContentLicense: CC BY-SA 4.0

Body:
According to my test, if you want to upload file to Azure blob, please refer to the following steps

Create an angular web app

ng new <appname>

install Azure storage SDk

npm install @azure/storage-blob

Update app.component.html File

<div class="form-group">
  <label for="file">Choose File</label>
  <input type="file"
         id="file"
         (change)="onFileChange($event)">
</div>

Update Environment.ts

export const environment = {
  production: false,
  accountName : "<account name>",
  containerName:"",
   key:""
};

Add the following code in polyfills.ts

(window as any).global = window;
(window as any).process = require( 'process' );
(window as any).Buffer = require( 'buffer' ).Buffer;

Add the following code in app.component.ts

import { Component } from '@angular/core';
import {BlobServiceClient,AnonymousCredential,newPipeline } from '@azure/storage-blob';
import { environment } from './../environments/environment';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'web1';
  currentFile : File =null;
  onFileChange(event) {
    this.currentFile = event.target.files[0];
    this.upload();
 }

 async upload(){
// generate account sas token
  const accountName =environment.accountName;
  const key=environment.key;
  const start = new Date(new Date().getTime() - (15 * 60 * 1000));
  const end = new Date(new Date().getTime() + (30 * 60 * 1000));
const signedpermissions = 'rwdlac';
  const signedservice = 'b';
  const signedresourcetype = 'sco';
  const signedexpiry = end.toISOString().substring(0, end.toISOString().lastIndexOf('.')) + 'Z';
  const signedProtocol = 'https';
  const signedversion = '2018-03-28';

  const StringToSign =
      accountName+ '\n' +
      signedpermissions + '\n' +
      signedservice + '\n' +
      signedresourcetype + '\n' +
       '\n' +
      signedexpiry + '\n' +
       '\n' +
      signedProtocol + '\n' +
signedversion + '\n';
  const crypto =require('crypto')
   const sig = crypto.createHmac('sha256', Buffer.from(key, 'base64')).update(StringToSign, 'utf8').digest('base64');
  const sasToken =`sv=${(signedversion)}&ss=${(signedservice)}&srt=${(signedresourcetype)}&sp=${(signedpermissions)}&se=${encodeURIComponent(signedexpiry)}&spr=${(signedProtocol)}&sig=${encodeURIComponent(sig)}`;
  const containerName=environment.containerName;

            const pipeline =newPipeline (new AnonymousCredential(),{
            retryOptions: { maxTries: 4 }, // Retry options
            userAgentOptions: { userAgentPrefix: "AdvancedSample V1.0.0" }, // Customized telemetry string
            keepAliveOptions: {
                // Keep alive is enabled by default, disable keep alive by setting false
                enable: false
            }
            });

            const blobServiceClient =new BlobServiceClient(`https://${accountname}.blob.core.windows.net?${sasToken}`,
                                                             pipeline  )
            const containerClient =blobServiceClient.getContainerClient(containerName)
            if(!containerClient.exists()){
            console.log("the container does not exit")
            await containerClient.create()

            }
            const client = containerClient.getBlockBlobClient(this.currentFile.name)
           const response = await client.uploadBrowserData(this.currentFile,{
                  blockSize: 4 * 1024 * 1024, // 4MB block size
                  concurrency: 20, // 20 concurrency
                  onProgress: (ev) => console.log(ev),
                  blobHTTPHeaders :{blobContentType:this.currentFile.type}
                  })
    console.log(response._response.status)
 }
}

7 Test. I upload a 1.3 GB video.


问:
AJAX send to php controller not working in javascript
The snippet shows my html and js.  In my php controller I just print_r($_POST) but I only see the form data for myName I can't figure out how to access zzz

UPDATE: I added some code to make sure the send request is complete.  However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request.  I still can't get any js data into php.  I could create hidden inputs and fill those in from js and the submit but that seems ugly.  can someone help?

function swagSend() {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();

  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("zzz=" + henry);

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {

      document.getElementById("myForm").submit();

    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname'>
  <button type='submit' value='submit' onClick=swagSend();>Submit</button>

</form></code>```

答: you should only send with xhttp.send and not additionally with document.getElementById("myForm").submit();</p>

Body:
The snippet shows my html and js.  In my php controller I just print_r($_POST) but I only see the form data for myName I can't figure out how to access zzz

UPDATE: I added some code to make sure the send request is complete.  However, if I don't submit the form the controller doesn't execute from just issuing the xhttp request.  I still can't get any js data into php.  I could create hidden inputs and fill those in from js and the submit but that seems ugly.  can someone help?

function swagSend() {
  event.preventDefault();

  var xhttp = new XMLHttpRequest();

  xhttp.open("POST", "https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php", true);
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
      console.log(xhttp.responseText);
    }
  }

  var henry = "henry"
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xhttp.send("zzz=" + henry);

  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {

      document.getElementById("myForm").submit();

    }
  }
}

<form action="https://www.sustainablewestonma.org/wp-content/themes/twentytwelve-child/php/send_email.php" method="POST" id='myForm'>

  <input type='text' name='myname'>
  <button type='submit' value='submit' onClick=swagSend();>Submit</button>

</form>


问:
Equivalent of startActivityForResult() with Android Architecture Navigation
I have a workflow with 3 screens. From "screen 1" to access to "screen 2", the user must accept some kind of terms and conditions that I call in my picture "modal". But he only has to accept those conditions once. The next time he is on the first screen, he can go directly to screen 2. The user can chose to NOT accept the terms, and therefore we go back to "screen 1" and do not try to go to "screen 2".

I am wondering how to do it with the new navigation component.

Previously, what I would do it:

On screen 1, check if the user must accept the conditions

If no, start "screen 2" activity

If yes, use startActivityForResult() and wait result from the modal. Mark the terms as accepted. Start "screen 2"

But with the navigation graph, there is no way to start a Fragment to obtain a result.

I could mark the terms as accepted in the "modal" screen and start the "screen 2" from there. The thing is that to access to the screen 2, I need to do a network request. I do not want to duplicate the call to the API and processing its outcome in both "screen 1" and "modal".

Is there a way to go back from "modal" to "screen 1" with some information (user accepted the terms), using Jetpack navigation?

Edit: I currently get around it by using the same flow that Yahya suggests below: using an Activity just for the modal and using startActivityForResult from the "screen 1". I am just wondering if I could continue to use the navigation graph for the whole flow.

答:
Recently (in androidx-navigation-2.3.0-alpha02 ) Google was released a correct way for achieve this behaviour with fragments.

In short: (from release note)

If Fragment A needs a result from Fragment B..

A should get the savedStateHandle from the currentBackStackEntry, call getLiveData providing a key and observe the result.

```<code>findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Type>("key")?.observe(
    viewLifecycleOwner) {result ->
    // Do something with the result.
}
</code>```

B should get the savedStateHandle from the previousBackStackEntry, and set the result with the same key as the LiveData in A

```<code>findNavController().previousBackStackEntry?.savedStateHandle?.set("key", result)
</code>```

Related documentation

Body:
Recently (in androidx-navigation-2.3.0-alpha02 ) Google was released a correct way for achieve this behaviour with fragments.

In short: (from release note)

If Fragment A needs a result from Fragment B..

A should get the savedStateHandle from the currentBackStackEntry, call getLiveData providing a key and observe the result.

findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Type>("key")?.observe(
    viewLifecycleOwner) {result ->
    // Do something with the result.
}

B should get the savedStateHandle from the previousBackStackEntry, and set the result with the same key as the LiveData in A

findNavController().previousBackStackEntry?.savedStateHandle?.set("key", result)

Related documentation


问:
Power law regression problem between curve_fit, python and excel
Sorry, I am new in python and stack flow. So I can not post an image.

I want to do the power law regression with curve_fit function in python. But the result is quite strange to me. I use excel to check it further. It looks big difference between these two. Black line is the result from curve_fit and the parameter of red line is from excel. Could someone let me know the difference? Thank you!

```<code>x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x,a,b):
    return a*x**b

popt,pocv=curve_fit(f,x,y)

ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)

ax.scatter(x,y)

px=np.linspace(10,1000000,1000)

#parameter form curve_fit
py=a*px**b
[enter image description here][1]
#parameter from excel
pyy=3E-6*px**0.8305

ax.loglog(px,pyy,color="red")
ax.loglog(px,py,color="k")
</code>```

答:
The fact that you are plotting the data in log-log space should give you a good hint to fit in log space.  That is, fit np.log(a*x**b) to the np.log(y).  A modification of your script that actually runs and gets a good fit would be:

```<code>import numpy as np
from scipy.optimize import curve_fit
import  matplotlib.pyplot as plt

x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x, a, b):
    return np.log(a*x**b)

popt,pcov=curve_fit(f, x, np.log(y), [1.e-6, 0.9])

ax = plt.gca()

ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)

ax.scatter(x,y)

px = np.linspace(10,1000000,1000)
a, b = popt
print("Parameters: a=%g,  b=%g" % (a, b))

#parameter form curve_fit
py=a*px**b

#parameter from excel
pyy=3e-6*px**0.8305

ax.loglog(px,pyy, color="red")
ax.loglog(px,py,  color="k")
plt.show()
</code>```

Always be sure to provide initial values for the Parameters, and be sure to print out the results.  By way of example, running this will print out Parameters: a=2.78612e-06,  b=0.829763 and shows both predicted lines to be nearly on top of each other.

For a better curve-fitting experience, you might find lmfit (https://lmfit.github.io/lmfit-py/) useful (yes, I am a lead author and biased).  With lmfit, your fit could be:

```<code>import numpy as np
from scipy.optimize import curve_fit
import  matplotlib.pyplot as plt
from lmfit import Model

x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x, a, b):
    return np.log(a*x**b)

model = Model(f)
params = model.make_params(a=1.e-6, b=0.9)
result = model.fit(np.log(y), params, x=x)

print(result.fit_report())

px = np.linspace(10,1000000,1000)
plt.scatter(x,y)
plt.loglog(px, np.exp(result.eval(x=px)),  color="k")
plt.show()
</code>```

Note that with lmfit, Parameters are named, using the names in your f() model function.  This will print out a fit report that includes the estimated uncertainties:

```<code>[[Model]]
    Model(f)
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 16
    # data points      = 7
    # variables        = 2
    chi-square         = 14.7591170
    reduced chi-square = 2.95182340
    Akaike info crit   = 9.22165592
    Bayesian info crit = 9.11347621
[[Variables]]
    a:  2.7861e-06 +/- 6.3053e-06 (226.31%) (init = 1e-06)
    b:  0.82976271 +/- 0.25700150 (30.97%) (init = 0.9)
[[Correlations]] (unreported correlations are < 0.100)
    C(a, b) = -0.958
</code>```

and produce a plot of

Body:
Sorry, I am new in python and stack flow. So I can not post an image.

I want to do the power law regression with curve_fit function in python. But the result is quite strange to me. I use excel to check it further. It looks big difference between these two. Black line is the result from curve_fit and the parameter of red line is from excel. Could someone let me know the difference? Thank you!

x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x,a,b):
    return a*x**b

popt,pocv=curve_fit(f,x,y)

ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)

ax.scatter(x,y)

px=np.linspace(10,1000000,1000)

#parameter form curve_fit
py=a*px**b
[enter image description here][1]
#parameter from excel
pyy=3E-6*px**0.8305

ax.loglog(px,pyy,color="red")
ax.loglog(px,py,color="k")

Body:
The fact that you are plotting the data in log-log space should give you a good hint to fit in log space.  That is, fit np.log(a*x**b) to the np.log(y).  A modification of your script that actually runs and gets a good fit would be:

import numpy as np
from scipy.optimize import curve_fit
import  matplotlib.pyplot as plt

x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x, a, b):
    return np.log(a*x**b)

popt,pcov=curve_fit(f, x, np.log(y), [1.e-6, 0.9])

ax = plt.gca()

ax.set_xscale("log")
ax.set_yscale("log")
ax.set_ylim(0.00001,0.1)
ax.set_xlim(10,1000000)

ax.scatter(x,y)

px = np.linspace(10,1000000,1000)
a, b = popt
print("Parameters: a=%g,  b=%g" % (a, b))

#parameter form curve_fit
py=a*px**b

#parameter from excel
pyy=3e-6*px**0.8305

ax.loglog(px,pyy, color="red")
ax.loglog(px,py,  color="k")
plt.show()

Always be sure to provide initial values for the Parameters, and be sure to print out the results.  By way of example, running this will print out Parameters: a=2.78612e-06,  b=0.829763 and shows both predicted lines to be nearly on top of each other.

For a better curve-fitting experience, you might find lmfit (https://lmfit.github.io/lmfit-py/) useful (yes, I am a lead author and biased).  With lmfit, your fit could be:

import numpy as np
from scipy.optimize import curve_fit
import  matplotlib.pyplot as plt
from lmfit import Model

x=[164000,400,13000,700,57000,108,12000]
y=[0.011970,0.000098,0.066100,0.004300,0.042600,0.000061,0.002858 ]

def f(x, a, b):
    return np.log(a*x**b)

model = Model(f)
params = model.make_params(a=1.e-6, b=0.9)
result = model.fit(np.log(y), params, x=x)

print(result.fit_report())

px = np.linspace(10,1000000,1000)
plt.scatter(x,y)
plt.loglog(px, np.exp(result.eval(x=px)),  color="k")
plt.show()

Note that with lmfit, Parameters are named, using the names in your f() model function.  This will print out a fit report that includes the estimated uncertainties:

[[Model]]
    Model(f)
[[Fit Statistics]]
    # fitting method   = leastsq
    # function evals   = 16
    # data points      = 7
    # variables        = 2
    chi-square         = 14.7591170
    reduced chi-square = 2.95182340
    Akaike info crit   = 9.22165592
    Bayesian info crit = 9.11347621
[[Variables]]
    a:  2.7861e-06 +/- 6.3053e-06 (226.31%) (init = 1e-06)
    b:  0.82976271 +/- 0.25700150 (30.97%) (init = 0.9)
[[Correlations]] (unreported correlations are < 0.100)
    C(a, b) = -0.958

and produce a plot of


问:
How does defining a function nested in another work?
In the Python implementation of the Xiaolin Wu's line algorithm, a function is defined while being nested in another function. Part of the code:

```<code>def draw_line(img, p1, p2, color):
    """Draws an anti-aliased line in img from p1 to p2 with the given color."""
    x1, y1 = p1
    x2, y2 = p2
    dx, dy = x2-x1, y2-y1
    steep = abs(dx) < abs(dy)
    p = lambda px, py: ((px,py), (py,px))[steep]

    if steep:
        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx
    if x2 < x1:
        x1, x2, y1, y2 = x2, x1, y2, y1

    grad = dy/dx
    intery = y1 + _rfpart(x1) * grad
    def draw_endpoint(pt):
        x, y = pt
        xend = round(x)
        yend = y + grad * (xend - x)
        xgap = _rfpart(x + 0.5)
        px, py = int(xend), int(yend)
        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)
        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)
        return px
</code>```

How does this work? Why didn't the programmer just define the code somewhere else and then call it in this function? If this function where to be called in a loop to draw multiple lines, wouldn't it be more efficient to just, as I said, define the nested function somewhere else?

答:
The reason why is because you are calling the function from the class definition, as opposed to the initialized object. You can do two things to fix this:

Call the function from the object that has been initialized:

class Foo:

    def bar(x):
        print(x)

a = Foo()
a.bar(10)
```

<p>Or, define the function as a <code>staticmethod</code>:</p>

<pre class="lang-py prettyprint-override"><code>class Foo:

    @staticmethod
    def bar(x):
        print(x)

Foo.bar(10)
</code>```

Both will output:

```<code>10
</code>```

Body:
In the Python implementation of the Xiaolin Wu's line algorithm, a function is defined while being nested in another function. Part of the code:

def draw_line(img, p1, p2, color):
    """Draws an anti-aliased line in img from p1 to p2 with the given color."""
    x1, y1 = p1
    x2, y2 = p2
    dx, dy = x2-x1, y2-y1
    steep = abs(dx) < abs(dy)
    p = lambda px, py: ((px,py), (py,px))[steep]

    if steep:
        x1, y1, x2, y2, dx, dy = y1, x1, y2, x2, dy, dx
    if x2 < x1:
        x1, x2, y1, y2 = x2, x1, y2, y1

    grad = dy/dx
    intery = y1 + _rfpart(x1) * grad
    def draw_endpoint(pt):
        x, y = pt
        xend = round(x)
        yend = y + grad * (xend - x)
        xgap = _rfpart(x + 0.5)
        px, py = int(xend), int(yend)
        putpixel(img, p(px, py), color, _rfpart(yend) * xgap)
        putpixel(img, p(px, py+1), color, _fpart(yend) * xgap)
        return px

How does this work? Why didn't the programmer just define the code somewhere else and then call it in this function? If this function where to be called in a loop to draw multiple lines, wouldn't it be more efficient to just, as I said, define the nested function somewhere else?

Body:
The reason why is because you are calling the function from the class definition, as opposed to the initialized object. You can do two things to fix this:

Call the function from the object that has been initialized:

class Foo:

    def bar(x):
        print(x)

a = Foo()
a.bar(10)

Or, define the function as a staticmethod:

class Foo:

    @staticmethod
    def bar(x):
        print(x)

Foo.bar(10)

Both will output:

10


问:
Encrypting and then decrypting same string in python
Here is the question:

In cryptography, a simple substitution cypher is a method of encryption in which each letter of a phrase is replaced by a different letter or sequence of letters. The phrase can then be decrypted by performing the inverse of the substitution.

In this question, we will implement a simple substitution cypher in which a character (letter, number, or special symbol) is substituted by a two-digit number between 00 and 99 (inclusive). For example, the letter ‘a’ could be encrypted to become the number ‘06’, or the special symbol ‘!’ could become the number ‘57’.

We will use a dictionary to store the mapping between each character and its corresponding encrypted form. That is, the keys of the dictionary will be the regular characters (letters, numbers and special symbols), and the values will be the encrypted forms of the characters (the two-digit numbers between 00 and 99).

Your code should implement the following five functions for this question.

Name: create cypher dictionary

Parameters: No parameters.

Return value: A dictionary where each key is a regular character and each value is a random two-digit number between 00 and 99, inclusive.

What it should do: At the top of the code provided to you, the string LETTERS is defined. This string contains all the letters, numbers and special symbols that should be keys in the dictionary. You will have to loop over this string, and generate a two-digit random number between 00 and 99 for each character. The two-digit numbers will be the values in the dictionary; each character (key) will have one two-digit number (value).

Note that the numbers 0, 1, 2, ..., 9 should not be values; instead, they should be the numbers 00, 01, 02, ..., 09. Further, note that each character should have a unique random number. That is, if the character ‘a’ maps to the value ‘57’, no other character should map to the value ‘57’. (You will need to use some sort of loop to keep generating new random numbers until a unique one is found.)

Name: encrypt

Parameters: A string s.

Return value: The encrypted version of the string s. Each character of the original string s should be replaced by its corresponding two-digit number in the cypher dictionary.

Name: decrypt

Parameters: A string s.
Return value: The decrypted version of the string s. Each two-digit number of the encrypted string s should be replaced by its corresponding character in the cypher dictionary. Note that here, we have the encrypted form (value in the dictionary), and are looking to find the regular character (key 7 in the dictionary). To do this, we will need to use the reverse lookup function as seen in class. This function has been provided to you in the included encryption.py file.

We will write two further functions to increase the strength of our encryption. One function will repeatedly encrypt the string multiple times. The other function will attempt to decrypt the string, without knowing the number of times it was encrypted (thus defeating the point of the stronger encryption).

Name: encrypt multiple times

Parameters: A string s and integer value n for the number of times to encrypt the string.

Return value: The string s encrypted n times. I.e., the string will be encrypted a first time, with each character turned into its two-digit representation. Then, the encrypted string will be re- encrypted, with each digit turned into its two-digit representation. (The length of the string will thus double after every encryption.) (Hint: You will have to call your encrypt function multiple times.)

Name: decrypt multiple times

Parameters: A string s.

Return value: The decrypted version of the string s. As we do not know how many times to decrypt the string, we will keep calling decrypt on the string until the string contains a common word in the English language. A list of common words, COMMON WORDS, has been provided for you in the encryption.py file. If, after decrypting once, the string contains any word in this list, then you should immediately return the decrypted string. Otherwise, continue calling decrypt on the string until it does contain one of the common words. (We will assume that the fully decrypted string will always contain at least one common word.)

Finally, at the end of the file encryption.py, you will notice some code already written for you. This code asks the user to input a string, then calls the various functions and prints what they return (to produce the examples seen below). You must alter this code so that if the user enters a string that does not contain any of the words in the COMMON WORDS list, then the program should output ”Invalid input.” and not execute the rest of the code. Otherwise, the program should continue with the rest of the code. (Hint: Think back to Assignment 1 and if/else branches.)

Here is what I tried as an input:

def reverse_lookup(d,v):
    for key in d:
        if d[key]==v:
            return key
    return None

LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()`~-=_+[]{}|;\':",./<>? '
def create_cypher_dictionary():
    random.seed(1337)
    cypher={}

    ar=[0]*100
    for c in LETTERS:
        n=random.randrange(0, 100, 1)
        while ar[n]!=0:
            n=random.randrange(0, 100, 1)
        ar[n]=1
        if n<10:
            cypher[c]=str('0')+str(n)
        else:
            cypher[c]=str(n)

    return cypher

def encrypt(s):
    cypher=create_cypher_dictionary()

    new_s=''
    for c in s:
        new_s=new_s+cypher[c]

    return new_s

def decrypt(s):
    cypher=create_cypher_dictionary()

    new_s=''
    for i in range(len(s)-1):
        c=s[i]+s[i+1]
        for cc in cypher:
            if cypher[cc]==c:
                new_s=new_s+cc

    return new_s

def encrypt_multiple_times(s,n):

    for i in range(n):
        s=encrypt(s)
    return s

COMMON_WORDS= ['the','be','to','of','and','a','in','that','have','I','it','for','not','on','with','he','as','you','do','at']

def check_common_words(s):
    for word in COMMON_WORDS:
        if word in s:
            return False
    return True

def decrypt_multiple_times(s):

    cypher=create_cypher_dictionary()
    while check_common_words(s):
        s=decrypt(s)

    return s

s=input('Enter text to encrypt:')

if check_common_words(s)==False:

    print("Encrypted string:", encrypt(s))
    print("Decrypted string:", decrypt(encrypt(s)))

    salted_s = encrypt_multiple_times(s, 2)

    print("Encrypted x2 string:", salted_s)
    print("Decrypted x2 string:", decrypt_multiple_times(salted_s))

else:
    print('Invalid input.')
```

<p>And here is the output it produced:</p>

```Enter text to encrypt:The quick brown fox jumps over the lazy dog
Encrypted string:   36217337975199904937688489645037748985374251392613378908738437542173378179944437468993
Decrypted string: T0h-eK aq?u(iic,kg CbIr~o@wBn8 Jf~o>x[ fjLusm3p=sK Yocv<e/r" ?tjh-eK Yl-aizyy" fdboig
Encrypted x2 string: 9223712963929263666327296666666282669263230303820366238227629263638203660327926382712729926671232992926303666203639203829263278271296392926303296366668282829263822303666692
Decrypted x2 string: 36 21@7m313p7T997#5W1@9999990+4p9!3p7#6'8'8/4_8T906/45C013p7T7/4_8T9]8#5a3p7/4525W1i3p9N26#1i313p7'8T990_8T7m3_8/413p7#5Y4521@7m313p7'8#1@7T999b4+4+413p7/46'8T999!3
```

<p>However, it was supposed to output:</p>

```Enter text to encrypt: The quick brown fox jumps over the lazy dog.
Encrypted string: 0766546138001892056159999714256163973761640073940161973354996169665461919809956156975155
Decrypted string: The quick brown fox jumps over the lazy dog.
Encrypted x2 string: 3417626247536227487834342778713634476227477171717117275336 4762276248711748176227625334341748715334276227711748484753717162276271626247536227712771783471714762274762711747274747
Decrypted x2 string: The quick brown fox jumps over the lazy dog.
```

I'm really out of ideas, if someone can help, it would be greatly appreciated.

答:
You're converting the ASCII incorrectly by taking only one digit at a time, when you should be taking two digits. Just change the step of the for loop in your decrypt function:</p>

```<code>def decrypt(s):
    cypher=create_cypher_dictionary()

    new_s=''
    for i in range(0,len(s)-1,2): # Make the for loop step 2 instead of 1 (default)
        c=s[i]+s[i+1]
        for cc in cypher:
            if cypher[cc]==c:
                new_s=new_s+cc

    return new_s
</code>```

Body:
Here is the question:

In cryptography, a simple substitution cypher is a method of encryption in which each letter of a phrase is replaced by a different letter or sequence of letters. The phrase can then be decrypted by performing the inverse of the substitution.

In this question, we will implement a simple substitution cypher in which a character (letter, number, or special symbol) is substituted by a two-digit number between 00 and 99 (inclusive). For example, the letter ‘a’ could be encrypted to become the number ‘06’, or the special symbol ‘!’ could become the number ‘57’.

We will use a dictionary to store the mapping between each character and its corresponding encrypted form. That is, the keys of the dictionary will be the regular characters (letters, numbers and special symbols), and the values will be the encrypted forms of the characters (the two-digit numbers between 00 and 99).

Your code should implement the following five functions for this question.

Name: create cypher dictionary

Parameters: No parameters.

Return value: A dictionary where each key is a regular character and each value is a random two-digit number between 00 and 99, inclusive.

What it should do: At the top of the code provided to you, the string LETTERS is defined. This string contains all the letters, numbers and special symbols that should be keys in the dictionary. You will have to loop over this string, and generate a two-digit random number between 00 and 99 for each character. The two-digit numbers will be the values in the dictionary; each character (key) will have one two-digit number (value).

Note that the numbers 0, 1, 2, ..., 9 should not be values; instead, they should be the numbers 00, 01, 02, ..., 09. Further, note that each character should have a unique random number. That is, if the character ‘a’ maps to the value ‘57’, no other character should map to the value ‘57’. (You will need to use some sort of loop to keep generating new random numbers until a unique one is found.)

Name: encrypt

Parameters: A string s.

Return value: The encrypted version of the string s. Each character of the original string s should be replaced by its corresponding two-digit number in the cypher dictionary.

Name: decrypt

Parameters: A string s.
Return value: The decrypted version of the string s. Each two-digit number of the encrypted string s should be replaced by its corresponding character in the cypher dictionary. Note that here, we have the encrypted form (value in the dictionary), and are looking to find the regular character (key 7 in the dictionary). To do this, we will need to use the reverse lookup function as seen in class. This function has been provided to you in the included encryption.py file.

We will write two further functions to increase the strength of our encryption. One function will repeatedly encrypt the string multiple times. The other function will attempt to decrypt the string, without knowing the number of times it was encrypted (thus defeating the point of the stronger encryption).

Name: encrypt multiple times

Parameters: A string s and integer value n for the number of times to encrypt the string.

Return value: The string s encrypted n times. I.e., the string will be encrypted a first time, with each character turned into its two-digit representation. Then, the encrypted string will be re- encrypted, with each digit turned into its two-digit representation. (The length of the string will thus double after every encryption.) (Hint: You will have to call your encrypt function multiple times.)

Name: decrypt multiple times

Parameters: A string s.

Return value: The decrypted version of the string s. As we do not know how many times to decrypt the string, we will keep calling decrypt on the string until the string contains a common word in the English language. A list of common words, COMMON WORDS, has been provided for you in the encryption.py file. If, after decrypting once, the string contains any word in this list, then you should immediately return the decrypted string. Otherwise, continue calling decrypt on the string until it does contain one of the common words. (We will assume that the fully decrypted string will always contain at least one common word.)

Finally, at the end of the file encryption.py, you will notice some code already written for you. This code asks the user to input a string, then calls the various functions and prints what they return (to produce the examples seen below). You must alter this code so that if the user enters a string that does not contain any of the words in the COMMON WORDS list, then the program should output ”Invalid input.” and not execute the rest of the code. Otherwise, the program should continue with the rest of the code. (Hint: Think back to Assignment 1 and if/else branches.)

Here is what I tried as an input:

def reverse_lookup(d,v):
    for key in d:
        if d[key]==v:
            return key
    return None

LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()`~-=_+[]{}|;\':",./<>? '
def create_cypher_dictionary():
    random.seed(1337)
    cypher={}

    ar=[0]*100
    for c in LETTERS:
        n=random.randrange(0, 100, 1)
        while ar[n]!=0:
            n=random.randrange(0, 100, 1)
        ar[n]=1
        if n<10:
            cypher[c]=str('0')+str(n)
        else:
            cypher[c]=str(n)

    return cypher

def encrypt(s):
    cypher=create_cypher_dictionary()

    new_s=''
    for c in s:
        new_s=new_s+cypher[c]

    return new_s

def decrypt(s):
    cypher=create_cypher_dictionary()

    new_s=''
    for i in range(len(s)-1):
        c=s[i]+s[i+1]
        for cc in cypher:
            if cypher[cc]==c:
                new_s=new_s+cc

    return new_s

def encrypt_multiple_times(s,n):

    for i in range(n):
        s=encrypt(s)
    return s

COMMON_WORDS= ['the','be','to','of','and','a','in','that','have','I','it','for','not','on','with','he','as','you','do','at']

def check_common_words(s):
    for word in COMMON_WORDS:
        if word in s:
            return False
    return True

def decrypt_multiple_times(s):

    cypher=create_cypher_dictionary()
    while check_common_words(s):
        s=decrypt(s)

    return s

s=input('Enter text to encrypt:')

if check_common_words(s)==False:

    print("Encrypted string:", encrypt(s))
    print("Decrypted string:", decrypt(encrypt(s)))

    salted_s = encrypt_multiple_times(s, 2)

    print("Encrypted x2 string:", salted_s)
    print("Decrypted x2 string:", decrypt_multiple_times(salted_s))

else:
    print('Invalid input.')

And here is the output it produced:

Enter text to encrypt:The quick brown fox jumps over the lazy dog
Encrypted string:   36217337975199904937688489645037748985374251392613378908738437542173378179944437468993
Decrypted string: T0h-eK aq?u(iic,kg CbIr~o@wBn8 Jf~o>x[ fjLusm3p=sK Yocv<e/r" ?tjh-eK Yl-aizyy" fdboig
Encrypted x2 string: 9223712963929263666327296666666282669263230303820366238227629263638203660327926382712729926671232992926303666203639203829263278271296392926303296366668282829263822303666692
Decrypted x2 string: 36 21@7m313p7T997#5W1@9999990+4p9!3p7#6'8'8/4_8T906/45C013p7T7/4_8T9]8#5a3p7/4525W1i3p9N26#1i313p7'8T990_8T7m3_8/413p7#5Y4521@7m313p7'8#1@7T999b4+4+413p7/46'8T999!3

However, it was supposed to output:

Enter text to encrypt: The quick brown fox jumps over the lazy dog.
Encrypted string: 0766546138001892056159999714256163973761640073940161973354996169665461919809956156975155
Decrypted string: The quick brown fox jumps over the lazy dog.
Encrypted x2 string: 3417626247536227487834342778713634476227477171717117275336 4762276248711748176227625334341748715334276227711748484753717162276271626247536227712771783471714762274762711747274747
Decrypted x2 string: The quick brown fox jumps over the lazy dog.

I'm really out of ideas, if someone can help, it would be greatly appreciated.

Body:
You're converting the ASCII incorrectly by taking only one digit at a time, when you should be taking two digits. Just change the step of the for loop in your decrypt function:

def decrypt(s):
    cypher=create_cypher_dictionary()

    new_s=''
    for i in range(0,len(s)-1,2): # Make the for loop step 2 instead of 1 (default)
        c=s[i]+s[i+1]
        for cc in cypher:
            if cypher[cc]==c:
                new_s=new_s+cc

    return new_s


问:
Unable to SSH into Docker container running Alpine Linux 3.10
I am having problems using SSH to connect into a Docker container (from this image) running Alpine Linux 3.10.

SSH must be used for this connection, as I am using a backup software barman which requires an SSH connection to the PostgreSQL 11 database running inside the Docker container.

First I connected into the docker container using

```<code>docker exec -it <container_name> /bin/bash
</code>```

then tried to reinstall and start sshd

```<code>bash-5.0# apk add openssh --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# apk add openrc --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# rc-update add sshd
 * rc-update: sshd already installed in runlevel `sysinit'; skipping

bash-5.0# /etc/init.d/sshd start
 * WARNING: sshd is already starting
</code>```

However, I am unable to connect to the local sshd server from inside the Docker container

```<code># ssh root@127.0.0.1
ssh: connect to host 127.0.0.1 port 22: Connection refused
</code>```

Similarly, connecting into the Docker container via SSH from the Ubuntu host machine fails as well.

```<code>$ ssh postgres@172.26.0.4
ssh: connect to host 172.26.0.4 port 22: Connection refused
</code>```

where 172.26.0.4 is the IP address shown from running ifconfig inside the Docker container.

Any ideas how we can solve this?

答:
I didn't download the image you're referring to, but worked w/ the default docker alpine-image.  To get ssh to run inside the container a few extra steps were required - there's a good chance that you need to take the same:</p>

```<code>ssh-keygen -A
rc-status
touch /run/openrc/softlevel
/etc/init.d/sshd start
</code>```

Body:
I am having problems using SSH to connect into a Docker container (from this image) running Alpine Linux 3.10.

SSH must be used for this connection, as I am using a backup software barman which requires an SSH connection to the PostgreSQL 11 database running inside the Docker container.

First I connected into the docker container using

docker exec -it <container_name> /bin/bash

then tried to reinstall and start sshd

bash-5.0# apk add openssh --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# apk add openrc --no-cache
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.10/community/x86_64/APKINDEX.tar.gz
OK: 117 MiB in 42 packages

bash-5.0# rc-update add sshd
 * rc-update: sshd already installed in runlevel `sysinit'; skipping

bash-5.0# /etc/init.d/sshd start
 * WARNING: sshd is already starting

However, I am unable to connect to the local sshd server from inside the Docker container

# ssh root@127.0.0.1
ssh: connect to host 127.0.0.1 port 22: Connection refused

Similarly, connecting into the Docker container via SSH from the Ubuntu host machine fails as well.

$ ssh postgres@172.26.0.4
ssh: connect to host 172.26.0.4 port 22: Connection refused

where 172.26.0.4 is the IP address shown from running ifconfig inside the Docker container.

Any ideas how we can solve this?

Body:
I didn't download the image you're referring to, but worked w/ the default docker alpine-image.  To get ssh to run inside the container a few extra steps were required - there's a good chance that you need to take the same:

ssh-keygen -A
rc-status
touch /run/openrc/softlevel
/etc/init.d/sshd start


答:
You may try this:

```<code>LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()`~-=_+[]{}|;\':",./<>? '

def create_cypher_dictionary():
    numbers = [ '%02d' % i for i in range(100) ]
    random.shuffle( numbers )
    return { a : b for a,b in zip( LETTERS, numbers ) }

def encrypt( cypher, string ) :
    return ''.join( cypher[ch] for ch in string )

def decrypt( cypher, string ) :
    inverse_cypher = { b : a for a,b in cypher.items() }
    return ''.join( inverse_cypher[a+b] for a,b in zip(*[iter(string)]*2) )
</code>```

Checking:

```<code>>>> cypher = create_cypher_dictionary()
>>> encoded = encrypt( cypher, 'The quick brown fox jumps over the lazy dog' )
>>> encoded
'93684236886025540636378012826636001276363960074903361250428036306842367064856536261211'
>>> decrypt( cypher, encoded )
'The quick brown fox jumps over the lazy dog'
>>>
</code>```

And yeah, you cannot create cypher every time, you have to make one, and reuse it, otherwise your results will be kind of random =)

Title: Encrypting and then decrypting same string in python

Body:
You may try this:

LETTERS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()`~-=_+[]{}|;\':",./<>? '

def create_cypher_dictionary():
    numbers = [ '%02d' % i for i in range(100) ]
    random.shuffle( numbers )
    return { a : b for a,b in zip( LETTERS, numbers ) }

def encrypt( cypher, string ) :
    return ''.join( cypher[ch] for ch in string )

def decrypt( cypher, string ) :
    inverse_cypher = { b : a for a,b in cypher.items() }
    return ''.join( inverse_cypher[a+b] for a,b in zip(*[iter(string)]*2) )

Checking:

>>> cypher = create_cypher_dictionary()
>>> encoded = encrypt( cypher, 'The quick brown fox jumps over the lazy dog' )
>>> encoded
'93684236886025540636378012826636001276363960074903361250428036306842367064856536261211'
>>> decrypt( cypher, encoded )
'The quick brown fox jumps over the lazy dog'
>>>

And yeah, you cannot create cypher every time, you have to make one, and reuse it, otherwise your results will be kind of random =)


问:
Passing value from dialog form to main form

Possible Duplicate:

  How do you pass an object from form1 to form2 and back to form1?

I'm used to passing variables between windows forms by simply passing them as a parameter.
Now I have a form that is already open (let's call it FormMain), and another form that should act like a dialog (FormTask). The user cannot interact with the main form until he has filled in the information on FormTask. FormTask simply contains a single textbox, and the value of this textbox should be returned to FormMain, and kept track of as a variable. FormTask requires a parameter exerciseType. When FormTask opens it checks the value of this parameter and sets the default value of the textbox accordingly. This already works, I'm just kind of clueless on how to return my string value to the already open MainForm.
These dialogs only seem to be able to return DialogResults, which isn't what I'm after. I'm not too experienced either, and I'd rather avoid fumbling around to make my own custom dialog.

FormMain:

```<code>FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();
</code>```

FormTask:

```<code>private void button1_Click(object sender, EventArgs e)
{
    string opgave = textBoxOpgave.Text;
    // return string value to MainForm here
}
</code>```

答:
Create public property in FormTask

```<code>public string Opgave { get {return textBoxOpgave.Text;}}
</code>```

And check it after ShowDialog();

```<code>FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoer.ShowDialog();
formOpgaveInvoer.Opgave;  // here it is
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Possible Duplicate:

  How do you pass an object from form1 to form2 and back to form1?

I'm used to passing variables between windows forms by simply passing them as a parameter.
Now I have a form that is already open (let's call it FormMain), and another form that should act like a dialog (FormTask). The user cannot interact with the main form until he has filled in the information on FormTask. FormTask simply contains a single textbox, and the value of this textbox should be returned to FormMain, and kept track of as a variable. FormTask requires a parameter exerciseType. When FormTask opens it checks the value of this parameter and sets the default value of the textbox accordingly. This already works, I'm just kind of clueless on how to return my string value to the already open MainForm.
These dialogs only seem to be able to return DialogResults, which isn't what I'm after. I'm not too experienced either, and I'd rather avoid fumbling around to make my own custom dialog.

FormMain:

FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoker.ShowDialog();

FormTask:

private void button1_Click(object sender, EventArgs e)
{
    string opgave = textBoxOpgave.Text;
    // return string value to MainForm here
}

Body:
Create public property in FormTask

public string Opgave { get {return textBoxOpgave.Text;}}

And check it after ShowDialog();

FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoer.ShowDialog();
formOpgaveInvoer.Opgave;  // here it is


问:
What is causing the input box text not to re-order in the ReactJS page example of Reconciliation?
In the ReactJS page of Reconciliation, there are two examples:

an example of the issues that can be caused by using indexes as keys

an updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues

As of Feb 18, 2020, there is no telling of how to reproduce the issue on the page. I tried clicking on "Add New to Start" or "to End" a few times and reorder the list, and they seemed to work fine. Only later I found out you need to enter some text into the box, and then just "Add New to End", and do it three times, and reorder the list.

In the first example, the text in the input box were not re-ordered. In the second example, the text in the input box were re-ordered as expected.

The two programs differ by using

```<code><ToDo key={index} {...todo} />
</code>```

vs

```<code><ToDo key={todo.id} {...todo} />
</code>```

There are also some slightly re-ordering of code and using todoCounter vs toDoCounter (capital D) between the two versions, which I wonder why and the React team might fix it later.  But you can modify the first version from key={index} to key={todo.id} and you can also see the problem solved.

But then when I looked into the code, the input box doesn't actually add the text data to the state property list (an array). Only id and createdAt are added per new entry to list.

So while we can say using key={todo.id} fixed the problem, what was causing the problem in the first place?

You can say that the id and createdAt are sorted correctly.  What is not sorted correctly are the input boxes... but according to the rule of reconciliation to decide whether to refresh actual DOM elements on the page, the new Virtual DOM subtree is compared to the previous virtual DOM subtree.

Now the "property" of the input box value is not part of the virtual DOM, unless if React actually silently puts the value into the virtual DOM.

So when "diff'ing" recursively, React should think the input boxes are all the same.  So is this how it worked: if we used the key={index}, now React diff'ed each column in the current virtual DOM subtree with the previous one, and see that the "ID" and "createAt" cells are different, therefore forcing a refresh to the actual DOM.  React saw the input boxes all the same and didn't bother to force a refresh to the actual DOM.

However, if we use key={todo.id}, now React will think, the whole row is different, because the row "id" has changed. So React will force a refresh to the actual DOM for the whole row, including the input box.

So we can say, this bug occur only when some data is not in the virtual DOM subtree... which is rare, such as in this current case. In other cases, all the data would be given out by the render() of class component or the return of function component, and therefore, able to tell ReactJS that, "yes, force a refresh to the actual DOM".

Is this really how it worked?

答:
Using index as keys is very dangerous and is highly advised against.

For example, if you delete an item from the middle of the list, another item will take its place, React needs a unique key to recognize a DOM element as an individual/independent  element and not something that is temporary or useless.

Your list is being sorted as intended, you can see that the ID column is sorted accurately.

But in your case, React doesn't know which todo belongs to which ID, indexes are not todo list ID, they're numbers that were generated in order.

Imagine this

```<code>Todos:
id 1
todo: "take out the trash"

id 2
todo: "make dinner"

if you sort your todos by the shortest string
it will end up like this:
2
1
</code>```

the normal order is:

```<code>1
2
</code>```

No matter how you sort your list and change its order, if you tell React to use indexes, it will always render it like this:

```<code>1
2
3
4
...etc
</code>```

If you use object IDs, React will keep track of the elements and will connect the keys to the IDs, then render your elements based on the order of your sorted IDs.

Body:
In the ReactJS page of Reconciliation, there are two examples:

an example of the issues that can be caused by using indexes as keys

an updated version of the same example showing how not using indexes as keys will fix these reordering, sorting, and prepending issues

As of Feb 18, 2020, there is no telling of how to reproduce the issue on the page. I tried clicking on "Add New to Start" or "to End" a few times and reorder the list, and they seemed to work fine. Only later I found out you need to enter some text into the box, and then just "Add New to End", and do it three times, and reorder the list.

In the first example, the text in the input box were not re-ordered. In the second example, the text in the input box were re-ordered as expected.

The two programs differ by using

<ToDo key={index} {...todo} />

vs

<ToDo key={todo.id} {...todo} />

There are also some slightly re-ordering of code and using todoCounter vs toDoCounter (capital D) between the two versions, which I wonder why and the React team might fix it later.  But you can modify the first version from key={index} to key={todo.id} and you can also see the problem solved.

But then when I looked into the code, the input box doesn't actually add the text data to the state property list (an array). Only id and createdAt are added per new entry to list.

So while we can say using key={todo.id} fixed the problem, what was causing the problem in the first place?

You can say that the id and createdAt are sorted correctly.  What is not sorted correctly are the input boxes... but according to the rule of reconciliation to decide whether to refresh actual DOM elements on the page, the new Virtual DOM subtree is compared to the previous virtual DOM subtree.

Now the "property" of the input box value is not part of the virtual DOM, unless if React actually silently puts the value into the virtual DOM.

So when "diff'ing" recursively, React should think the input boxes are all the same.  So is this how it worked: if we used the key={index}, now React diff'ed each column in the current virtual DOM subtree with the previous one, and see that the "ID" and "createAt" cells are different, therefore forcing a refresh to the actual DOM.  React saw the input boxes all the same and didn't bother to force a refresh to the actual DOM.

However, if we use key={todo.id}, now React will think, the whole row is different, because the row "id" has changed. So React will force a refresh to the actual DOM for the whole row, including the input box.

So we can say, this bug occur only when some data is not in the virtual DOM subtree... which is rare, such as in this current case. In other cases, all the data would be given out by the render() of class component or the return of function component, and therefore, able to tell ReactJS that, "yes, force a refresh to the actual DOM".

Is this really how it worked?

Body:
Using index as keys is very dangerous and is highly advised against.

For example, if you delete an item from the middle of the list, another item will take its place, React needs a unique key to recognize a DOM element as an individual/independent  element and not something that is temporary or useless.

Your list is being sorted as intended, you can see that the ID column is sorted accurately.

But in your case, React doesn't know which todo belongs to which ID, indexes are not todo list ID, they're numbers that were generated in order.

Imagine this

Todos:
id 1
todo: "take out the trash"

id 2
todo: "make dinner"

if you sort your todos by the shortest string
it will end up like this:
2
1

the normal order is:

1
2

No matter how you sort your list and change its order, if you tell React to use indexes, it will always render it like this:

1
2
3
4
...etc

If you use object IDs, React will keep track of the elements and will connect the keys to the IDs, then render your elements based on the order of your sorted IDs.


问:
How can I use a dev dependency locally on my machine only and not have to push it to the team repo?
I'm part of a time working with a remote repo.
I recently installed a great Webpack plugin that plays a sound when Webpack finishes building the project. I love it but my team lead does not want it becoming part of the repo.

The problem is that every time I change branches, I have to reinstall the plugin and add it back to the webpack config. Sometimes, Git lets me get away with leaving it but sometimes it doesn't and tells me to commit or stash before proceeding with an action. I've done stashing but it becomes a pain because I need to constantly stash/un-stash and often rerun install/add and restart Webpack.

Is there any way I can make this part of Webpack and the project on my machine only in a way that is seamless and simple and doesn't affect anyone else?

答:
It seems the webpack config file has been added and committed to the repository. Usually such configuration files are not supposed to be committed as part of the repository from the beginning, because they vary a lot in different workspaces and cause conflicts if contributors commit and push their own versions. But as @BenPetty commented, a webpack config file should be committed. I am completely new to webpack, so please ignore my opinion here.

As it's already there and I have no idea about your repository, I'd suggest you try this workaround. Since you switch branches a lot, you could use git worktree to generate a worktree for every branch or even every revision. One worktree is independent from another and you can commit, pull or push in the worktree.

Say you have 3 branches dev1, dev2 and dev3. The repository is now on master. You can use git worktree add /foo/dev1 dev1 to create the path /foo/dev1, and dev1 is checked out in it. Run git worktree add /foo/dev2 dev2 and git worktree add /foo/dev3 dev3 for the rest two branches. This way, you don't need to switch branches or clone a new repo for another branch. You can just enter the worktree path and install the plugin.

When dev1 is done, you can use git worktree remove /foo/dev1 to remove the worktree /foo/dev1. If you manually remove the path /foo/dev1 first, you can then use git worktree prune to prune its information from the repository.


问:
How to insert
 in markaby (rails)
I have to do something like this

 Freeze

 2010-6-1

How can i write it in markaby?
Now I have:
td "#{user.username} #{user.created_at}"

答:
try this it may work for you</p>

```<code>td do
    user.username {br} user.created_at
end
</code>```

Title: How to insert <br> in markaby (rails)

Body:
try this it may work for you

td do
    user.username {br} user.created_at
end


问:
docker-compose can't connect to docker daemon?
I am trying to build a docker environment through docker-compose, however it gives errors.

```<code>$ docker-compose build
ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.
</code>```

Docker daemon is running

```<code>$ sudo systemctl status docker
[sudo] password for mansop:
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2020-02-19 12:07:27 AEDT; 22min ago
     Docs: http://docs.docker.com
 Main PID: 8972 (dockerd-current)
    Tasks: 22
   Memory: 22.8M
   CGroup: /system.slice/docker.service
           ├─8972 /usr/bin/dockerd-current --add-runtime docker-runc=/usr/libexec/docker/docker-runc-current --default-runtime=docker-runc --exec-opt native.cgroupdriver=systemd --userland-proxy-path=/usr/l...
           └─8978 /usr/bin/docker-containerd-current -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containe...
</code>```

Docker installed from centos7 repository:

```<code>$ docker --version
Docker version 1.13.1, build 4ef4b30/1.13.1
</code>```

I tried setting up DOCKER_HOST following the error message but the issue persists:

```<code>$ echo $DOCKER_HOST
127.0.0.1:2375
</code>```

Any thoughts?

答:
For some reason there were no docker group in my system, my user was not part of docker group and the docker socket file was not under the docker group.

The commands below fixed my issue:

```<code>sudo useradd docker
usermod aG docker mansop
sudo chown root:docker /var/run/docker.sock
</code>```

Body:
I am trying to build a docker environment through docker-compose, however it gives errors.

$ docker-compose build
ERROR: Couldn't connect to Docker daemon at http+docker://localhost - is it running?

If it's at a non-standard location, specify the URL with the DOCKER_HOST environment variable.

Docker daemon is running

$ sudo systemctl status docker
[sudo] password for mansop:
● docker.service - Docker Application Container Engine
   Loaded: loaded (/usr/lib/systemd/system/docker.service; enabled; vendor preset: disabled)
   Active: active (running) since Wed 2020-02-19 12:07:27 AEDT; 22min ago
     Docs: http://docs.docker.com
 Main PID: 8972 (dockerd-current)
    Tasks: 22
   Memory: 22.8M
   CGroup: /system.slice/docker.service
           ├─8972 /usr/bin/dockerd-current --add-runtime docker-runc=/usr/libexec/docker/docker-runc-current --default-runtime=docker-runc --exec-opt native.cgroupdriver=systemd --userland-proxy-path=/usr/l...
           └─8978 /usr/bin/docker-containerd-current -l unix:///var/run/docker/libcontainerd/docker-containerd.sock --metrics-interval=0 --start-timeout 2m --state-dir /var/run/docker/libcontainerd/containe...

Docker installed from centos7 repository:

$ docker --version
Docker version 1.13.1, build 4ef4b30/1.13.1

I tried setting up DOCKER_HOST following the error message but the issue persists:

$ echo $DOCKER_HOST
127.0.0.1:2375

Any thoughts?

Body:
For some reason there were no docker group in my system, my user was not part of docker group and the docker socket file was not under the docker group.

The commands below fixed my issue:

sudo useradd docker
usermod aG docker mansop
sudo chown root:docker /var/run/docker.sock


问:
react useEffect fetch data is completed but returning a value is undefined
I am using useEffect to fetch array data then display items. When I fetch data I could see that the data is fetched successfully.

But when I try to display data in the view it gives me an error Cannot read property 'name' of undefined

I think the view is rendering before the fetch. But I used async await to make sure the useEffect is called first.

Any idea of how to get the data display in the view?

Any comments or advice would be really helpful. Thanks in advance :)

```<code>const FetchUsers = () => {

    const [data, setData] = useState([])
    const [loading, setLoading] = useState([])
    const URL = "myurl..."

    useEffect(() => {
        async function fetchData() {
            const res = await axios.get(URL, {headers: {"x-access-token":memberToken}});
            const response = await res;
            console.log(response.data.data,'data')
            //when I console log
            // [{…}, {…}] "data"
            //0: { name: "kevin", age: 39}
            //1: { name: "john", age: 23}
            console.log(response.data.data[0].title, 'name')
            setData(response.data.data);
            setLoading(false);
        }
        fetchData()
    }, [])

  return(

    <View>
      //I am trying to display fetched data
      <Text>{data[0].name}</Text>
    </View>
    )
  }
</code>```

答:
There is no "called first". Your component renders immediately, useEffect contains a "side-effect" - something that happens at some unknown point after your component renders....

Because of this, data will be set at some point in the future, so you have to check if it's available first, if it's not, then render something in it's place, like:

```<code>return(
 <View>
  <Text>{!data.length ? 'Loading...' : data[0].name}</Text>
 </View>
)
</code>```

Body:
I am using useEffect to fetch array data then display items. When I fetch data I could see that the data is fetched successfully.

But when I try to display data in the view it gives me an error Cannot read property 'name' of undefined

I think the view is rendering before the fetch. But I used async await to make sure the useEffect is called first.

Any idea of how to get the data display in the view?

Any comments or advice would be really helpful. Thanks in advance :)

const FetchUsers = () => {

    const [data, setData] = useState([])
    const [loading, setLoading] = useState([])
    const URL = "myurl..."

    useEffect(() => {
        async function fetchData() {
            const res = await axios.get(URL, {headers: {"x-access-token":memberToken}});
            const response = await res;
            console.log(response.data.data,'data')
            //when I console log
            // [{…}, {…}] "data"
            //0: { name: "kevin", age: 39}
            //1: { name: "john", age: 23}
            console.log(response.data.data[0].title, 'name')
            setData(response.data.data);
            setLoading(false);
        }
        fetchData()
    }, [])

  return(

    <View>
      //I am trying to display fetched data
      <Text>{data[0].name}</Text>
    </View>
    )
  }

Body:
There is no "called first". Your component renders immediately, useEffect contains a "side-effect" - something that happens at some unknown point after your component renders....

Because of this, data will be set at some point in the future, so you have to check if it's available first, if it's not, then render something in it's place, like:

return(
 <View>
  <Text>{!data.length ? 'Loading...' : data[0].name}</Text>
 </View>
)


问:
Angular TypeError: Cannot read property '0' of undefined when using event.target.file[0]
I'm currently trying to take a file input from a user and store it to Firebase Storage using AngularFire. Since it's undefined, I'm convinced that whatever file they're looking at, it's NULL, but my UI clearly shows that I'm successfully inputting a file, but the error gets caught as soon as I select the file. Am I misunderstanding how the input sends information to my TypeScript file?

Here's my TS file:

```<code>import { AngularFirestore } from '@angular/fire/firestore';
import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core';
import { finalize, tap, map } from 'rxjs/operators';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { SubmitPostService } from './submit-post.service';
import { Post } from '../post.model';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-post-creation',
  templateUrl: './post-creation.component.html',
  styleUrls: ['./post-creation.component.scss']
})
export class PostCreationComponent implements OnInit {

  private uuidv4 = require('uuid/v4');

  // Main task
  task: AngularFireUploadTask;

  // Progress Monitoring
  percentage: Observable<number>;

  // Download URL
  downloadURL: Observable<string>;

  myForm: FormGroup;
  post: Post;
  ref: AngularFireStorageReference;
  files: Observable<any>;

  constructor(
    private formBuilder: FormBuilder,
    private postService: SubmitPostService,
    private storage: AngularFireStorage,
  ) { }

  ngOnInit() {
    this.myForm = this.formBuilder.group({
      title: ['', [Validators.required]],
      artists: ['', [Validators.required]],
      description: '',
      medium: ''
    });

    this.myForm.valueChanges.subscribe(console.log);
  }

  onSubmit() {
    this.post = new Post(
      this.uuidv4(),
      this.myForm.get('artists').value,
      this.myForm.get('title').value,
      new Date(),
      new Date(),
      `images/${Date.now()}_${this.myForm.get('title').value}`,
      this.myForm.get('description').value,
      this.myForm.get('medium').value
      );
    this.postService.submitPost(this.post);
  }

  upload(event: any) {
    console.log('Upload successful');
    try {
      const file = event.target.file[0];

      // The storage path
      const path = `images/${Date.now()}_${file.name}`;

      // Reference to storage bucket
      this.ref = this.storage.ref(path);

      // Main Task
      this.task = this.ref.put(file);

      // Tracks progress
      this.percentage = this.task.percentageChanges();

      this.percentage = this.task.snapshotChanges()
      .pipe(map(s => (s.bytesTransferred / s.totalBytes) * 100));

      this.downloadURL = this.ref.getDownloadURL();

    } catch (err) { console.log(err); }

    }

}
</code>```

Here's my HTML:

```<code>  <div>
    <div class="progress">
      <progress max="100" [value]="(percentage | async)"></progress>
    </div>
    <h1>Post Creation</h1>
    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">

      <mat-form-field>
        <input matInput placeholder="Title" formControlName="title">
      </mat-form-field>

      <br>

      <mat-form-field>
        <input matInput placeholder="Artists" formControlName="artists">
      </mat-form-field>

      <br>

      <mat-form-field>
        <input matInput placeholder="Description" formControlName="description">
      </mat-form-field>

      <br>

      <mat-form-field>
        <input matInput placeholder="Medium" formControlName="medium">
      </mat-form-field>

      <br>

      <input type="file" (change)="upload($event)" accept=".png,.jpg">

      <br>
      <br>

      <button mat-raised-button [disabled]="myForm.invalid" color="primary">Submit Post</button>
    </form>
  </div>
</body>
</code>```

I've successfully created the Post objects in the Firestore, so it's not an issue of my firebase configs aren't correctly initialize.

答: In your upload method, in the const file = event.target.file[0]; statement, the file property should be plural

Body:
I'm currently trying to take a file input from a user and store it to Firebase Storage using AngularFire. Since it's undefined, I'm convinced that whatever file they're looking at, it's NULL, but my UI clearly shows that I'm successfully inputting a file, but the error gets caught as soon as I select the file. Am I misunderstanding how the input sends information to my TypeScript file?

Here's my TS file:

import { AngularFirestore } from '@angular/fire/firestore';
import { Component, OnInit, Input, ChangeDetectorRef } from '@angular/core';
import { finalize, tap, map } from 'rxjs/operators';
import { FormBuilder, FormGroup, FormArray, Validators } from '@angular/forms';
import { SubmitPostService } from './submit-post.service';
import { Post } from '../post.model';
import { Observable } from 'rxjs';

@Component({
  selector: 'app-post-creation',
  templateUrl: './post-creation.component.html',
  styleUrls: ['./post-creation.component.scss']
})
export class PostCreationComponent implements OnInit {

  private uuidv4 = require('uuid/v4');

  // Main task
  task: AngularFireUploadTask;

  // Progress Monitoring
  percentage: Observable<number>;

  // Download URL
  downloadURL: Observable<string>;

  myForm: FormGroup;
  post: Post;
  ref: AngularFireStorageReference;
  files: Observable<any>;

  constructor(
    private formBuilder: FormBuilder,
    private postService: SubmitPostService,
    private storage: AngularFireStorage,
  ) { }

  ngOnInit() {
    this.myForm = this.formBuilder.group({
      title: ['', [Validators.required]],
      artists: ['', [Validators.required]],
      description: '',
      medium: ''
    });

    this.myForm.valueChanges.subscribe(console.log);
  }

  onSubmit() {
    this.post = new Post(
      this.uuidv4(),
      this.myForm.get('artists').value,
      this.myForm.get('title').value,
      new Date(),
      new Date(),
      `images/${Date.now()}_${this.myForm.get('title').value}`,
      this.myForm.get('description').value,
      this.myForm.get('medium').value
      );
    this.postService.submitPost(this.post);
  }

  upload(event: any) {
    console.log('Upload successful');
    try {
      const file = event.target.file[0];

      // The storage path
      const path = `images/${Date.now()}_${file.name}`;

      // Reference to storage bucket
      this.ref = this.storage.ref(path);

      // Main Task
      this.task = this.ref.put(file);

      // Tracks progress
      this.percentage = this.task.percentageChanges();

      this.percentage = this.task.snapshotChanges()
      .pipe(map(s => (s.bytesTransferred / s.totalBytes) * 100));

      this.downloadURL = this.ref.getDownloadURL();

    } catch (err) { console.log(err); }

    }

}

Here's my HTML:

      <progress max="100" [value]="(percentage | async)"></progress>

Post Creation

    <form [formGroup]="myForm" (ngSubmit)="onSubmit()">

      <mat-form-field>
        <input matInput placeholder="Title" formControlName="title">
      </mat-form-field>

      <mat-form-field>
        <input matInput placeholder="Artists" formControlName="artists">
      </mat-form-field>

      <mat-form-field>
        <input matInput placeholder="Description" formControlName="description">
      </mat-form-field>

      <mat-form-field>
        <input matInput placeholder="Medium" formControlName="medium">
      </mat-form-field>

      <input type="file" (change)="upload($event)" accept=".png,.jpg">

      <button mat-raised-button [disabled]="myForm.invalid" color="primary">Submit Post</button>
    </form>

I've successfully created the Post objects in the Firestore, so it's not an issue of my firebase configs aren't correctly initialize.


问:
Change bullet color (amCharts)
Trying to change the bullet colour in my chart, but can't figure out how. The docs say the colour should inherit, but it's not doing so?

Demo:

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;
theXAxis.renderer.grid.template.stroke = "#ff0000";

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;
theYAxis.renderer.grid.template.stroke = "#ff0000";

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";

series1.bullets.push(new am4charts.CircleBullet());
series1.stroke = "#ffbb00";
series1.bullets.stroke = am4core.color("#ffbb00");
series1.bullets.fill = am4core.color("#ffbb00");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  background: grey;
}</code>```

```

I just want the blue bullets to become yellow, like the stroke.

答:
series.bullets is a list, you can't set visual properties directly on it. You need the bullet object that you create from new am4charts.CircleBullet(); the demos on the AmCharts website use the return value of push and go from there:

```<code>var bullet = series1.bullets.push(new am4charts.CircleBullet());
series1.stroke = "#ffbb00";
bullet.stroke = am4core.color("#ffbb00");
bullet.fill = am4core.color("#ffbb00");
</code>```

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;
theXAxis.renderer.grid.template.stroke = "#ff0000";

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;
theYAxis.renderer.grid.template.stroke = "#ff0000";

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";

var bullet = series1.bullets.push(new am4charts.CircleBullet());
series1.stroke = "#ffbb00";
bullet.stroke = am4core.color("#ffbb00");
bullet.fill = am4core.color("#ffbb00");```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  background: grey;
}</code>```

```

Title: Change bullet color (amCharts)

Body:
Trying to change the bullet colour in my chart, but can't figure out how. The docs say the colour should inherit, but it's not doing so?

Demo:

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;
theXAxis.renderer.grid.template.stroke = "#ff0000";

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;
theYAxis.renderer.grid.template.stroke = "#ff0000";

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";

series1.bullets.push(new am4charts.CircleBullet());
series1.stroke = "#ffbb00";
series1.bullets.stroke = am4core.color("#ffbb00");
series1.bullets.fill = am4core.color("#ffbb00");

body{
  background: grey;
}

I just want the blue bullets to become yellow, like the stroke.

Body:
series.bullets is a list, you can't set visual properties directly on it. You need the bullet object that you create from new am4charts.CircleBullet(); the demos on the AmCharts website use the return value of push and go from there:

var bullet = series1.bullets.push(new am4charts.CircleBullet());
series1.stroke = "#ffbb00";
bullet.stroke = am4core.color("#ffbb00");
bullet.fill = am4core.color("#ffbb00");

var chart = am4core.create("dataChart", am4charts.XYChart);

chart.data = [{
    "xValue": "Q1",
    "yValue": 3
}, {
    "xValue": "Q2",
    "yValue": 4
}, {
    "xValue": "Q3",
    "yValue": 7
}, {
    "xValue": "Q4",
    "yValue": 2
}, {
    "xValue": "Q5",
    "yValue": 9
}];

/* Create axes */
var theXAxis = chart.xAxes.push(new am4charts.CategoryAxis());
theXAxis.dataFields.category = "xValue";
theXAxis.renderer.minGridDistance = 30;
theXAxis.renderer.grid.template.stroke = "#ff0000";

/* Create value axis */
var theYAxis = chart.yAxes.push(new am4charts.ValueAxis());
theYAxis.renderer.labels.template.disabled = true;
theYAxis.renderer.grid.template.stroke = "#ff0000";

/* Create series */
var series1 = chart.series.push(new am4charts.LineSeries());
series1.dataFields.valueY = "yValue";
series1.dataFields.categoryX = "xValue";
series1.bullets.push(new am4charts.CircleBullet());
series1.tooltipText = "{valueY} / 10";
series1.fill = "#2c3e96";

var bullet = series1.bullets.push(new am4charts.CircleBullet());
series1.stroke = "#ffbb00";
bullet.stroke = am4core.color("#ffbb00");
bullet.fill = am4core.color("#ffbb00");

body{
  background: grey;
}

<script src="https://www.amcharts.com/lib/4/core.js"></script>
<script src="https://www.amcharts.com/lib/4/charts.js"></script>
<script src="https://www.amcharts.com/lib/4/themes/animated.js"></script>

<div id="dataChart"></div>


答:
Add a property to the FormTask for example String1 like

```<code>public string String1 {get; set;}
</code>```

Set String1 value in button1_Click for example,

You can access that property in MainForm like

```<code>FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoer.ShowDialog();
string str = formTask.String1;
</code>```

Title: Passing value from dialog form to main form

Body:
Add a property to the FormTask for example String1 like

public string String1 {get; set;}

Set String1 value in button1_Click for example,

You can access that property in MainForm like

FormTask formTask = new FormTask(exerciseType);
formOpgaveInvoer.ShowDialog();
string str = formTask.String1;


问:
Taylor series expansion in maxima
How to expand taylor series/polynomials about Q=0 , and then extract coefficients as a list

example :

```<code>taylor ( (sin(q)), q, 0, 9); //taylor expansion for first 9 terms gives the next line

(%o1)/T/    q\-q^3/6+q^5/120\-q^7/5040+q^9/362880+...
</code>```

then using coeff ((%o1), q ^n); gives me the coefficient at n only, what i want is a list for all the coefficients of that expression

答:
Edit:

I see now that I misread your question and there is already an answer. Nevertheless I will keep it because it is related to your question.

Use powerseries instead of taylor:

```<code>(%i1) expr:powerseries(sin(x),x,0);
                           inf
                           ====        i2  2 i2 + 1
                           \      (- 1)   x
(%o1)                       >     -----------------
                           /         (2 i2 + 1)!
                           ====
                           i2 = 0
</code>```

You can access the coefficient by the args or part function

```<code>(%i2) op(expr);
(%o2)                                 sum
(%i3) args(expr);
                              i2  2 i2 + 1
                         (- 1)   x
(%o3)                   [-----------------, i2, 0, inf]
                            (2 i2 + 1)!
(%i4) part(expr,1);
                                    i2  2 i2 + 1
                               (- 1)   x
(%o4)                          -----------------
                                  (2 i2 + 1)!
(%i5) args(expr)[1];
                                    i2  2 i2 + 1
                               (- 1)   x
(%o5)                          -----------------
                                  (2 i2 + 1)!
</code>```

If you want to change the index variable:

```<code>(%i6) niceindices(expr),niceindicespref=[n];
                             inf
                             ====       n  2 n + 1
                             \     (- 1)  x
(%o6)                        >    ---------------
                             /       (2 n + 1)!
                             ====
                             n = 0
</code>```

Title: Taylor series expansion in maxima

Body:
How to expand taylor series/polynomials about Q=0 , and then extract coefficients as a list

example :

taylor ( (sin(q)), q, 0, 9); //taylor expansion for first 9 terms gives the next line

(%o1)/T/    q\-q^3/6+q^5/120\-q^7/5040+q^9/362880+...

then using coeff ((%o1), q ^n); gives me the coefficient at n only, what i want is a list for all the coefficients of that expression

Body:
Edit:

I see now that I misread your question and there is already an answer. Nevertheless I will keep it because it is related to your question.

Use powerseries instead of taylor:

(%i1) expr:powerseries(sin(x),x,0);
                           inf
                           ====        i2  2 i2 + 1
                           \      (- 1)   x
(%o1)                       >     -----------------
                           /         (2 i2 + 1)!
                           ====
                           i2 = 0

You can access the coefficient by the args or part function

(%i2) op(expr);
(%o2)                                 sum
(%i3) args(expr);
                              i2  2 i2 + 1
                         (- 1)   x
(%o3)                   [-----------------, i2, 0, inf]
                            (2 i2 + 1)!
(%i4) part(expr,1);
                                    i2  2 i2 + 1
                               (- 1)   x
(%o4)                          -----------------
                                  (2 i2 + 1)!
(%i5) args(expr)[1];
                                    i2  2 i2 + 1
                               (- 1)   x
(%o5)                          -----------------
                                  (2 i2 + 1)!

If you want to change the index variable:

(%i6) niceindices(expr),niceindicespref=[n];
                             inf
                             ====       n  2 n + 1
                             \     (- 1)  x
(%o6)                        >    ---------------
                             /       (2 n + 1)!
                             ====
                             n = 0


问:
Nav Bar Text Not Centering & Covering Text
I have an html page that "contains" many pages meaning I have links at the top of the page but when they are clicked you are not actually taken to a new page. The links stay on the same page but just take you to another part of the same html page. (I think this is called single page layout with multiple pages, I forget). My page is split into 4 sections, and the first section under the nav bar contains the least amount of text. I'm not sure why but the nav bar is cutting off my p tag text. It looks like the text is covered under the nav bar.

I'm not sure how to stop the nav bar from covering my text

Another problem I'm having is the nav bar itself, I'm trying to center the text inside and also make the nav bar extend the full width of my page.

I tried things like padding, margin, and text align but I'm still having trouble with these 2 things. Can someone please help me out? Thanks.

Code:

```<code>    nav {
        width: 100%;
        background: #1B2631;
        overflow: hidden;
        position: fixed;
        top: 0;
    }

    ul {

        list-style: none;
    }

    li {
        text-align: center;
        float: left;

    }

<nav>
    <ul>
        <li><a href="#page1">page1</a>
        </li>
        <li><a href="#page2">page2</a>
        </li>
        <li><a href="#page3">page3</a>
        </li>
        <li><a href="#page4">page4</a>
        </li>
        <li><a href="#page5">page5</a>
        </li>
    </ul>
</nav>
</code>```

答:
Just added Some CSS menu text align center. hope this help you.

nav {
  width: 100%;
  background: #1B2631;
  overflow: hidden;
  position: fixed;
  top: 0;
}

ul {
  list-style: none;
  text-align: center;
}

li {
  text-align: center;
  float: none;
  display: inline-block;
  padding: 5px 15px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>page1
    </li>
    <li>page2
    </li>
    <li>page3
    </li>
    <li>page4
    </li>
    <li>page5
    </li>
  </ul>
</nav></code>```

Body:
I have an html page that "contains" many pages meaning I have links at the top of the page but when they are clicked you are not actually taken to a new page. The links stay on the same page but just take you to another part of the same html page. (I think this is called single page layout with multiple pages, I forget). My page is split into 4 sections, and the first section under the nav bar contains the least amount of text. I'm not sure why but the nav bar is cutting off my p tag text. It looks like the text is covered under the nav bar.

I'm not sure how to stop the nav bar from covering my text

Another problem I'm having is the nav bar itself, I'm trying to center the text inside and also make the nav bar extend the full width of my page.

I tried things like padding, margin, and text align but I'm still having trouble with these 2 things. Can someone please help me out? Thanks.

Code:

    nav {
        width: 100%;
        background: #1B2631;
        overflow: hidden;
        position: fixed;
        top: 0;
    }

    ul {

        list-style: none;
    }

    li {
        text-align: center;
        float: left;

    }

page1

page2

page3

page4

page5

Body:
Just added Some CSS menu text align center. hope this help you.

nav {
  width: 100%;
  background: #1B2631;
  overflow: hidden;
  position: fixed;
  top: 0;
}

ul {
  list-style: none;
  text-align: center;
}

li {
  text-align: center;
  float: none;
  display: inline-block;
  padding: 5px 15px;
}

<nav>
  <ul>
    <li><a href="#page1">page1</a>
    </li>
    <li><a href="#page2">page2</a>
    </li>
    <li><a href="#page3">page3</a>
    </li>
    <li><a href="#page4">page4</a>
    </li>
    <li><a href="#page5">page5</a>
    </li>
  </ul>
</nav>