问:
How to avoid "Too many open files" error when using uproot.daskframes to create daskframe from many ROOT files
I wanted to try using uproot to read a number of root files with flat ROOT NTupels into a desk frame. 214 files, 500kb each, about 8000 rows and 16 columns/variables in each. They easily fit in a pandas data frame in memory, but I am trying to learn dask (and uproot, only worked with root_pandas previously) since I expect larger datasets in the future.

So I thought that uproot.daskframes(list_of_paths, flatten=True) would be the tool to read the files into a desk frame. Creating the frameworks nice, but computing it in the following Too many open files error: https://pastebin.com/mfHgB16Q .
When I limit the files to for example 100, it computation works but is slow (30 seconds), on few files, it is no problem. When I use 100 files and increase the basketcase (e.g. 100Mb) to increase the speed, I get a RecursionError: https://pastebin.com/xTHa1Wav

My own solution was to just create normal pandas data frames with uprooting, delay the creation and use dask to create a concatenate them, which works well for me and results in a faster computation than uproot.daskframes for large numbers of files.

import uproot
from dask import delayed
import dask.dataframe as dd

def daskframe_from_rootfiles(path_list, treepath, branches=None):
    @delayed
    def get_df(file, treepath=None, branches=None):
        tree = uproot.open(file)[treepath]
        return tree.pandas.df(branches=branches)

    dfs = [get_df(path, treepath, branches=branches) for path in path_list]
    daskframe = dd.from_delayed(dfs)
    return daskframe
```

The advantage of delaying the dataframe creation is that I can use dask to parallelize it.

But I feel like there should be some canonical way and probably something I am missing and maybe there are other options that I should use for the daskframes function or maybe I should use some other function entirely to do that in. Can you help me with any ideas or best practices?

答:
```<code>    @delayed
    def get_df(file, treepath=None, branches=None):
        tree = uproot.open(file)[treepath]
        return tree.pandas.df(branches=branches)
</code>```

My guess is that this function is leaving an open file handle.  Maybe there is some way to close the file after opening?

```<code>    @delayed
    def get_df(filename, treepath=None, branches=None):
        file = uproot.open(filename)
        tree = file[treepath]
        df = tree.pandas.df(branches=branches)
        file.close()  # does something like this exist?
        return df
</code>```

Body:
I wanted to try using uproot to read a number of root files with flat ROOT NTupels into a desk frame. 214 files, 500kb each, about 8000 rows and 16 columns/variables in each. They easily fit in a pandas data frame in memory, but I am trying to learn dask (and uproot, only worked with root_pandas previously) since I expect larger datasets in the future.

So I thought that uproot.daskframes(list_of_paths, flatten=True) would be the tool to read the files into a desk frame. Creating the frameworks nice, but computing it in the following Too many open files error: https://pastebin.com/mfHgB16Q .
When I limit the files to for example 100, it computation works but is slow (30 seconds), on few files, it is no problem. When I use 100 files and increase the basketcase (e.g. 100Mb) to increase the speed, I get a RecursionError: https://pastebin.com/xTHa1Wav

My own solution was to just create normal pandas data frames with uprooting, delay the creation and use dask to create a concatenate them, which works well for me and results in a faster computation than uproot.daskframes for large numbers of files.

import uproot
from dask import delayed
import dask.dataframe as dd

def daskframe_from_rootfiles(path_list, treepath, branches=None):
    @delayed
    def get_df(file, treepath=None, branches=None):
        tree = uproot.open(file)[treepath]
        return tree.pandas.df(branches=branches)

    dfs = [get_df(path, treepath, branches=branches) for path in path_list]
    daskframe = dd.from_delayed(dfs)
    return daskframe

The advantage of delaying the dataframe creation is that I can use dask to parallelize it.

But I feel like there should be some canonical way and probably something I am missing and maybe there are other options that I should use for the daskframes function or maybe I should use some other function entirely to do that in. Can you help me with any ideas or best practices?

Body:
    @delayed
    def get_df(file, treepath=None, branches=None):
        tree = uproot.open(file)[treepath]
        return tree.pandas.df(branches=branches)

My guess is that this function is leaving an open file handle.  Maybe there is some way to close the file after opening?

    @delayed
    def get_df(filename, treepath=None, branches=None):
        file = uproot.open(filename)
        tree = file[treepath]
        df = tree.pandas.df(branches=branches)
        file.close()  # does something like this exist?
        return df


来源: stackexchange

问:
no value for a variable that is set in laravel
**1st code: **

```<code>       <div class="card-header">
        {{ isset($categories) ? 'Edit Category' : 'Create Category'}}
    </div>
</code>```

2cd code :

```<code>            <label for="name">Name-->{{ isset($categories) ? $categories->Name : ''}}</label>
</code>```

im working on a categories table in laravel. the problem is when im creating a new category the 1st code goes -> 'Create Category', and the 2nd code goes : '  ' which it super good ! BUT when im editing a category the 1st code goes : 'edit category' and the 2nd code goes : '' instead of the value of $categories->name value . Can any one help !?

答:
I think you should use !empty($categories), this may solve your problem.

ISSET checks the variable to see if it has been set. In other words, it checks to see if the variable is any value except NULL or not assigned a value, which means it will return true even if it's "".

EMPTY checks to see if a variable is empty. in your case "" will be considered as empty.

For more info  check

this

ContentLicense: CC BY-SA 4.0

Body:
**1st code: **

        {{ isset($categories) ? 'Edit Category' : 'Create Category'}}

2cd code :

            Name-->{{ isset($categories) ? $categories->Name : ''}}

im working on a categories table in laravel. the problem is when im creating a new category the 1st code goes -> 'Create Category', and the 2nd code goes : '  ' which it super good ! BUT when im editing a category the 1st code goes : 'edit category' and the 2nd code goes : '' instead of the value of $categories->name value . Can any one help !?


问:
Ambiguous use of 'dispatch_get_main_queue()' swift 5
These two line are giving the error  Ambiguous use of 'dispatch_get_main_queue()' swift 5 any help on how to fix it?

```<code>let voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue())
  voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP])
  voipRegistry.delegate = self;
}
</code>```

#-----

```<code>  dispatch_async(dispatch_get_main_queue(), { () -> Void in

              let alert = UIAlertView(title: "VoIP Notification", message: message, delegate: nil, cancelButtonTitle: "Ok");
              alert.show()
          })
</code>```

答: The problem is that dispatch_async(dispatch_get_main_queue() is not Swift. You would say DispatchQueue.main.async.

Body:
These two line are giving the error  Ambiguous use of 'dispatch_get_main_queue()' swift 5 any help on how to fix it?

let voipRegistry = PKPushRegistry(queue: dispatch_get_main_queue())
  voipRegistry.desiredPushTypes = Set([PKPushTypeVoIP])
  voipRegistry.delegate = self;
}

#-----

  dispatch_async(dispatch_get_main_queue(), { () -> Void in

              let alert = UIAlertView(title: "VoIP Notification", message: message, delegate: nil, cancelButtonTitle: "Ok");
              alert.show()
          })


问:
Best practice to deliver Core Data App with content?
Hey guys,

what would you say is the best way to ship initial data with an Core Data iOS App?

Is it maybe to once run the app, store the data and then insert the datafile in the build?
There must be a better way..

答:
I have had good experiences with loading the data into a sqlite backing in the simulator, and then bundling the resulting sqlite file with the app.

Especially for bigger datasets, first-run filling of the database is not really an option.

ContentLicense: CC BY-SA 3.0


问:
MySQL aggregate select query returning incorrect data
I have the following code:

```<code>SELECT gl.account_description AS invoice_total, COUNT(ili.invoice_id) AS total_invoice,
    SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl JOIN
     invoice_line_items ili
     ON gl.account_number = ili.account_number JOIN
     invoices i
     ON ili.invoice_id = i.invoice_id
GROUP BY gl.account_description, i.invoice_date, ili.account_number
HAVING i.invoice_date BETWEEN '2014-04-01' AND '2014-06-30' AND
      COUNT(ili.account_number) > 1
ORDER BY account_description DESC;
</code>```

In my query I am supposed to have 10 rows of data returned and I'm only having 7 return and none of them with the correct information. What I should have returning is the account_description column from the general_ledger_accounts table, a count of the items in the invoice_line_items table, a sum of the line_item_amount columns in the invoice_line_items table that have the same account number. It should only be searching within invoices between the dates '2014-04-01' and '2014-06-30'. I'm supposed to join in the invoices table.

Can anyone see what it is that I'm doing wrong in my syntax to get the wrong results?

答:
Obviously, you want a WHERE clause and not a HAVING clause for filtering on the dates -- and to remove the date from the GROUP BY (you are not selecting it):

```<code>SELECT gl.account_description AS invoice_total,
       COUNT(*) AS total_invoice,
       SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl JOIN
     invoice_line_items ili
     ON gl.account_number = ili.account_number JOIN
     invoices i
     ON ili.invoice_id = i.invoice_id
WHERE i.invoice_date BETWEEN '2014-04-01' AND '2014-06-30'
GROUP BY gl.account_description, ili.account_number
HAVING COUNT(*) > 1
ORDER BY account_description DESC;
</code>```

I don't know if there are other issues.

Body:
I have the following code:

SELECT gl.account_description AS invoice_total, COUNT(ili.invoice_id) AS total_invoice,
    SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl JOIN
     invoice_line_items ili
     ON gl.account_number = ili.account_number JOIN
     invoices i
     ON ili.invoice_id = i.invoice_id
GROUP BY gl.account_description, i.invoice_date, ili.account_number
HAVING i.invoice_date BETWEEN '2014-04-01' AND '2014-06-30' AND
      COUNT(ili.account_number) > 1
ORDER BY account_description DESC;

In my query I am supposed to have 10 rows of data returned and I'm only having 7 return and none of them with the correct information. What I should have returning is the account_description column from the general_ledger_accounts table, a count of the items in the invoice_line_items table, a sum of the line_item_amount columns in the invoice_line_items table that have the same account number. It should only be searching within invoices between the dates '2014-04-01' and '2014-06-30'. I'm supposed to join in the invoices table.

Can anyone see what it is that I'm doing wrong in my syntax to get the wrong results?

Body:
Obviously, you want a WHERE clause and not a HAVING clause for filtering on the dates -- and to remove the date from the GROUP BY (you are not selecting it):

SELECT gl.account_description AS invoice_total,
       COUNT(*) AS total_invoice,
       SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl JOIN
     invoice_line_items ili
     ON gl.account_number = ili.account_number JOIN
     invoices i
     ON ili.invoice_id = i.invoice_id
WHERE i.invoice_date BETWEEN '2014-04-01' AND '2014-06-30'
GROUP BY gl.account_description, ili.account_number
HAVING COUNT(*) > 1
ORDER BY account_description DESC;

I don't know if there are other issues.


问:
How to update firefox driver options in Selenium Python
so I'm trying to make a web crawler to download stuff online and in my class method i have

```<code>Class Webcrawler():
    def __init__(self, file):
        self.file = file
        self.folderName = None
        self.directory = 'C:\\Downloads\\'
        self.options = Options()
        self.options.set_preference('browser.download.folderList', 2)
        self.options.set_preference("browser.download.dir", self.directory + '\\' + self.folderName)
        self.driver = webdriver.Firefox(options=self.options)
</code>```

And I have a createDir function, which creates the folder where the files will be downloaded and updates self.folderName, but the driver never seems to update its options at all. How can I force it to update download.dir directory?

答:
As and alternative you can use the following code block which will create a new folder on each execution as per the current timestamp as follows:

```<code>Class Webcrawler():
    def __init__(self, file):
    self.directory = 'C:\\Downloads\\'
    self.fmt='{self.directory}%Y-%m-%d-%H-%M-%S'
    self.options = Options()
    self.options.set_preference('browser.download.folderList', 2)
    self.options.set_preference("browser.download.dir", os.makedirs(datetime.datetime.now().strftime(self.fmt).format(directory=self.directory)))
    self.driver = webdriver.Firefox(options=self.options)
</code>```

Body:
so I'm trying to make a web crawler to download stuff online and in my class method i have

Class Webcrawler():
    def __init__(self, file):
        self.file = file
        self.folderName = None
        self.directory = 'C:\\Downloads\\'
        self.options = Options()
        self.options.set_preference('browser.download.folderList', 2)
        self.options.set_preference("browser.download.dir", self.directory + '\\' + self.folderName)
        self.driver = webdriver.Firefox(options=self.options)

And I have a createDir function, which creates the folder where the files will be downloaded and updates self.folderName, but the driver never seems to update its options at all. How can I force it to update download.dir directory?

Body:
As and alternative you can use the following code block which will create a new folder on each execution as per the current timestamp as follows:

Class Webcrawler():
    def __init__(self, file):
    self.directory = 'C:\\Downloads\\'
    self.fmt='{self.directory}%Y-%m-%d-%H-%M-%S'
    self.options = Options()
    self.options.set_preference('browser.download.folderList', 2)
    self.options.set_preference("browser.download.dir", os.makedirs(datetime.datetime.now().strftime(self.fmt).format(directory=self.directory)))
    self.driver = webdriver.Firefox(options=self.options)


问:
distributed.worker Memory use is high but worker has no data to store to disk
```<code>distributed.worker - WARNING - Memory use is high but worker has no data to store to disk.  Perhaps some other process is leaking memory?  Process memory: 3.91 GB -- Worker memory limit: 2.00 GB
distributed.worker - WARNING - Worker is at 41% memory usage. Resuming worker. Process memory: 825.12 MB -- Worker memory limit: 2.00 GB
</code>```

The above error appears when I try to run a piece of code that applies an algorithm to a dataset that I have. Having read through the documentation at  https://distributed.dask.org/en/latest/worker.html, it's still not clear to me what the impact of this error will be on the results of this application. Does this just affect the speed or efficiency of this code, or will it impact my results?

答:
That warning is saying that your process is taking up much more memory than you are saying is OK.  In this situation Dask may pause execution or even start restarting your workers.

The warning also says that Dask itself isn't holding on to any data, so there isn't much that it can do to help the situation (like remove its data).  My guess is that some of the libraries that you are using taking up a lot of memory.  You might want to use Dask workers that have more than 2GB of memory.

Body:
distributed.worker - WARNING - Memory use is high but worker has no data to store to disk.  Perhaps some other process is leaking memory?  Process memory: 3.91 GB -- Worker memory limit: 2.00 GB
distributed.worker - WARNING - Worker is at 41% memory usage. Resuming worker. Process memory: 825.12 MB -- Worker memory limit: 2.00 GB

The above error appears when I try to run a piece of code that applies an algorithm to a dataset that I have. Having read through the documentation at  https://distributed.dask.org/en/latest/worker.html, it's still not clear to me what the impact of this error will be on the results of this application. Does this just affect the speed or efficiency of this code, or will it impact my results?


问:
Why is the “root.after ()” method not stoppable?
I'm trying to make a simple tool-path program with directional buttons. It works, but sometimes releasing the button is ineffective and the turtle stops just clicking the "Home" button. Else it just runs continuously as if I did not release the button.

Here is the code:

```<code>from tkinter import *
from turtle import RawTurtle, TurtleScreen

def showPos():
    monitor.delete('1.0', END)
    monitor.insert(END, "X: " + str(tool.ycor()) +" Z: " + str(tool.xcor()))

def goHome():
    tool.home()
    showPos()
    stop_move()

def goUp():
    tool.sety(tool.ycor() + 10)

def goDown():
    tool.sety(tool.ycor() - 10)

def goRight():
    tool.setx(tool.xcor() + 10)

def goLeft():
    tool.setx(tool.xcor() - 10)

def stop_move():
    global jobid
    root.after_cancel(jobid)

def move(direction):
    global jobid

    if direction == "-X":
        goDown()

    if direction == "+X":
        goUp()

    if direction == "-Z":
        goLeft()

    if direction == "+Z":
        goRight()

    jobid = root.after(10, move, direction)
    showPos()

jobid = None

root = Tk()
root.title("CNC Lathe")

canvas = Canvas(root, width=800, height=600)
canvas.pack()

screen = TurtleScreen(canvas)
screen.bgcolor("black")
screen.register_shape("wnmg.gif")

tool = RawTurtle(screen, shape="wnmg.gif")
tool.pencolor("white")

monitor = Text(root, height=1, width=16, font="Helvetica")
monitor.pack()

topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()

for direction in ("-X", "+X", "-Z", "+Z"):
    if direction == "+X":
        button = Button(topFrame, text=direction)
        button.pack()

    if direction == "-X":
        button = Button(bottomFrame, text=direction)
        button.pack()

    if direction == "-Z":
        button = Button(middleFrame, text=direction)
        button.pack(side=LEFT)

    if direction == "+Z":
        button = Button(middleFrame, text=direction)
        button.pack(side=RIGHT)

    button.bind('<ButtonPress-1>', lambda event, direction=direction: move(direction))
    button.bind('<ButtonRelease-1>', lambda event: stop_move())

Button(middleFrame, text="Home", command=goHome).pack()

root.mainloop()
</code>```

I tried to set the variable "jobid" to "None" after the "root.after_cancel ()" method, but nothing changed. At times this does not seem to detect the release of the button. Does anyone know a solution?

答:
I tried to make your code work with your jobid model, and although I could improve it, the flaw eventually surfaced -- I can't say exactly why.  You have to consider that, in your implementation, jobid doesn't always represent a pending job, it could be one that has fired successfuly.

Another issue to consider is the timing of:

```<code>jobid = root.after(10, move, direction)
</code>```

The 10ms time has to be greater than the time it takes to execute the move() method, plus time to react.  That is, if you can't draw the minimal size box (10 x 10) without repitition getting in your way, you again need to incress this time.

Below is my rework of your code using a simple state variable instead of the job id (plus some other changes.)  It seems to solve the problem:

```<code>from tkinter import *
from turtle import RawTurtle, TurtleScreen

def showPos():
    monitor.delete('1.0', END)
    monitor.insert(END, "X: " + str(tool.ycor()) + " Z: " + str(tool.xcor()))

def goHome():
    tool.home()
    showPos()

def goUp():
    tool.sety(tool.ycor() + 10)

def goDown():
    tool.sety(tool.ycor() - 10)

def goRight():
    tool.setx(tool.xcor() + 10)

def goLeft():
    tool.setx(tool.xcor() - 10)

pressing = False

def start_move(event):
    global pressing

    event.widget.unbind('<ButtonPress-1>')  # unbind event handler inside handler(s)

    pressing = True

    move(event)

def stop_move(event):
    global pressing

    pressing = False

    event.widget.bind('<ButtonPress-1>', start_move)

def move(event):
    if not pressing:
        return

    direction = event.widget['text']

    if direction == '-X':
        goDown()
    elif direction == '+X':
        goUp()
    elif direction == '-Z':
        goLeft()
    elif direction == '+Z':
        goRight()

    showPos()

    root.after(75, move, event)

root = Tk()
root.title("CNC Lathe")

canvas = Canvas(root, width=800, height=600)
canvas.pack()

screen = TurtleScreen(canvas)
screen.bgcolor('black')
# screen.register_shape("wnmg.gif")

# tool = RawTurtle(screen, shape="wnmg.gif")
tool = RawTurtle(screen, shape='turtle')
tool.pencolor('white')

monitor = Text(root, height=1, width=16, font='Helvetica')
monitor.pack()

topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()

for direction in ('-X', '+X', '-Z', '+Z'):
    if direction == '+X':
        button = Button(topFrame, text=direction)
        button.pack()

    if direction == '-X':
        button = Button(bottomFrame, text=direction)
        button.pack()

    if direction == '-Z':
        button = Button(middleFrame, text=direction)
        button.pack(side=LEFT)

    if direction == '+Z':
        button = Button(middleFrame, text=direction)
        button.pack(side=RIGHT)

    button.bind('<ButtonPress-1>', start_move)
    button.bind('<ButtonRelease-1>', stop_move)

Button(middleFrame, text="Home", command=goHome).pack()

root.mainloop()
</code>```

I changed the cursor to a turtle as I didn't have your "wnmg.gif" image to work with.

Body:
I'm trying to make a simple tool-path program with directional buttons. It works, but sometimes releasing the button is ineffective and the turtle stops just clicking the "Home" button. Else it just runs continuously as if I did not release the button.

Here is the code:

from tkinter import *
from turtle import RawTurtle, TurtleScreen

def showPos():
    monitor.delete('1.0', END)
    monitor.insert(END, "X: " + str(tool.ycor()) +" Z: " + str(tool.xcor()))

def goHome():
    tool.home()
    showPos()
    stop_move()

def goUp():
    tool.sety(tool.ycor() + 10)

def goDown():
    tool.sety(tool.ycor() - 10)

def goRight():
    tool.setx(tool.xcor() + 10)

def goLeft():
    tool.setx(tool.xcor() - 10)

def stop_move():
    global jobid
    root.after_cancel(jobid)

def move(direction):
    global jobid

    if direction == "-X":
        goDown()

    if direction == "+X":
        goUp()

    if direction == "-Z":
        goLeft()

    if direction == "+Z":
        goRight()

    jobid = root.after(10, move, direction)
    showPos()

jobid = None

root = Tk()
root.title("CNC Lathe")

canvas = Canvas(root, width=800, height=600)
canvas.pack()

screen = TurtleScreen(canvas)
screen.bgcolor("black")
screen.register_shape("wnmg.gif")

tool = RawTurtle(screen, shape="wnmg.gif")
tool.pencolor("white")

monitor = Text(root, height=1, width=16, font="Helvetica")
monitor.pack()

topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()

for direction in ("-X", "+X", "-Z", "+Z"):
    if direction == "+X":
        button = Button(topFrame, text=direction)
        button.pack()

    if direction == "-X":
        button = Button(bottomFrame, text=direction)
        button.pack()

    if direction == "-Z":
        button = Button(middleFrame, text=direction)
        button.pack(side=LEFT)

    if direction == "+Z":
        button = Button(middleFrame, text=direction)
        button.pack(side=RIGHT)

    button.bind('<ButtonPress-1>', lambda event, direction=direction: move(direction))
    button.bind('<ButtonRelease-1>', lambda event: stop_move())

Button(middleFrame, text="Home", command=goHome).pack()

root.mainloop()

I tried to set the variable "jobid" to "None" after the "root.after_cancel ()" method, but nothing changed. At times this does not seem to detect the release of the button. Does anyone know a solution?

Body:
I tried to make your code work with your jobid model, and although I could improve it, the flaw eventually surfaced -- I can't say exactly why.  You have to consider that, in your implementation, jobid doesn't always represent a pending job, it could be one that has fired successfuly.

Another issue to consider is the timing of:

jobid = root.after(10, move, direction)

The 10ms time has to be greater than the time it takes to execute the move() method, plus time to react.  That is, if you can't draw the minimal size box (10 x 10) without repitition getting in your way, you again need to incress this time.

Below is my rework of your code using a simple state variable instead of the job id (plus some other changes.)  It seems to solve the problem:

from tkinter import *
from turtle import RawTurtle, TurtleScreen

def showPos():
    monitor.delete('1.0', END)
    monitor.insert(END, "X: " + str(tool.ycor()) + " Z: " + str(tool.xcor()))

def goHome():
    tool.home()
    showPos()

def goUp():
    tool.sety(tool.ycor() + 10)

def goDown():
    tool.sety(tool.ycor() - 10)

def goRight():
    tool.setx(tool.xcor() + 10)

def goLeft():
    tool.setx(tool.xcor() - 10)

pressing = False

def start_move(event):
    global pressing

    event.widget.unbind('<ButtonPress-1>')  # unbind event handler inside handler(s)

    pressing = True

    move(event)

def stop_move(event):
    global pressing

    pressing = False

    event.widget.bind('<ButtonPress-1>', start_move)

def move(event):
    if not pressing:
        return

    direction = event.widget['text']

    if direction == '-X':
        goDown()
    elif direction == '+X':
        goUp()
    elif direction == '-Z':
        goLeft()
    elif direction == '+Z':
        goRight()

    showPos()

    root.after(75, move, event)

root = Tk()
root.title("CNC Lathe")

canvas = Canvas(root, width=800, height=600)
canvas.pack()

screen = TurtleScreen(canvas)
screen.bgcolor('black')
# screen.register_shape("wnmg.gif")

# tool = RawTurtle(screen, shape="wnmg.gif")
tool = RawTurtle(screen, shape='turtle')
tool.pencolor('white')

monitor = Text(root, height=1, width=16, font='Helvetica')
monitor.pack()

topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()

for direction in ('-X', '+X', '-Z', '+Z'):
    if direction == '+X':
        button = Button(topFrame, text=direction)
        button.pack()

    if direction == '-X':
        button = Button(bottomFrame, text=direction)
        button.pack()

    if direction == '-Z':
        button = Button(middleFrame, text=direction)
        button.pack(side=LEFT)

    if direction == '+Z':
        button = Button(middleFrame, text=direction)
        button.pack(side=RIGHT)

    button.bind('<ButtonPress-1>', start_move)
    button.bind('<ButtonRelease-1>', stop_move)

Button(middleFrame, text="Home", command=goHome).pack()

root.mainloop()

I changed the cursor to a turtle as I didn't have your "wnmg.gif" image to work with.


问:
Convert factor value into numeric in a column of dataframe
I have a data frame that has two string characters stored in each row

```<code>s   ['64.0', '2']
a   ['63.0', '2']
b   ['63.0', '1']
</code>```

How to convert the first character string into numeric value,and omit the second character string,which results into data frame as follows :

```<code>s    64.0
a    63.0
b    63.0
</code>```

答:
Here is another base R solution using regmatches, i.e.,

```<code>df <- within(df, col2 <- as.numeric(sapply(regmatches(col2,gregexpr("[0-9\\.]+",col2)),`[[`,1)))
</code>```

such that

```<code>> df
  col1 col2
1    s   64
2    a   63
3    b   63
</code>```

Body:
I have a data frame that has two string characters stored in each row

s   ['64.0', '2']
a   ['63.0', '2']
b   ['63.0', '1']

How to convert the first character string into numeric value,and omit the second character string,which results into data frame as follows :

s    64.0
a    63.0
b    63.0

Body:
Here is another base R solution using regmatches, i.e.,

df <- within(df, col2 <- as.numeric(sapply(regmatches(col2,gregexpr("[0-9\\.]+",col2)),`[[`,1)))

such that

> df
  col1 col2
1    s   64
2    a   63
3    b   63


问:
CDN links in php include files
I am working a site project with Bootstrap 4.4.1. I use the CDN links to place them right before closing the . In order to avoid lots of coding in all pages, I want to use a php include file which contains all the scripts below/ This file I named "js-remote.php". This is inside a folder called "js".

I inserted the code on every content page (I am doing all php pages) and the path is:

<?php include '../js/js-remote.php'>

But doesn't work. I have navigation bar also as included file, the menu is shown but the dropdowns don't work properly. Even when I paste the full scripts codes of the CDN (without using any php include) don't work either.

ONLY works when I don't use the include files, just when pasting the complete code as a regular html file.Get below the code I wanna use in a php include file. Observations, please.

```<code><script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</body>
</code>```

But instead of pasting the whole scripts I just want to put one single line:

```<code><?php include '../js/js-remote.php' ?>
</body>
<--! Could it work?-->
</code>```

Where "js-remote.php" is a page which contains all the cdn scripts above and more coming in the future.

Sorry for the redundance but it's necessary. The "js-remote.php" file contains:

```<code><script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
</code>```

答:
I see errors in the way the code is written here that would break the functionality if they're in the actual document.
The include should be written

```<code><?php include '../js/js-remote.php'; ?>
</code>```

In your post you left out the semicolon and ?> in the first case and the final quote and semicolon in the second.

Title: CDN links in php include files

Body:
I am working a site project with Bootstrap 4.4.1. I use the CDN links to place them right before closing the . In order to avoid lots of coding in all pages, I want to use a php include file which contains all the scripts below/ This file I named "js-remote.php". This is inside a folder called "js".

I inserted the code on every content page (I am doing all php pages) and the path is:

<?php include '../js/js-remote.php'>

But doesn't work. I have navigation bar also as included file, the menu is shown but the dropdowns don't work properly. Even when I paste the full scripts codes of the CDN (without using any php include) don't work either.

ONLY works when I don't use the include files, just when pasting the complete code as a regular html file.Get below the code I wanna use in a php include file. Observations, please.

But instead of pasting the whole scripts I just want to put one single line:

<?php include '../js/js-remote.php' ?>

<--! Could it work?-->

Where "js-remote.php" is a page which contains all the cdn scripts above and more coming in the future.

Sorry for the redundance but it's necessary. The "js-remote.php" file contains:

Body:
I see errors in the way the code is written here that would break the functionality if they're in the actual document.
The include should be written

<?php include '../js/js-remote.php'; ?>

In your post you left out the semicolon and ?> in the first case and the final quote and semicolon in the second.


问:
Get name and value with PHP
I have this simple form:

HTML:

```<code><input type="checkbox" name="product[]" value="20$" /> book
<input type="checkbox" name="product[]" value="30$" /> plane
</code>```

PHP:

```
<code>
$product = $_POST['product'];
foreach($product as $value) {
    echo $value;
}
</code>
```

Note:

The user can choose one or two ... products.

Question:

I want to know if there is a solution to get the name too, like adding an ID class or something ..

Basically I cant get the name attribute because I didn't sent it with the form.

答:
You can use the option presented by elusive, but it seems that in this case you're passing the price from the client to the server. That might allow people to fraud. They could with only a little hacking send another (lower) price. If you just send 'book' and redetermine the price on the server, this won't be a problem.

If you choose that path, you can just put the product ('book') in the value:

```<code><input type="checkbox" id="book" name="product[]" value="book" />
<label for="book">book</label>
<input type="checkbox" id="plane" name="product[]" value="plane" />
<label for="plane">plane</label>
</code>```

Title: Get name and value with PHP

Body:
I have this simple form:

HTML:

<input type="checkbox" name="product[]" value="20$" /> book
<input type="checkbox" name="product[]" value="30$" /> plane

PHP:

$product = $_POST['product'];
foreach($product as $value) {
    echo $value;
}

Note:

The user can choose one or two ... products.

Question:

I want to know if there is a solution to get the name too, like adding an ID class or something ..

Basically I cant get the name attribute because I didn't sent it with the form.

Body:
You can use the option presented by elusive, but it seems that in this case you're passing the price from the client to the server. That might allow people to fraud. They could with only a little hacking send another (lower) price. If you just send 'book' and redetermine the price on the server, this won't be a problem.

If you choose that path, you can just put the product ('book') in the value:

<input type="checkbox" id="book" name="product[]" value="book" />
<label for="book">book</label>
<input type="checkbox" id="plane" name="product[]" value="plane" />
<label for="plane">plane</label>


问:
Smart way to map knotty json
I have below json and I'm looking for smart way to map this for java object. Till now I tried this way, but it didnt helped.

JSON:https://pastebin.com/NBCGXgUD

This is what i tried

```<code>@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class TravelpayoutsResponse {
    private boolean success;
    private TravelpayoutsData data;
    private String error;
    private String currency;
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class TravelpayoutsData {
    private FlightDetails flightDetails[];
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FlightDetails {
private FlightDetail[] flightDetails;
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FlightDetail {
    private int price;
    private String airline;
    @JsonProperty("flight_number")
    private String flightNumber;
    @JsonProperty("departure_at")
    private String departureDate;
    @JsonProperty("return_at")
    private String returnDate;
    @JsonProperty("expires_at")
    private String expirationDate;
}
</code>```

But it didnt worked for me. Maybe do you have any idea how to map it? I would be very thankfull

答:
There aren't any arrays in the JSON.</p>

```<code>@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class TravelpayoutsResponse {
    private boolean success;
    private Map<String, Map<String, FlightDetail> data;
    private String error;
    private String currency;
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FlightDetail {
    private int price;
    private String airline;
    @JsonProperty("flight_number")
    private String flightNumber;
    @JsonProperty("departure_at")
    private String departureDate;
    @JsonProperty("return_at")
    private String returnDate;
    @JsonProperty("expires_at")
    private String expirationDate;
}
</code>```

Title: Smart way to map knotty json

Body:
I have below json and I'm looking for smart way to map this for java object. Till now I tried this way, but it didnt helped.

JSON:https://pastebin.com/NBCGXgUD

This is what i tried

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class TravelpayoutsResponse {
    private boolean success;
    private TravelpayoutsData data;
    private String error;
    private String currency;
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class TravelpayoutsData {
    private FlightDetails flightDetails[];
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FlightDetails {
private FlightDetail[] flightDetails;
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FlightDetail {
    private int price;
    private String airline;
    @JsonProperty("flight_number")
    private String flightNumber;
    @JsonProperty("departure_at")
    private String departureDate;
    @JsonProperty("return_at")
    private String returnDate;
    @JsonProperty("expires_at")
    private String expirationDate;
}

But it didnt worked for me. Maybe do you have any idea how to map it? I would be very thankfull

Body:
There aren't any arrays in the JSON.

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class TravelpayoutsResponse {
    private boolean success;
    private Map<String, Map<String, FlightDetail> data;
    private String error;
    private String currency;
}

@Getter
@Setter
@JsonIgnoreProperties(ignoreUnknown = true)
public class FlightDetail {
    private int price;
    private String airline;
    @JsonProperty("flight_number")
    private String flightNumber;
    @JsonProperty("departure_at")
    private String departureDate;
    @JsonProperty("return_at")
    private String returnDate;
    @JsonProperty("expires_at")
    private String expirationDate;
}


答:
I suspect that you want to remove columns i.invoice_date and ili.account_number from the group by clause. Otherwise, you get one record per distinct values of these three columns, which does not seem to be what you want.

Accordingly, you should move the filter on the dates to the where clause:

```<code>SELECT
    gl.account_description AS invoice_total,
    COUNT(ili.invoice_id) AS total_invoice,
    SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl
INNER JOIN invoice_line_items ili
    ON gl.account_number = ili.account_number
INNER JOIN invoices i
    ON ili.invoice_id = i.invoice_id
WHERE
    i.invoice_date >= '2014-04-01'
    AND i.invoice_date < '2014-07-01'
GROUP BY gl.account_description
HAVING COUNT(ili.account_number) > 1
ORDER BY g1.account_description DESC;
</code>```

Note that I modified the condition on the dates to use half-open intervals: this way, you don't have to worry about whether the last month has 30 or 31 days (or 28, or 29...); this would also smoothly handle the time part of the dates, if any.

Title: MySQL aggregate select query returning incorrect data

Body:
I suspect that you want to remove columns i.invoice_date and ili.account_number from the group by clause. Otherwise, you get one record per distinct values of these three columns, which does not seem to be what you want.

Accordingly, you should move the filter on the dates to the where clause:

SELECT
    gl.account_description AS invoice_total,
    COUNT(ili.invoice_id) AS total_invoice,
    SUM(ili.line_item_amount) AS total_convert
FROM general_ledger_accounts gl
INNER JOIN invoice_line_items ili
    ON gl.account_number = ili.account_number
INNER JOIN invoices i
    ON ili.invoice_id = i.invoice_id
WHERE
    i.invoice_date >= '2014-04-01'
    AND i.invoice_date < '2014-07-01'
GROUP BY gl.account_description
HAVING COUNT(ili.account_number) > 1
ORDER BY g1.account_description DESC;

Note that I modified the condition on the dates to use half-open intervals: this way, you don't have to worry about whether the last month has 30 or 31 days (or 28, or 29...); this would also smoothly handle the time part of the dates, if any.


问:
Creating a counter for C++ with a button
I am trying to put together a button press counter with my argon device. I have a couple sounds I want to alternate between but can not get a counter to work for me to change songs A and B.  I wanted to set song A as counter evens and song B on counter odds. I currently have very little and do not know where to go from where I am at. Not sure how to upload what I have currently. </p>

```<code>int button = A0;

int buzzer = A2;

// Defining Sound
int sound1[] = {1700,2500,2800,2000,2500,1500,2000,1800};

int sound2[] = {3800,3600,3400,3200,2400,2600,2800,3000};

//Defining Duration Of Notes

int Duration1[] = {4,2,4,2,4,2,4,2};

int Duration2[] = {2,4,2,4,2,2,4,2};

//Setting Button Count
int bcount = 0;
#define MAX 2

//Creates The Setup Of Code
void setup()
{
    //Creates The Input Of Button Being Pressed
    pinMode (button, INPUT);
    //Creates The Output Of The Buzzer
    pinMode (buzzer, OUTPUT);
}

void loop() {
    //When Button Is Pressed
    if (digitalRead(button) == 1) {
        bcount = bcount + 1;
        }
        else if
                (bcount = 0);
        for (int i = 0; i < bcount; i++) {
            digitalWrite(buzzer, 1);

    if (bcount == MAX) {
        bcount = 0;
        break;
    }
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration1[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound1[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
        }
    }
        //When Button Is Pressed 2nd Time
      if(digitalRead(button) == 2) {
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration2[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound2[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
}
}
}
</code>```

答:
Try this:

```<code>int counter = 0;
void loop() {
    if (digitalRead(button) == HIGH) {
        counter = counter + 1;
        if (counter % 2 == 1) {
            // ... place your code for sound#1 here.
        } else {
            // ... place your code for sound#2 here.
        }
    }
}
</code>```

What's going on here is: we're incrementing a counter every time the button is pressed. If the number of times the button has been pressed is odd, we play the first sound, if it's even, we play the second sound.

It's important to store the counter outside the loop function, so that it does not lose it's value between calls of loop.

Also, notice that digitalRead returns HIGH if the button is pressed, or LOW if it is not. Any counting of presses beyond that you have to do yourself.

https://docs.particle.io/reference/device-os/firmware/argon/#digitalread-

Body:
I am trying to put together a button press counter with my argon device. I have a couple sounds I want to alternate between but can not get a counter to work for me to change songs A and B.  I wanted to set song A as counter evens and song B on counter odds. I currently have very little and do not know where to go from where I am at. Not sure how to upload what I have currently.

int button = A0;

int buzzer = A2;

// Defining Sound
int sound1[] = {1700,2500,2800,2000,2500,1500,2000,1800};

int sound2[] = {3800,3600,3400,3200,2400,2600,2800,3000};

//Defining Duration Of Notes

int Duration1[] = {4,2,4,2,4,2,4,2};

int Duration2[] = {2,4,2,4,2,2,4,2};

//Setting Button Count
int bcount = 0;
#define MAX 2

//Creates The Setup Of Code
void setup()
{
    //Creates The Input Of Button Being Pressed
    pinMode (button, INPUT);
    //Creates The Output Of The Buzzer
    pinMode (buzzer, OUTPUT);
}

void loop() {
    //When Button Is Pressed
    if (digitalRead(button) == 1) {
        bcount = bcount + 1;
        }
        else if
                (bcount = 0);
        for (int i = 0; i < bcount; i++) {
            digitalWrite(buzzer, 1);

    if (bcount == MAX) {
        bcount = 0;
        break;
    }
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration1[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound1[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
        }
    }
        //When Button Is Pressed 2nd Time
      if(digitalRead(button) == 2) {
        //Reads Notes
        for (int Note = 0; Note < 8; Note++){
            //Note Duration
            int Duration = 1000/Duration2[Note];
            //Sends Notes To Speaker
            tone(buzzer, sound2[Note], Duration);
            //Sets Delay Between Notes
            int pauseBetweenNotes = Duration * 1.50;
            //Delay Itself
            delay(pauseBetweenNotes);
            //Stop To The Sound
            noTone(buzzer);
}
}
}

Body:
Try this:

int counter = 0;
void loop() {
    if (digitalRead(button) == HIGH) {
        counter = counter + 1;
        if (counter % 2 == 1) {
            // ... place your code for sound#1 here.
        } else {
            // ... place your code for sound#2 here.
        }
    }
}

What's going on here is: we're incrementing a counter every time the button is pressed. If the number of times the button has been pressed is odd, we play the first sound, if it's even, we play the second sound.

It's important to store the counter outside the loop function, so that it does not lose it's value between calls of loop.

Also, notice that digitalRead returns HIGH if the button is pressed, or LOW if it is not. Any counting of presses beyond that you have to do yourself.

https://docs.particle.io/reference/device-os/firmware/argon/#digitalread-


答:
This should work:</p>

```<code>df = df.sort_values("count", ascending=False).groupby(["dt", "id2"], as_index=False).first()
df = df.groupby("dt").apply(lambda x: x.iloc[0:3]).reset_index(drop=True)
</code>```

Title: Reducing a pandas dataframe by keeping nth largest values

Body:
Let say I have the follwing dataframe:

id1    dt                   id2   count
0      2010-02-06 07:21:45  id0   78
0      2010-02-06 07:21:45  id1   79
0      2010-02-06 07:21:45  id2   80
0      2010-02-06 07:21:45  id3   69
0      2010-02-06 07:58:25  id4   58
1      2010-02-06 07:58:25  id0   67

I want to keep for each "dt" the nth most "id2" that are selected by the higher "count".
Hence obtaining, for nth=3:

id1    dt                   id2   count
0      2010-02-06 07:21:45  id0   78
0      2010-02-06 07:21:45  id1   79
0      2010-02-06 07:21:45  id2   80
0      2010-02-06 07:58:25  id4   58
1      2010-02-06 07:58:25  id0   67

It should also detect multiple "id2". Hence if input is:

id1    dt                   id2   count
0      2010-02-06 07:21:45  id0   78
0      2010-02-06 07:21:45  id1   79
0      2010-02-06 07:21:45  id2   80
0      2010-02-06 07:21:45  id2   79
0      2010-02-06 07:21:45  id3   69
0      2010-02-06 07:58:25  id4   58
1      2010-02-06 07:58:25  id0   67

It must return for nth=3

id1    dt                   id2   count
0      2010-02-06 07:21:45  id0   78
0      2010-02-06 07:21:45  id1   79
0      2010-02-06 07:21:45  id2   80
0      2010-02-06 07:58:25  id4   58
1      2010-02-06 07:58:25  id0   67

Body:
This should work:

df = df.sort_values("count", ascending=False).groupby(["dt", "id2"], as_index=False).first()
df = df.groupby("dt").apply(lambda x: x.iloc[0:3]).reset_index(drop=True)


问:
How to avoid submitting dask tasks-within-tasks to main scheduler
The task launch documentation shows that the default behavior of dask.compute within a dask worker is to launch tasks on the main scheduler.

My desire is NOT to launch on the main scheduler.  My task is doing two steps: using a non-python binary to process 0.1-1.0 TB of data copied onto the local disk, then using dask to convert and write the data out to a zarr store. The binary is multi-threaded, and I'd also like to using a dask locally in multi-process or multi-threaded local way.

For this worker, I use a multi-core machine, but reserve only one thread for dask worker.  I believe this means my task can use all the cores on the machine for both of the above steps.

Is this a viable model, and how would I call compute (distributed.Client().compute does not seem to work)?  Are there other approaches where I can run my binary exclusively on the machine, and run my parallel zarr write via tasks?

答:
When calling dask.compute you can specify a scheduler= option like the following:

```<code>dask.compute(x, y, scheduler="processes")
</code>```

See https://docs.dask.org/en/latest/scheduling.html for more information

Body:
When calling dask.compute you can specify a scheduler= option like the following:

dask.compute(x, y, scheduler="processes")

See https://docs.dask.org/en/latest/scheduling.html for more information


问:
"do" in "do Application.Run(form)" sentence
What is the difference between

```<code>do Application.Run(form)
</code>```

and, simply:

```<code>Application.Run(form) ?
</code>```

What is the role of do keyword in the first sentence?

答:
I think it's just a holdover - like how you can still CALL a sub or SET a variable instead of just doing those things directly, as in:

```<code>SET varname = 5
CALL mysub()
</code>```

Versus just:

```<code>varname = 5
mysub()
</code>```

In other words, I don't think it matters, and the compiler just discards it.

OwnerDisplayName: Vladimir Aks

LastEditorDisplayName: Drew Noakes

ContentLicense: CC BY-SA 2.5

Body:
What is the difference between

do Application.Run(form)

and, simply:

Application.Run(form) ?

What is the role of do keyword in the first sentence?

Body:
I think it's just a holdover - like how you can still CALL a sub or SET a variable instead of just doing those things directly, as in:

SET varname = 5
CALL mysub()

Versus just:

varname = 5
mysub()

In other words, I don't think it matters, and the compiler just discards it.

OwnerDisplayName: rwmnau


问:
Can we call RESTful webservices created using Spring REST support from .NETapplication?
We have created RESTful web services using Spring's REST support.

We need to call those web services from .NET aplication.

Is it possible to do this i.e. calling web services written in java from .NET?

答:
Just use Spring.NET REST Client Framework using the RestTemplate :
http://springframework.net/index.html#spring-rest-1.0.0-released

I think you will not get lost!

Bruno


问:
Types in object destructuring
This

```<code>const { foo: IFoo[] } = bar;
</code>```

and this

```<code>const { foo: Array<IFoo> } = bar;
</code>```

will reasonably cause an error.

And this

```<code>const { foo: TFoo } = bar;
</code>```

will just destructure TFoo property.

How can types be specified for destructured object properties?

答:
A follow-up to my own question.

Types don't need to be specified for object properties because they are inferred from destructured object.

Considering that bar was typed properly, foo type will be inferred:

```<code>const bar = { foo: [fooValue], ... }; // bar type is { foo: IFoo[], ... }
...
const { foo } = bar; // foo type is IFoo[]
</code>```

Even if bar wasn't correctly typed (any or unknown), its type can be asserted:

```<code>const { foo } = bar as { foo: IFoo[] }; // foo type is IFoo[]
</code>```

Title: Types in object destructuring

Body:
This

const { foo: IFoo[] } = bar;

and this

const { foo: Array<IFoo> } = bar;

will reasonably cause an error.

And this

const { foo: TFoo } = bar;

will just destructure TFoo property.

How can types be specified for destructured object properties?

Body:
A follow-up to my own question.

Types don't need to be specified for object properties because they are inferred from destructured object.

Considering that bar was typed properly, foo type will be inferred:

const bar = { foo: [fooValue], ... }; // bar type is { foo: IFoo[], ... }
...
const { foo } = bar; // foo type is IFoo[]

Even if bar wasn't correctly typed (any or unknown), its type can be asserted:

const { foo } = bar as { foo: IFoo[] }; // foo type is IFoo[]


问:
regex match line in which the first word repeats elsewhere in the line
I am looking for a way to match a line that has two or more occurrences of a pattern (a word). Example:

```<code>abc cde abc dd
</code>```

should be matched because the sequence abc is present twice. The sequences are always separated by a space. If it helps, it is enough to test for multiple presence of the first word.

答:
Based on the sentence if it helps, I am ok, to test for multiple presence of the first sequence, I deduce that your primal interest was in matching the repeated words without such a limitation that the word is at the beginning of the line.

This will match all words which are repeated (it does not match the last repetition):

(\b\w+\b)(?=.*\b\1\b)
```

<p>For instance, given the line</p>

```aaa abc dd cde abc dd cde fga dd hello
```

it matches abc, dd, cde, dd (yes, it matches the first and second dd, as both are followed by another dd).

Body:
I am looking for a way to match a line that has two or more occurrences of a pattern (a word). Example:

abc cde abc dd

should be matched because the sequence abc is present twice. The sequences are always separated by a space. If it helps, it is enough to test for multiple presence of the first word.

Body:
Based on the sentence if it helps, I am ok, to test for multiple presence of the first sequence, I deduce that your primal interest was in matching the repeated words without such a limitation that the word is at the beginning of the line.

This will match all words which are repeated (it does not match the last repetition):

(\b\w+\b)(?=.*\b\1\b)

For instance, given the line

aaa abc dd cde abc dd cde fga dd hello

it matches abc, dd, cde, dd (yes, it matches the first and second dd, as both are followed by another dd).


问:
Visual studio 2013 web form and design view equivalent in Visual studio 2019?
I'm following an ASP.NET course series where the instructor uses Visual Studio 2013, and I can't figure out what the equivalent is in 2019 for the settings he uses. He creates a new ASP.NET Web Application, then picks the Empty template, but there are additional options that I can't see when creating mine, specifically the web forms box.

Web form (https://i.imgur.com/63lAKSg.png)

I tried to do the same, but when he continues he is able to "Add a web form" to the project. He creates a web form with the .aspx extension.

Web form (https://i.imgur.com/rSgtqlT.png)

He is also able to enter a design view mode, which I can't see. I can right click html or htmlcs files and open them with a web forms editor option, but at that point all the HTML items in my toolbox disappear(pointer, button, textarea, input, etc.). I tried to pick the ASP.NET Web application template as well but it didn't make a difference with my issue.

Design mode (https://i.imgur.com/q5uL2UI.png)

Or would it be better to just use VS 2013 for this course?

答:
OP is requesting comparison between the "New Project" gui wizard steps, for Visual Studio 2019 (vs-2019) to pre-2019 versions. The request also has a student learning context.

Please find an example doing that for the task of creating a "Web Forms with Master" application with vs-2019 mapped to vs-2015, using:
Murach's ASP.NET 4.6 with C# 2015,
Microsoft Visual Studio Community 2019,
Visual Studio 16.4.3

The vs-2015 version has an option for the user to create a web forms with master application. The button "Web Form with Master" is routinely illustrated in books and online tutorials, walking learners through step-by-step to reach an intended result. That button is gone, the feature is not gone.

The web form with master option in vs-2019 is called "Web API" and can be enabled on the "Create New Web Application" wizard/gui screen.

 "Web Web Form with Master Page" button has become  in vs-2019.

Mapping Steps

See illustrations to create a Master Page ASP.NET application in vs-2019. How to enable Web API and Site.Master

With vs-2019 running, a user activates the new project gui/wizard with the following toolbar selections: File -> New -> Project...

Wizard/GUI vs-2019

Create a New Project in ~ image 3 missing ~ next ~ ASP.NET Web Application (DOT.NET) ~  ~ next ~ Configure your new project ~~ (i.e., name it, and set file system path) ~  ~ next ~ Create a new ASP.NET Web Application ~ Web Forms ~~ Add folders & core references ~~ [ Checkbox ] Web API

The resulting
The resulting

add dots to see missing image three: i stack imgur com/FpKBb png


问:
Dask parallel processing is much slower than using pathos multiprocessing
I am a relative newbie using dask and I was trying to understand how can I leverage dask multiprocessing up and above pathos multiprocessing. To my surprise dask is 3-4 times slower than pathos. I am clearly doing something wrong and would appreciate any guidance on this.

Below is the code where I am trying to set up a trivial arithmetic manipulation:

```<code>from pathos.multiprocessing import ProcessingPool as Pool
import pandas as pd, numpy as np,time
from dask import dataframe as dd
from dask.multiprocessing import get
from multiprocessing import cpu_count
nCores = cpu_count()

class test_pathos:
    def __init__(self):
        self.NumCols = 270
        self.NumRows = 250000
        self.cols = ['Col'+ str(i) for i in range(self.NumCols)]
        self.data = pd.DataFrame(np.random.randint(0,5,size=(self.NumRows,self.NumCols)),columns=self.cols)

    def ProcessCol(self,x):
        colname = x.name
        DQCol = colname + r'_DQ'
        self.data.loc[:, DQCol] = self.data[colname] + 1

    def AddTodata(self,colname):
        DQColumn = colname+r'_DQ'
        self.data.loc[:,DQColumn] = self.data[colname]+1
        return self.data[DQColumn]

    def AddProcess(self):
        p = Pool(nodes = nCores)
        ChangedCols = p.map(self.AddTodata,self.cols)
        ChangedColsDf = pd.concat(ChangedCols,axis=1)
        self.data = pd.concat([self.data,ChangedColsDf],axis=1)

    def AddProcess_apply(self):
        '---self.data.apply(self.ProcessCol)'
        dd.from_pandas(self.data, npartitions=nCores).map_partitions(lambda df : df.apply(self.ProcessCol)).compute(scheduler='processes')

'----------------------------------------------------MAIN---------------------------------------------------------------------'
if __name__ == "__main__":
    test_obj = test_pathos()
    tinit = time.time()
    shapebeforetransmutation = test_obj.data.shape
    test_obj.AddProcess()
    shapeaftertransmutation = test_obj.data.shape
    print('Pathos call time is :', time.time() - tinit)
    tinit = time.time()
    test_obj.AddProcess_apply()
    print('Dask call time is : ', time.time() - tinit)
</code>```

答:
Performance depends on many things.  It could be overheads, data transfers, or anything else.  Unfortunately it's not very easy to tell without actually redoing your experiment.

For more understanding on Dask performance I recommend reading through the docs Understanding Performance

Body:
I am a relative newbie using dask and I was trying to understand how can I leverage dask multiprocessing up and above pathos multiprocessing. To my surprise dask is 3-4 times slower than pathos. I am clearly doing something wrong and would appreciate any guidance on this.

Below is the code where I am trying to set up a trivial arithmetic manipulation:

from pathos.multiprocessing import ProcessingPool as Pool
import pandas as pd, numpy as np,time
from dask import dataframe as dd
from dask.multiprocessing import get
from multiprocessing import cpu_count
nCores = cpu_count()

class test_pathos:
    def __init__(self):
        self.NumCols = 270
        self.NumRows = 250000
        self.cols = ['Col'+ str(i) for i in range(self.NumCols)]
        self.data = pd.DataFrame(np.random.randint(0,5,size=(self.NumRows,self.NumCols)),columns=self.cols)

    def ProcessCol(self,x):
        colname = x.name
        DQCol = colname + r'_DQ'
        self.data.loc[:, DQCol] = self.data[colname] + 1

    def AddTodata(self,colname):
        DQColumn = colname+r'_DQ'
        self.data.loc[:,DQColumn] = self.data[colname]+1
        return self.data[DQColumn]

    def AddProcess(self):
        p = Pool(nodes = nCores)
        ChangedCols = p.map(self.AddTodata,self.cols)
        ChangedColsDf = pd.concat(ChangedCols,axis=1)
        self.data = pd.concat([self.data,ChangedColsDf],axis=1)

    def AddProcess_apply(self):
        '---self.data.apply(self.ProcessCol)'
        dd.from_pandas(self.data, npartitions=nCores).map_partitions(lambda df : df.apply(self.ProcessCol)).compute(scheduler='processes')

'----------------------------------------------------MAIN---------------------------------------------------------------------'
if __name__ == "__main__":
    test_obj = test_pathos()
    tinit = time.time()
    shapebeforetransmutation = test_obj.data.shape
    test_obj.AddProcess()
    shapeaftertransmutation = test_obj.data.shape
    print('Pathos call time is :', time.time() - tinit)
    tinit = time.time()
    test_obj.AddProcess_apply()
    print('Dask call time is : ', time.time() - tinit)


问:
How do I use loop in the following problem?
I want to loop through some variables and create nine new variables which are equal to 1 if the first three variables are "433" or "434". I am using the following code but its showing 1 for everything, can someone help</p>

```<code>data icd_dim;
set asg3;
array icd (9) $ ICD9_DGNS_CD_1-ICD9_DGNS_CD_9;
array flag_icd (9) flag_icd_1-flag_icd_9;
do i = 1 to 9;
if icd(i)=substr(icd(i),1,3)="433" OR "434" then flag_icd(i)=1; end;
run;

</code>```

答:
You are looking for the IN operator to compare one value to a list of value.  Your current code is testing if "433" is True or False.  Since it is non-blank it is treated as True.

You want:

```<code>if substr(icd(i),1,3) in ("433" "434") then flag_icd(i)=1;
</code>```

Or to eliminate the missing values just assign the result of the test to the variable and get either 1 (true) or 0 (false).

```<code>flag_icd(i) =  substr(icd(i),1,3) in ("433" "434") ;
</code>```

Body:
I want to loop through some variables and create nine new variables which are equal to 1 if the first three variables are "433" or "434". I am using the following code but its showing 1 for everything, can someone help

data icd_dim;
set asg3;
array icd (9) $ ICD9_DGNS_CD_1-ICD9_DGNS_CD_9;
array flag_icd (9) flag_icd_1-flag_icd_9;
do i = 1 to 9;
if icd(i)=substr(icd(i),1,3)="433" OR "434" then flag_icd(i)=1; end;
run;

Body:
You are looking for the IN operator to compare one value to a list of value.  Your current code is testing if "433" is True or False.  Since it is non-blank it is treated as True.

You want:

if substr(icd(i),1,3) in ("433" "434") then flag_icd(i)=1;

Or to eliminate the missing values just assign the result of the test to the variable and get either 1 (true) or 0 (false).

flag_icd(i) =  substr(icd(i),1,3) in ("433" "434") ;


问:
store data into a text file using php?
i am trying to store data in a text file, something like an array into a text file using php instead of storing into mysql database.

for example here are the data to be stored in a text file

```<code>name=>john
age=>25
location=>australia
</code>```

then after saving it to a text file , how can I get the contents out and parse it with php , for like php can find the name , age and location and echo it out(something like parsing an array)

I need it for storing the data into a text file so it can be easily access from other domains without requiring to be on the same domain , connect to database , get the data from database. I am looking for a speedy solution. :)

I'm not sure which direction should I look into for this kind of functionality , hoping someone can point me out.

答:
You should make a uniqid then they won't be able to access any other txt files in the server.</p>

```<code><?php

    #Get a secure filename
    $username = "myUsername"
    $filename = uniqid($username, true).".txt";

    //Create the array
    $userInfo = ["username" => $username, "points" => 0];

    // Store the data
    file_put_contents($filename, serialize($userInfo));

    // How to get the data
    $userInfo = unserialize(file_get_contents($filename));
    print($userInfo["points"]);
    //or
    print($userInfo["username"]);

?>
</code>```

Title: store data into a text file using php?

Body:
i am trying to store data in a text file, something like an array into a text file using php instead of storing into mysql database.

for example here are the data to be stored in a text file

name=>john
age=>25
location=>australia

then after saving it to a text file , how can I get the contents out and parse it with php , for like php can find the name , age and location and echo it out(something like parsing an array)

I need it for storing the data into a text file so it can be easily access from other domains without requiring to be on the same domain , connect to database , get the data from database. I am looking for a speedy solution. :)

I'm not sure which direction should I look into for this kind of functionality , hoping someone can point me out.

Body:
You should make a uniqid then they won't be able to access any other txt files in the server.

<?php

    #Get a secure filename
    $username = "myUsername"
    $filename = uniqid($username, true).".txt";

    //Create the array
    $userInfo = ["username" => $username, "points" => 0];

    // Store the data
    file_put_contents($filename, serialize($userInfo));

    // How to get the data
    $userInfo = unserialize(file_get_contents($filename));
    print($userInfo["points"]);
    //or
    print($userInfo["username"]);

?>


问:
how does bastion know which rds instance to connect to in AWS
I am trying to set up a bastion host in AWS in order to perform administrative options on an RDS instance in a private subnet. I am following the instructions from the official documentation (https://docs.aws.amazon.com/quickstart/latest/linux-bastion/step1.html), but there it is not clear how the bastion will know which RDS instance to connect to. How would I make sure that it can 'talk to' my intended RDS? (as far as I understand, the key pair is just something I can create anytime and enter to connect to the bastion itself, but not the RDS, or am I wrong?)</p>

答:
The documentation you linked uses an AWS CloudFormation stack to deploy the Bastion. I'm not sure exactly what configuration it is using, so my answer will be generic, rather than applying to this specific situation.

The normal configuration is:

A database in a private subnet

A Bastion server (EC2 instance) in a public subnet

A connection is made to the Bastion, which then allows an on-connection to the database

There are a number of ways of connecting to the database through the Bastion. Here's one that I use:

```<code>ssh -i key.pem ec2-user@BASTION-IP -L 3306:DATABASE-DNS-NAME:3306
</code>```

This tells the SSH connection to forward any traffic sent to my local port 3306 (the first number), through the SSH connection, but then send it to DATABASE-DNS-NAME:3306 (the database server). Any response from the database will come back the same way.

Then, when I wish to refer to the database from my computer, I reference:

```<code>localhost:3306
</code>```

It appears that the database is on my own computer, but the traffic is actually sent across SSH to the Bastion, then onto the database.

There are newer and better ways of doing this forwarding that other people might (hopefully) add as a comment or another answer, but this is the way I make my connections through a Bastion.

Fun fact: A Bastion is the bit of a castle wall that sticks out, allowing defenders to shoot arrows at attackers attempting to climb the wall. In a similar way, the Bastion Server sticks out into the Internet, beyond the protected part of the network.

Body:
The documentation you linked uses an AWS CloudFormation stack to deploy the Bastion. I'm not sure exactly what configuration it is using, so my answer will be generic, rather than applying to this specific situation.

The normal configuration is:

A database in a private subnet

A Bastion server (EC2 instance) in a public subnet

A connection is made to the Bastion, which then allows an on-connection to the database

There are a number of ways of connecting to the database through the Bastion. Here's one that I use:

ssh -i key.pem ec2-user@BASTION-IP -L 3306:DATABASE-DNS-NAME:3306

This tells the SSH connection to forward any traffic sent to my local port 3306 (the first number), through the SSH connection, but then send it to DATABASE-DNS-NAME:3306 (the database server). Any response from the database will come back the same way.

Then, when I wish to refer to the database from my computer, I reference:

localhost:3306

It appears that the database is on my own computer, but the traffic is actually sent across SSH to the Bastion, then onto the database.

There are newer and better ways of doing this forwarding that other people might (hopefully) add as a comment or another answer, but this is the way I make my connections through a Bastion.

Fun fact: A Bastion is the bit of a castle wall that sticks out, allowing defenders to shoot arrows at attackers attempting to climb the wall. In a similar way, the Bastion Server sticks out into the Internet, beyond the protected part of the network.


问:
Hello world flask app stops working when customizing host to "0.0.0.0"
If you initialize the default PyCharm Flask starter project, or just follow the first section that starts up "hello world" or just this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

```

<p>you'll have the same code as me. And it works fine, until I change the <code>host</code> argument to <code>0.0.0.0</code>, and then the application starts up like this:</p>

<pre class="lang-sh prettyprint-override"><code>$ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
</code>```

And then when I go to that link, I get an invalid address error:

I need to use 0.0.0.0 instead of 127.0.0.1 because that's the IP address AWS uses for open connections.

How can I even start to get the 0.0.0.0 address to work locally?

I'm working on Windows.

答:
0.0.0.0 mean all IPv4 address , so it's incorrect to use it as a destination or a host address it's generally used to specify all ip  source ip addresses for I coming address ,

So should either give 127.0.0.1 or your machine ip adddress
[Link]https://www.rfc-editor.org/rfc/rfc5735

Body:
If you initialize the default PyCharm Flask starter project, or just follow the first section that starts up "hello world" or just this:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello World!'

if __name__ == '__main__':
    app.run()

you'll have the same code as me. And it works fine, until I change the host argument to 0.0.0.0, and then the application starts up like this:

$ python app.py
 * Serving Flask app "app" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)

And then when I go to that link, I get an invalid address error:

I need to use 0.0.0.0 instead of 127.0.0.1 because that's the IP address AWS uses for open connections.

How can I even start to get the 0.0.0.0 address to work locally?

I'm working on Windows.


问:
Deleting Rows via For-Loop (within a multi Area Range)
Usually, I would delete Rows using a For-Loop with row-numbers by working backward, which would look similar to this:

```<code>For rowIndex = 10 to 1 Step (-1)
    'delete Row with current row index
    next rowIndex
</code>```

How do I do this while cycling through a specified cell range? The following code obviously won't work (it will skip a cell/row in the next iteration when the delete command has been executed, check here or here):

```<code>Dim someRange as Range
'Note: someRange might be a multi area range (multiple unadjoined cells) within one sheet
Dim singleCell as Range
For each singleCell In SomeRange.Cells
    'check for some condition e.g. based (but not limited to) the singleCell's value
    If condition = True then
        singleCell.EntireRow.Delete
        'Note: the deletion has to be done before the next loop-iteration starts
               'Unfortunately, this makes solutions like working with Union unfeasible
        End If
    Next singleCell
</code>```

Has anyone an idea how to make the second code block work without switching to a "Backward-Row-Number-Loop" (see first code block)? Is there a way to somehow "reset" the singleCell-pointer/counter to a new value so the loop does not skip the next cell/row? Or any other alternative (like make the Range-Loop work backward etc.)? Any hint for a solution would be appreciated, a code snipped as well but if necessary I can do without.

I have to avoid adding the undesired row into an array (range etc.) and deleting the whole array after the loop is done. Unfortunately as a condition for the implementation the row has to be deleted before the next cell is evaluated.

Essentially there might be a case where two cell which rows ought to be deleted will be in the same row. In this case the 2nd cell will be deleted before it's even checked, that's desired behaviour. The solution does not have to but should be expandable to include this case.

EDIT: Another solution I'm thinking about is reversing the range before doing the For-Loop (see here), so far I haven't tried it out though.

答:
'If you are deleting rows downwards based on a criteria, the row number of the next row to be evaluated will be the same as the current deleted row number.

'Please try following.

```<code>Sub test()

Dim someRange As Range
'Note: someRange might be a multi area range (multiple unadjoined cells)
within one sheet
Set someRange = Range("B1:B18")
J = someRange.Rows.Count
Dim i As Long
i = 1
Dim singleCell As Long
For singleCell = 1 To someRange.Rows.Count
'check for some condition
If someRange.Cells(singleCell, 1) = 0 Then
    someRange.Cells(singleCell, 1).EntireRow.Delete
    'now as the row is deleted you should reset the value of singleCell
    singleCell = singleCell - 1
    'Note: the deletion has to be done before the next loop-iteration starts
    End If

    i = i + 1
    If i = J Then Exit For
    'someRange.Rows.Count will be the max number of rows to be evaluated
    'otherwise there will be infinite loop and macro wont stop

Next

End Sub
</code>```

Body:
Usually, I would delete Rows using a For-Loop with row-numbers by working backward, which would look similar to this:

For rowIndex = 10 to 1 Step (-1)
    'delete Row with current row index
    next rowIndex

How do I do this while cycling through a specified cell range? The following code obviously won't work (it will skip a cell/row in the next iteration when the delete command has been executed, check here or here):

Dim someRange as Range
'Note: someRange might be a multi area range (multiple unadjoined cells) within one sheet
Dim singleCell as Range
For each singleCell In SomeRange.Cells
    'check for some condition e.g. based (but not limited to) the singleCell's value
    If condition = True then
        singleCell.EntireRow.Delete
        'Note: the deletion has to be done before the next loop-iteration starts
               'Unfortunately, this makes solutions like working with Union unfeasible
        End If
    Next singleCell

Has anyone an idea how to make the second code block work without switching to a "Backward-Row-Number-Loop" (see first code block)? Is there a way to somehow "reset" the singleCell-pointer/counter to a new value so the loop does not skip the next cell/row? Or any other alternative (like make the Range-Loop work backward etc.)? Any hint for a solution would be appreciated, a code snipped as well but if necessary I can do without.

I have to avoid adding the undesired row into an array (range etc.) and deleting the whole array after the loop is done. Unfortunately as a condition for the implementation the row has to be deleted before the next cell is evaluated.

Essentially there might be a case where two cell which rows ought to be deleted will be in the same row. In this case the 2nd cell will be deleted before it's even checked, that's desired behaviour. The solution does not have to but should be expandable to include this case.

EDIT: Another solution I'm thinking about is reversing the range before doing the For-Loop (see here), so far I haven't tried it out though.

Body:
'If you are deleting rows downwards based on a criteria, the row number of the next row to be evaluated will be the same as the current deleted row number.

'Please try following.

Sub test()

Dim someRange As Range
'Note: someRange might be a multi area range (multiple unadjoined cells)
within one sheet
Set someRange = Range("B1:B18")
J = someRange.Rows.Count
Dim i As Long
i = 1
Dim singleCell As Long
For singleCell = 1 To someRange.Rows.Count
'check for some condition
If someRange.Cells(singleCell, 1) = 0 Then
    someRange.Cells(singleCell, 1).EntireRow.Delete
    'now as the row is deleted you should reset the value of singleCell
    singleCell = singleCell - 1
    'Note: the deletion has to be done before the next loop-iteration starts
    End If

    i = i + 1
    If i = J Then Exit For
    'someRange.Rows.Count will be the max number of rows to be evaluated
    'otherwise there will be infinite loop and macro wont stop

Next

End Sub


问:
Function is not returning 'China UnionPay', not sure why
My function takes in a card number that is a string and returns the name of the card. Every card seems to be working but the China Pay one. I am getting undefined, not sure why. There are about 800 China Pay prefixes. I iterated through those 800 numbers and pushed them in to an empty array that I then searched the index of. If it matches one of the prefixes in the array and one of the two lengths it should return the name but its not.  </p>

<p>Any help would be greatly appreciated. I am sure there is a more efficient way to do this but this is where my brain went. It should work, not sure why it's not. </p>

```<code>  // loop through the 800 numbers and push to an empty array
  var chinaPayPrefix = [];
  for (let i = 622126; i <= 622925; i++){
    let chinaPayStringOne = i.toString();
    chinaPayPrefix.push(chinaPayStringOne);
  }
  for (let j = 6282; j <= 6288; j++){
    let chinaPayStringTwo = j.toString();
    chinaPayPrefix.push(chinaPayStringTwo);
  }
  // card lengths
  const discoverCardLength = [16,19];
  const maestroCardLength = [12,13,14,15,16,17,18,19];
  const visaCardLength = [13,16,19];
  const masterCardLength = 16;
  const dinersCardLength = 14;
  const americanExpressLength = 15;
  const chinaPayLength = [16,19];
  // card prefixes
  const discoverPrefix = ['6011','644','645','646','647','648','649','65'];
  const maestroPrefix = ['5018','5020','5038','6304'];
  const visaPrefix = ['4'];
  const mastercardPrefix = ['51','52','53','54','55'];
  const dinersPrefix = ['38', '39'];
  const americanExpressPrefix = ['34', '37'];
  // substrings of cardNumber
  let singleSplit = cardNumber.substring(0,1);
  let doubleSplit = cardNumber.substring(0,2);
  let tripleSplit = cardNumber.substring(0,3);
  let quadSplit = cardNumber.substring(0,4);
  let sextupleSplit = cardNumber.substring(0,7);
  // search if the applicable substring is present and length is correct
  if (dinersPrefix.indexOf(doubleSplit) > -1 && cardNumber.length === dinersCardLength) {
    return 'Diner\'s Club';
  } else if (americanExpressPrefix.indexOf(doubleSplit) > -1 && cardNumber.length === americanExpressLength) {
    return 'American Express';
  } else if (visaPrefix.indexOf(singleSplit) > -1 && visaCardLength.indexOf(cardNumber.length) > - 1){
    return 'Visa';
  } else if (mastercardPrefix.indexOf(doubleSplit) > -1 && cardNumber.length === masterCardLength){
    return 'MasterCard';
  } else if (discoverPrefix.indexOf(doubleSplit) > -1 || discoverPrefix.indexOf(tripleSplit) > -1 || discoverPrefix.indexOf(quadSplit) > -1 && discoverCardLength.indexOf(cardNumber.length) > - 1){
    return 'Discover';
  } else if (maestroPrefix.indexOf(quadSplit) > - 1 && maestroCardLength.indexOf(cardNumber.length) > - 1){
    return 'Maestro';
  } else if (chinaPayPrefix.indexOf(sextupleSplit) > - 1 && chinaPayLength.indexOf(cardNumber.length) > - 1){
    return 'China UnionPay';
  }else if (chinaPayPrefix.indexOf(quadSplit) > - 1 && chinaPayLength.indexOf(cardNumber.length) > - 1){
    return 'China UnionPay';
  }else if (chinaPayPrefix.indexOf(tripleSplit) > - 1 && chinaPayLength.indexOf(cardNumber.length) > - 1){
    return 'China UnionPay';
  }
};
</code>```

答:
```<code>let sextupleSplit = cardNumber.substring(0,7);
</code>```

should be

```<code>let sextupleSplit = cardNumber.substring(0,6);
</code>```

to only take the first 6 digits

quadSplit and tripleSplit are ok

Body:
My function takes in a card number that is a string and returns the name of the card. Every card seems to be working but the China Pay one. I am getting undefined, not sure why. There are about 800 China Pay prefixes. I iterated through those 800 numbers and pushed them in to an empty array that I then searched the index of. If it matches one of the prefixes in the array and one of the two lengths it should return the name but its not.

Any help would be greatly appreciated. I am sure there is a more efficient way to do this but this is where my brain went. It should work, not sure why it's not.

  // loop through the 800 numbers and push to an empty array
  var chinaPayPrefix = [];
  for (let i = 622126; i <= 622925; i++){
    let chinaPayStringOne = i.toString();
    chinaPayPrefix.push(chinaPayStringOne);
  }
  for (let j = 6282; j <= 6288; j++){
    let chinaPayStringTwo = j.toString();
    chinaPayPrefix.push(chinaPayStringTwo);
  }
  // card lengths
  const discoverCardLength = [16,19];
  const maestroCardLength = [12,13,14,15,16,17,18,19];
  const visaCardLength = [13,16,19];
  const masterCardLength = 16;
  const dinersCardLength = 14;
  const americanExpressLength = 15;
  const chinaPayLength = [16,19];
  // card prefixes
  const discoverPrefix = ['6011','644','645','646','647','648','649','65'];
  const maestroPrefix = ['5018','5020','5038','6304'];
  const visaPrefix = ['4'];
  const mastercardPrefix = ['51','52','53','54','55'];
  const dinersPrefix = ['38', '39'];
  const americanExpressPrefix = ['34', '37'];
  // substrings of cardNumber
  let singleSplit = cardNumber.substring(0,1);
  let doubleSplit = cardNumber.substring(0,2);
  let tripleSplit = cardNumber.substring(0,3);
  let quadSplit = cardNumber.substring(0,4);
  let sextupleSplit = cardNumber.substring(0,7);
  // search if the applicable substring is present and length is correct
  if (dinersPrefix.indexOf(doubleSplit) > -1 && cardNumber.length === dinersCardLength) {
    return 'Diner\'s Club';
  } else if (americanExpressPrefix.indexOf(doubleSplit) > -1 && cardNumber.length === americanExpressLength) {
    return 'American Express';
  } else if (visaPrefix.indexOf(singleSplit) > -1 && visaCardLength.indexOf(cardNumber.length) > - 1){
    return 'Visa';
  } else if (mastercardPrefix.indexOf(doubleSplit) > -1 && cardNumber.length === masterCardLength){
    return 'MasterCard';
  } else if (discoverPrefix.indexOf(doubleSplit) > -1 || discoverPrefix.indexOf(tripleSplit) > -1 || discoverPrefix.indexOf(quadSplit) > -1 && discoverCardLength.indexOf(cardNumber.length) > - 1){
    return 'Discover';
  } else if (maestroPrefix.indexOf(quadSplit) > - 1 && maestroCardLength.indexOf(cardNumber.length) > - 1){
    return 'Maestro';
  } else if (chinaPayPrefix.indexOf(sextupleSplit) > - 1 && chinaPayLength.indexOf(cardNumber.length) > - 1){
    return 'China UnionPay';
  }else if (chinaPayPrefix.indexOf(quadSplit) > - 1 && chinaPayLength.indexOf(cardNumber.length) > - 1){
    return 'China UnionPay';
  }else if (chinaPayPrefix.indexOf(tripleSplit) > - 1 && chinaPayLength.indexOf(cardNumber.length) > - 1){
    return 'China UnionPay';
  }
};

Body:
let sextupleSplit = cardNumber.substring(0,7);

should be

let sextupleSplit = cardNumber.substring(0,6);

to only take the first 6 digits

quadSplit and tripleSplit are ok


问:
Complex string match in SQL Query
I have a complex scenario for string matching and want input from you guys.
I have a table Named Customers. This table contains a field CustomerName varchar.
Data in the column is prefixed with Mr. Mrs. Ms.
Data could be

Mr. John Brady

Ms. Abraham Lenin

Mrs. John Brady

Mr. Michael King

Mrs. Neil Thomas

Mrs. Micheal King

Now I need to design a search query that returns me rows of only Couples and in a sequenced manner.

Like Select CustomerName from Customer where ...??
Result needs to be like

Mr. John Brady

Mrs. John Brady

Mr. Michael King

Mrs. Micheal King

Any Idea ?

Thanks in advance for the consideration.

答:
```<code>  WITH pattern_cnt
     AS (SELECT string_pattern,
                Count(string_pattern) AS CNT
         FROM   (SELECT Substr(NAME, Instr(NAME, '.') + 1) AS STRING_PATTERN
                 FROM   couples)
         GROUP  BY string_pattern),
     string_match
     AS (SELECT NAME,
                Substr(NAME, Instr(NAME, '.') + 1) AS PATTERN
         FROM   couples)
SELECT a.NAME
FROM   pattern_cnt b,
       string_match a
WHERE  a.pattern = b.string_pattern
       AND b.cnt > 1;
</code>```

Title: Complex string match in SQL Query


问:
Automator (2.5) Script to create folder based on file name and move file to folder
Thank you for taking the time to look.  I am trying to create a workflow using automator 2.5 that will read the video files in my directory, create a folder with the file name, and move the file into the newly created folder.  I have tried multiple scripts available online and encountered errors.  Then I created this hybrid script which does not error or do anything.  any assistance would be appreciated (I am not new to programming but inexperience with this version of automator)
<img src="https://i.stack.imgur.com/XymJT.png" alt="Screenshot of script"> </p>

答:
With your files selected in the front Finder window, running this following code in Script Editor.app should accomplish what you're looking to achieve</p>

```<code>tell application "Finder"
    activate
    set selectedFiles to selection as alias list
    set containingFolder to container of (item 1 of selectedFiles) --as alias
    repeat with i from 1 to count of selectedFiles
        set foldersRef to (a reference to folders of containingFolder)
        set foldersRefItems to name of (contents of foldersRef)
        set thisItem to item i of selectedFiles
        set fileName to (text items 1 thru -5) of (name of thisItem as text) as string
        if fileName is not in foldersRefItems then
            move thisItem to (make new folder at containingFolder ¬
                with properties {name:fileName})
        else
            move thisItem to folder fileName of containingFolder
        end if
    end repeat
end tell
</code>```

Body:
With your files selected in the front Finder window, running this following code in Script Editor.app should accomplish what you're looking to achieve

tell application "Finder"
    activate
    set selectedFiles to selection as alias list
    set containingFolder to container of (item 1 of selectedFiles) --as alias
    repeat with i from 1 to count of selectedFiles
        set foldersRef to (a reference to folders of containingFolder)
        set foldersRefItems to name of (contents of foldersRef)
        set thisItem to item i of selectedFiles
        set fileName to (text items 1 thru -5) of (name of thisItem as text) as string
        if fileName is not in foldersRefItems then
            move thisItem to (make new folder at containingFolder ¬
                with properties {name:fileName})
        else
            move thisItem to folder fileName of containingFolder
        end if
    end repeat
end tell


问:
How do I replace the deprecated "constructor" method for PHP7 in Wordpress?
I'm working on moving a site from a PHP5 server to a server with PHP7. My client is using a theme from the company Themelovin which appears to have gone dark. They have a few helper plugins like a Portfolio plugin, Twitter plugin and Teams plugin that come from a private repo with the purchase of a theme. I tried to get the latest version to see if it's been fixed but it hasn't.

Their Portfolio and Teams plugins both used an old constructor that is now deprecated with PHP7.

The original code looked like so:

```<code> class thmlv_widget_team extends WP_Widget{
   function thmlv_widget_team(){
     $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
     $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
     $this->WP_Widget('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
   }
</code>```

From what i've read, the issue here is the class "thmlv_widget_team" is the same name as the function. I am very poor at PHP but my understanding is that is the conflict. I read that you can fix this using __construct() and creating something that uses that plus a backup however that still isn't working. This is what I have now:

```<code>class thmlv_widget_team extends WP_Widget{
    function __construct(){
      $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
      $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
      $this->WP_Widget('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
    }

    function thmlv_widget_team(){
      self::__construct();
    }
</code>```

Ultimately I created the function __construct() with the code and then had a fallback for the original function to reference the construct I created.

Can you assist in what i'm missing here? The error i'm getting is as follows:

Notice: The called constructor method for WP_Widget in thmlv_widget_team is deprecated since version 4.3.0! Use __construct() instead. in /wordpress/wp-includes/functions.php on line 4716

I don't know why it's referencing the functions.php file but i'm updated to the latest version of Wordpress (5.3.2).

This is the Wordpress Theme in use.

https://themeforest.net/item/tag-creative-agencyportfolio-fullscreen-theme/9294146

答:
Hi from a quick look i think that this

```<code>class thmlv_widget_team extends WP_Widget{
   function thmlv_widget_team(){
     $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
     $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
     $this->WP_Widget('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
   }
</code>```

shoud be this

```<code>class thmlv_widget_team extends WP_Widget{
   function thmlv_widget_team(){
     $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
     $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
     parent::__construct('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
   }
</code>```

more info https://mainwp.com/notice-the-called-constructor-method-for-wp_widget-is-deprecated-since-version-4-3-0-use-__construct/

Body:
I'm working on moving a site from a PHP5 server to a server with PHP7. My client is using a theme from the company Themelovin which appears to have gone dark. They have a few helper plugins like a Portfolio plugin, Twitter plugin and Teams plugin that come from a private repo with the purchase of a theme. I tried to get the latest version to see if it's been fixed but it hasn't.

Their Portfolio and Teams plugins both used an old constructor that is now deprecated with PHP7.

The original code looked like so:

 class thmlv_widget_team extends WP_Widget{
   function thmlv_widget_team(){
     $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
     $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
     $this->WP_Widget('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
   }

From what i've read, the issue here is the class "thmlv_widget_team" is the same name as the function. I am very poor at PHP but my understanding is that is the conflict. I read that you can fix this using __construct() and creating something that uses that plus a backup however that still isn't working. This is what I have now:

class thmlv_widget_team extends WP_Widget{
    function __construct(){
      $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
      $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
      $this->WP_Widget('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
    }

    function thmlv_widget_team(){
      self::__construct();
    }

Ultimately I created the function __construct() with the code and then had a fallback for the original function to reference the construct I created.

Can you assist in what i'm missing here? The error i'm getting is as follows:

Notice: The called constructor method for WP_Widget in thmlv_widget_team is deprecated since version 4.3.0! Use __construct() instead. in /wordpress/wp-includes/functions.php on line 4716

I don't know why it's referencing the functions.php file but i'm updated to the latest version of Wordpress (5.3.2).

This is the Wordpress Theme in use.

https://themeforest.net/item/tag-creative-agencyportfolio-fullscreen-theme/9294146

Body:
Hi from a quick look i think that this

class thmlv_widget_team extends WP_Widget{
   function thmlv_widget_team(){
     $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
     $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
     $this->WP_Widget('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
   }

shoud be this

class thmlv_widget_team extends WP_Widget{
   function thmlv_widget_team(){
     $widget_ops = array('classname' => 'team-items', 'description' => __('Display team members.', 'themelovin'));
     $control_ops = array('width' => 300, 'height' => 350, 'id_base' => 'thmlv_widget_team');
     parent::__construct('thmlv_widget_team', __('Themelovin Team', 'themelovin'), $widget_ops, $control_ops);
   }

more info https://mainwp.com/notice-the-called-constructor-method-for-wp_widget-is-deprecated-since-version-4-3-0-use-__construct/