问:
Why can't I scroll over a listView? I get the typic error `A RenderFlex overflowed by xx pixels on the bottom`
I am new to flutter and I am trying to avoid the scroll problem at the bottom. I wanted to use a ListView to scroll through a series of elements.
My question is, why am I getting the problem of A RenderFlex overflowed by 94 pixels on the bottom.? the element that exceeds these pixels is my ListView, but this element is supposed to have its own scroll inside it.

this is my code:

```<code>    Widget build(BuildContext context) {
      return GestureDetector(
        onTap: () {
          //here
          FocusScope.of(context).unfocus();
          new TextEditingController().clear();
        },
        child: Scaffold(
          backgroundColor: Colors.black,
          body: SafeArea(
              child: Stack(children: <Widget>[
            Align(
                alignment: Alignment.bottomCenter,
                child: SingleChildScrollView(
                  child: Container(
                    padding: EdgeInsets.only(top: 40),
                    color: Colors.white,
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height * 0.78,
                    child: Column(
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(),
                            Expanded(
                                child: Container(
                              child: Container(),
                            ))
                          ],
                        ),
                        SizedBox(height: 20),
                        Row(
                          children: <Widget>[Container()],
                        ),
                        SizedBox(height: 20),
                        Container(
                            child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                SizedBox(width: 10),
                              ],
                            ),
                            SizedBox(height: 10),
                            Row(
                              children: <Widget>[(Container())],
                            ),
                            SizedBox(height: 10),
                          ],
                        )),
                        Divider(
                          height: 50.0,
                          color: Colors.red,
                        ),

                        SizedBox(height: 35), //SingleChildScrollView
                        Container(
                          child: ListView(shrinkWrap: true, children: <Widget>[
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                          ]),
                        )
                      ],
                    ),
                  ),
                )),
          ])),
        ),
      );
    }
</code>```

答:
my friend, when you want to use listview you must define height for the listview because listview takes unlimited height

Example:

```<code>Container(
height: 50,
child: ListView(shrinkWrap: true, children: <Widget>[
Text("LOREM "),
Text("LOREM "),
Text("LOREM "),
Text("LOREM "),
]),)
</code>```

Body:
I am new to flutter and I am trying to avoid the scroll problem at the bottom. I wanted to use a ListView to scroll through a series of elements.
My question is, why am I getting the problem of A RenderFlex overflowed by 94 pixels on the bottom.? the element that exceeds these pixels is my ListView, but this element is supposed to have its own scroll inside it.

this is my code:

    Widget build(BuildContext context) {
      return GestureDetector(
        onTap: () {
          //here
          FocusScope.of(context).unfocus();
          new TextEditingController().clear();
        },
        child: Scaffold(
          backgroundColor: Colors.black,
          body: SafeArea(
              child: Stack(children: <Widget>[
            Align(
                alignment: Alignment.bottomCenter,
                child: SingleChildScrollView(
                  child: Container(
                    padding: EdgeInsets.only(top: 40),
                    color: Colors.white,
                    width: MediaQuery.of(context).size.width,
                    height: MediaQuery.of(context).size.height * 0.78,
                    child: Column(
                      children: <Widget>[
                        Row(
                          children: <Widget>[
                            Container(),
                            Expanded(
                                child: Container(
                              child: Container(),
                            ))
                          ],
                        ),
                        SizedBox(height: 20),
                        Row(
                          children: <Widget>[Container()],
                        ),
                        SizedBox(height: 20),
                        Container(
                            child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                SizedBox(width: 10),
                              ],
                            ),
                            SizedBox(height: 10),
                            Row(
                              children: <Widget>[(Container())],
                            ),
                            SizedBox(height: 10),
                          ],
                        )),
                        Divider(
                          height: 50.0,
                          color: Colors.red,
                        ),

                        SizedBox(height: 35), //SingleChildScrollView
                        Container(
                          child: ListView(shrinkWrap: true, children: <Widget>[
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                            Text("LOREM "),
                          ]),
                        )
                      ],
                    ),
                  ),
                )),
          ])),
        ),
      );
    }

Body:
my friend, when you want to use listview you must define height for the listview because listview takes unlimited height

Example:

Container(
height: 50,
child: ListView(shrinkWrap: true, children: <Widget>[
Text("LOREM "),
Text("LOREM "),
Text("LOREM "),
Text("LOREM "),
]),)


来源: stackexchange

问:
I cant seem to save my json files in python?
My Json Code for this basic login system will not work and i am a bit confused plz help. it would be grately appreciated if you could.

-Thanks alot ^__^

'''

```<code>import json

sign_or_log = input('If you have an account on this repl please press 1 if you do not please press 2: ')

if sign_or_log == '2':
    username = input('Please enter your new Username: ')
    password = input('Please enter your new Password: ')
    write = [
      {
          "name": username,
          "password": password
      }
  ]
    file = open("data.json", "w+")
    file.write(json.dumps(write))
    file.close()
    print('Thank you for subminting your new account.')
    sign_or_log = input('If you have an account on this repl please press 1 if you do not please press 2: ')

    if sign_or_log == '1':
        login1 = input('Please enter your existing username: ')
        login2 = input('Please enter your existing password: ')
    try:
        file = open("data.json", "r")
        data = json.loads(file)
        file.close()
    except:
        print('Access Denied')
print(data)
</code>```

'''

答:
Use json.dumps to add to a json file like this:

import json

def log_in():
    while True:
        login1 = input('Please enter your existing username: ')
        login2 = input('Please enter your existing password: ')

        if login1 != "" and login2 != "":
            break

    with open("data.json") as f:
        data = json.load(f) # <-- Fixed the bug, again

    if data[login1] == login2:
        # User sucessfully logged in
    else:
        print('Access Denied')

def sign_up():
    username = input('Please enter your new Username: ')
    password = input('Please enter your new Password: ')
    user = {
        "name": username,
        "password": password
    }

    with open('data.json') as f:
        data = json.load(f)

    data.update(user)

    with open('data.json', 'w') as f:
        json.dump(data, f)

    print('Thank you for submitting your new account.')
    log_in()

message = 'If you have an account on this repl'
message += 'please press 1 if you do not please press 2:'

while True:
    sign_or_log = input(message)
    if sign_or_log == "1":
        log_in()
        break
    if sign_or_log == "2":
        sign_up()
        break
```

ContentLicense: CC BY-SA 4.0

Body:
My Json Code for this basic login system will not work and i am a bit confused plz help. it would be grately appreciated if you could.

-Thanks alot ^__^

'''

import json

sign_or_log = input('If you have an account on this repl please press 1 if you do not please press 2: ')

if sign_or_log == '2':
    username = input('Please enter your new Username: ')
    password = input('Please enter your new Password: ')
    write = [
      {
          "name": username,
          "password": password
      }
  ]
    file = open("data.json", "w+")
    file.write(json.dumps(write))
    file.close()
    print('Thank you for subminting your new account.')
    sign_or_log = input('If you have an account on this repl please press 1 if you do not please press 2: ')

    if sign_or_log == '1':
        login1 = input('Please enter your existing username: ')
        login2 = input('Please enter your existing password: ')
    try:
        file = open("data.json", "r")
        data = json.loads(file)
        file.close()
    except:
        print('Access Denied')
print(data)

'''


问:
Efficient way to save multiple rasters within a single .pdf using R
I'm very new to R and am wondering if there's a faster way to save multiple rasters within a single .pdf than by manually entering each raster file name as I've done below:

```<code>pdf(file = "file_name.pdf", width = 11, height = 8.5)
plot(raster(file.path(dir_path_data,"nutrient_pollution_2003_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2004_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2005_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2006_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2007_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2008_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2009_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2010_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2011_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2012_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2013_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2003-2013_trend.tif")))
dev.off()
</code>```

Thank you in advance for your help!

答:
Start with a vector of filenames, that you can get with list.files. Perhaps like this

```<code>f <- list.files(dir_path_data, pattern="^nutrient_pollution.*\\.tif$", full=TRUE)
</code>```

You can now make a list using lapply

```<code>library(raster)
pdf(file = "file_name.pdf", width = 11, height = 8.5)
lapply(f, function(n) plot(raster(n)))
dev.off()
</code>```

Or use a loop

```<code>pdf(file = "file_name.pdf", width = 11, height = 8.5)
for (n in f) {
   r <- raster(n)
   plot(r)
}
dev.off()
</code>```

If the rasters have the same extent and resolution, you can also do

```<code>s <- stack(f)
pdf(file = "file_name.pdf", width = 11, height = 8.5)
for (i in 1:nlayers(s)) {
   plot(s[[i]])
}
dev.off()
</code>```

Body:
I'm very new to R and am wondering if there's a faster way to save multiple rasters within a single .pdf than by manually entering each raster file name as I've done below:

pdf(file = "file_name.pdf", width = 11, height = 8.5)
plot(raster(file.path(dir_path_data,"nutrient_pollution_2003_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2004_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2005_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2006_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2007_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2008_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2009_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2010_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2011_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2012_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2013_impact.tif")))
plot(raster(file.path(dir_path_data,"nutrient_pollution_2003-2013_trend.tif")))
dev.off()

Thank you in advance for your help!

Body:
Start with a vector of filenames, that you can get with list.files. Perhaps like this

f <- list.files(dir_path_data, pattern="^nutrient_pollution.*\\.tif$", full=TRUE)

You can now make a list using lapply

library(raster)
pdf(file = "file_name.pdf", width = 11, height = 8.5)
lapply(f, function(n) plot(raster(n)))
dev.off()

Or use a loop

pdf(file = "file_name.pdf", width = 11, height = 8.5)
for (n in f) {
   r <- raster(n)
   plot(r)
}
dev.off()

If the rasters have the same extent and resolution, you can also do

s <- stack(f)
pdf(file = "file_name.pdf", width = 11, height = 8.5)
for (i in 1:nlayers(s)) {
   plot(s[[i]])
}
dev.off()


问:
XSLT accumulate
I have a parent variable and two child variables for accumulate

I would like to use those two child variables to select two different values

I can only hardcode it to make it works like all other tutorial
for example: $parent[1]/Price and $parent[1]/Quantity

but insteads I want the following:

```<code>$parent[1]/$child1 where $parent[1] = orders[1]/order and $child1 = price
$parent[1]/$child2 where $parent[1] = orders[1]/order and $child2 = quantity

    <xsl:call-template name="total">
    <xsl:with-param name="pList" select="$parent"/>
    <xsl:with-param name="price" select="Price"/>
    <xsl:with-param name="quantity" select="Quantity"/>
    </xsl:call-template>

<xsl:template name="total">
    <xsl:param name="pListItem"/>
    <xsl:param name="pAccum" select="0"/>
    <xsl:param name="price"/>
    <xsl:param name="quantity"/>

    <xsl:choose>
      <xsl:when test="$pListItem">
        <xsl:call-template name="total">
          <xsl:with-param name="pListItem" select="$pListItem[position() > 1]"/>
          <xsl:with-param name="pAccum"
           select="$pAccum + $vHead/$price * $vHead/$quantity"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$pAccum"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</code>```

答:
Thanks a lot.

All I need is the 'Price' and $vthisSale/*[name()=$pPriceName]

It really help!! I have been stuck for ages because of the magic ' '

ContentLicense: CC BY-SA 3.0

Title: XSLT accumulate

Body:
I have a parent variable and two child variables for accumulate

I would like to use those two child variables to select two different values

I can only hardcode it to make it works like all other tutorial
for example: $parent[1]/Price and $parent[1]/Quantity

but insteads I want the following:

$parent[1]/$child1 where $parent[1] = orders[1]/order and $child1 = price
$parent[1]/$child2 where $parent[1] = orders[1]/order and $child2 = quantity

    <xsl:call-template name="total">
    <xsl:with-param name="pList" select="$parent"/>
    <xsl:with-param name="price" select="Price"/>
    <xsl:with-param name="quantity" select="Quantity"/>
    </xsl:call-template>

<xsl:template name="total">
    <xsl:param name="pListItem"/>
    <xsl:param name="pAccum" select="0"/>
    <xsl:param name="price"/>
    <xsl:param name="quantity"/>

    <xsl:choose>
      <xsl:when test="$pListItem">
        <xsl:call-template name="total">
          <xsl:with-param name="pListItem" select="$pListItem[position() > 1]"/>
          <xsl:with-param name="pAccum"
           select="$pAccum + $vHead/$price * $vHead/$quantity"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:otherwise>
        <xsl:value-of select="$pAccum"/>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>


答: Wrap your listview in Expanded or any such flexible widget(Flexible).</p>

Title: Why can't I scroll over a listView? I get the typic error `A RenderFlex overflowed by xx pixels on the bottom`


问:
How to use variables/values as arguments for imported modules/functions
The context of this is that I'm trying to make a common module that can be imported into other programs. The code here is from the common module. The idea of this function is that it checks if the value given from the main program is a positive integer or not.

```<code>def checkpoints(x):
        if x.isdigit() == False:
                num = print('Please enter valid interger.')
                return num
        else:
                print('all g')
                return
</code>```

Another question is that is it possible to use a variable from the main program and have that set as an argument in an imported function/module? How would I do that?

答:
Yes you can use this function in your main program and pass an argument. What you want to do between the two files is first set up your function to receive an argument, notice 'x' added in the parenthesis:

```<code>def checkpoints(x):
        if x.isdigit() == False:
                num = print('Please enter valid interger.')
                return num
        else:
                print('all g')
                return
</code>```

Then in your main where you want to import the file as Clinton showed you above. So if your filename is 'myfunctions.py'  , You can 'import *' from that file, or specifically your function:

```<code>from myfunctions import checkpoints
</code>```

I hope this helps!

Body:
The context of this is that I'm trying to make a common module that can be imported into other programs. The code here is from the common module. The idea of this function is that it checks if the value given from the main program is a positive integer or not.

def checkpoints(x):
        if x.isdigit() == False:
                num = print('Please enter valid interger.')
                return num
        else:
                print('all g')
                return

Another question is that is it possible to use a variable from the main program and have that set as an argument in an imported function/module? How would I do that?

Body:
Yes you can use this function in your main program and pass an argument. What you want to do between the two files is first set up your function to receive an argument, notice 'x' added in the parenthesis:

def checkpoints(x):
        if x.isdigit() == False:
                num = print('Please enter valid interger.')
                return num
        else:
                print('all g')
                return

Then in your main where you want to import the file as Clinton showed you above. So if your filename is 'myfunctions.py'  , You can 'import *' from that file, or specifically your function:

from myfunctions import checkpoints

I hope this helps!


问:
How to append lists from Selenium get attribute?
I'm new to coding and I finally got the data I want from the website. The problem here is I can't figure out how to get these into one DataFrame. I can't concat because these aren't assigned to a variable, it's just coming from the scraper.

Here's the code:

```<code>import pandas as pd
import numpy as np
import requests
from csv import writer

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://app.hedgeye.com/feed_items/all?page=1&with_category=33-risk-ranges")

#login
import requests
import sys

url = 'https://accounts.hedgeye.com/users/sign_in'
driver.get(url)

username = driver.find_element_by_id("user_email")
password = driver.find_element_by_id("user_password")

username.send_keys("")
password.send_keys("")

driver.find_element_by_name("commit").click()
#end login

for tr in driver.find_elements_by_tag_name("tr"):

        data = tr.get_attribute("innerText")
        data2= data.split()[-3:]

        #makes the list rows not columns
        df = pd.DataFrame(np.array(data2).reshape(-1,len(data2)))
        print (df)

driver.quit()
</code>```

Here's what the dataframe looks like:

Here is what the scraper looks like before I put it into a dataframe and what the webpage looks like:

Final Product

答:
Try initializing df outside of the for loop first. Then, df could be amended with each iteration with pd.concat.

So, outside the for loop you'd have something like:

```<code>df = DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
</code>```

then after the data2 variable assignment:

```<code>df = pd.concat([df, DataFrame(data=data2.reshape(-1,len(data2)))])
</code>```

Body:
I'm new to coding and I finally got the data I want from the website. The problem here is I can't figure out how to get these into one DataFrame. I can't concat because these aren't assigned to a variable, it's just coming from the scraper.

Here's the code:

import pandas as pd
import numpy as np
import requests
from csv import writer

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.keys import Keys

chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("https://app.hedgeye.com/feed_items/all?page=1&with_category=33-risk-ranges")

#login
import requests
import sys

url = 'https://accounts.hedgeye.com/users/sign_in'
driver.get(url)

username = driver.find_element_by_id("user_email")
password = driver.find_element_by_id("user_password")

username.send_keys("")
password.send_keys("")

driver.find_element_by_name("commit").click()
#end login

for tr in driver.find_elements_by_tag_name("tr"):

        data = tr.get_attribute("innerText")
        data2= data.split()[-3:]

        #makes the list rows not columns
        df = pd.DataFrame(np.array(data2).reshape(-1,len(data2)))
        print (df)

driver.quit()

Here's what the dataframe looks like:

Here is what the scraper looks like before I put it into a dataframe and what the webpage looks like:

Final Product

Body:
Try initializing df outside of the for loop first. Then, df could be amended with each iteration with pd.concat.

So, outside the for loop you'd have something like:

df = DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)

then after the data2 variable assignment:

df = pd.concat([df, DataFrame(data=data2.reshape(-1,len(data2)))])


答:
If you just want to pass in a variable x that you have in main(), you could just import the function and call it in main as follows.

from common_module import checkpoints  # import the function you want
..
..
def main():
..
..
  checkpoints(x)  # You can now call this function in main
..
..
```

Note that you'll have to change the definition of checkpoints to take in x as an argument.

Title: How to use variables/values as arguments for imported modules/functions

Body:
If you just want to pass in a variable x that you have in main(), you could just import the function and call it in main as follows.

from common_module import checkpoints  # import the function you want
..
..
def main():
..
..
  checkpoints(x)  # You can now call this function in main
..
..

Note that you'll have to change the definition of checkpoints to take in x as an argument.


问:
Accessing a list with only recursion and lambdas
As part of my homework I have to access every element o a list without a for loop to use it in a function I'm allowed to use, e.g:

```<code>myList=['Hello','World']
</code>```

I've tried using lambda functions (Because I'm not allowed to declare functions with Def) but didn't work.

```<code>function(next(myList))
</code>```

Also tried using next(myList) but sometimes the list can have 1000+ elements.

答:
I believe the cleanest way to do this is with a map function:

l = [1,2,3]
list(map(lambda x : print(x), l))
# returns
# >> 1
# >> 2
# >> 3
```

Body:
As part of my homework I have to access every element o a list without a for loop to use it in a function I'm allowed to use, e.g:

myList=['Hello','World']

I've tried using lambda functions (Because I'm not allowed to declare functions with Def) but didn't work.

function(next(myList))

Also tried using next(myList) but sometimes the list can have 1000+ elements.


问:
Doctrine how to setup Many to Many to Many relationship
Summary:
  Using the following YML I get a reference to a FOREIGN KEY (role_id) that is not in my YML.

Problem:
  I'm trying to create a system where there is a user (CreditName) who can belong to many role's (all of which can have many users).  There are also many projects, which can contain many User+Roles, so I'd like the Project to have a Many-to-Many relationship with the entry in the refclass for the Many-to-Many relationship between Users and Roles.

Here's the relevant YML:

```<code>Project:
  columns:
    title:              { type: string(255), notnull: true, unique: true }
  relations:
    CreditNameRoles:
      class: CreditNameRole
      refClass: ProjectCreditNameRole
      foreignAlias: Projects
      onDelete: CASCADE

ProjectCreditNameRole:
  columns:
    project_id:          { type: integer, primary: true }
    credit_name_role_id: { type: integer, primary: true }
  relations:
    Project:             { foreignAlias: ProjectGenres, onDelete: CASCADE }
    CreditNameRole:      { foreignAlias: CreditNameRole, onDelete: CASCADE }

CreditName:
  columns:
    name:        { type: string(255) }
  relations:
    Roles:
      class: Role
      refClass: CreditNameRole
      foreignAlias: CreditNames
      onDelete: CASCADE

CreditNameRole:
  columns:
    id:              { type: integer}
    credit_name_id:  { type: integer, primary: true }
    role_id:         { type: integer, primary: true }
  relations:
    CreditName:      { foreignAlias: CreditNameRoles, onDelete: CASCADE }
    Role:            { foreignAlias: CreditNameRoles, onDelete: CASCADE }

Role:
  columns:
    name:            { type: string(255) }
</code>```

Using doctrine/symfony to try and use this YML to generate the database I get the following:

```<code>bash-3.2$ ./symfony doctrine:build --all --no-confirmation

  SQLSTATE[HY000]: General error: 1005 Can't create table 'database_name.#sql-68_148' (errno: 150). Failing Query: "ALTER TABLE credit_name_role ADD CONSTRAINT crpc FOREIGN KEY (role_id) REFERENCES project_credit_name_role(credit_name_role_id)". Failing Query: ALTER TABLE credit_name_role ADD CONSTRAINT crpc FOREIGN KEY (role_id) REFERENCES project_credit_name_role(credit_name_role_id)
</code>```

Where is this 'FOREIGN KEY (role_id)' coming from and how do I correct it?  Thanks!

答:
I think u need to remove those line and run symfony doctrine:build --all </p>

```<code>CreditNameRoles:
 id:              { type: integer}
relations:
    CreditName:      { foreignAlias: CreditNameRoles, onDelete: CASCADE }
    Role:            { foreignAlias: CreditNameRoles, onDelete: CASCADE }
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Summary:
  Using the following YML I get a reference to a FOREIGN KEY (role_id) that is not in my YML.

Problem:
  I'm trying to create a system where there is a user (CreditName) who can belong to many role's (all of which can have many users).  There are also many projects, which can contain many User+Roles, so I'd like the Project to have a Many-to-Many relationship with the entry in the refclass for the Many-to-Many relationship between Users and Roles.

Here's the relevant YML:

Project:
  columns:
    title:              { type: string(255), notnull: true, unique: true }
  relations:
    CreditNameRoles:
      class: CreditNameRole
      refClass: ProjectCreditNameRole
      foreignAlias: Projects
      onDelete: CASCADE

ProjectCreditNameRole:
  columns:
    project_id:          { type: integer, primary: true }
    credit_name_role_id: { type: integer, primary: true }
  relations:
    Project:             { foreignAlias: ProjectGenres, onDelete: CASCADE }
    CreditNameRole:      { foreignAlias: CreditNameRole, onDelete: CASCADE }

CreditName:
  columns:
    name:        { type: string(255) }
  relations:
    Roles:
      class: Role
      refClass: CreditNameRole
      foreignAlias: CreditNames
      onDelete: CASCADE

CreditNameRole:
  columns:
    id:              { type: integer}
    credit_name_id:  { type: integer, primary: true }
    role_id:         { type: integer, primary: true }
  relations:
    CreditName:      { foreignAlias: CreditNameRoles, onDelete: CASCADE }
    Role:            { foreignAlias: CreditNameRoles, onDelete: CASCADE }

Role:
  columns:
    name:            { type: string(255) }

Using doctrine/symfony to try and use this YML to generate the database I get the following:

bash-3.2$ ./symfony doctrine:build --all --no-confirmation

  SQLSTATE[HY000]: General error: 1005 Can't create table 'database_name.#sql-68_148' (errno: 150). Failing Query: "ALTER TABLE credit_name_role ADD CONSTRAINT crpc FOREIGN KEY (role_id) REFERENCES project_credit_name_role(credit_name_role_id)". Failing Query: ALTER TABLE credit_name_role ADD CONSTRAINT crpc FOREIGN KEY (role_id) REFERENCES project_credit_name_role(credit_name_role_id)

Where is this 'FOREIGN KEY (role_id)' coming from and how do I correct it?  Thanks!

Body:
I think u need to remove those line and run symfony doctrine:build --all

CreditNameRoles:
 id:              { type: integer}
relations:
    CreditName:      { foreignAlias: CreditNameRoles, onDelete: CASCADE }
    Role:            { foreignAlias: CreditNameRoles, onDelete: CASCADE }


问:
MySQL Error: Authentication plugin 'caching_sha2_password' cannot be loaded
I just installed MySQL Ver 14.14 Distrib 5.7.22 with Homebrew on my macOS v10.13.4.

I ran the command:

brew install mysql

After the installation completed, as directed by Homebrew, I ran the command:

mysql_secure_installation

and was returned the error: Error: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/Cellar/mysql/5.7.22/lib/plugin/caching_sha2_password.so, 2): image not found

I tried a few things like changing default_authentication_plugin to mysql_native_password in the my.cnf file but it still throws the same error.

Next I tried running:

mysql_upgrade -u root

and I was thrown the same error again mysql_upgrade: Got error: 2059: Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/Cellar/mysql/5.7.22/lib/plugin/caching_sha2_password.so, 2): image not found while connecting to the MySQL server
Upgrade process encountered error and will not continue.

Any help is appreciated.

答:
I got this error in Sequel Pro trying to connect over SSH to an AWS Ubuntu server with MySQL installed locally.

I was using a non-root MySQL user and it gave me that error. It worked when I ran it with the root user and password.


问:
how to identify when a dynamic element is ready?
I need to identify when a dynamic element is ready or when $('root').append(""); is loaded, so that I can load another element within child element.

Currently I have:

$('root').after("");
setTimeout(function(){
  $('#child').append("
brah
");
}, 1000);
```

While the above solution does work, 1 second is too long to wait for each element. And if I set the timer to 0, it become inconsistent.

Is there any better way to identify when a DOM is fully loaded?

答:
You can define the child element as a variable like this:

```<code>var child = $('<span id="child"></span>');

$('root').append(child);

child.append("<h1>brah</h1>");
</code>```

After appending, you can use it to append another child element immediately, no need to delay,

Body:
I need to identify when a dynamic element is ready or when $('root').append(""); is loaded, so that I can load another element within child element.

Currently I have:

$('root').after("");
setTimeout(function(){
  $('#child').append("
brah
");
}, 1000);

While the above solution does work, 1 second is too long to wait for each element. And if I set the timer to 0, it become inconsistent.

Is there any better way to identify when a DOM is fully loaded?

Body:
You can define the child element as a variable like this:

var child = $('<span id="child"></span>');

$('root').append(child);

child.append("<h1>brah</h1>");

After appending, you can use it to append another child element immediately, no need to delay,


问:
_redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is not a function
I have searched so many but could'nt find answer on this bug please can you help.

_redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is not a function

This is my redux store

```<code>import {combineReducers, createStore} from "redux";
import profileReducer from "./profile-reduce";
import dialogsReducer from "./dialogs-reduce";
import sidebarReducer from "./sidebar-reduce";

let reducers = combineReducers({
    profilePage: profileReducer,
    dialogsPage:dialogsReducer,
    sidebar: sidebarReducer
});

let store = createStore(reducers);

export default store;
</code>```

This is index.js

```<code>import React from 'react';
import * as serviceWorker from './serviceWorker';
import store from "./redux/redux-store"
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from "react-router-dom";

let rerenderEntireTree = (state)=> {
    ReactDOM.render(
        <BrowserRouter>
            <App state={state} dispatch={store.dispatch.bind(store)} store={store}/>
        </BrowserRouter> ,document.getElementById('root'));
}

rerenderEntireTree(store.getState());

store.subscribe(()=>{
    let state = store.getState();
    rerenderEntireTree(state);
});

serviceWorker.unregister();
</code>```

答:
In your index.js try doing this</p>

```<code>import React from 'react';
import * as serviceWorker from './serviceWorker';
import store from "./redux/redux-store"
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from "react-router-dom";
import { Provider } from 'react-redux';

    ReactDOM.render(
      <Provider store={store}>
        <BrowserRouter>
          <App />
       </BrowserRouter>
      </Provider>,
      document.getElementById('root')
    );
</code>```

Body:
I have searched so many but could'nt find answer on this bug please can you help.

_redux_redux_store__WEBPACK_IMPORTED_MODULE_2___default.a.getState is not a function

This is my redux store

import {combineReducers, createStore} from "redux";
import profileReducer from "./profile-reduce";
import dialogsReducer from "./dialogs-reduce";
import sidebarReducer from "./sidebar-reduce";

let reducers = combineReducers({
    profilePage: profileReducer,
    dialogsPage:dialogsReducer,
    sidebar: sidebarReducer
});

let store = createStore(reducers);

export default store;

This is index.js

import React from 'react';
import * as serviceWorker from './serviceWorker';
import store from "./redux/redux-store"
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from "react-router-dom";

let rerenderEntireTree = (state)=> {
    ReactDOM.render(
        <BrowserRouter>
            <App state={state} dispatch={store.dispatch.bind(store)} store={store}/>
        </BrowserRouter> ,document.getElementById('root'));
}

rerenderEntireTree(store.getState());

store.subscribe(()=>{
    let state = store.getState();
    rerenderEntireTree(state);
});

serviceWorker.unregister();

Body:
In your index.js try doing this

import React from 'react';
import * as serviceWorker from './serviceWorker';
import store from "./redux/redux-store"
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import {BrowserRouter} from "react-router-dom";
import { Provider } from 'react-redux';

    ReactDOM.render(
      <Provider store={store}>
        <BrowserRouter>
          <App />
       </BrowserRouter>
      </Provider>,
      document.getElementById('root')
    );


问:
Actual/Hard Timeout with Ping in C#
Sooo... I found an instance where the specified timeout with Ping.Send() or Ping.SendAsync do not adhere to the specified timeouts or TTLs and I am trying to work around it. When an invalid host is attempted to be pinged the specified timeout is ignored and in my case a full 2 seconds passes before the ping fails. For the project I am working on I need that to be something like 100 ms or less (if the host was valid it would only be a hop or 2 away so 100 ms seems plenty).

I've tried Ping.Send() and Ping.SendAsync and cannot for the life me figure out how to do this. The closest I got was doing a .Close on the AutoResetEvent but I couldn't catch/suppress the error that was created doing that. (Code not shown here)

Here is the current iteration of the code, as you can see I use both .Send and .SendAsync; I would prefer to use SendAsync I think... If you run the code below everything is executed in under 100ms (usually 60ms) for a host on the same network, but if the host in invalid the code doesn't exit till after 2000ms.

```<code>    //.NETCore.App\3.1.4
    // Microsoft Visual Studio Community 2019 - Version 16.5.5
    // Microsoft Windows [Version 10.0.18362.836]

using System;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text.RegularExpressions;

class Program
    {
        public static void Main(string[] args)
        {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            string who = String.Empty;

            //who = "firewall0"; //Hostname of my local firewall
            //who = "www.yahoo.com";
            who = "not-a-valid-host";
            //who = "10.1.1.151"; //My interface
            //who = "localhost"; //Should succeed but error has to be suppressed because of IPv6
            //who = "2a03:2880:f131:83:face:b00c:0:25de"; //Facebook IPv6, should fail quickly
            //who = "127.0.0.1";

            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 1;
            int numMaxHops = 1; //Supposedly this is TTL, but after some experimenting it appears to be number of hops not TTL in ms
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions(numMaxHops, true);

            if (true) //Use false to toggle off this section of code while testing
            {
                AutoResetEvent waiter = new AutoResetEvent(false);
                pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
                Console.WriteLine("Time to live set to: {0}", options.Ttl);
                Console.WriteLine("");
                pingSender.SendAsync(who, timeout, buffer, options, waiter);
                waiter.WaitOne();
                Console.WriteLine("Ping example completed.");
            }

            if (true) //Use false to toggle off this section of code while testing
            {
                try
                {
                    PingReply reply = pingSender.Send(who, timeout, buffer, options);

                    if (reply.Status == IPStatus.Success)
                    {
                        Console.WriteLine("Address: {0}", reply.Address.ToString());
                        Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                        if (reply.Address.ToString() != "::1")
                        {
                            Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                            Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                            Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                        }
                    }
                    else
                    {
                        Console.WriteLine(reply.Status);
                    }
                }
                catch (Exception ex)
                {
                    Regex noHostMatch = new Regex("No such host is known");
                    if (noHostMatch.IsMatch(ex.InnerException.ToString()))
                    //if (false)
                    {
                        Console.WriteLine("No such host is known.");
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            watch.Stop();
            Console.WriteLine("");
            Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
            Console.WriteLine("Press the Enter key");
            Console.ReadLine();
        }//End Main()

        private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
        {
            // If the operation was canceled, display a message to the user.

            if (e.Cancelled)
            {
                Console.WriteLine("Ping canceled.");

                // Let the main thread resume.
                // UserToken is the AutoResetEvent object that the main thread
                // is waiting for.
                ((AutoResetEvent)e.UserState).Set();
            }

            // If an error occurred, display the exception to the user.
            if (e.Error != null)
            {
                Console.WriteLine("Ping failed:");
                //Console.WriteLine(e.Error.ToString());

                // Let the main thread resume.
                ((AutoResetEvent)e.UserState).Set();
            }
            else
            {
                PingReply reply = e.Reply;
                DisplayReply(reply);

                // Let the main thread resume.
                ((AutoResetEvent)e.UserState).Set();
            }

        }//End PingCompletedCallback()

        public static void DisplayReply(PingReply reply)
        {
            if (reply == null)
                return;

            Console.WriteLine("Ping Status: {0}", reply.Status);
            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine("Address: {0}", reply.Address.ToString());
                Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);

                if (reply.Address.ToString() != "::1")
                {
                    Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                    Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                    Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                }
            }
        }//End DisplayReply()
</code>```

Out out from running the above while pinging my local firewall.

```<code>Time to live set to: 1

Ping Status: Success
Address: 10.1.1.1
RoundTrip time: 0
Time to live: 64
Don't fragment: False
Buffer size: 32
Ping example completed.
Address: 10.1.1.1
RoundTrip time: 0
Time to live: 64
Don't fragment: False
Buffer size: 32

Execution Time: 61 ms
Press the Enter key
</code>```

Output when pinging not-a-valid-host

```<code>Time to live set to: 1

Ping failed:
Ping example completed.
No such host is known.

Execution Time: 2139 ms
Press the Enter key
</code>```

^ I want to get that execution time down to under 100ms with an invalid host.

答:
Put the ping call inside a Task and Wait() up to your chosen timeout, after that has completed or timed out, we check to see if reply was set.

I've implemented this into your code below

```<code>//.NETCore.App\3.1.4
// Microsoft Visual Studio Community 2019 - Version 16.5.5
// Microsoft Windows [Version 10.0.18362.836]

using System;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

class Program
{
    public static void Main(string[] args)
    {
        var watch = new System.Diagnostics.Stopwatch();
        watch.Start();

        string who = String.Empty;

        //who = "firewall0"; //Hostname of my local firewall
        //who = "www.yahoo.com";
        who = "not-a-valid-host";
        //who = "10.1.1.151"; //My interface
        //who = "localhost"; //Should succeed but error has to be suppressed because of IPv6
        //who = "2a03:2880:f131:83:face:b00c:0:25de"; //Facebook IPv6, should fail quickly
        //who = "127.0.0.1";

        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 1;
        int numMaxHops = 1; //Supposedly this is TTL, but after some experimenting it appears to be number of hops not TTL in ms
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions(numMaxHops, true);

        if (false) //Use false to toggle off this section of code while testing
        {
            AutoResetEvent waiter = new AutoResetEvent(false);
            pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
            Console.WriteLine("Time to live set to: {0}", options.Ttl);
            Console.WriteLine("");
            pingSender.SendAsync(who, timeout, buffer, options, waiter);
            waiter.WaitOne();
            Console.WriteLine("Ping example completed.");
        }

        if (true) //Use false to toggle off this section of code while testing
        {
            try
            {
                PingReply reply = null;

            var t = Task.Run(() =>
            {
                reply = pingSender.Send(who, timeout, buffer, options);
                Console.WriteLine("Ping example completed.");
            });

            t.Wait(TimeSpan.FromMilliseconds(100));

            if (reply == null)
            {
                Console.WriteLine("timed out");
            }
            else if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine("Address: {0}", reply.Address.ToString());
                Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                if (reply.Address.ToString() != "::1")
                    {
                        Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                        Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                        Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                    }
                }
                else
                {
                    Console.WriteLine(reply.Status);
                }
            }
            catch (Exception ex)
            {
                Regex noHostMatch = new Regex("No such host is known");
                if (noHostMatch.IsMatch(ex.InnerException.ToString()))
                //if (false)
                {
                    Console.WriteLine("No such host is known.");
                }
                else
                {
                    throw;
                }
            }
        }

        watch.Stop();
        Console.WriteLine("");
        Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
        Console.WriteLine("Press the Enter key");
        Console.ReadLine();
    }//End Main()

    private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        // If the operation was canceled, display a message to the user.

        if (e.Cancelled)
        {
            Console.WriteLine("Ping canceled.");

            // Let the main thread resume.
            // UserToken is the AutoResetEvent object that the main thread
            // is waiting for.
            ((AutoResetEvent)e.UserState).Set();
        }

        // If an error occurred, display the exception to the user.
        if (e.Error != null)
        {
            Console.WriteLine("Ping failed:");
            //Console.WriteLine(e.Error.ToString());

            // Let the main thread resume.
            ((AutoResetEvent)e.UserState).Set();
        }
        else
        {
            PingReply reply = e.Reply;
            DisplayReply(reply);

            // Let the main thread resume.
            ((AutoResetEvent)e.UserState).Set();
        }

    }//End PingCompletedCallback()

    public static void DisplayReply(PingReply reply)
    {
        if (reply == null)
            return;

        Console.WriteLine("Ping Status: {0}", reply.Status);
        if (reply.Status == IPStatus.Success)
        {
            Console.WriteLine("Address: {0}", reply.Address.ToString());
            Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);

            if (reply.Address.ToString() != "::1")
            {
                Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
            }
        }
    }//End DisplayReply()
}
</code>```

Title: Actual/Hard Timeout with Ping in C#

Body:
Sooo... I found an instance where the specified timeout with Ping.Send() or Ping.SendAsync do not adhere to the specified timeouts or TTLs and I am trying to work around it. When an invalid host is attempted to be pinged the specified timeout is ignored and in my case a full 2 seconds passes before the ping fails. For the project I am working on I need that to be something like 100 ms or less (if the host was valid it would only be a hop or 2 away so 100 ms seems plenty).

I've tried Ping.Send() and Ping.SendAsync and cannot for the life me figure out how to do this. The closest I got was doing a .Close on the AutoResetEvent but I couldn't catch/suppress the error that was created doing that. (Code not shown here)

Here is the current iteration of the code, as you can see I use both .Send and .SendAsync; I would prefer to use SendAsync I think... If you run the code below everything is executed in under 100ms (usually 60ms) for a host on the same network, but if the host in invalid the code doesn't exit till after 2000ms.

    //.NETCore.App\3.1.4
    // Microsoft Visual Studio Community 2019 - Version 16.5.5
    // Microsoft Windows [Version 10.0.18362.836]

using System;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text.RegularExpressions;

class Program
    {
        public static void Main(string[] args)
        {
            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            string who = String.Empty;

            //who = "firewall0"; //Hostname of my local firewall
            //who = "www.yahoo.com";
            who = "not-a-valid-host";
            //who = "10.1.1.151"; //My interface
            //who = "localhost"; //Should succeed but error has to be suppressed because of IPv6
            //who = "2a03:2880:f131:83:face:b00c:0:25de"; //Facebook IPv6, should fail quickly
            //who = "127.0.0.1";

            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes(data);
            int timeout = 1;
            int numMaxHops = 1; //Supposedly this is TTL, but after some experimenting it appears to be number of hops not TTL in ms
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions(numMaxHops, true);

            if (true) //Use false to toggle off this section of code while testing
            {
                AutoResetEvent waiter = new AutoResetEvent(false);
                pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
                Console.WriteLine("Time to live set to: {0}", options.Ttl);
                Console.WriteLine("");
                pingSender.SendAsync(who, timeout, buffer, options, waiter);
                waiter.WaitOne();
                Console.WriteLine("Ping example completed.");
            }

            if (true) //Use false to toggle off this section of code while testing
            {
                try
                {
                    PingReply reply = pingSender.Send(who, timeout, buffer, options);

                    if (reply.Status == IPStatus.Success)
                    {
                        Console.WriteLine("Address: {0}", reply.Address.ToString());
                        Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                        if (reply.Address.ToString() != "::1")
                        {
                            Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                            Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                            Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                        }
                    }
                    else
                    {
                        Console.WriteLine(reply.Status);
                    }
                }
                catch (Exception ex)
                {
                    Regex noHostMatch = new Regex("No such host is known");
                    if (noHostMatch.IsMatch(ex.InnerException.ToString()))
                    //if (false)
                    {
                        Console.WriteLine("No such host is known.");
                    }
                    else
                    {
                        throw;
                    }
                }
            }

            watch.Stop();
            Console.WriteLine("");
            Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
            Console.WriteLine("Press the Enter key");
            Console.ReadLine();
        }//End Main()

        private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
        {
            // If the operation was canceled, display a message to the user.

            if (e.Cancelled)
            {
                Console.WriteLine("Ping canceled.");

                // Let the main thread resume.
                // UserToken is the AutoResetEvent object that the main thread
                // is waiting for.
                ((AutoResetEvent)e.UserState).Set();
            }

            // If an error occurred, display the exception to the user.
            if (e.Error != null)
            {
                Console.WriteLine("Ping failed:");
                //Console.WriteLine(e.Error.ToString());

                // Let the main thread resume.
                ((AutoResetEvent)e.UserState).Set();
            }
            else
            {
                PingReply reply = e.Reply;
                DisplayReply(reply);

                // Let the main thread resume.
                ((AutoResetEvent)e.UserState).Set();
            }

        }//End PingCompletedCallback()

        public static void DisplayReply(PingReply reply)
        {
            if (reply == null)
                return;

            Console.WriteLine("Ping Status: {0}", reply.Status);
            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine("Address: {0}", reply.Address.ToString());
                Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);

                if (reply.Address.ToString() != "::1")
                {
                    Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                    Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                    Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                }
            }
        }//End DisplayReply()

Out out from running the above while pinging my local firewall.

Time to live set to: 1

Ping Status: Success
Address: 10.1.1.1
RoundTrip time: 0
Time to live: 64
Don't fragment: False
Buffer size: 32
Ping example completed.
Address: 10.1.1.1
RoundTrip time: 0
Time to live: 64
Don't fragment: False
Buffer size: 32

Execution Time: 61 ms
Press the Enter key

Output when pinging not-a-valid-host

Time to live set to: 1

Ping failed:
Ping example completed.
No such host is known.

Execution Time: 2139 ms
Press the Enter key

^ I want to get that execution time down to under 100ms with an invalid host.

Body:
Put the ping call inside a Task and Wait() up to your chosen timeout, after that has completed or timed out, we check to see if reply was set.

I've implemented this into your code below

//.NETCore.App\3.1.4
// Microsoft Visual Studio Community 2019 - Version 16.5.5
// Microsoft Windows [Version 10.0.18362.836]

using System;
using System.Text;
using System.Net.NetworkInformation;
using System.Threading;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

class Program
{
    public static void Main(string[] args)
    {
        var watch = new System.Diagnostics.Stopwatch();
        watch.Start();

        string who = String.Empty;

        //who = "firewall0"; //Hostname of my local firewall
        //who = "www.yahoo.com";
        who = "not-a-valid-host";
        //who = "10.1.1.151"; //My interface
        //who = "localhost"; //Should succeed but error has to be suppressed because of IPv6
        //who = "2a03:2880:f131:83:face:b00c:0:25de"; //Facebook IPv6, should fail quickly
        //who = "127.0.0.1";

        string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
        byte[] buffer = Encoding.ASCII.GetBytes(data);
        int timeout = 1;
        int numMaxHops = 1; //Supposedly this is TTL, but after some experimenting it appears to be number of hops not TTL in ms
        Ping pingSender = new Ping();
        PingOptions options = new PingOptions(numMaxHops, true);

        if (false) //Use false to toggle off this section of code while testing
        {
            AutoResetEvent waiter = new AutoResetEvent(false);
            pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
            Console.WriteLine("Time to live set to: {0}", options.Ttl);
            Console.WriteLine("");
            pingSender.SendAsync(who, timeout, buffer, options, waiter);
            waiter.WaitOne();
            Console.WriteLine("Ping example completed.");
        }

        if (true) //Use false to toggle off this section of code while testing
        {
            try
            {
                PingReply reply = null;

            var t = Task.Run(() =>
            {
                reply = pingSender.Send(who, timeout, buffer, options);
                Console.WriteLine("Ping example completed.");
            });

            t.Wait(TimeSpan.FromMilliseconds(100));

            if (reply == null)
            {
                Console.WriteLine("timed out");
            }
            else if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine("Address: {0}", reply.Address.ToString());
                Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);
                if (reply.Address.ToString() != "::1")
                    {
                        Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                        Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                        Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
                    }
                }
                else
                {
                    Console.WriteLine(reply.Status);
                }
            }
            catch (Exception ex)
            {
                Regex noHostMatch = new Regex("No such host is known");
                if (noHostMatch.IsMatch(ex.InnerException.ToString()))
                //if (false)
                {
                    Console.WriteLine("No such host is known.");
                }
                else
                {
                    throw;
                }
            }
        }

        watch.Stop();
        Console.WriteLine("");
        Console.WriteLine($"Execution Time: {watch.ElapsedMilliseconds} ms");
        Console.WriteLine("Press the Enter key");
        Console.ReadLine();
    }//End Main()

    private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
    {
        // If the operation was canceled, display a message to the user.

        if (e.Cancelled)
        {
            Console.WriteLine("Ping canceled.");

            // Let the main thread resume.
            // UserToken is the AutoResetEvent object that the main thread
            // is waiting for.
            ((AutoResetEvent)e.UserState).Set();
        }

        // If an error occurred, display the exception to the user.
        if (e.Error != null)
        {
            Console.WriteLine("Ping failed:");
            //Console.WriteLine(e.Error.ToString());

            // Let the main thread resume.
            ((AutoResetEvent)e.UserState).Set();
        }
        else
        {
            PingReply reply = e.Reply;
            DisplayReply(reply);

            // Let the main thread resume.
            ((AutoResetEvent)e.UserState).Set();
        }

    }//End PingCompletedCallback()

    public static void DisplayReply(PingReply reply)
    {
        if (reply == null)
            return;

        Console.WriteLine("Ping Status: {0}", reply.Status);
        if (reply.Status == IPStatus.Success)
        {
            Console.WriteLine("Address: {0}", reply.Address.ToString());
            Console.WriteLine("RoundTrip time: {0}", reply.RoundtripTime);

            if (reply.Address.ToString() != "::1")
            {
                Console.WriteLine("Time to live: {0}", reply.Options.Ttl);
                Console.WriteLine("Don't fragment: {0}", reply.Options.DontFragment);
                Console.WriteLine("Buffer size: {0}", reply.Buffer.Length);
            }
        }
    }//End DisplayReply()
}


问:
How to tell my .NET application which IP address to request from?
If I have a Windows server with more than one IP address, how do I pro grammatically tell different instances of my application to use a different IP address when communicating with the internet?</p>

答: I managed to get round this problem by setting up port forwarding, so the server thought it was just using a different port, but from outside the router it looks like it's using a different IP address. I remember coming to the conclusion that a server can only be assigned one IP address, even if it receives from several.</p>


问:
How to add new column with values based on another column in pandas
Lets say I have the following df:

```<code>rs = np.random.RandomState(1979)
x = rs.randn(500)
g = np.tile(list("ABCDEFGHIJ"), 50)
df = pd.DataFrame(dict(x=x, g=g))
m = df.g.map(ord)
df["x"] += m

df

           x    g
0   64.038123   A
1   66.147050   B
2   66.370011   C
3   68.791019   D
4   70.583534   E
... ... ...
495 69.358022   F
496 72.212877   G
497 70.474247   H
498 73.251022   I
499 74.461828   J
</code>```

I would Like to add a new column that consists of a number 1-10 that matches the letter of the alphabet, like so:

```<code>g new
A  1
B  2
C  3
D  4
</code>```

The actual data I'm working with uses names instead of alphabet letters, but I obviously don't want to put those on here. But again, my goal is make a new column with a values I want for certain names.

Thanks!

答:
It sounds like a dictionary that maps names to their respective ordered position you want in your graph is the way to go. Here's a simple example:</p>

```<code>>>> import pandas as pd
>>> df = pd.DataFrame({"Name": ["Alice", "Bob", "Bob", "Alice", "Charlie"]})
>>> ordering = {"Alice": 1, "Bob": 3, "Charlie": 2}
>>> df["Ordering"] = df["Name"].map(ordering)
>>> df
      Name  Ordering
0    Alice         1
1      Bob         3
2      Bob         3
3    Alice         1
4  Charlie         2
</code>```

Body:
Lets say I have the following df:

rs = np.random.RandomState(1979)
x = rs.randn(500)
g = np.tile(list("ABCDEFGHIJ"), 50)
df = pd.DataFrame(dict(x=x, g=g))
m = df.g.map(ord)
df["x"] += m

df

           x    g
0   64.038123   A
1   66.147050   B
2   66.370011   C
3   68.791019   D
4   70.583534   E
... ... ...
495 69.358022   F
496 72.212877   G
497 70.474247   H
498 73.251022   I
499 74.461828   J

I would Like to add a new column that consists of a number 1-10 that matches the letter of the alphabet, like so:

g new
A  1
B  2
C  3
D  4

The actual data I'm working with uses names instead of alphabet letters, but I obviously don't want to put those on here. But again, my goal is make a new column with a values I want for certain names.

Thanks!

Body:
It sounds like a dictionary that maps names to their respective ordered position you want in your graph is the way to go. Here's a simple example:

>>> import pandas as pd
>>> df = pd.DataFrame({"Name": ["Alice", "Bob", "Bob", "Alice", "Charlie"]})
>>> ordering = {"Alice": 1, "Bob": 3, "Charlie": 2}
>>> df["Ordering"] = df["Name"].map(ordering)
>>> df
      Name  Ordering
0    Alice         1
1      Bob         3
2      Bob         3
3    Alice         1
4  Charlie         2


问:
tinymce dynamic add mutiple menu items to dropdown menu-all onclick direct to last menu item click
I am using tinymce + tinymce-variable. I want to create drop down menu that have dynamic menu item. Based on items from sql, I am able to create multiple drop down menu. I created each menu item using editor.addMenuItem() inside the loop.

```<code>for(i=0;i<data.length;i++)
{
    template_var    =data[i]['variable'];
    text_val        =template_var.replace(/\s/g , " ");
    editor.addMenuItem(template_var,
    {
        text    :text_val,
        context :'newmenu',
        onclick :function ()
        {
            editor.plugins.variable.addVariable(template_var);
        }
    })
}
</code>```

The problem I am facing is when I click any of the menu item, it adding last menu item to the editor and not the menu item that I have clicked. I guess, It overwrite the editor.plugins.variable.addVariable(template_var); to last menu item for all menu item. How is that possible?

Thanks in advance.

答:
A click on menu item directly go to specific line editor.plugins.variable.addVariable(template_var); of particular menu item. When we execute in loop, it only find one line of this code.That is why click on any menu item perform click only on last menu item because this code overridden for last item at end of loop. So, I solve it this way. I concatenate the editor.addMenuItem() code for execution for each menu item as string.Then, I execute that string in setup :function (editor){} of tinymce.init({}) using eval(). In this way, when we click on menu item, it can find editor.plugins.variable.addVariable(template_var); for particular menu item.

```<code><script type="text/javascript">
variablenames_concat='';
addmenu_concat      ='';
for(j=0;j<data.length;j++)
        {
            variablenames_concat+=data[j]['variable']+',';
            template_var        =data[j]['variable'];
            text_val            =template_var.replace(/\s/g , " ");//remove underscore
            //string concatenate editor.addMenuItem for each of item
            addmenu_concat      +='editor.addMenuItem("'+template_var+'",{text  : "'+text_val+'",context: "newmenu",onclick: function (){editor.plugins.variable.addVariable("'+template_var+'");}});';
        }
variablenames_concat = variablenames_concat.replace(/,\s*$/, "");//remove last coma

tinymce.init
({
  selector  : 'textarea',
  height    :  500,
  plugins   : 'variable',
  menu      :
            {
                newmenu:
                {
                    title : 'Menu', items : variablenames_concat,
                }
            },
 content_css:
            [
                '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
                '//www.tinymce.com/css/codepen.min.css'
            ],
content_style:".variable{cursor:default;background-color:#65b9dd;color:#FFF;padding:2px;border-radius:3px;font-weight: bold;font-style:normal;display:inline-block;}",

setup        : function (editor)
                    {
                      eval(addmenu_concat);
                    }
});
</script>
</code>```

Body:
I am using tinymce + tinymce-variable. I want to create drop down menu that have dynamic menu item. Based on items from sql, I am able to create multiple drop down menu. I created each menu item using editor.addMenuItem() inside the loop.

for(i=0;i<data.length;i++)
{
    template_var    =data[i]['variable'];
    text_val        =template_var.replace(/\s/g , " ");
    editor.addMenuItem(template_var,
    {
        text    :text_val,
        context :'newmenu',
        onclick :function ()
        {
            editor.plugins.variable.addVariable(template_var);
        }
    })
}

The problem I am facing is when I click any of the menu item, it adding last menu item to the editor and not the menu item that I have clicked. I guess, It overwrite the editor.plugins.variable.addVariable(template_var); to last menu item for all menu item. How is that possible?

Thanks in advance.

Body:
A click on menu item directly go to specific line editor.plugins.variable.addVariable(template_var); of particular menu item. When we execute in loop, it only find one line of this code.That is why click on any menu item perform click only on last menu item because this code overridden for last item at end of loop. So, I solve it this way. I concatenate the editor.addMenuItem() code for execution for each menu item as string.Then, I execute that string in setup :function (editor){} of tinymce.init({}) using eval(). In this way, when we click on menu item, it can find editor.plugins.variable.addVariable(template_var); for particular menu item.

<script type="text/javascript">
variablenames_concat='';
addmenu_concat      ='';
for(j=0;j<data.length;j++)
        {
            variablenames_concat+=data[j]['variable']+',';
            template_var        =data[j]['variable'];
            text_val            =template_var.replace(/\s/g , " ");//remove underscore
            //string concatenate editor.addMenuItem for each of item
            addmenu_concat      +='editor.addMenuItem("'+template_var+'",{text  : "'+text_val+'",context: "newmenu",onclick: function (){editor.plugins.variable.addVariable("'+template_var+'");}});';
        }
variablenames_concat = variablenames_concat.replace(/,\s*$/, "");//remove last coma

tinymce.init
({
  selector  : 'textarea',
  height    :  500,
  plugins   : 'variable',
  menu      :
            {
                newmenu:
                {
                    title : 'Menu', items : variablenames_concat,
                }
            },
 content_css:
            [
                '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
                '//www.tinymce.com/css/codepen.min.css'
            ],
content_style:".variable{cursor:default;background-color:#65b9dd;color:#FFF;padding:2px;border-radius:3px;font-weight: bold;font-style:normal;display:inline-block;}",

setup        : function (editor)
                    {
                      eval(addmenu_concat);
                    }
});
</script>


问:
ReadBeanPHP SQL query doesnt go throught. Does anybody see a mistake? Did everything by manual and it doesnt work
Here is my SQL - query with ReadBeanPHP.

```<code>$idItem = $this->route['alias']; //some $_GET value

$product = \R::findMulti('listings, users',
            'SELECT listings.*, users.*
            RIGHT JOIN listings.id_user = users.id_user
            WHERE listings.id = ?  AND listings.status = 0', [$idItem]);
</code>```

Here is a mistake what it prints me out

```<code> Code error Exception

Text error SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'JOIN listings.id_user = users.id_user WHERE listings.id = 4 AND lis' at line 2

Where error /opt/lampp/htdocs/sellbuyschool42/vendor/gabordemooij/redbean/RedBeanPHP/Driver/RPDO.php

Line error 194
</code>```

I did everything as it's written on official web-site of ReadBeanPHP https://redbeanphp.com/index.php?p=/finding
I want to get couple so-call beans, but getting error. Or if anybody know how easy to combine two tables with ReadBeanPHP that would work to. Providing pics of tables as well.

答:
Your join statement is wrong, there is no from and even you have not declare which table you want to do a right join. you can try the following.

```<code>SELECT
    l.*,
    u.*
from listings l
RIGHT JOIN users u
on l.id_user = u.id_user
WHERE l.id = ?
AND l.status = 0
</code>```

Body:
Here is my SQL - query with ReadBeanPHP.

$idItem = $this->route['alias']; //some $_GET value

$product = \R::findMulti('listings, users',
            'SELECT listings.*, users.*
            RIGHT JOIN listings.id_user = users.id_user
            WHERE listings.id = ?  AND listings.status = 0', [$idItem]);

Here is a mistake what it prints me out

 Code error Exception

Text error SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'JOIN listings.id_user = users.id_user WHERE listings.id = 4 AND lis' at line 2

Where error /opt/lampp/htdocs/sellbuyschool42/vendor/gabordemooij/redbean/RedBeanPHP/Driver/RPDO.php

Line error 194

I did everything as it's written on official web-site of ReadBeanPHP https://redbeanphp.com/index.php?p=/finding
I want to get couple so-call beans, but getting error. Or if anybody know how easy to combine two tables with ReadBeanPHP that would work to. Providing pics of tables as well.

Body:
Your join statement is wrong, there is no from and even you have not declare which table you want to do a right join. you can try the following.

SELECT
    l.*,
    u.*
from listings l
RIGHT JOIN users u
on l.id_user = u.id_user
WHERE l.id = ?
AND l.status = 0


问:
Python is not playing sound but it finishes the program successfully without errors
I am trying to play sound in Python. When I run my code, it finishes successfully but the audio is not played by my computer.

I have tried with all the libraries like playsound, simpleaudio, pydub and kivy core audio.

Sample code I tried is:

from playsound import playsound

playsound('myfile.wav')
```

答:
As i think it should work, check either your audio file (maybe it's empty) or check your audio drivers and audio output.

OR, You can try

pip install playsound
one more time


问:
Entity Framework: Modeling against an existing database scheme
I've been scratching my head over this for over a week now and haven't gotten anywhere :( We have an existing legacy DB that I'm trying to model my entities against. The tables are extremely bloated and we do not have enough bandwidth to create new, optimized tables. So I'm having to work with what we already have. However, I do not want to use all the redundant columns that are exposed by the DB. My initial plan was to use Views in my Model but that is looking to be equally hairy with very little documentation around.

Now, what would be the best way to go about creating a Model with just a select few columns? All I need is a bunch of read-only entities; so if there is a way to ignore non-nullable columns from the schema, I'd be all set. I was planning on making use of POCOs else I'd have to create my own mappings I reckon.

UPDATE: By POCOs, I mean I'd like to use the ADO.NET POCO Entity Generator.

答: add the table to your EF, and just delete the properties you don't want. it just won't map those DB fields.</p>


问:
Get type from typeguard's type predicate
Typically, a typeguard's type is defined as such:

```<code>(value: unknown) => value is Type
</code>```

Where the highlighted part is called a type predicate by the documentation:

```<code>(value: unknown) => **value is Type**
</code>```

Going even forward, we could say (I don't know how, if even, the docs defines this) that the value is the typeguard's parameter, is is a TypeScript binary operator/keyword for defining type predicates and Type is the type the typeguard actually guarantee, the guaranteed type.
Since we use typeguards to guarantee a value's type, we could say that Type is the most interesting part of the definition.

Being such, is it possible to extract Type from the type definition of a typeguard? How?

I'm thinking of something like:

```<code>type Type = typeof typeguard; // (value: unknown) => value is Type
type TypePredicate = TypePredicateOf<Type>; // value is Type
type GuaranteedType = IsOf<TypePredicate>; // Type
</code>```

Where GuaranteedType is the desired result.

Googling around, I've only found answers about generic typeguards type definitions, but did not get how to get the Type part from it.

答:
You can use conditional type inference with the infer keyword to extract the guarded type from a type guard signature.  Something like:

```<code>type GuardedType<T> = T extends (x: any) => x is infer U ? U : never;
</code>```

And given some user-defined type guards:

```<code>function isString(x: any): x is string {
  return typeof x === "string";
}

interface Foo {
  a: string;
}

function isFoo(x: any): x is Foo {
  return "a" in x && typeof x.a === "string"
}
</code>```

You can see that it works as advertised:

```<code>type S = GuardedType<typeof isString>; // string
type F = GuardedType<typeof isFoo>; // Foo
</code>```

Okay, hope that helps; good luck!

Playground link to code

Body:
Typically, a typeguard's type is defined as such:

(value: unknown) => value is Type

Where the highlighted part is called a type predicate by the documentation:

(value: unknown) => **value is Type**

Going even forward, we could say (I don't know how, if even, the docs defines this) that the value is the typeguard's parameter, is is a TypeScript binary operator/keyword for defining type predicates and Type is the type the typeguard actually guarantee, the guaranteed type.
Since we use typeguards to guarantee a value's type, we could say that Type is the most interesting part of the definition.

Being such, is it possible to extract Type from the type definition of a typeguard? How?

I'm thinking of something like:

type Type = typeof typeguard; // (value: unknown) => value is Type
type TypePredicate = TypePredicateOf<Type>; // value is Type
type GuaranteedType = IsOf<TypePredicate>; // Type

Where GuaranteedType is the desired result.

Googling around, I've only found answers about generic typeguards type definitions, but did not get how to get the Type part from it.

Body:
You can use conditional type inference with the infer keyword to extract the guarded type from a type guard signature.  Something like:

type GuardedType<T> = T extends (x: any) => x is infer U ? U : never;

And given some user-defined type guards:

function isString(x: any): x is string {
  return typeof x === "string";
}

interface Foo {
  a: string;
}

function isFoo(x: any): x is Foo {
  return "a" in x && typeof x.a === "string"
}

You can see that it works as advertised:

type S = GuardedType<typeof isString>; // string
type F = GuardedType<typeof isFoo>; // Foo

Okay, hope that helps; good luck!

Playground link to code


问:
PHP/MYSQLI how can I return a variable from a while loop inside a form to use in a $_GET request in that form's action/method?
I have a html form which uses a PHP while loop to populate a select menu from a MYSQLi database. Code below;

```<code>$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1 ";
$result = mysqli_query($conn, $query);

echo '<p><label for="current_clients">Select Client by name: </label>
        <select id="current_clients" name="current_clients">
        <option> -- Select Client -- </option>';

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
          echo '<option>'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
        }
echo '</select>';
</code>```

The above works, the form populates with the required client records. However, I am then looking to use this data to link to an individual client page, which I tried using

```<code>echo ' <a href="selected_client.php?id='.$row['id'].'" onClick="this.form.submit()">Go!</a>';
</code>```

which did not work, so I tried setting the form action to

```<code>action="selected_client.php?id='.$row['id'].'"
</code>```

with the method as "GET", which also did not work. As you can see in the query I am selecting 'id' from the table as well so I can call on that part of the array later, I just don't particularly need or want to echo it. Using the form action method, the $row['id'] variable is not set, and using the onClick method, I get a "Trying to access array offset on value of type null" error.

I imagine that the variable needs to be set before the form action can take place, but I can't think how I would be able to do that without moving the while loop or at least returning a value from it. Is it possible to call the form method and action at submission, rather than at the top of the form? Would that make any difference at all?

Edit; as requested, my attempt at using a hidden method for the form

```<code>echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" value="'.$row['id'].'">';
</code>```

Which still returns the value of type null error.

Edit #2 - all code inline.

```<code>$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1 ";
$result = mysqli_query($conn, $query);
echo  '<form action="selected_client.php" method="get">
    <fieldset>';

echo '<p><label for="current_clients">Select Client by name: </label>
        <select id="current_clients" name="current_clients">
        <option> -- Select Client -- </option>';

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
          echo '<option>'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
        }
echo '</select>';
echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" value="'.$row['id'].'">';

echo '</fieldset></form>';
</code>```

答:
Add onChange event and pass the selected value to some function, in that function set the hidden field with this selected value.Now you can submit the form and your selected value can be received.Below is solution.

```<code>$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1";
$result = mysqli_query($conn, $query);
echo  '<form action="selected_client.php" method="get">
    <fieldset>';

echo '<p><label for="current_clients">Select Client by name: </label>
        <select id="current_clients" name="current_clients" onChange="setId(this.value);">
        <option value=""> -- Select Client -- </option>';

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
          echo '<option value="'.$row['id'].'">'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
        }
echo '</select>';
echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" id="hidden_field" value="">';

echo '</fieldset></form>';
</code>```

Add this script to set value in hidden field.

```<code><script>
function setId(rowValue){
   document.getElementById("hidden_field").value=rowValue;
}
</script>
</code>```

Body:
I have a html form which uses a PHP while loop to populate a select menu from a MYSQLi database. Code below;

$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1 ";
$result = mysqli_query($conn, $query);

echo '
Select Client by name:
        <select id="current_clients" name="current_clients">
        <option> -- Select Client -- </option>';

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
          echo '<option>'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
        }
echo '</select>';

The above works, the form populates with the required client records. However, I am then looking to use this data to link to an individual client page, which I tried using

echo ' Go!';

which did not work, so I tried setting the form action to

action="selected_client.php?id='.$row['id'].'"

with the method as "GET", which also did not work. As you can see in the query I am selecting 'id' from the table as well so I can call on that part of the array later, I just don't particularly need or want to echo it. Using the form action method, the $row['id'] variable is not set, and using the onClick method, I get a "Trying to access array offset on value of type null" error.

I imagine that the variable needs to be set before the form action can take place, but I can't think how I would be able to do that without moving the while loop or at least returning a value from it. Is it possible to call the form method and action at submission, rather than at the top of the form? Would that make any difference at all?

Edit; as requested, my attempt at using a hidden method for the form

echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" value="'.$row['id'].'">';

Which still returns the value of type null error.

Edit #2 - all code inline.

$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1 ";
$result = mysqli_query($conn, $query);
echo  '<form action="selected_client.php" method="get">
    <fieldset>';

echo '
Select Client by name:
        <select id="current_clients" name="current_clients">
        <option> -- Select Client -- </option>';

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
          echo '<option>'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
        }
echo '</select>';
echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" value="'.$row['id'].'">';

echo '</fieldset></form>';

Body:
Add onChange event and pass the selected value to some function, in that function set the hidden field with this selected value.Now you can submit the form and your selected value can be received.Below is solution.

$query = "SELECT on_programme, last_name, first_name, middle_name, id FROM constant_client WHERE on_programme=1";
$result = mysqli_query($conn, $query);
echo  '<form action="selected_client.php" method="get">
    <fieldset>';

echo '<p><label for="current_clients">Select Client by name: </label>
        <select id="current_clients" name="current_clients" onChange="setId(this.value);">
        <option value=""> -- Select Client -- </option>';

        while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
          echo '<option value="'.$row['id'].'">'.ucwords($row['last_name']).', '.ucwords($row['first_name']).' '.ucwords($row['middle_name']).'</option>';
        }
echo '</select>';
echo '<input type="submit" name="submit" value="Go!">
<input type="hidden" name="id" id="hidden_field" value="">';

echo '</fieldset></form>';

Add this script to set value in hidden field.

<script>
function setId(rowValue){
   document.getElementById("hidden_field").value=rowValue;
}
</script>


问:
How to rebase and push correctly in git using terminal
I was using VS Code git plugin for a while and now my new project is using the terminals to do the Gits and kid of new to the terminal mode.

Here is what I did so far, please suggest...

git clone http://remoteurl

git branch : output name is showing a branch name like 'stagingonly' ( not showing a name like master, let it be that)

git checkout -b X  : to create branch X

I did all the codings in X
: and now my team has alot new codes in the remote repo http://remoteurl , and adviced me to do rebase and push the code for code-review using terminal.

Please advice the missing step to do a rebase & remove conflicts and push the code ( remote repo is an azure devops repo)

Saw alot of steps in google, but thought of not messing with the client repos.

答:
Checkout stagingonly and pull, to bring it up to date.

Now checkout X and rebase stagingonly, resolving any conflicts, and
push.

That way, your branch X branches off the end of stagingonly
    and it will be easier and cleaner to merge it in the pull request.


问:
Is there any difference between: window.localStorage and localStorage?
I have been doing the following:

```<code>var store = window.localStorage;
store.setItem()
</code>```

but now I see code doing this:

```<code>localStorage.setItem()
</code>```

Do both do the same thing?

答:
This is old, but today I may have found a difference.

I have a React app that was 'forgetting' the localstorage values when I ran it on my server with SSL without the WI DOW . Without SSL, it was working fine.

I went back and added the WINDOW to all the references to localstorage and the problem disappeared

Body:
I have been doing the following:

var store = window.localStorage;
store.setItem()

but now I see code doing this:

localStorage.setItem()

Do both do the same thing?


问:
How can I reject user registration with certain username in default laravel register form?
I'm trying to block users from using certain names like 'admin' or 'operator'.

I've tried fiddling with both Controllers/Auth/RegisterController and Controller/RegisterController but failed.

What I've tried was something like this:

```<code>in Controllers/Auth/RegisterController,

if ($data['name'] === 'admin' || $data['name'] === 'operator') {
             return redirect()->back()->withErrors(['Invalid username']);
        }
else {
    session()->flash('message', 'Welcome!');

    return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
            ]);
        }
</code>```

The code above gave me this error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an
  instance of Illuminate\Contracts\Auth\Authenticatable, string given,
  called in /var/www/vendor/laravel/ui/auth-backend/RegistersUsers.php
  on line 36

I've also searched whether validators can block specific words but failed.
I know I can work this around by using JS, but I think Laravel would have some function like this.

答:
Go to RegisterController.php.

There will be a validator(array $data) function that validates your registration input.

Add not_in validation check for the name field.

Something like this:

```<code>    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255', 'not_in:admin,operator'],
            'pan' => ['required', 'string', 'min:10', 'max:10', 'unique:users,username'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }
</code>```

Hopefully, this helps.

Body:
I'm trying to block users from using certain names like 'admin' or 'operator'.

I've tried fiddling with both Controllers/Auth/RegisterController and Controller/RegisterController but failed.

What I've tried was something like this:

in Controllers/Auth/RegisterController,

if ($data['name'] === 'admin' || $data['name'] === 'operator') {
             return redirect()->back()->withErrors(['Invalid username']);
        }
else {
    session()->flash('message', 'Welcome!');

    return User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => Hash::make($data['password']),
            ]);
        }

The code above gave me this error:

Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an
  instance of Illuminate\Contracts\Auth\Authenticatable, string given,
  called in /var/www/vendor/laravel/ui/auth-backend/RegistersUsers.php
  on line 36

I've also searched whether validators can block specific words but failed.
I know I can work this around by using JS, but I think Laravel would have some function like this.

Body:
Go to RegisterController.php.

There will be a validator(array $data) function that validates your registration input.

Add not_in validation check for the name field.

Something like this:

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name' => ['required', 'string', 'max:255', 'not_in:admin,operator'],
            'pan' => ['required', 'string', 'min:10', 'max:10', 'unique:users,username'],
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);
    }

Hopefully, this helps.


问:
Azure AD Device Registered Column
I cannot find any way to export the registered date from AAD using any Powershell commandlets.</p>

答:
Use Get-AzureADDevice and Export-Csv to export the registered device date from AAD.

An example for your reference:

```<code>Get-AzureADDevice -All $true | Export-Csv D:\Temp\AzureADDevice.csv
</code>```

If you want to list devices registered by a user, you should use Get-AzureADUserRegisteredDevice.

Title: Azure AD Device Registered Column

Body:
Use Get-AzureADDevice and Export-Csv to export the registered device date from AAD.

An example for your reference:

Get-AzureADDevice -All $true | Export-Csv D:\Temp\AzureADDevice.csv

If you want to list devices registered by a user, you should use Get-AzureADUserRegisteredDevice.