问:
Status Listbox update problem using a Background Worker in C#
I'm trying to use a background worker to update a listbox used for a status window in my Form in C#. It doesn't appear to work properly when the addToStausLog() method is called from another class outside of the MyForm class even though I pass an instance of the form to the other class that's calling the addToStatusLog update member. Instead the update doesn't happen until the class member finished and returns back to the MyForm class. Maybe there's a better a approach to creating real-time status windows that will run from any class that MyForm is passed into. I'm new to worker threads, so could someone review and let me know what I might be doing wrong or could improve on.

```<code>        public MyForm()
        {
            InitializeComponent();

            // Setup background task to update listbox status so UI is unaffected
            _lListBoxQue = new List<string>();
            bw_listBoxBGWorker = new BackgroundWorker();
            bw_listBoxBGWorker.DoWork += (o, args) => LstbxThread_doWork();
            bw_listBoxBGWorker.RunWorkerCompleted += (o, args) => LstbxThread_completed();
        }

        private void LstbxThread_doWork()
        {
            System.Threading.Thread.Sleep(100);
        }

        private void LstbxThread_completed()
        {
            // Update listbox
            lstStatusBox.BeginUpdate();
            lstStatusBox.Items.Clear(); // clear entries
            lstStatusBox.Items.AddRange(_lListBoxQue.ToArray());
            lstStatusBox.EndUpdate();
        }

        public String addToStatusLog(String sMsg)
        {
            _lListBoxQue.Add(sMsg);
            if (_lListBoxQue.Count > _iStatusLogMaxLines)    // > max?
                _lListBoxQue.RemoveAt(0); // remove top element?

            if( !bw_listBoxBGWorker.IsBusy )    // background not busy?
                bw_listBoxBGWorker.RunWorkerAsync();    // update listbox in back ground task
            System.Threading.Thread.Sleep(100);
            return sMsg;
        }
</code>```

This is the member that calls another class which attempts to call the addToStatusLog several times during the process, but the updates to the listbox don't happen until the MyClass(this).updateDB() finishes. I need to see real-time updates as the updateDB() function is running. There has to be a way to make this work, I'm hoping...

```<code>        private void btnUpdateDB_Click(object sender, EventArgs e)
        {
        if (_bIsUpdateEventRunning == false ) // is event not busy?
        {
            _bIsUpdateEventRunning = true;
            new MyClass(this).updateDB();
            _bIsUpdateEventRunning = false;
        }

        }
</code>```

Example of class called to update the form listbox.

```<code>    Public class MyClass{

            private MyForm _pForm;

            public MyClass(MyForm pForm){ _pForm= pForm; }

            public void updateDB(){
                _pForm.addToStatusLog("Hello World");
            }

    }
</code>```

Updated Fix w/o background worker:

```<code>        public String addToStatusLog(String sMsg)
        {
            _lListBoxQue.Add(sMsg);
            if (_lListBoxQue.Count > _iStatusLogMaxLines)    // > max?
                _lListBoxQue.RemoveAt(0); // remove top element?

            lstStatusBox.BeginUpdate();
            lstStatusBox.Items.Clear(); // clear entries
            lstStatusBox.Items.AddRange(_lListBoxQue.ToArray());
            lstStatusBox.EndUpdate();
            Application.DoEvents();

            return sMsg;
        }
</code>```

答:
Thread.Sleep is not the answer here. What you likely need is Application.DoEvents. This processes all messages currently waiting in the Windows message queue.

Thread.Sleep just tells the thread to go to sleep for the number of milliseconds you specify. If your background worker is running on the UI thread, you're putting the UI thread to sleep and it's effectively comatose. (Important: All Windows forms run on the UI thread.)

There are, of course, alternative designs that involve spinning up separate threads of execution. But these have their own issues, and you should be mindful of them before running blindly down that path.

Body:
I'm trying to use a background worker to update a listbox used for a status window in my Form in C#. It doesn't appear to work properly when the addToStausLog() method is called from another class outside of the MyForm class even though I pass an instance of the form to the other class that's calling the addToStatusLog update member. Instead the update doesn't happen until the class member finished and returns back to the MyForm class. Maybe there's a better a approach to creating real-time status windows that will run from any class that MyForm is passed into. I'm new to worker threads, so could someone review and let me know what I might be doing wrong or could improve on.

        public MyForm()
        {
            InitializeComponent();

            // Setup background task to update listbox status so UI is unaffected
            _lListBoxQue = new List<string>();
            bw_listBoxBGWorker = new BackgroundWorker();
            bw_listBoxBGWorker.DoWork += (o, args) => LstbxThread_doWork();
            bw_listBoxBGWorker.RunWorkerCompleted += (o, args) => LstbxThread_completed();
        }

        private void LstbxThread_doWork()
        {
            System.Threading.Thread.Sleep(100);
        }

        private void LstbxThread_completed()
        {
            // Update listbox
            lstStatusBox.BeginUpdate();
            lstStatusBox.Items.Clear(); // clear entries
            lstStatusBox.Items.AddRange(_lListBoxQue.ToArray());
            lstStatusBox.EndUpdate();
        }

        public String addToStatusLog(String sMsg)
        {
            _lListBoxQue.Add(sMsg);
            if (_lListBoxQue.Count > _iStatusLogMaxLines)    // > max?
                _lListBoxQue.RemoveAt(0); // remove top element?

            if( !bw_listBoxBGWorker.IsBusy )    // background not busy?
                bw_listBoxBGWorker.RunWorkerAsync();    // update listbox in back ground task
            System.Threading.Thread.Sleep(100);
            return sMsg;
        }

This is the member that calls another class which attempts to call the addToStatusLog several times during the process, but the updates to the listbox don't happen until the MyClass(this).updateDB() finishes. I need to see real-time updates as the updateDB() function is running. There has to be a way to make this work, I'm hoping...

        private void btnUpdateDB_Click(object sender, EventArgs e)
        {
        if (_bIsUpdateEventRunning == false ) // is event not busy?
        {
            _bIsUpdateEventRunning = true;
            new MyClass(this).updateDB();
            _bIsUpdateEventRunning = false;
        }

        }

Example of class called to update the form listbox.

    Public class MyClass{

            private MyForm _pForm;

            public MyClass(MyForm pForm){ _pForm= pForm; }

            public void updateDB(){
                _pForm.addToStatusLog("Hello World");
            }

    }

Updated Fix w/o background worker:

        public String addToStatusLog(String sMsg)
        {
            _lListBoxQue.Add(sMsg);
            if (_lListBoxQue.Count > _iStatusLogMaxLines)    // > max?
                _lListBoxQue.RemoveAt(0); // remove top element?

            lstStatusBox.BeginUpdate();
            lstStatusBox.Items.Clear(); // clear entries
            lstStatusBox.Items.AddRange(_lListBoxQue.ToArray());
            lstStatusBox.EndUpdate();
            Application.DoEvents();

            return sMsg;
        }


来源: stackexchange

问:
Why can't Whole Module Optimalization infer final on public non-overridden module classes/methods in the same module?
From this article, I quote the following sentence:

Use Whole Module Optimization to infer final on internal declarations.
  Declarations with internal access (the default if nothing is declared)
  are only visible within the module where they are declared. Because
  Swift normally compiles the files that make up a module separately,
  the compiler cannot ascertain whether or not an internal declaration
  is overridden in a different file. However, if Whole Module
  Optimization is enabled, all of the module is compiled together at the
  same time. This allows the compiler to make inferences about the
  entire module together and infer final on declarations with internal
  if there are no visible overrides.
       Let’s go back to the original code snippet, this time adding some extra public keywords to ParticleModel.

```<code>public class ParticleModel {
    var point = ( x: 0.0, y: 0.0 )
    var velocity = 100.0

    func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
        point = newPoint
        velocity = newVelocity
    }

    public func update(newP: (Double, Double), newV: Double) {
        updatePoint(newP, newVelocity: newV)
    }
}

var p = ParticleModel()
for i in stride(from: 0.0, through: times, by: 1.0) {
    p.update((i * sin(i), i), newV:i*1000)
}
</code>```

When compiling this snippet with Whole Module Optimization the
  compiler can infer final on the properties point, velocity, and the
  method call updatePoint(). In contrast, it can not be inferred that
  update() is final since update() has public access.

Why can't WMO static dispatch a call to update() if ParticalModel isn't overridden in the current module? It is not allowed to override ParicleModel in other modules (since it's access modifier is public, not open). I would expect that every method and property in the class can have final inferred because it isn't overridden in the current module, but the documentation explicitly mentions that it can not infer final.

答: The linked article was written for Swift 2, which predates the introduction of the open access level in Swift 3 (SE-0117). Therefore what it refers to as public is now semantically what the open access level is. You're indeed correct that a call to a public member will now be statically dispatched with whole module optimisation enabled if the compiler can prove it is not overriden within the same module.

ContentLicense: CC BY-SA 4.0

Body:
From this article, I quote the following sentence:

Use Whole Module Optimization to infer final on internal declarations.
  Declarations with internal access (the default if nothing is declared)
  are only visible within the module where they are declared. Because
  Swift normally compiles the files that make up a module separately,
  the compiler cannot ascertain whether or not an internal declaration
  is overridden in a different file. However, if Whole Module
  Optimization is enabled, all of the module is compiled together at the
  same time. This allows the compiler to make inferences about the
  entire module together and infer final on declarations with internal
  if there are no visible overrides.
       Let’s go back to the original code snippet, this time adding some extra public keywords to ParticleModel.

public class ParticleModel {
    var point = ( x: 0.0, y: 0.0 )
    var velocity = 100.0

    func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
        point = newPoint
        velocity = newVelocity
    }

    public func update(newP: (Double, Double), newV: Double) {
        updatePoint(newP, newVelocity: newV)
    }
}

var p = ParticleModel()
for i in stride(from: 0.0, through: times, by: 1.0) {
    p.update((i * sin(i), i), newV:i*1000)
}

When compiling this snippet with Whole Module Optimization the
  compiler can infer final on the properties point, velocity, and the
  method call updatePoint(). In contrast, it can not be inferred that
  update() is final since update() has public access.

Why can't WMO static dispatch a call to update() if ParticalModel isn't overridden in the current module? It is not allowed to override ParicleModel in other modules (since it's access modifier is public, not open). I would expect that every method and property in the class can have final inferred because it isn't overridden in the current module, but the documentation explicitly mentions that it can not infer final.


问:
Filter one column by matching to another column
I have a data frame with a variable containing elements to drop if they match to an element in another variable - see a small example below:

df <- data.frame(pair = c(1, 1, 2, 2, 3, 3),
                 animal = rep(c("dog", "cat"), 3),
                 value = seq(1, 12, 2),
                 drop = c("no", "no", "dog", "dog", "cat", "cat"))

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
3    2    dog     5  dog
4    2    cat     7  dog
5    3    dog     9  cat
6    3    cat    11  cat
```

<p>I'm trying to want to filter the data frame according to whether the value of <code>animal</code> matches the value of <code>drop</code>. I want something like <code>filter(df, animal != drop)</code> to remove rows where only the value of animal matches the value of drop:</p>

<pre class="lang-r prettyprint-override"><code>  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
4    2    cat     7  dog
5    3    dog     9  cat
</code>```

I also tried writing a simple loop to test whether animal matches drop for each row and remove the row if true, but I couldn't get it working. (I'm not very confident with loops and would prefer not to use one if possible as my data frame is very large but I was getting desperate!)

for(i in nrow(df)){
  if(df$animal[i] == df$drop[i]){
    df <- df[-i,]
    return(df)
  }
}
```

Is there a way of doing this using dplyr?

答:
The use of filter(df, animal != drop) is correct. However, as you haven't specified stringsAsFactors = F in your data.frame() call, all strings are converted to factors, raising the error of different level sets. Thus adding stringsAsFactors = F, should solve this

```<code>df <- data.frame(pair = c(1, 1, 2, 2, 3, 3),
                 animal = rep(c("dog", "cat"), 3),
                 value = seq(1, 12, 2),
                 drop = c("no", "no", "dog", "dog", "cat", "cat"),
                 stringsAsFactors = F)

df %>%
  filter(animal != drop)

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
3    2    cat     7  dog
4    3    dog     9  cat
</code>```

To avoid issues with this undesired string to factor behaviour I highly recommend the use of tibble

In case that one does not have the opportunity to change how the data is created I here include @akrun's solution:

```<code>library(dplyr)

df %>%
  mutate_at(vars(animal, drop), as.character) %>%
  filter(animal != drop)
#  pair animal value drop
#1    1    dog     1   no
#2    1    cat     3   no
#3    2    cat     7  dog
#4    3    dog     9  cat
</code>```

Body:
I have a data frame with a variable containing elements to drop if they match to an element in another variable - see a small example below:

df <- data.frame(pair = c(1, 1, 2, 2, 3, 3),
                 animal = rep(c("dog", "cat"), 3),
                 value = seq(1, 12, 2),
                 drop = c("no", "no", "dog", "dog", "cat", "cat"))

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
3    2    dog     5  dog
4    2    cat     7  dog
5    3    dog     9  cat
6    3    cat    11  cat

I'm trying to want to filter the data frame according to whether the value of animal matches the value of drop. I want something like filter(df, animal != drop) to remove rows where only the value of animal matches the value of drop:

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
4    2    cat     7  dog
5    3    dog     9  cat

I also tried writing a simple loop to test whether animal matches drop for each row and remove the row if true, but I couldn't get it working. (I'm not very confident with loops and would prefer not to use one if possible as my data frame is very large but I was getting desperate!)

for(i in nrow(df)){
  if(df$animal[i] == df$drop[i]){
    df <- df[-i,]
    return(df)
  }
}

Is there a way of doing this using dplyr?

Body:
The use of filter(df, animal != drop) is correct. However, as you haven't specified stringsAsFactors = F in your data.frame() call, all strings are converted to factors, raising the error of different level sets. Thus adding stringsAsFactors = F, should solve this

df <- data.frame(pair = c(1, 1, 2, 2, 3, 3),
                 animal = rep(c("dog", "cat"), 3),
                 value = seq(1, 12, 2),
                 drop = c("no", "no", "dog", "dog", "cat", "cat"),
                 stringsAsFactors = F)

df %>%
  filter(animal != drop)

  pair animal value drop
1    1    dog     1   no
2    1    cat     3   no
3    2    cat     7  dog
4    3    dog     9  cat

To avoid issues with this undesired string to factor behaviour I highly recommend the use of tibble

In case that one does not have the opportunity to change how the data is created I here include @akrun's solution:

library(dplyr)

df %>%
  mutate_at(vars(animal, drop), as.character) %>%
  filter(animal != drop)
#  pair animal value drop
#1    1    dog     1   no
#2    1    cat     3   no
#3    2    cat     7  dog
#4    3    dog     9  cat


问:
wxPython: Create a log system
I have an application that calls another script when clicking on a button. On that script, I have some prints that I would like to display on a wx.TextCtrl widget on the application but I have no clue where to start.

This is an example of the script called:

```<code>#export.py

def exportData():
    #some code
    #Some prints that I would like to display on the application
</code>```

And here is how I call the script from the application:

```<code>def loadData(self, event):
    from export import exportData
    exportData()
</code>```

I have some questions:

I assume that print won't work as a log, and I have to use some kind of logging system. Is that correct? I've tried to use log.write but I keep getting "log not defined error".

Maybe calling exportData() directly from def loadData isn't the best way to proceed. If it's the case, what is the correct way?

Finally, How can I display the prints/logs into the wx.TextCtrl widget of the application?

Don't hesitate if you need more information. Thank you in advance for your help.

EDIT

Here is a minimalist working example code of what I'm trying to do. Printing "This is my log" in the main.py TextCtrl.

```<code># main.py
import wx, sys
import export

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        log = wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.TE_READONLY)

        button = wx.Button(panel, label="Export", pos=(80, 80), size=(120, 30))

        self.Bind(wx.EVT_BUTTON, self.export, button)

        mySizer = wx.BoxSizer(wx.VERTICAL)
        mySizer.Add(button, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        mySizer.Add(log, 0, wx.ALL | wx.ALIGN_CENTER, 5)

        panel.SetSizer(mySizer)

    def export(self, event):
        from export import exportData
        exportData()

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()
</code>```

and the export file:

```<code>#export.py

def exportData():
    print("This is my log")
</code>```

答:
Firstly, congratulations on engineering the following statement import export, it makes me smile each time I see it.

Are you attempting something like this?

Here is your amended code to do that:

```<code># main.py
import wx, sys
from export import exportData

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        self.log = wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.TE_READONLY, size=(180,100))
        button = wx.Button(panel, label="Export")
        self.Bind(wx.EVT_BUTTON, self.export, button)
        mySizer = wx.BoxSizer(wx.VERTICAL)
        mySizer.Add(button, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        mySizer.Add(self.log, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        panel.SetSizer(mySizer)

    def export(self, event):
        exportData(parent=self)

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()
</code>```

and the export.py

```<code>import time
import wx

def exportData(parent=None):
    if not parent:
        return
    log = []
    print("This is my log")
    parent.log.write("This is my log\n")
    #solely for the purpose of illustrating updates in real time use sleep between updates
    # and yield to the gui main loop
    # in real time operation remove the sleep commands
    wx.Yield()
    time.sleep(1)
    print("Log line 2")
    parent.log.write("Log line 2\n")
    wx.Yield()
    time.sleep(1)
    print("Log line 3")
    parent.log.write("Log line 3\n")
    wx.Yield()
    time.sleep(1)
    print("Export data has concluded")
</code>```

All that is happening here is we pass the parent to the function, which allows the updates to occur in real-time. The call to Yield passes control momentarily back to the wx.App.MainLoop for the update to be seen occurring, otherwise, although the update occurred, the result isn't seen, until the MainLoop takes back control.

Title: wxPython: Create a log system

Body:
I have an application that calls another script when clicking on a button. On that script, I have some prints that I would like to display on a wx.TextCtrl widget on the application but I have no clue where to start.

This is an example of the script called:

#export.py

def exportData():
    #some code
    #Some prints that I would like to display on the application

And here is how I call the script from the application:

def loadData(self, event):
    from export import exportData
    exportData()

I have some questions:

I assume that print won't work as a log, and I have to use some kind of logging system. Is that correct? I've tried to use log.write but I keep getting "log not defined error".

Maybe calling exportData() directly from def loadData isn't the best way to proceed. If it's the case, what is the correct way?

Finally, How can I display the prints/logs into the wx.TextCtrl widget of the application?

Don't hesitate if you need more information. Thank you in advance for your help.

EDIT

Here is a minimalist working example code of what I'm trying to do. Printing "This is my log" in the main.py TextCtrl.

# main.py
import wx, sys
import export

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        log = wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.TE_READONLY)

        button = wx.Button(panel, label="Export", pos=(80, 80), size=(120, 30))

        self.Bind(wx.EVT_BUTTON, self.export, button)

        mySizer = wx.BoxSizer(wx.VERTICAL)
        mySizer.Add(button, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        mySizer.Add(log, 0, wx.ALL | wx.ALIGN_CENTER, 5)

        panel.SetSizer(mySizer)

    def export(self, event):
        from export import exportData
        exportData()

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()

and the export file:

#export.py

def exportData():
    print("This is my log")

Body:
Firstly, congratulations on engineering the following statement import export, it makes me smile each time I see it.

Are you attempting something like this?

Here is your amended code to do that:

# main.py
import wx, sys
from export import exportData

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        self.log = wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.TE_READONLY, size=(180,100))
        button = wx.Button(panel, label="Export")
        self.Bind(wx.EVT_BUTTON, self.export, button)
        mySizer = wx.BoxSizer(wx.VERTICAL)
        mySizer.Add(button, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        mySizer.Add(self.log, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        panel.SetSizer(mySizer)

    def export(self, event):
        exportData(parent=self)

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()

and the export.py

import time
import wx

def exportData(parent=None):
    if not parent:
        return
    log = []
    print("This is my log")
    parent.log.write("This is my log\n")
    #solely for the purpose of illustrating updates in real time use sleep between updates
    # and yield to the gui main loop
    # in real time operation remove the sleep commands
    wx.Yield()
    time.sleep(1)
    print("Log line 2")
    parent.log.write("Log line 2\n")
    wx.Yield()
    time.sleep(1)
    print("Log line 3")
    parent.log.write("Log line 3\n")
    wx.Yield()
    time.sleep(1)
    print("Export data has concluded")

All that is happening here is we pass the parent to the function, which allows the updates to occur in real-time. The call to Yield passes control momentarily back to the wx.App.MainLoop for the update to be seen occurring, otherwise, although the update occurred, the result isn't seen, until the MainLoop takes back control.


问:
python multiprocessing workers till response 200
good day, I am new in python, i've tried my best to build code below:

```<code>import http.client
import random
import string
import multiprocessing

def worker():
    """worker function"""
    if res.status == 200:
        print("Valid key found: " + key + " Got status: ", + res.status)
    elif res.status == 302:
        print("invalid key! " + key + "!")
    return

def randomStringDigits(stringLength=6):
    """Generate a random string of letters and digits """
    lettersAndDigits = string.ascii_letters + string.digits
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))

key = randomStringDigits(14);

conn = http.client.HTTPSConnection("www.pra1ser.com", timeout=10)

payload = "comment_text=%40asnikuwait1%20test2&replied_to_comment_id="

headers = {
    'cookie': "md5=5; prm_124024574287414=base_domain=api.pra1ser.com; csrftoken=5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1; session=CVzZzZz%3A" + key + "%3A8;",
    'x-csrftoken': "5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1",
    'content-type': "application/x-www-form-urlencoded"
    }

conn.request("POST", "/web/comments/2050815839087051573/add/", payload, headers)

res = conn.getresponse()
data = res.read()

#print(data.decode("utf-8"))
#print(headers)
#print(res.status)

if __name__ == '__main__':
    jobs = []
    for i in range(100):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()
</code>```

I'd like to make it work multiprocessing with 100 workers infinite till it get response "200" from server, then it break.

I've tried while true, but i break the code, lot of errors. and i've tried to infinite loop but with failed attempt.

i wish somebody can helps me out please.

Thank you,
regards.
pra1

答:
```<code>#!/usr/bin/python
 import http.client
 import random
 import string
 import multiprocessing
 import sys
 import threading

 exitFlag = 0

def randomStringDigits(stringLength=6):
    """Generate a random string of letters and digits """
    lettersAndDigits = string.ascii_letters + string.digits
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))

def worker(event):
    """worker function"""

    key = randomStringDigits(14)

    conn = http.client.HTTPSConnection("google.com", timeout=60)

    payload = "comment_text=%40asnikuwait1%20test2&replied_to_comment_id="

    headers = {
    'cookie': "md5=5; prm_124024574287414=base_domain=api.pra1ser.com; csrftoken=5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1; session=CVzZzZz%3A" + key + "%3A8;",
    'x-csrftoken': "5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1",
    'content-type': "application/x-www-form-urlencoded"
}

    conn.request("POST", "/web/comments/2050815839087051573/add/",
             payload, headers)

    res = conn.getresponse()

    if res.status == 200:
        print("Valid key found: " + key + " Got status: " + res.status)
        event.set()
    elif res.status == 302:
        print("invalid key! " + key + "!")
    else:
        print("invalid key! " + key + "!")

class myThread (threading.Thread):
    def __init__(self, threadID, event):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.event = event

    def run(self):
        worker(self.event)

if __name__ == '__main__':

    jobs = []
    max_threads = 10

    # Create Event
    event = multiprocessing.Event()

    # Create two processes
    while not event.is_set():
        for i in range(max_threads):
            thread = myThread(i, event)
            thread.start()
            jobs.append(thread)

        for i in jobs:
            i.join()

    # Check whether event is set or not
    # When set close all child processes
    while True:
        if event.is_set():
            # Terminating main process
            print('Exiting Process...')
            sys.exit(1)
</code>```

Body:
good day, I am new in python, i've tried my best to build code below:

import http.client
import random
import string
import multiprocessing

def worker():
    """worker function"""
    if res.status == 200:
        print("Valid key found: " + key + " Got status: ", + res.status)
    elif res.status == 302:
        print("invalid key! " + key + "!")
    return

def randomStringDigits(stringLength=6):
    """Generate a random string of letters and digits """
    lettersAndDigits = string.ascii_letters + string.digits
    return ''.join(random.choice(lettersAndDigits) for i in range(stringLength))

key = randomStringDigits(14);

conn = http.client.HTTPSConnection("www.pra1ser.com", timeout=10)

payload = "comment_text=%40asnikuwait1%20test2&replied_to_comment_id="

headers = {
    'cookie': "md5=5; prm_124024574287414=base_domain=api.pra1ser.com; csrftoken=5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1; session=CVzZzZz%3A" + key + "%3A8;",
    'x-csrftoken': "5es0TEJiV6JOOjEzqyAfyeyN1FtnRIi1",
    'content-type': "application/x-www-form-urlencoded"
    }

conn.request("POST", "/web/comments/2050815839087051573/add/", payload, headers)

res = conn.getresponse()
data = res.read()

#print(data.decode("utf-8"))
#print(headers)
#print(res.status)

if __name__ == '__main__':
    jobs = []
    for i in range(100):
        p = multiprocessing.Process(target=worker)
        jobs.append(p)
        p.start()

I'd like to make it work multiprocessing with 100 workers infinite till it get response "200" from server, then it break.

I've tried while true, but i break the code, lot of errors. and i've tried to infinite loop but with failed attempt.

i wish somebody can helps me out please.

Thank you,
regards.
pra1


问:
Specifying which cells a formula looks into, with a formula
Apologies for the title, unsure of how to ask this question. I am trying to specify the range of data I have in a column on excel, where the range of relevant values change. So to visualize, data could be in cells A1-A4, with zeros below (or data in cells A1-A3, or A1-A25, etc.). By using countif, I can get the number of non-zero values in the changing range, which is useful because it specifies the ending row I want for my range. My issue is how I use this value in a formula. In my head (if I put the countif formula in B1), the range would look something like this: $A$1:$A$(the value from B1) but I am not sure how to put this into practice. Any ideas?</p>

答:
You can use the INDIRECT or OFFSET functions

Using INDIRECT is the simpler approach:  to specify the range starting in Column A, Row 1 and ending in Column A, Row COUNTIF(A:A,">0"), you would just write INDIRECT("A1:A" & COUNTIF(A:A, ">0")) - so, if there are 7 cells with values greater than 0, this becomes INDIRECT("A1:A7")

Using OFFSET is more complicated - you have to specify how many cells left/down to move (0 and 0), how many rows of data to get (COUNTIF(A:A, ">0")), and how many columns of data to get (1), from your Starting position (A1) - so it looks something like this instead: OFFSET(A1, 0, 0, COUNTIF(A:A, ">0"), 1)


问:
How can I send an Api file to the server using the Api? With Retrofit2
I want to use this Api to send the file to the server using retrofit2 .. how can help me?

```<code>{
    "id": 6,
    "title": "sometitle",
    "image": "http://kavehkm.pythonanywhere.com/media/images/Koala.jpg",
    "description": "some",
    "price": 1000,
    "tell": "09303747240",
    "address": "some",
    "category": 2,
    "owner": 5
}
</code>```

this is true ?

```<code>@Multipart
@Post("ads")
Call<ResponseBody> uploadPost(@Header("Authorization") String Token
                                      ,@Part("title") RequestBody title
                                      ,@Part("description") RequestBody description
                                      ,@Part("price) RequestBody price
                                      ,@Part MultipartBody.Part image
                                      ,@Part("category") RequestBody category)
</code>```

答:
```<code>@Multipart
@POST(ClientEndPoints.UPLOAD_USER__IMAGE)
fun uploadUserImage(@Part(ClientValues.ID_USER) idUser : RequestBody,
              @Part file : MultipartBody.Part) : Observable<Response<UploadImageResponse>>
</code>```

And this is how you will send your petitions

```<code> @SuppressLint("CheckResult")
fun uploadUserImage(file : MultipartBody.Part){
    val user = UserData()
    val userId = RequestBody.create(MediaType.parse("text/plain"), user.idUser!!)
    ServiceGenerator.getService().uploadUserImage(userId, file)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({image -> onSuccessImage(image) },
                    {error -> onErrorImage(error)}
                    ,{onCompleteImage()})
}
</code>```

And this is how you prepare the file

private fun prepareFilePart(file : File): MultipartBody.Part {
        val requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val body = MultipartBody.Part.createFormData("image","image", requestFile)
        return body
    }

Body:
I want to use this Api to send the file to the server using retrofit2 .. how can help me?

{
    "id": 6,
    "title": "sometitle",
    "image": "http://kavehkm.pythonanywhere.com/media/images/Koala.jpg",
    "description": "some",
    "price": 1000,
    "tell": "09303747240",
    "address": "some",
    "category": 2,
    "owner": 5
}

this is true ?

@Multipart
@Post("ads")
Call<ResponseBody> uploadPost(@Header("Authorization") String Token
                                      ,@Part("title") RequestBody title
                                      ,@Part("description") RequestBody description
                                      ,@Part("price) RequestBody price
                                      ,@Part MultipartBody.Part image
                                      ,@Part("category") RequestBody category)

Body:
@Multipart
@POST(ClientEndPoints.UPLOAD_USER__IMAGE)
fun uploadUserImage(@Part(ClientValues.ID_USER) idUser : RequestBody,
              @Part file : MultipartBody.Part) : Observable<Response<UploadImageResponse>>

And this is how you will send your petitions

 @SuppressLint("CheckResult")
fun uploadUserImage(file : MultipartBody.Part){
    val user = UserData()
    val userId = RequestBody.create(MediaType.parse("text/plain"), user.idUser!!)
    ServiceGenerator.getService().uploadUserImage(userId, file)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({image -> onSuccessImage(image) },
                    {error -> onErrorImage(error)}
                    ,{onCompleteImage()})
}

And this is how you prepare the file

private fun prepareFilePart(file : File): MultipartBody.Part {
        val requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file)
        val body = MultipartBody.Part.createFormData("image","image", requestFile)
        return body
    }


问:
Prevent trailing zero with pandas "to_csv"
I'm trying to export a CSV string to a D3 web application, but the command to_csv insists on adding a trailing 0 to the data, which prevents a proper use by D3.

Here's a minimal example to illustrate the problem.

My (simplified) dataframe is:

```<code>>>> df = pd.DataFrame([['Alex',20.0000, 50.650]],columns=['Name','Age', 'Weight'])
   Name   Age  Weight
0  Alex  20.0   50.65
</code>```

df['Age'] contains a float, as indicated by:

```<code>>>> df['Age']
0    20.0
Name: Age, dtype: float64
</code>```

Then based on this answer I run .astype(object) to get the format I would like:

```<code>>>> df=df.astype(object)
   Name Age Weight
0  Alex  20  50.65
</code>```

Now, df['Age'] contains an object, with no trailing zero:

```<code>>>> df['Age']
0    20
Name: Age, dtype: object
</code>```

That's what I would like to export with to_csv, but this command reappends a trailing 0 to the number, which I want to avoid:

```<code>>>> df_csv = df.to_csv(sep=',', index = False)
>>> df_csv
'Name,Age,Weight\nAlex,20.0,50.65\n'
</code>```

I tried using df_csv = df.to_csv(sep=',', index = False, float_format='%.0f') based on this answer, but that doesn't work because there are other floats in my dataframe for which I wish to keep non-zero decimals.

How could I prevent this trailing 0 to appear for numbers with no decimals?

答:
Have you tried df['Age'] = df['Age'].astype(int)

this gets me

    Name    Age     Weight
0   Alex    20  50.65
```
<p>converting a column to type <code>object</code> essentially allows the column to hold floats, ints, strings etc. vs a typed column which will only hold that type.</p>
<p>And converting it to a csv:</p>
<pre class="lang-py prettyprint-override"><code>df_csv = df.to_csv(sep=',', index = False)

'Name,Age,Weight\r\nAlex,20,50.65\r\n'
</code>```

Body:
I'm trying to export a CSV string to a D3 web application, but the command to_csv insists on adding a trailing 0 to the data, which prevents a proper use by D3.

Here's a minimal example to illustrate the problem.

My (simplified) dataframe is:

>>> df = pd.DataFrame([['Alex',20.0000, 50.650]],columns=['Name','Age', 'Weight'])
   Name   Age  Weight
0  Alex  20.0   50.65

df['Age'] contains a float, as indicated by:

>>> df['Age']
0    20.0
Name: Age, dtype: float64

Then based on this answer I run .astype(object) to get the format I would like:

>>> df=df.astype(object)
   Name Age Weight
0  Alex  20  50.65

Now, df['Age'] contains an object, with no trailing zero:

>>> df['Age']
0    20
Name: Age, dtype: object

That's what I would like to export with to_csv, but this command reappends a trailing 0 to the number, which I want to avoid:

>>> df_csv = df.to_csv(sep=',', index = False)
>>> df_csv
'Name,Age,Weight\nAlex,20.0,50.65\n'

I tried using df_csv = df.to_csv(sep=',', index = False, float_format='%.0f') based on this answer, but that doesn't work because there are other floats in my dataframe for which I wish to keep non-zero decimals.

How could I prevent this trailing 0 to appear for numbers with no decimals?

Body:
Have you tried df['Age'] = df['Age'].astype(int)

this gets me

    Name    Age     Weight
0   Alex    20  50.65

converting a column to type object essentially allows the column to hold floats, ints, strings etc. vs a typed column which will only hold that type.

And converting it to a csv:

df_csv = df.to_csv(sep=',', index = False)

'Name,Age,Weight\r\nAlex,20,50.65\r\n'


问:
CakePHP setFlash() weird problem
I want to $this->Session->setFlash('text'); $this->redirect('page'); but the message is not displayed.
I have included both the Session Component and Helper, and the $this->Session->setFlash() in my layout. However, after the redirect, the session doesn't contain any message. If I don't redirect, the message is shown.

So my question is, why isn't the flash message preserved after a redirect? It should be, and this how I've done before, but...it doesn't work now.

Thanks for any help!

Here is my controller code:

```<code>if(!$this->Test->__test_possible()){
        $this->Session->setFlash(__('Insufficient data to create test.', true));
        $this->redirect(array('action' => 'index'));
    }
</code>```

...my layout...(the cake default.ctp)

```<code><?php echo $this->Session->flash(); ?>
</code>```

and the AppController:

```<code>var $helpers = array('Html', 'Form', 'Session', 'Facebook.Facebook');
var $components = array('Session', 'Auth', 'Facebook.Connect');
</code>```

答: Oh darn...I've put Configure::write('Session.cookie', 'Capitalize.me'); in the core.php and it seems he didn't like the dot in the name...now everything works fine. It's frustrating, really. Thanks for your help :)</p>

ContentLicense: CC BY-SA 2.5

Title: CakePHP setFlash() weird problem

Body:
I want to $this->Session->setFlash('text'); $this->redirect('page'); but the message is not displayed.
I have included both the Session Component and Helper, and the $this->Session->setFlash() in my layout. However, after the redirect, the session doesn't contain any message. If I don't redirect, the message is shown.

So my question is, why isn't the flash message preserved after a redirect? It should be, and this how I've done before, but...it doesn't work now.

Thanks for any help!

Here is my controller code:

if(!$this->Test->__test_possible()){
        $this->Session->setFlash(__('Insufficient data to create test.', true));
        $this->redirect(array('action' => 'index'));
    }

...my layout...(the cake default.ctp)

<?php echo $this->Session->flash(); ?>

and the AppController:

var $helpers = array('Html', 'Form', 'Session', 'Facebook.Facebook');
var $components = array('Session', 'Auth', 'Facebook.Connect');

ContentLicense: CC BY-SA 3.0


问:
Python: How can I enable use of kwargs when calling from command line? (perhaps with argparse)
suppose I have the module myscript.py; This module is production code, and is called often as %dir%>python myscript.py foo bar.

I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using

%dir%>python myscript.py main(foo, bar).

I know that I can use the argparse module, but I'm not sure how to do it.

```<code>import sys

def main(foo,bar,**kwargs):
    print 'Called myscript with:'
        print 'foo = %s' % foo
        print 'bar = %s' % bar
        if kwargs:
            for k in kwargs.keys():
                print 'keyword argument : %s' % k + ' = ' + '%s' % kwargs[k]

if __name__=="__main__":
    exec(''.join(sys.argv[1:]))
</code>```

答:
in two lines of code I can get args and kwargs that I can manipulate like standard args and kwargs:

```<code>import sys

if __name__=='__main__':
  argv=argv[1:]
  kwargs={kw[0]:kw[1] for kw in [ar.split('=') for ar in argv if ar.find('=')>0]}
  args=[arg for arg in argv if arg.find('=')<0]

  #and you can the use args and kwargs as so:
  if 'reset' in args:
    do_some_functions_with_reset()
  a_device_var=kwargs.get('device',False):
  #or whatever you want to do with args and kwargs
</code>```

and the result is :

```<code>$python test.py reset device=foo format=1 bar
->args=['reset','bar']
->kwargs={'device':'foo','format':'1'}
</code>```

Body:
suppose I have the module myscript.py; This module is production code, and is called often as %dir%>python myscript.py foo bar.

I want to extend it to take keyword arguments. I know that I can take these arguments using the script below, but unfortunately one would have to call it using

%dir%>python myscript.py main(foo, bar).

I know that I can use the argparse module, but I'm not sure how to do it.

import sys

def main(foo,bar,**kwargs):
    print 'Called myscript with:'
        print 'foo = %s' % foo
        print 'bar = %s' % bar
        if kwargs:
            for k in kwargs.keys():
                print 'keyword argument : %s' % k + ' = ' + '%s' % kwargs[k]

if __name__=="__main__":
    exec(''.join(sys.argv[1:]))

Body:
in two lines of code I can get args and kwargs that I can manipulate like standard args and kwargs:

import sys

if __name__=='__main__':
  argv=argv[1:]
  kwargs={kw[0]:kw[1] for kw in [ar.split('=') for ar in argv if ar.find('=')>0]}
  args=[arg for arg in argv if arg.find('=')<0]

  #and you can the use args and kwargs as so:
  if 'reset' in args:
    do_some_functions_with_reset()
  a_device_var=kwargs.get('device',False):
  #or whatever you want to do with args and kwargs

and the result is :

$python test.py reset device=foo format=1 bar
->args=['reset','bar']
->kwargs={'device':'foo','format':'1'}


问:
Use variable inside __init__ to outside __init__
I want to use a  variable inside def__init__ outside of def__init__. This is the def__init__ in my class :

```<code>class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
           qry = kwargs.pop('qry')
           super(UserResponseSearchForm,self).__init__(*args, **kwargs)
</code>```

I want to use variable qry outside def__init__ like this :

```<code>class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
           qry = kwargs.pop('qry')
           super(UserResponseSearchForm,self).__init__(*args, **kwargs)
gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(gejala__icontains = qry).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
</code>```

I use variable qry in gejala__icontains = qry like this:

```<code>filter(gejala__icontains = qry)
</code>```

And it return name 'qry' is not defined. What the problem with that? And how to use the qry variable?
Hope anyone can help me.

答:
You need to do this inside __init__:

```<code>class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        qry = kwargs.pop('qry')
        super(UserResponseSearchForm,self).__init__(*args, **kwargs)
        self.fields['gejala_id1'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains = qry).distinct().order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)
</code>```

Note you should not do values_list('gejala', flat=True) for a ModelMultipleChoiceField, because this field expects the objects, not a flat list of strings.

Body:
I want to use a  variable inside def__init__ outside of def__init__. This is the def__init__ in my class :

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
           qry = kwargs.pop('qry')
           super(UserResponseSearchForm,self).__init__(*args, **kwargs)

I want to use variable qry outside def__init__ like this :

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
           qry = kwargs.pop('qry')
           super(UserResponseSearchForm,self).__init__(*args, **kwargs)
gejala_id1 = forms.ModelMultipleChoiceField(queryset=Gejala.objects.all().values_list('gejala', flat=True).distinct().filter(gejala__icontains = qry).order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)

I use variable qry in gejala__icontains = qry like this:

filter(gejala__icontains = qry)

And it return name 'qry' is not defined. What the problem with that? And how to use the qry variable?
Hope anyone can help me.

Body:
You need to do this inside __init__:

class UserResponseSearchForm(forms.Form):
    def __init__(self, *args, **kwargs):
        qry = kwargs.pop('qry')
        super(UserResponseSearchForm,self).__init__(*args, **kwargs)
        self.fields['gejala_id1'] = forms.ModelMultipleChoiceField(queryset=Gejala.objects.filter(gejala__icontains = qry).distinct().order_by('gejala'), widget=forms.CheckboxSelectMultiple, required=False)

Note you should not do values_list('gejala', flat=True) for a ModelMultipleChoiceField, because this field expects the objects, not a flat list of strings.


问:
how to trigger python code after an event
I want to start some python codes after another software.

This software do some data extractions and gives me periodically some results in CVS file form (weekly). What I want to do is to trigger my Python code to be executed on these file in order to do some functions with them and I want this to be done after every extraction.

I have tried while(1) but it doesn't seem to be efficient.

Is there any Python codes or a software to execute the Python that I can use to solve this problem? Thanks in advance.

答:
You can watch the folder then act on the files creation and/or modify events. Your script can be watching a remote drive on the network if needed.

The following is cut out of working code but I can't confirm it works in this snippet state.  It'll call HandleNewlyCreated() for newly created files.

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class WatchPendingHandler(FileSystemEventHandler):
    ''' Run a handler for every file added to the pending dir

    This class also handles what I call a bug in the watchdog module
    which means that you can get more than one call per real event
    in the watched dir tree.
    '''

    def __init__(self):
        super(WatchPendingHandler, self).__init__()
        # wip is used to avoid bug in watchdog which means multiple calls
        # for one real event.
        # For reference: https://github.com/gorakhargosh/watchdog/issues/346
        self.wip = []

    def on_created(self, event):
        path = event.src_path
        if event.is_directory:
            logging.debug('WatchPendingHandler() New dir created in pending dir: {}'.format(path))
            return
        if path in self.wip:
            logging.debug('WatchPendingHandler() Dup created event for %s', path)
            return
        self.wip.append(path)
        logging.debug('WatchPendingHandler() New file created in pending dir: {}'.format(path))
        HandleNewlyCreated(path)

    def on_moved(self, event):
        logging.debug('WatchPendingHandler() %s has been moved', event.src_path)
        with contextlib.suppress(ValueError):
            self.wip.remove(event.src_path)

    def on_deleted(self, event):
        path = event.src_path
        logging.debug('WatchPendingHandler() %s has been deleted', path)
        with contextlib.suppress(ValueError):
            self.wip.remove(path)

observer = Observer()
observer.schedule(WatchPendingHandler(), DIR_PENDING, recursive=True)
observer.start()
logging.info('Watching %s', DIR_PENDING)
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()
```

Explanation of on_created():
It will check if the event was for the creation of a directory.  If so it logs the event and then returns/ignores it.  It then checks whether the file created event has previously happened (path in self.wip).  If so, it also ignores the event and returns.  Now it can record the event in self.wip, log the new event and then call HandleNewlyCreated() to process the newly created file.

If the file is moved or deleted, then we need to remove the path from self.wip so that the next created event for a new file won't be ignored.

More info here: https://pypi.org/project/watchdog/

Body:
You can watch the folder then act on the files creation and/or modify events. Your script can be watching a remote drive on the network if needed.

The following is cut out of working code but I can't confirm it works in this snippet state.  It'll call HandleNewlyCreated() for newly created files.

from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class WatchPendingHandler(FileSystemEventHandler):
    ''' Run a handler for every file added to the pending dir

    This class also handles what I call a bug in the watchdog module
    which means that you can get more than one call per real event
    in the watched dir tree.
    '''

    def __init__(self):
        super(WatchPendingHandler, self).__init__()
        # wip is used to avoid bug in watchdog which means multiple calls
        # for one real event.
        # For reference: https://github.com/gorakhargosh/watchdog/issues/346
        self.wip = []

    def on_created(self, event):
        path = event.src_path
        if event.is_directory:
            logging.debug('WatchPendingHandler() New dir created in pending dir: {}'.format(path))
            return
        if path in self.wip:
            logging.debug('WatchPendingHandler() Dup created event for %s', path)
            return
        self.wip.append(path)
        logging.debug('WatchPendingHandler() New file created in pending dir: {}'.format(path))
        HandleNewlyCreated(path)

    def on_moved(self, event):
        logging.debug('WatchPendingHandler() %s has been moved', event.src_path)
        with contextlib.suppress(ValueError):
            self.wip.remove(event.src_path)

    def on_deleted(self, event):
        path = event.src_path
        logging.debug('WatchPendingHandler() %s has been deleted', path)
        with contextlib.suppress(ValueError):
            self.wip.remove(path)

observer = Observer()
observer.schedule(WatchPendingHandler(), DIR_PENDING, recursive=True)
observer.start()
logging.info('Watching %s', DIR_PENDING)
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

Explanation of on_created():
It will check if the event was for the creation of a directory.  If so it logs the event and then returns/ignores it.  It then checks whether the file created event has previously happened (path in self.wip).  If so, it also ignores the event and returns.  Now it can record the event in self.wip, log the new event and then call HandleNewlyCreated() to process the newly created file.

If the file is moved or deleted, then we need to remove the path from self.wip so that the next created event for a new file won't be ignored.

More info here: https://pypi.org/project/watchdog/


问:
Invalid type for parameter error when using put_item dynamodb
I want to write data in dataframe to dynamodb table

```<code>item = {}
for row in datasource_archived_df_join_repartition.rdd.collect():
    item['x'] = row.x
    item['y'] = row.y
    client.put_item( TableName='tryfail',
    Item=item)
</code>```

but im gettin this error
Invalid type for parameter Item.x, value: 478.2, type: '<'type 'float''>', valid types: '<'type 'dict''>'
Invalid type for parameter Item.y, value: 696- 18C 12, type: '<'type 'unicode''>', valid types: '<'type 'dict''>'

答:
The error message is indicating you are using the wrong type, it looks like you need to be using a dictionary when assigning values to item['x'] and item[y]. e.g.

```<code>item['x'] = {'value': row.x}
item['y'] = {'value': row.y}
</code>```

Body:
I want to write data in dataframe to dynamodb table

item = {}
for row in datasource_archived_df_join_repartition.rdd.collect():
    item['x'] = row.x
    item['y'] = row.y
    client.put_item( TableName='tryfail',
    Item=item)

but im gettin this error
Invalid type for parameter Item.x, value: 478.2, type: '<'type 'float''>', valid types: '<'type 'dict''>'
Invalid type for parameter Item.y, value: 696- 18C 12, type: '<'type 'unicode''>', valid types: '<'type 'dict''>'

Body:
The error message is indicating you are using the wrong type, it looks like you need to be using a dictionary when assigning values to item['x'] and item[y]. e.g.

item['x'] = {'value': row.x}
item['y'] = {'value': row.y}


问:
Open a OpenFileDialog to change the value of a property in a PropertyGrid control?
In Windows Forms, I'm representing a custom class in a PropertyGid control, which has various string properties as you can notice in the next image:

The problem is that I'm not totally satisfied with the current behavior for changing the value of the string properties. For those properties that expects a file or directory path, like "Target" or "Working Directory" properties, I would like to know if it could be possible and viable to implement a TypeConverter / Type Descriptor that would open a OpenFileDialog when clicking in the down arrow at the right of the field in the property grid. That is, to select a file or folder through a OpenFileDialog, instead of directly writing the path in the property grid, but still letting the option to directly write the path if I want to do so.

Maybe .NET Framework class library already provides the TypeConverter / TypeDescriptor that I'm requesting?. If not, is this possible to do?. And how to start doing so?.

Or any other idea to be able open a OpenFileDialog to change the value of a specific property in a PropertyGrid control?.

答:
In my application, I have a property that takes a icon file path, another property that can take a file or folder, and other property that takes a folder path.

So, I had to write variations for each one of these properties...

The easiest one, and in case of you are satisfied with the FolderBrowserDialog appearance and limitations, then is to directly specify the System.Windows.Forms.Design.FolderNameEditor class in the EditorAttribute class. Otherwise, Ooki.Dialogs is a good open-source library as an alternative to get a modern-look dialog.

The second easiest one is the editor for selecting a icon file path:

'''
''' Provides a user interface for selecting a icon file name.
'''
''' <seealso cref="FileNameEditor"/>
Friend Class IconFileNameEditor : Inherits FileNameEditor

#Region " Constructors "

    '''
    ''' Initializes a new instance of the <see cref="IconFileNameEditor"/> class.
    '''
    Public Sub New()
        MyBase.New()
    End Sub

#End Region

#Region " Private Methods "

    '''
    ''' Initializes the open file dialog when it is created.
    '''
    ''' <param name="ofd">
    ''' The <see cref="OpenFileDialog"/> to use to select a file name.
    ''' </param>
    Protected Overrides Sub InitializeDialog(ByVal dlg As OpenFileDialog)
        MyBase.InitializeDialog(dlg)

        With dlg
            .Multiselect = False
            .RestoreDirectory = True
            .DereferenceLinks = True
            .Filter = "Icon Files (*.ico;*.icl;*.exe;*.dll)|*.ico;*.icl;*.exe;*.dll|Icons|*.ico|Libraries|*.dll|Programs|*.exe"
            .FilterIndex = 1
            .SupportMultiDottedExtensions = True
        End With
    End Sub

#End Region

End Class
```

<p>For selecting a file path or folder path, and in search of something already done and open-source in order to avoid adding external dependancies to my project, I took a custom <code>FileFolderDialog</code> class  provided in this article, and I managed to write the editor like this:</p>

<pre class="lang-vb prettyprint-override"><code>''' <summary>
''' Provides a user interface for selecting a file or folder name.
''' </summary>
''' <seealso cref="UITypeEditor"/>
Public Class FileOrFolderNameEditor : Inherits UITypeEditor

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="FileOrFolderNameEditor"/> class.
    ''' </summary>
    Public Sub New()
        MyBase.New()
    End Sub

#End Region

#Region " Public Methods"

    ''' <summary>
    ''' Gets the editor style used by the <see cref="UITypeEditor.EditValue(IServiceProvider, Object)"/> method.
    ''' </summary>
    ''' <param name="context">
    ''' An <see cref="ITypeDescriptorContext"/> that can be used to gain additional context information.
    ''' </param>
    ''' <returns>
    ''' A <see cref="UITypeEditorEditStyle"/> value that indicates the style of editor used
    ''' by the <see cref="UITypeEditor.EditValue(IServiceProvider, Object)"/> method.
    ''' <para></para>
    ''' If the <see cref="UITypeEditor"/> does not support this method,
    ''' then <see cref="UITypeEditor.GetEditStyle"/> will return <see cref="UITypeEditorEditStyle.None"/>.
    ''' </returns>
    Public Overrides Function GetEditStyle(ByVal context As ITypeDescriptorContext) As UITypeEditorEditStyle
        Return UITypeEditorEditStyle.Modal
    End Function

    ''' <summary>
    ''' Edits the specified object's value using the editor style indicated by the <see cref="UITypeEditor.GetEditStyle"/> method.
    ''' </summary>
    ''' <param name="context">
    ''' An <see cref="ITypeDescriptorContext"/> that can be used to gain additional context information.
    ''' </param>
    ''' <param name="provider">
    ''' An <see cref="IServiceProvider"/> that this editor can use to obtain services.
    ''' </param>
    ''' <param name="value">
    ''' The object to edit.
    ''' </param>
    ''' <returns>
    ''' The new value of the object.
    ''' <para></para>
    ''' If the value of the object has not changed, this should return the same object it was passed.
    ''' </returns>
    Public Overrides Function EditValue(ByVal context As ITypeDescriptorContext, ByVal provider As IServiceProvider, ByVal value As Object) As Object

        Using dlg As New OpenFileOrFolderDialog()
            If (dlg.ShowDialog = DialogResult.OK) Then
                Return dlg.SelectedPath
            End If
        End Using

        Return MyBase.EditValue(context, provider, value)

    End Function

#End Region

End Class
</code>```

It was pretty easy at all.

Body:
In my application, I have a property that takes a icon file path, another property that can take a file or folder, and other property that takes a folder path.

So, I had to write variations for each one of these properties...

The easiest one, and in case of you are satisfied with the FolderBrowserDialog appearance and limitations, then is to directly specify the System.Windows.Forms.Design.FolderNameEditor class in the EditorAttribute class. Otherwise, Ooki.Dialogs is a good open-source library as an alternative to get a modern-look dialog.

The second easiest one is the editor for selecting a icon file path:

''' <summary>
''' Provides a user interface for selecting a icon file name.
''' </summary>
''' <seealso cref="FileNameEditor"/>
Friend Class IconFileNameEditor : Inherits FileNameEditor

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="IconFileNameEditor"/> class.
    ''' </summary>
    Public Sub New()
        MyBase.New()
    End Sub

#End Region

#Region " Private Methods "

    ''' <summary>
    ''' Initializes the open file dialog when it is created.
    ''' </summary>
    ''' <param name="ofd">
    ''' The <see cref="OpenFileDialog"/> to use to select a file name.
    ''' </param>
    Protected Overrides Sub InitializeDialog(ByVal dlg As OpenFileDialog)
        MyBase.InitializeDialog(dlg)

        With dlg
            .Multiselect = False
            .RestoreDirectory = True
            .DereferenceLinks = True
            .Filter = "Icon Files (*.ico;*.icl;*.exe;*.dll)|*.ico;*.icl;*.exe;*.dll|Icons|*.ico|Libraries|*.dll|Programs|*.exe"
            .FilterIndex = 1
            .SupportMultiDottedExtensions = True
        End With
    End Sub

#End Region

End Class

For selecting a file path or folder path, and in search of something already done and open-source in order to avoid adding external dependancies to my project, I took a custom FileFolderDialog class  provided in this article, and I managed to write the editor like this:

''' <summary>
''' Provides a user interface for selecting a file or folder name.
''' </summary>
''' <seealso cref="UITypeEditor"/>
Public Class FileOrFolderNameEditor : Inherits UITypeEditor

#Region " Constructors "

    ''' <summary>
    ''' Initializes a new instance of the <see cref="FileOrFolderNameEditor"/> class.
    ''' </summary>
    Public Sub New()
        MyBase.New()
    End Sub

#End Region

#Region " Public Methods"

    ''' <summary>
    ''' Gets the editor style used by the <see cref="UITypeEditor.EditValue(IServiceProvider, Object)"/> method.
    ''' </summary>
    ''' <param name="context">
    ''' An <see cref="ITypeDescriptorContext"/> that can be used to gain additional context information.
    ''' </param>
    ''' <returns>
    ''' A <see cref="UITypeEditorEditStyle"/> value that indicates the style of editor used
    ''' by the <see cref="UITypeEditor.EditValue(IServiceProvider, Object)"/> method.
    ''' <para></para>
    ''' If the <see cref="UITypeEditor"/> does not support this method,
    ''' then <see cref="UITypeEditor.GetEditStyle"/> will return <see cref="UITypeEditorEditStyle.None"/>.
    ''' </returns>
    Public Overrides Function GetEditStyle(ByVal context As ITypeDescriptorContext) As UITypeEditorEditStyle
        Return UITypeEditorEditStyle.Modal
    End Function

    ''' <summary>
    ''' Edits the specified object's value using the editor style indicated by the <see cref="UITypeEditor.GetEditStyle"/> method.
    ''' </summary>
    ''' <param name="context">
    ''' An <see cref="ITypeDescriptorContext"/> that can be used to gain additional context information.
    ''' </param>
    ''' <param name="provider">
    ''' An <see cref="IServiceProvider"/> that this editor can use to obtain services.
    ''' </param>
    ''' <param name="value">
    ''' The object to edit.
    ''' </param>
    ''' <returns>
    ''' The new value of the object.
    ''' <para></para>
    ''' If the value of the object has not changed, this should return the same object it was passed.
    ''' </returns>
    Public Overrides Function EditValue(ByVal context As ITypeDescriptorContext, ByVal provider As IServiceProvider, ByVal value As Object) As Object

        Using dlg As New OpenFileOrFolderDialog()
            If (dlg.ShowDialog = DialogResult.OK) Then
                Return dlg.SelectedPath
            End If
        End Using

        Return MyBase.EditValue(context, provider, value)

    End Function

#End Region

End Class

It was pretty easy at all.


问:
UIView detaches from bottom of UICollectionView on scroll
I have a UICollectionView that allows a user to enter reps via a UIView containing a picker. The picker container attaches to the bottom of the view as long as the UICollectionView doesn't need to scroll. As more cells are added and the view must scroll, my picker container no longer attaches to the bottom of my view. I have attached a screenshot of my issue and code showing how I have attached my pickerContainer to the bottom of my collectionView.

```<code>let pickerContainer = UIView(frame: CGRect(x: 0, y: self.collectionView.frame.height - pickerContainerHeight, width: self.collectionView.frame.width, height: pickerContainerHeight))
<....some other code that i dont think matters....>
collectionView.addSubview(pickerContainer)
</code>```

答:
Don’t add it to the collection view as it will be added to scrollable area.

You can add it to the superview of collection view and put it above collection if you using storyboard. Or move in front using pickerContainer.superview?.bringSubviewToFront(view: pickerContainer) in case you interested in only in programmatically version.

Body:
I have a UICollectionView that allows a user to enter reps via a UIView containing a picker. The picker container attaches to the bottom of the view as long as the UICollectionView doesn't need to scroll. As more cells are added and the view must scroll, my picker container no longer attaches to the bottom of my view. I have attached a screenshot of my issue and code showing how I have attached my pickerContainer to the bottom of my collectionView.

let pickerContainer = UIView(frame: CGRect(x: 0, y: self.collectionView.frame.height - pickerContainerHeight, width: self.collectionView.frame.width, height: pickerContainerHeight))
<....some other code that i dont think matters....>
collectionView.addSubview(pickerContainer)


问:
object property undefined, One line after being console.log()'d
I am trying to draw a table and form to add data to said table on a page, based on a json object retrieved from the server. I am getting a Uncaught typeError and cannot figure out why.

If I console.log() the object, It prints out in the console as expected. I can even output specific properties no problem. But when I try and use any of the properties, In a html sting, I get "Uncaught TypeError: Cannot read property 'formName' of undefined"

```<code>function testFunc(subform){
    console.log(subForm.layout.formName); //<--- prints the name to the console

    var form = '<div class="assetSubForm"><h2>' + subForm.layout.formName + '</h2>';
    console.log(form); //<--- error's out???

    return form;
}
</code>```

The object is as follows:

```<code>{records: false, layout: {…}}
layout:
    fields: (5) [{…}, {…}, {…}, {…}, {…}]
    formID: 30
    formName: "Part 11 - Building Clearance And Fire Appliances"
    position: 120
    __proto__: Object
records: false
__proto__: Object
</code>```

I can't for the life of me wrap my head around why. I have tried googling it but have come up empty as I can't figure out how to word it in an appropriate search term and all the results that do come up relate to scope or spelling errors (eg. object defined in anonymous function and referenced outside).

答:
You are taking argument as subform but you are trying to access subForm in console.log

see line 1 and line 2 of your code.

Body:
I am trying to draw a table and form to add data to said table on a page, based on a json object retrieved from the server. I am getting a Uncaught typeError and cannot figure out why.

If I console.log() the object, It prints out in the console as expected. I can even output specific properties no problem. But when I try and use any of the properties, In a html sting, I get "Uncaught TypeError: Cannot read property 'formName' of undefined"

function testFunc(subform){
    console.log(subForm.layout.formName); //<--- prints the name to the console

    var form = '

' + subForm.layout.formName + '
';
    console.log(form); //<--- error's out???

    return form;
}

The object is as follows:

{records: false, layout: {…}}
layout:
    fields: (5) [{…}, {…}, {…}, {…}, {…}]
    formID: 30
    formName: "Part 11 - Building Clearance And Fire Appliances"
    position: 120
    __proto__: Object
records: false
__proto__: Object

I can't for the life of me wrap my head around why. I have tried googling it but have come up empty as I can't figure out how to word it in an appropriate search term and all the results that do come up relate to scope or spelling errors (eg. object defined in anonymous function and referenced outside).


问:
Why For Let loop is returning numbers instead of data?
Accessing local csv file to obtain data in column A, using "for (let" is returning numbers and not the text data.

Have searched but no solutions.

```<code>const searchkeywords = fs.readFileSync('kwords.csv');
    for (let kword of searchkeywords) {
    console.log(`Search Keyword: ${kword}`);
    }
</code>```

Need to retrieve actual text from csv file.

答:
By default readFileSync returns buffer. Just add second argument like 'utf8'.</p>

```<code>   const searchkeywords = fs.readFileSync('kwords.csv', 'utf8');
    for (let kword of searchkeywords) {
        console.log(`Search Keyword: ${kword}`);
    }
</code>```

Body:
Accessing local csv file to obtain data in column A, using "for (let" is returning numbers and not the text data.

Have searched but no solutions.

const searchkeywords = fs.readFileSync('kwords.csv');
    for (let kword of searchkeywords) {
    console.log(`Search Keyword: ${kword}`);
    }

Need to retrieve actual text from csv file.

Body:
By default readFileSync returns buffer. Just add second argument like 'utf8'.

   const searchkeywords = fs.readFileSync('kwords.csv', 'utf8');
    for (let kword of searchkeywords) {
        console.log(`Search Keyword: ${kword}`);
    }


问:
ajax success function with callback
I need to add a callback to the $.ajax() success callback function. I am working in jQuery 1.3

```<code>success : ajaxCartFormSubmitted(),

function ajaxCartFormSubmitted(e) {
  longRunningOperation();
  if (e)...
});
</code>```

My function which should run after ajaxCartFormSubmitted() is:

```<code>function modalopen () {
  if ($('#ajax-cart-popup .full').length) {
    openmodal('ajax-cart-popup');
  } else {
    return false;
  }
};
</code>```

I tried to add callback to ajaxCartFormSubmitted(e) like this ajaxCartFormSubmitted(e, callback) and use it like this success : ajaxCartFormSubmitted('modalopen()'),
but I get no results, it seems that the function is not firing. Is the problem in first e argument? Thank you.

Update: I need to fire modalopen function after the ajaxCartFormSubmitted function. Ideally in the success callback.

答:
There's a few issues here. Firstly you need to pass a function reference to success. By invoking the function immediately you're actually assigning its return value to success, hence nothing appears to happen. To fix that simply remove the parentheses from the function name:

```<code>success: ajaxCartFormSubmitted,
</code>```

Next, to have modalopen() execute after ajaxCartFormSubmitted() you need to call it at that time. Passing the name of the function as an argument alone is not enough. You need to expressly call the function. You can either do this in ajaxCartFormSubmitted():

```<code>function ajaxCartFormSubmitted(e) {
  // do something...

  modalopen();
});
</code>```

Alternatively you can provide an anonymous function to success which calls both functions:

```<code>success: function() {
  ajaxCartFormSubmitted();
  modalopen();
},
</code>```

Finally, a couple of notes. You need to update jQuery as 1.3 is over 10 years out of date. 3.4 is the latest version. Also I'd be careful with your function names. You appear to have both openmodal() and modalopen(), and that kind of similarity is just asking for problems.

Edit

The ajaxCartFormSubmitted function contains another function which needs some time to process. That is why I need to call my function after ajaxCartFormSubmitted

In which case you need to implement the callback pattern, as $.ajax() does, yourself. You can make ajaxCartFormSubmitted() accept a function as an argument which will be executed after the async operation completes, like this:

```<code>// in $.ajax settings:
success: function() {
  ajaxCartFormSubmitted(openmodal);
}

// function definition:
function ajaxCartFormSubmitted(cb) {
  some.longRunningOperation({
    oncomplete: function() {
      cb && cb(); // invoke the function you passed in here, openmodal() in this case
    }
  });
}
</code>```

Title: ajax success function with callback

Body:
I need to add a callback to the $.ajax() success callback function. I am working in jQuery 1.3

success : ajaxCartFormSubmitted(),

function ajaxCartFormSubmitted(e) {
  longRunningOperation();
  if (e)...
});

My function which should run after ajaxCartFormSubmitted() is:

function modalopen () {
  if ($('#ajax-cart-popup .full').length) {
    openmodal('ajax-cart-popup');
  } else {
    return false;
  }
};

I tried to add callback to ajaxCartFormSubmitted(e) like this ajaxCartFormSubmitted(e, callback) and use it like this success : ajaxCartFormSubmitted('modalopen()'),
but I get no results, it seems that the function is not firing. Is the problem in first e argument? Thank you.

Update: I need to fire modalopen function after the ajaxCartFormSubmitted function. Ideally in the success callback.

Body:
There's a few issues here. Firstly you need to pass a function reference to success. By invoking the function immediately you're actually assigning its return value to success, hence nothing appears to happen. To fix that simply remove the parentheses from the function name:

success: ajaxCartFormSubmitted,

Next, to have modalopen() execute after ajaxCartFormSubmitted() you need to call it at that time. Passing the name of the function as an argument alone is not enough. You need to expressly call the function. You can either do this in ajaxCartFormSubmitted():

function ajaxCartFormSubmitted(e) {
  // do something...

  modalopen();
});

Alternatively you can provide an anonymous function to success which calls both functions:

success: function() {
  ajaxCartFormSubmitted();
  modalopen();
},

Finally, a couple of notes. You need to update jQuery as 1.3 is over 10 years out of date. 3.4 is the latest version. Also I'd be careful with your function names. You appear to have both openmodal() and modalopen(), and that kind of similarity is just asking for problems.

Edit

The ajaxCartFormSubmitted function contains another function which needs some time to process. That is why I need to call my function after ajaxCartFormSubmitted

In which case you need to implement the callback pattern, as $.ajax() does, yourself. You can make ajaxCartFormSubmitted() accept a function as an argument which will be executed after the async operation completes, like this:

// in $.ajax settings:
success: function() {
  ajaxCartFormSubmitted(openmodal);
}

// function definition:
function ajaxCartFormSubmitted(cb) {
  some.longRunningOperation({
    oncomplete: function() {
      cb && cb(); // invoke the function you passed in here, openmodal() in this case
    }
  });
}


问:
Quadratic Bézier Curve: Calculate Points
I'd like to calculate a point on a quadratic curve. To use it with the canvas element of HTML5.

When I use the quadraticCurveTo() function in JavaScript, I have a source point, a target point and a control point.

How can I calculate a point on the created quadratic curve at let's say t=0.5 with "only" knowing this three points?

答:
Use the quadratic Bézier formula, found, for instance, on the Wikipedia page for Bézier Curves:

In pseudo-code, that's

```<code>t = 0.5; // given example value
x = (1 - t) * (1 - t) * p[0].x + 2 * (1 - t) * t * p[1].x + t * t * p[2].x;
y = (1 - t) * (1 - t) * p[0].y + 2 * (1 - t) * t * p[1].y + t * t * p[2].y;
</code>```

p[0] is the start point, p[1] is the control point, and p[2] is the end point. t is the parameter, which goes from 0 to 1.

Body:
Use the quadratic Bézier formula, found, for instance, on the Wikipedia page for Bézier Curves:

In pseudo-code, that's

t = 0.5; // given example value
x = (1 - t) * (1 - t) * p[0].x + 2 * (1 - t) * t * p[1].x + t * t * p[2].x;
y = (1 - t) * (1 - t) * p[0].y + 2 * (1 - t) * t * p[1].y + t * t * p[2].y;

p[0] is the start point, p[1] is the control point, and p[2] is the end point. t is the parameter, which goes from 0 to 1.


问:
React appevent termination
I'm trying to find a way to execute a function upon termination of the app, what function can I use to do this in react native?

Basically, whenever the user closes the app (completely terminate).

答:
This might help:</p>

```<code>AppState.addEventListener('change', state => {
  if (state === 'active') {
    // do this
  } else if (state === 'background') {
    // do that
  } else if (state === 'inactive') {
    // do that other thing
   }
});
</code>```

Title: React appevent termination

Body:
This might help:

AppState.addEventListener('change', state => {
  if (state === 'active') {
    // do this
  } else if (state === 'background') {
    // do that
  } else if (state === 'inactive') {
    // do that other thing
   }
});


问:
Running script on page load
I am using the following code to run a calculation as the user type in a number.

```<code>   <form action="index.php" method="post" autocomplete="off" data-abide>
   <input type="text" id="rate" name="rate">
   <input type="text" name="supplier_cost" class="value-right" pattern="\d*" value="<?php echo $supplier_cost; ?>" id="decimal" required>
   <input type="text" name="sterling" id="sterling" class="value-right" disabled>
   <button type="submit" class="button tiny ebc-theme" name="save"><i class="fa fa-floppy-o" aria-hidden="true"></i> SAVE</button>
   </form>

$(document).ready(function(){

        var supplier_id = $('#supplier').val().split(",");
        var period = "<?php echo $period; ?>";
        $.ajax({
            url: "fetch_rate.php",
            method: "POST",
            data:{supplierID:supplier_id[1], periodID:period},
            dataType:"text",
            success:function(data)
            {
                $('#rate').val(data);
            }
        });

});

   $(document).ready(SterlingCalc);
   document.getElementById('decimal').addEventListener("keyup", SterlingCalc);

   var rate = document.getElementById('rate');
   var sup_cost = document.getElementById('decimal');

   function SterlingCalc(){

      document.getElementById('sterling').value = (sup_cost.value / rate.value).toFixed(2) || 0;

   }
</code>```

How do I add code so that the calulation runs on the page load if both the "rate" and "decimal" fields are already loaded (for example, values are populated by database)?

Thanks,

John

答:
you are tryng to mix some of jquery with standard js that it's not a best practice, with jquery you can do something like this:</p>

```<code>    $(document).ready(function () {

     let sterlingFunc = function (){

     let rate = $('#rate');
     let sup_cost = $('#decimal');
     let value = (sup_cost.value / rate.value).toFixed(2) || 0;
     $('#sterling').val(value);
     // maybe return value
     }

     $("#decimal").on("keyup", sterlingFunc());

     // to run when page is loaded
     sterlingFunc();

    });
</code>```

Title: Running script on page load

Body:
I am using the following code to run a calculation as the user type in a number.

   <form action="index.php" method="post" autocomplete="off" data-abide>
   <input type="text" id="rate" name="rate">
   <input type="text" name="supplier_cost" class="value-right" pattern="\d*" value="<?php echo $supplier_cost; ?>" id="decimal" required>
   <input type="text" name="sterling" id="sterling" class="value-right" disabled>
   <button type="submit" class="button tiny ebc-theme" name="save"> SAVE</button>
   </form>

$(document).ready(function(){

        var supplier_id = $('#supplier').val().split(",");
        var period = "<?php echo $period; ?>";
        $.ajax({
            url: "fetch_rate.php",
            method: "POST",
            data:{supplierID:supplier_id[1], periodID:period},
            dataType:"text",
            success:function(data)
            {
                $('#rate').val(data);
            }
        });

});

   $(document).ready(SterlingCalc);
   document.getElementById('decimal').addEventListener("keyup", SterlingCalc);

   var rate = document.getElementById('rate');
   var sup_cost = document.getElementById('decimal');

   function SterlingCalc(){

      document.getElementById('sterling').value = (sup_cost.value / rate.value).toFixed(2) || 0;

   }

How do I add code so that the calulation runs on the page load if both the "rate" and "decimal" fields are already loaded (for example, values are populated by database)?

Thanks,

John

Body:
you are tryng to mix some of jquery with standard js that it's not a best practice, with jquery you can do something like this:

    $(document).ready(function () {

     let sterlingFunc = function (){

     let rate = $('#rate');
     let sup_cost = $('#decimal');
     let value = (sup_cost.value / rate.value).toFixed(2) || 0;
     $('#sterling').val(value);
     // maybe return value
     }

     $("#decimal").on("keyup", sterlingFunc());

     // to run when page is loaded
     sterlingFunc();

    });


问:
Selectively copy and paste rows with given criteria
I am trying to select rows in a table based on the word "Yes" being present in column J.

I have a table going from column A to J, and I want to select the rows where there is a "Yes" in column J and paste only those rows into a new sheet.

Once selected, I need to copy these rows to a new sheet or word document.

I have tried a range of forumulas, this is for Windows MS Excel software, using a VBA Macro.

I am using the following VBA, but having issues:

```<code>Sub Macro1()
 Dim rngJ As Range
    Dim cell As Range

    Set rngJ = Range("J1", Range("J65536").End(xlUp))
    Set wsNew = ThisWorkbook.Worksheets.Add

    For Each cell In rngJ
        If cell.Value = "Yes" Then
            cell.EntireRow.Copy

            wsNew.Sheets("Sheet1").Range("J65536").End(xlUp).Offset(1, 0).Select

            ActiveSheet.Paste
        End If
    Next cell

End Sub
</code>```

Any help would be very much appreciated!

答:
Use something like this

```<code>Option Explicit

Public Sub CopyYesRowsToNewWorksheet()
    Dim wsSource As Worksheet
    Set wsSource = ThisWorkbook.ActiveSheet 'better define sheet by name ThisWorkbook.Worksheets("SourceSheet")

    Dim DataRangeJ As Variant 'read "yes" data into array for faster access
    DataRangeJ = wsSource.Range("J1", wsSource.Range("J" & wsSource.Rows.Count).End(xlUp)).Value

    Dim wsNew As Worksheet
    Set wsNew = ThisWorkbook.Worksheets.Add

    Dim NextFreeRow As Long
    NextFreeRow = 1 'start pasting in this row in the new sheet

    If IsArray(DataRangeJ) Then
        Dim iRow As Long
        For iRow = LBound(DataRangeJ) To UBound(DataRangeJ) 'loop through data array
            If DataRangeJ(iRow, 1) = "yes" Then
                wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value 'copy the values of the row
                NextFreeRow = NextFreeRow + 1
            End If
        Next iRow
    ElseIf DataRangeJ = "yes" Then 'if only the first row has data
        wsNew.Rows(NextFreeRow).Value = wsSource.Rows(1).Value
    End If
End Sub
</code>```

The line

```<code>wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value
</code>```

only copys the value without formatting. If you also want to copy the formatting replace it with

```<code>wsSource.Rows(iRow).Copy Destination:=wsNew.Rows(NextFreeRow)
</code>```

Body:
I am trying to select rows in a table based on the word "Yes" being present in column J.

I have a table going from column A to J, and I want to select the rows where there is a "Yes" in column J and paste only those rows into a new sheet.

Once selected, I need to copy these rows to a new sheet or word document.

I have tried a range of forumulas, this is for Windows MS Excel software, using a VBA Macro.

I am using the following VBA, but having issues:

Sub Macro1()
 Dim rngJ As Range
    Dim cell As Range

    Set rngJ = Range("J1", Range("J65536").End(xlUp))
    Set wsNew = ThisWorkbook.Worksheets.Add

    For Each cell In rngJ
        If cell.Value = "Yes" Then
            cell.EntireRow.Copy

            wsNew.Sheets("Sheet1").Range("J65536").End(xlUp).Offset(1, 0).Select

            ActiveSheet.Paste
        End If
    Next cell

End Sub

Any help would be very much appreciated!

Body:
Use something like this

Option Explicit

Public Sub CopyYesRowsToNewWorksheet()
    Dim wsSource As Worksheet
    Set wsSource = ThisWorkbook.ActiveSheet 'better define sheet by name ThisWorkbook.Worksheets("SourceSheet")

    Dim DataRangeJ As Variant 'read "yes" data into array for faster access
    DataRangeJ = wsSource.Range("J1", wsSource.Range("J" & wsSource.Rows.Count).End(xlUp)).Value

    Dim wsNew As Worksheet
    Set wsNew = ThisWorkbook.Worksheets.Add

    Dim NextFreeRow As Long
    NextFreeRow = 1 'start pasting in this row in the new sheet

    If IsArray(DataRangeJ) Then
        Dim iRow As Long
        For iRow = LBound(DataRangeJ) To UBound(DataRangeJ) 'loop through data array
            If DataRangeJ(iRow, 1) = "yes" Then
                wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value 'copy the values of the row
                NextFreeRow = NextFreeRow + 1
            End If
        Next iRow
    ElseIf DataRangeJ = "yes" Then 'if only the first row has data
        wsNew.Rows(NextFreeRow).Value = wsSource.Rows(1).Value
    End If
End Sub

The line

wsNew.Rows(NextFreeRow).Value = wsSource.Rows(iRow).Value

only copys the value without formatting. If you also want to copy the formatting replace it with

wsSource.Rows(iRow).Copy Destination:=wsNew.Rows(NextFreeRow)


问:
Why does TS do not get React state assertion from Interface?
So, I have this component:

```<code>type TypeofArray<
    ArrayTypeInstance
> = ArrayTypeInstance extends (infer ElementType)[] ? ElementType : never;

type Property = {
    dataId: number;
    address: string;
    price?: number;
    transactionType: string;
    bedrooms?: number;
    coverImageUrl?: string;
    modifiedWhen: string;
    currentStage?: string;
};

type PropertiesState = {
    searchType: TypeofArray<typeof SEARCH_TYPES>;
    properties: Property[];
    [key: number]: boolean;
};

export class Properties extends Component<{}, PropertiesState> {
    readonly state = {
        searchType: 'buy',
        properties: []
    };
...
</code>```

And here I am trying access this piece of state [key: number]: boolean;:

```<code> <PropertyCard
                    isFavorite={this.state[property.dataId]}
                />
</code>```

But I get this error:

Error:(98, 33) TS7017: Element implicitly has an 'any' type because type '{ searchType: string; properties: never[]; }' has no index signature.

If I explicitly annotate state like this:

```<code>readonly state: PropertiesState = {
    searchType: 'buy',
    properties: []
};
</code>```

error disappears.

Why? What is better way to fix this error?

Thanks!

答:
Declaring state = { searchType: 'buy', properties: [] } narrows the type of state to { searchType: 'buy', properties: never[] } (never[] essentially being an empty array). Depending of your compiler settings, properties may be narrowed to any[] instead.

This happens because TypeScript infers types from property declarations. Those inferred types override any shadowed types from extended classes such as React.Component.

To resolve, there's a few options:

Re-widen the type as you did by annotating state with PropertiesState

Re-widen by casting state = { /* ... */ } as PropertiesState.

Assign this.state in the constructor to avoid narrowing:

```<code>export class Properties extends Component<{}, PropertiesState> {
    constructor(props: {}) {
        super(props);
        state = {
            searchType: 'buy',
            properties: []
        };
    }
    // ...
};
</code>```

Body:
So, I have this component:

type TypeofArray<
    ArrayTypeInstance
> = ArrayTypeInstance extends (infer ElementType)[] ? ElementType : never;

type Property = {
    dataId: number;
    address: string;
    price?: number;
    transactionType: string;
    bedrooms?: number;
    coverImageUrl?: string;
    modifiedWhen: string;
    currentStage?: string;
};

type PropertiesState = {
    searchType: TypeofArray<typeof SEARCH_TYPES>;
    properties: Property[];
    [key: number]: boolean;
};

export class Properties extends Component<{}, PropertiesState> {
    readonly state = {
        searchType: 'buy',
        properties: []
    };
...

And here I am trying access this piece of state [key: number]: boolean;:

 <PropertyCard
                    isFavorite={this.state[property.dataId]}
                />

But I get this error:

Error:(98, 33) TS7017: Element implicitly has an 'any' type because type '{ searchType: string; properties: never[]; }' has no index signature.

If I explicitly annotate state like this:

readonly state: PropertiesState = {
    searchType: 'buy',
    properties: []
};

error disappears.

Why? What is better way to fix this error?

Thanks!

Body:
Declaring state = { searchType: 'buy', properties: [] } narrows the type of state to { searchType: 'buy', properties: never[] } (never[] essentially being an empty array). Depending of your compiler settings, properties may be narrowed to any[] instead.

This happens because TypeScript infers types from property declarations. Those inferred types override any shadowed types from extended classes such as React.Component.

To resolve, there's a few options:

Re-widen the type as you did by annotating state with PropertiesState

Re-widen by casting state = { /* ... */ } as PropertiesState.

Assign this.state in the constructor to avoid narrowing:

export class Properties extends Component<{}, PropertiesState> {
    constructor(props: {}) {
        super(props);
        state = {
            searchType: 'buy',
            properties: []
        };
    }
    // ...
};


问:
How to write a column name with dot (".") in the SELECT clause?
I'm trying to write a column name using "." with no success

sample:

```<code>SELECT PrmTable.Value = MAX(Value)
FROM TempTable
</code>```

or

```<code>SELECT MAX(Value) AS PrmTable.Value
FROM TempTable
</code>```

Any idea ?

答:
Just enclose it in square brackets, and it will work

e.g.

```<code>SELECT MAX(Value) AS [PrmTable.Value]
FROM TempTable
</code>```

Body:
I'm trying to write a column name using "." with no success

sample:

SELECT PrmTable.Value = MAX(Value)
FROM TempTable

or

SELECT MAX(Value) AS PrmTable.Value
FROM TempTable

Any idea ?

Body:
Just enclose it in square brackets, and it will work

e.g.

SELECT MAX(Value) AS [PrmTable.Value]
FROM TempTable


问:
How can I select only some child nodes from an XML file in C#?
I have an XML file that I want to parse. It is longer than what I shall post here, but only this part interests me in this question:

```<code>       <Team>
        <TeamId>1187457</TeamId>
        <TeamName>Zanardi Redwings</TeamName>
        <Arena>
          <ArenaId>1184019</ArenaId>
          <ArenaName>Evolution</ArenaName>
        </Arena>
        <League>
          <LeagueId>37</LeagueId>
          <LeagueName>România</LeagueName>
        </League>
        <Country>
          <CountryId>36</CountryId>
          <CountryName>România</CountryName>
        </Country>
        <LeagueLevelUnit>
          <LeagueLevelUnitId>4109</LeagueLevelUnitId>
          <LeagueLevelUnitName>V.171</LeagueLevelUnitName>
        </LeagueLevelUnit>
        <Region>
          <RegionId>799</RegionId>
          <RegionName>Prahova</RegionName>
        </Region>
        <YouthTeam>
          <YouthTeamId>2337461</YouthTeamId>
          <YouthTeamName>Little Redwings</YouthTeamName>
          <YouthLeague>
            <YouthLeagueId>436902</YouthLeagueId>
            <YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName>
          </YouthLeague>
        </YouthTeam>
      </Team>
</code>```

From the part above, I only need to read the data from the TeamId and TeamName child nodes. To achieve this, I wrote the following code:

```<code>Nodes = Node.SelectNodes("Team");
foreach (XmlNode j in Nodes)
  {
    XmlNodeList TeamDetails = j.SelectNodes("*");
    foreach (XmlNode k in TeamDetails)
      {
         switch (k.Name)
           {
             case "TeamName":
               {
                  UserTeamNames[counter] = k.InnerXml;
                  break;
               }
             case "TeamId":
               {
                  if (!int.TryParse(k.InnerXml, out UserTeamIDs[counter]))
                   {
                      ShowErrorMessageBox("Parsing TeamID from XML file failed!"); //A function which sets some parameters for MessageBox.Show() then calls it
                   }
                  break;
                }
            }
       }
   }
</code>```

In the code above, counter is an int variable, which I need in other part of the code.

The code works perfectly, but I want to eliminate the useless looping and testing when the node I am working on is not either TeamName or TeamID.

I suspect the answer I am looking for has something to do with XPath expressions, but I am not sure.

How can I read the data from only the mentioned nodes, without any useless operations?

答:
You can use XmlDocument.GetElementsByTagName method.
For your example I will do something like this :

```<code>XmlNodeList elemList = doc.GetElementsByTagName("TeamName");
XmlNodeList elemList = doc.GetElementsByTagName("TeamId");
</code>```

The result is An XmlNodeList containing a list of all matching nodes. If no nodes match name, the returned collection will be empty.

Body:
I have an XML file that I want to parse. It is longer than what I shall post here, but only this part interests me in this question:

       <Team>
        <TeamId>1187457</TeamId>
        <TeamName>Zanardi Redwings</TeamName>
        <Arena>
          <ArenaId>1184019</ArenaId>
          <ArenaName>Evolution</ArenaName>
        </Arena>
        <League>
          <LeagueId>37</LeagueId>
          <LeagueName>România</LeagueName>
        </League>
        <Country>
          <CountryId>36</CountryId>
          <CountryName>România</CountryName>
        </Country>
        <LeagueLevelUnit>
          <LeagueLevelUnitId>4109</LeagueLevelUnitId>
          <LeagueLevelUnitName>V.171</LeagueLevelUnitName>
        </LeagueLevelUnit>
        <Region>
          <RegionId>799</RegionId>
          <RegionName>Prahova</RegionName>
        </Region>
        <YouthTeam>
          <YouthTeamId>2337461</YouthTeamId>
          <YouthTeamName>Little Redwings</YouthTeamName>
          <YouthLeague>
            <YouthLeagueId>436902</YouthLeagueId>
            <YouthLeagueName>Normandie Ligue des jeunes</YouthLeagueName>
          </YouthLeague>
        </YouthTeam>
      </Team>

From the part above, I only need to read the data from the TeamId and TeamName child nodes. To achieve this, I wrote the following code:

Nodes = Node.SelectNodes("Team");
foreach (XmlNode j in Nodes)
  {
    XmlNodeList TeamDetails = j.SelectNodes("*");
    foreach (XmlNode k in TeamDetails)
      {
         switch (k.Name)
           {
             case "TeamName":
               {
                  UserTeamNames[counter] = k.InnerXml;
                  break;
               }
             case "TeamId":
               {
                  if (!int.TryParse(k.InnerXml, out UserTeamIDs[counter]))
                   {
                      ShowErrorMessageBox("Parsing TeamID from XML file failed!"); //A function which sets some parameters for MessageBox.Show() then calls it
                   }
                  break;
                }
            }
       }
   }

In the code above, counter is an int variable, which I need in other part of the code.

The code works perfectly, but I want to eliminate the useless looping and testing when the node I am working on is not either TeamName or TeamID.

I suspect the answer I am looking for has something to do with XPath expressions, but I am not sure.

How can I read the data from only the mentioned nodes, without any useless operations?

Body:
You can use XmlDocument.GetElementsByTagName method.
For your example I will do something like this :

XmlNodeList elemList = doc.GetElementsByTagName("TeamName");
XmlNodeList elemList = doc.GetElementsByTagName("TeamId");

The result is An XmlNodeList containing a list of all matching nodes. If no nodes match name, the returned collection will be empty.