问:
Gridview updated whole table and not a single row and after i gave it ID im getting error"Must declare the scalar variable "@IDDjelatnik"
In code behind i only have SqlDataSource1.Insert() which im using to insert text from the table down to gridview. Im trying to edit but after i edit one row it applies to the whole table, but after i added the ID to update command im getting error that i need to declare scalar variable @IDDjelatnik. Im using web forms

```<code><asp:Content ID="content1" runat="server" ContentPlaceHolderID="content">
<div>
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="IDDjelatnik" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="Black" AllowPaging="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellSpacing="2" Width="1105px">
        <Columns>
            <%--<asp:BoundField DataField="ImeTima" HeaderText="ImeTima" SortExpression="ImeTima" />--%>
            <asp:CommandField ShowEditButton="True" />
            <asp:BoundField DataField="ImePrezime" HeaderText="ImePrezime" SortExpression="ImePrezime" />
            <asp:BoundField DataField="TipDjelatnika" HeaderText="TipDjelatnika" SortExpression="TipDjelatnika" />
            <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label Text='<%# Bind("ImeTima") %>' ID="lbImeTima" runat="server" />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="DropImeTima" runat="server" DataSourceID="SqlDataSource2" DataTextField="ImeTima" DataValueField="IDTim" SelectedValue='<%# Bind("TimID") %>'>
                    </asp:DropDownList>
                </EditItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#CCCCCC" ForeColor="White" HorizontalAlign="Left" />
        <RowStyle BackColor="White" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#808080" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        InsertCommand="INSERT INTO [Djelatnik] ([ImePrezime], [TipDjelatnika], [Email], [TimID]) VALUES (@ImePrezime, @TipDjelatnika, @Email, @TimID)" OldValuesParameterFormatString="original_{0}"
        SelectCommand="select IDDjelatnik,ImePrezime, TipDjelatnika, Email,TimID, Tim.ImeTima as ImeTima from Djelatnik inner join Tim on Tim.IDTim = Djelatnik.TimID"
        UpdateCommand="update Djelatnik set IDDjelatnik = @IDDjelatnik, ImePrezime = @ImePrezime, TipDjelatnika = @TipDjelatnika, Email = @Email,TimID = @TimID">

        <InsertParameters>
            <asp:Parameter Name="IDDjelatnik" Type="Int32"/>
            <asp:ControlParameter Name="ImePrezime" Type="String" ControlID="txtImePrezime" />
            <asp:ControlParameter Name="TipDjelatnika" Type="String" ControlID="txtTipDjelatnika" />
            <asp:ControlParameter Name="Email" Type="String" ControlID="txtEmail" />
            <asp:ControlParameter Name="TimID" Type="Int32" ControlID="txtImeTima" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="IDDjelatnik" Type="int32" />
            <asp:Parameter Name="ImePrezime" Type="String" />
            <asp:Parameter Name="TipDjelatnika" Type="String" />
            <asp:Parameter Name="Email" Type="String" />
            <asp:Parameter Name="TimID" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="select ImeTima,IDTim from Tim"></asp:SqlDataSource>
</div>

<table CssClass="table table-light">
    <tr>
        <td>
            <asp:Label Text="Ime Prezime: " runat="server"/>
            <asp:TextBox ID="txtImePrezime" runat="server"></asp:TextBox>
        </td>
        <td>
            <asp:Label Text="Tip Djelatnika: " runat="server" />
            <asp:TextBox ID="txtTipDjelatnika" runat="server"></asp:TextBox>
        </td>
        <td>
            <asp:Label Text="Email: " runat="server" />
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
        </td>
        <td>
            <asp:Label Text="Tim: " runat="server" />
            <asp:TextBox runat="server" ID="txtImeTima"></asp:TextBox>
        </td>
        <td>
            <asp:Button Text="Dodaj" ID="btnDodaj" OnClick="btnDodaj_Click" runat="server" CssClass="btn btn-primary" />
        </td>
    </tr>
</table>
</code>```

答: In UpdateParameters you need to declare your id field @IDDjelatnik</p>

Body:
In code behind i only have SqlDataSource1.Insert() which im using to insert text from the table down to gridview. Im trying to edit but after i edit one row it applies to the whole table, but after i added the ID to update command im getting error that i need to declare scalar variable @IDDjelatnik. Im using web forms

<asp:Content ID="content1" runat="server" ContentPlaceHolderID="content">

    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="IDDjelatnik" DataSourceID="SqlDataSource1" CellPadding="4" ForeColor="Black" AllowPaging="True" BackColor="#CCCCCC" BorderColor="#999999" BorderStyle="Solid" BorderWidth="3px" CellSpacing="2" Width="1105px">
        <Columns>
            <%--<asp:BoundField DataField="ImeTima" HeaderText="ImeTima" SortExpression="ImeTima" />--%>
            <asp:CommandField ShowEditButton="True" />
            <asp:BoundField DataField="ImePrezime" HeaderText="ImePrezime" SortExpression="ImePrezime" />
            <asp:BoundField DataField="TipDjelatnika" HeaderText="TipDjelatnika" SortExpression="TipDjelatnika" />
            <asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:Label Text='<%# Bind("ImeTima") %>' ID="lbImeTima" runat="server" />
                </ItemTemplate>
                <EditItemTemplate>
                    <asp:DropDownList ID="DropImeTima" runat="server" DataSourceID="SqlDataSource2" DataTextField="ImeTima" DataValueField="IDTim" SelectedValue='<%# Bind("TimID") %>'>
                    </asp:DropDownList>
                </EditItemTemplate>
            </asp:TemplateField>
        </Columns>
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <PagerStyle BackColor="#CCCCCC" ForeColor="White" HorizontalAlign="Left" />
        <RowStyle BackColor="White" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#808080" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        InsertCommand="INSERT INTO [Djelatnik] ([ImePrezime], [TipDjelatnika], [Email], [TimID]) VALUES (@ImePrezime, @TipDjelatnika, @Email, @TimID)" OldValuesParameterFormatString="original_{0}"
        SelectCommand="select IDDjelatnik,ImePrezime, TipDjelatnika, Email,TimID, Tim.ImeTima as ImeTima from Djelatnik inner join Tim on Tim.IDTim = Djelatnik.TimID"
        UpdateCommand="update Djelatnik set IDDjelatnik = @IDDjelatnik, ImePrezime = @ImePrezime, TipDjelatnika = @TipDjelatnika, Email = @Email,TimID = @TimID">

        <InsertParameters>
            <asp:Parameter Name="IDDjelatnik" Type="Int32"/>
            <asp:ControlParameter Name="ImePrezime" Type="String" ControlID="txtImePrezime" />
            <asp:ControlParameter Name="TipDjelatnika" Type="String" ControlID="txtTipDjelatnika" />
            <asp:ControlParameter Name="Email" Type="String" ControlID="txtEmail" />
            <asp:ControlParameter Name="TimID" Type="Int32" ControlID="txtImeTima" />
        </InsertParameters>
        <UpdateParameters>
            <asp:Parameter Name="IDDjelatnik" Type="int32" />
            <asp:Parameter Name="ImePrezime" Type="String" />
            <asp:Parameter Name="TipDjelatnika" Type="String" />
            <asp:Parameter Name="Email" Type="String" />
            <asp:Parameter Name="TimID" Type="Int32" />
        </UpdateParameters>
    </asp:SqlDataSource>
    <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConflictDetection="CompareAllValues" ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="select ImeTima,IDTim from Tim"></asp:SqlDataSource>

            <asp:Label Text="Ime Prezime: " runat="server"/>
            <asp:TextBox ID="txtImePrezime" runat="server"></asp:TextBox>

            <asp:Label Text="Tip Djelatnika: " runat="server" />
            <asp:TextBox ID="txtTipDjelatnika" runat="server"></asp:TextBox>

            <asp:Label Text="Email: " runat="server" />
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

            <asp:Label Text="Tim: " runat="server" />
            <asp:TextBox runat="server" ID="txtImeTima"></asp:TextBox>

            <asp:Button Text="Dodaj" ID="btnDodaj" OnClick="btnDodaj_Click" runat="server" CssClass="btn btn-primary" />


来源: stackexchange

问:
is pyspark MLlib still maintained developed?
I the 2017 book "learning pyspark" one can read:

Even though MLlib is now in a maintenance mode, that is, it not actively being developed (and will be most likely be deprecated later) ...

So I wanted to know if there is any update about the situation. Is MLlib still maintained? Will it be deprecated soon?

答:
As of Spark 2.0, the RDD-based APIs in the spark.mllib package have entered maintenance mode. The primary Machine Learning API for Spark is now the DataFrame-based API in the spark.ml package.

Taken from https://spark.apache.org/docs/latest/ml-guide.html

So, MLlib is in "maintenance mode", and spark.ml is here as a replacement.

ContentLicense: CC BY-SA 4.0


问:
Why does the output keep returning a 'None' value at the last?
```<code>def range_test(start, end):
    while start <= end:
        print(start)
        start+=1

print(range_test(1,5))
</code>```

Output:

```<code>1
2
3
4
5
None

Process finished with exit code 0
</code>```

答:
You don't define a return value in your code, so by default it returns None. Calling print(func) prints the returned value. It would display normally if you did either of these:

```<code>def range_test(start, end):
    while start <= end:
        print(start)
        start+=1

range_test(1,5)

def range_test(start, end):
    range_list = []
    while start <= end:
        range_list.append(start)
        start+=1
    return "\n".join(range_list)
range_test(1,5)
</code>```

Body:
def range_test(start, end):
    while start <= end:
        print(start)
        start+=1

print(range_test(1,5))

Output:

1
2
3
4
5
None

Process finished with exit code 0

Body:
You don't define a return value in your code, so by default it returns None. Calling print(func) prints the returned value. It would display normally if you did either of these:

def range_test(start, end):
    while start <= end:
        print(start)
        start+=1

range_test(1,5)

def range_test(start, end):
    range_list = []
    while start <= end:
        range_list.append(start)
        start+=1
    return "\n".join(range_list)
range_test(1,5)


问:
Random number generator with conditions - Python
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

```<code>import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)
</code>```

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

```<code>rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)
</code>```

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you

答:
The question is, as pointed out by others, whether we allow correlations between the numbers being high/low and even/odd. The following code does not introduce this correlation.

```<code>import random
n = 5
odd = 2
high = 2

odd_indices = random.sample(range(n), odd)
high_indices = random.sample(range(n), high)
out = random.sample(range(26),n)
for i in range(n):
    out[i] *= 2
    if i in odd_indices:
        out[i] += 1
    if i in high_indices:
        out[i] += 50
</code>```

Please note that this includes the number 100 as output option. Strictly speaking you did not include it, so one could introduce a shift if the 100 is hit:

```<code>    if out[i]==100:
        out[i] -= random.sample(range(1,25),1)[0]*2
</code>```

This code is not optimized for performance.

edit

This code will have an irregularity, though, as in each possible output 2k and 2k+1 never occur at the same time for any k.

Body:
I am new to Python and trying to generate 5 numbers with 2 conditions:

There must be 3 even and 2 odd numbers

From those 5 numbers 3 must be low (1,51) and 2 high (51,100). Which number will be low or high is not of interest.

I have managed to solve the first part:

import random
rand_even = random.sample(range(0, 100, 2), 3)
rand_odd = random.sample(range(1, 100, 2), 2)
rand_total = rand_even,rand_odd
print(rand_total)

Obviously this is not getting me anywhere
For the second part i thought i could use something like:

rand_low = random.sample(range(0, 51), 3)
rand_high = random.sample(range(51,100), 2)

But obviously this is not the way as i am getting more than 5 numbers.

Any help would be appriciated.
Thank you

Body:
The question is, as pointed out by others, whether we allow correlations between the numbers being high/low and even/odd. The following code does not introduce this correlation.

import random
n = 5
odd = 2
high = 2

odd_indices = random.sample(range(n), odd)
high_indices = random.sample(range(n), high)
out = random.sample(range(26),n)
for i in range(n):
    out[i] *= 2
    if i in odd_indices:
        out[i] += 1
    if i in high_indices:
        out[i] += 50

Please note that this includes the number 100 as output option. Strictly speaking you did not include it, so one could introduce a shift if the 100 is hit:

    if out[i]==100:
        out[i] -= random.sample(range(1,25),1)[0]*2

This code is not optimized for performance.

edit

This code will have an irregularity, though, as in each possible output 2k and 2k+1 never occur at the same time for any k.


问:
Best practise for Progress Bar in Python's PyGTK
I would like to get feedback on others' opinions of best practice for how to implement a progress bar in Python's PyGTK.

The work that the progress bar was to represent was very significant computationally.  Therefore, I wanted the work to be done in a separate process (thus giving the operating system the possibility to run it on a different core).  I wanted to be able to start the work, and then continue to use the GUI for other tasks while waiting for the results.

I have seen many people asking this question indirectly, but I have not seen any concrete expert advice.  I hope that by asking this question we will see a community's combined expertise.

答:
I realise now that I do not have enough reputation to make this a community wiki, so I hope someone else can change this to wiki-status.  Thanks.

I am by no means an expert Python programmer, however I have spent some time trying to find an acceptable solution.  I hope that the following code may act as a starting point to this discussion.

```<code>import gobject
import pygtk
pygtk.require('2.0')
import gtk
import multiprocessing
import threading
import time

gtk.gdk.threads_init()

class Listener(gobject.GObject):
    __gsignals__ = {
        'updated' : (gobject.SIGNAL_RUN_LAST,
                     gobject.TYPE_NONE,
                     (gobject.TYPE_FLOAT, gobject.TYPE_STRING)),
        'finished': (gobject.SIGNAL_RUN_LAST,
                     gobject.TYPE_NONE,
                     ())
    }

    def __init__(self, queue):
        gobject.GObject.__init__(self)
        self.queue = queue

    def go(self):
        print "Listener has started"
        while True:
            # Listen for results on the queue and process them accordingly
            data = self.queue.get()
            # Check if finished
            if data[1]=="finished":
                print "Listener is finishing."
            self.emit("finished")
            return
            else:
                self.emit('updated', data[0], data[1])

gobject.type_register(Listener)

class Worker():
    def __init__(self, queue):
        self.queue = queue

    def go(self):
        print "The worker has started doing some work (counting from 0 to 9)"
        for i in range(10):
        proportion = (float(i+1))/10
        self.queue.put((proportion, "working..."))
            time.sleep(0.5)
        self.queue.put((1.0, "finished"))
        print "The worker has finished."

class Interface:
    def __init__(self):
        self.process = None
        self.progress = gtk.ProgressBar()
        button = gtk.Button("Go!")
        button.connect("clicked", self.go)
        vbox = gtk.VBox(spacing=5)
        vbox.pack_start(self.progress)
        vbox.pack_start(button)
        vbox.show_all()
        self.frame = vbox

    def main(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_border_width(10)
        window.add(self.frame)
        window.show()
        window.connect("destroy", self.destroy)

        gtk.main()

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def callbackDisplay(self, obj, fraction, text, data=None):
        self.progress.set_fraction(fraction)
        self.progress.set_text(text)

    def callbackFinished(self, obj, data=None):
        if self.process==None:
            raise RuntimeError("No worker process started")
        print "all done; joining worker process"
        self.process.join()
        self.process = None

        self.progress.set_fraction(1.0)
        self.progress.set_text("done")

   def go(self, widget, data=None):
        if self.process!=None:
            return

        print "Creating shared Queue"
        queue = multiprocessing.Queue()

        print "Creating Worker"
        worker = Worker(queue)

        print "Creating Listener"
        listener = Listener(queue)
        listener.connect("updated",self.callbackDisplay)
        listener.connect("finished",self.callbackFinished)

        print "Starting Worker"
        self.process = multiprocessing.Process(target=worker.go, args=())
        self.process.start()

        print "Starting Listener"
        thread = threading.Thread(target=listener.go, args=())
        thread.start()

if __name__ == '__main__':
    gui = Interface()
    gui.main()
</code>```

Some of the references I found useful were:

A Progress Bar using Threads

Sub-classing GObject in Python

Signals and Threads

Always always always always make sure you have called gtk.gdk.threads_init

OwnerDisplayName: Matthew Walker

ContentLicense: CC BY-SA 2.5

Body:
I realise now that I do not have enough reputation to make this a community wiki, so I hope someone else can change this to wiki-status.  Thanks.

I am by no means an expert Python programmer, however I have spent some time trying to find an acceptable solution.  I hope that the following code may act as a starting point to this discussion.

import gobject
import pygtk
pygtk.require('2.0')
import gtk
import multiprocessing
import threading
import time

gtk.gdk.threads_init()

class Listener(gobject.GObject):
    __gsignals__ = {
        'updated' : (gobject.SIGNAL_RUN_LAST,
                     gobject.TYPE_NONE,
                     (gobject.TYPE_FLOAT, gobject.TYPE_STRING)),
        'finished': (gobject.SIGNAL_RUN_LAST,
                     gobject.TYPE_NONE,
                     ())
    }

    def __init__(self, queue):
        gobject.GObject.__init__(self)
        self.queue = queue

    def go(self):
        print "Listener has started"
        while True:
            # Listen for results on the queue and process them accordingly
            data = self.queue.get()
            # Check if finished
            if data[1]=="finished":
                print "Listener is finishing."
            self.emit("finished")
            return
            else:
                self.emit('updated', data[0], data[1])

gobject.type_register(Listener)

class Worker():
    def __init__(self, queue):
        self.queue = queue

    def go(self):
        print "The worker has started doing some work (counting from 0 to 9)"
        for i in range(10):
        proportion = (float(i+1))/10
        self.queue.put((proportion, "working..."))
            time.sleep(0.5)
        self.queue.put((1.0, "finished"))
        print "The worker has finished."

class Interface:
    def __init__(self):
        self.process = None
        self.progress = gtk.ProgressBar()
        button = gtk.Button("Go!")
        button.connect("clicked", self.go)
        vbox = gtk.VBox(spacing=5)
        vbox.pack_start(self.progress)
        vbox.pack_start(button)
        vbox.show_all()
        self.frame = vbox

    def main(self):
        window = gtk.Window(gtk.WINDOW_TOPLEVEL)
        window.set_border_width(10)
        window.add(self.frame)
        window.show()
        window.connect("destroy", self.destroy)

        gtk.main()

    def destroy(self, widget, data=None):
        gtk.main_quit()

    def callbackDisplay(self, obj, fraction, text, data=None):
        self.progress.set_fraction(fraction)
        self.progress.set_text(text)

    def callbackFinished(self, obj, data=None):
        if self.process==None:
            raise RuntimeError("No worker process started")
        print "all done; joining worker process"
        self.process.join()
        self.process = None

        self.progress.set_fraction(1.0)
        self.progress.set_text("done")

   def go(self, widget, data=None):
        if self.process!=None:
            return

        print "Creating shared Queue"
        queue = multiprocessing.Queue()

        print "Creating Worker"
        worker = Worker(queue)

        print "Creating Listener"
        listener = Listener(queue)
        listener.connect("updated",self.callbackDisplay)
        listener.connect("finished",self.callbackFinished)

        print "Starting Worker"
        self.process = multiprocessing.Process(target=worker.go, args=())
        self.process.start()

        print "Starting Listener"
        thread = threading.Thread(target=listener.go, args=())
        thread.start()

if __name__ == '__main__':
    gui = Interface()
    gui.main()

Some of the references I found useful were:

A Progress Bar using Threads

Sub-classing GObject in Python

Signals and Threads

Always always always always make sure you have called gtk.gdk.threads_init


问:
How do I get lftp to use SSL/TLS security mechanism from the command line?
I'm trying to log into an ftps site. I've tried giving the login creds at the command line (and putting set parameters in ~/.lftprc, then opening an lftp session and typing those parameters with lftp job control statements. Regardless, I keep hitting the same roadblock:

```<code> 421 Sorry, cleartext sessions are not accepted on this server.
 Please reconnect using SSL/TLS security mechanisms.
</code>```

I got furthest with the following parameters, but keep getting the error above.

How do I get lftp to use SSL/TLS security mechanism from the command line?

The objective is to script the access to this ftps site using bash (programming without using expect).

```<code> lftp
 lftp :~> set ssl-allow false
 lftp :~> set passive-mode yes
 lftp :~> open ftp.abc.com
 lftp ftp.abc.com:~> login theuser
 Password:
 lftp theuser@ftp.abc.com:~> cd
  `cd' at 0 [Delaying before reconnect: 26]
 CTRL-C
 lftp theuser@ftp.abc.com:~> debug
 lftp theuser@ftp.abc.com:~> cd
 ---- Connecting to ftp.abc.com (XX.XXX.XX.XX) port 21
 <--- 220-Welcome to the Yahoo! Web Hosting FTP server
 <--- 220-Need help? Get all details at:
 <--- 220-http://help.yahoo.com/help/us/webhosting/gftp/
 <--- 220-
 <--- 220-No anonymous logins accepted.
 <--- 220-Yahoo!
 <--- 220-Local time is now 15:30. Server port: 21.
 <--- 220-This is a private system - No anonymous login
 <--- 220 You will be disconnected after 5 minutes of inactivity.
 ---> FEAT
 <--- 211-Extensions supported:
 <---  EPRT
 <---  IDLE
 <---  MDTM
 <---  SIZE
 <---  MFMT
 <---  REST STREAM
 <---  MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;
 <---  MLSD
 <---  XDBG
 <---  AUTH TLS
 <---  PBSZ
 <---  PROT
 <---  TVFS
 <---  ESTA
 <---  PASV
 <---  EPSV
 <---  SPSV
 <---  ESTP
 <--- 211 End.
 ---> OPTS MLST type;size;modify;UNIX.mode;UNIX.uid;UNIX.gid;
 <--- 200  MLST OPTS type;size;sizd;modify;UNIX.mode;UNIX.uid;UNIX.gid;unique;
 ---> USER theuser
 <--- 421 Sorry, cleartext sessions are not accepted on this server.
 Please reconnect using SSL/TLS security mechanisms.
</code>```

答:
What worked for me step by step with lftp:

get certificate of host with openssl s_client -connect <ftp_hostname>:21 -starttls ftp, at the begining of result I got something like -----BEGIN CERTIFICATE-----
MIIEQzCCAyu.....XjMO
-----END CERTIFICATE-----

copy that -----BEGIN CERTIFICATE-----
MIIEQzCCAyu.....XjMO
-----END CERTIFICATE----- into /etc/ssl/certs/ca-certificates.crt

Into lftp configuration reference this certificate file adding to /etc/lftp.conf for systemwide set ssl:ca-file "/etc/ssl/certs/ca-certificates.crt"

and then do your sync or whatever with lftp, on my case it is lftp -u "${FTP_USER},${FTP_PWD}" ${FTP_HOST} -e "set net:timeout 10;mirror ${EXCLUDES} -R ${LOCAL_SOURCE_PATH} ${REMOTE_DEST_PATH} ; quit"

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to log into an ftps site. I've tried giving the login creds at the command line (and putting set parameters in ~/.lftprc, then opening an lftp session and typing those parameters with lftp job control statements. Regardless, I keep hitting the same roadblock:

 421 Sorry, cleartext sessions are not accepted on this server.
 Please reconnect using SSL/TLS security mechanisms.

I got furthest with the following parameters, but keep getting the error above.

How do I get lftp to use SSL/TLS security mechanism from the command line?

The objective is to script the access to this ftps site using bash (programming without using expect).

 lftp
 lftp :~> set ssl-allow false
 lftp :~> set passive-mode yes
 lftp :~> open ftp.abc.com
 lftp ftp.abc.com:~> login theuser
 Password:
 lftp theuser@ftp.abc.com:~> cd
  `cd' at 0 [Delaying before reconnect: 26]
 CTRL-C
 lftp theuser@ftp.abc.com:~> debug
 lftp theuser@ftp.abc.com:~> cd
 ---- Connecting to ftp.abc.com (XX.XXX.XX.XX) port 21
 <--- 220-Welcome to the Yahoo! Web Hosting FTP server
 <--- 220-Need help? Get all details at:
 <--- 220-http://help.yahoo.com/help/us/webhosting/gftp/
 <--- 220-
 <--- 220-No anonymous logins accepted.
 <--- 220-Yahoo!
 <--- 220-Local time is now 15:30. Server port: 21.
 <--- 220-This is a private system - No anonymous login
 <--- 220 You will be disconnected after 5 minutes of inactivity.
 ---> FEAT
 <--- 211-Extensions supported:
 <---  EPRT
 <---  IDLE
 <---  MDTM
 <---  SIZE
 <---  MFMT
 <---  REST STREAM
 <---  MLST type*;size*;sizd*;modify*;UNIX.mode*;UNIX.uid*;UNIX.gid*;unique*;
 <---  MLSD
 <---  XDBG
 <---  AUTH TLS
 <---  PBSZ
 <---  PROT
 <---  TVFS
 <---  ESTA
 <---  PASV
 <---  EPSV
 <---  SPSV
 <---  ESTP
 <--- 211 End.
 ---> OPTS MLST type;size;modify;UNIX.mode;UNIX.uid;UNIX.gid;
 <--- 200  MLST OPTS type;size;sizd;modify;UNIX.mode;UNIX.uid;UNIX.gid;unique;
 ---> USER theuser
 <--- 421 Sorry, cleartext sessions are not accepted on this server.
 Please reconnect using SSL/TLS security mechanisms.


问:
generate two git patch files simultaneously without conflicts
My colleague and I both work on the same latest version of a branch and we are developing
two totally isolated features, in other words, there would no any conflict/overlapping between his change and mine.

Once we both complete our features and generate the patch file against the latest version of the branch individually.  We both handed our patches to another colleague and he also has the latest version of the latest branch. Could I assume that the colleague could just apply two patches in any order/way successfully?

In other words, we don't have to rebase/merge each other's change before we make the patch file if we know those changes could not cause any conflicts. Is that correct?

Thank you.

答: It's not that simple because patches will use references to line numbers... that might have changed once one of the two patches has been applied (if you both worked on the same file, for example). The safest bet there is to have your colleague that is getting the patches to apply each one of them on a separate branch from the latest revision that you all share and then they could merge fine.


问:
Extract specific dictionaries from a list of nested dictionaries to a temp list
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.

I tried this:

new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
    def approachA():
        for data in new_users:          # new_users is a list of nested dictionaries
            if data == '0':
                 print("found 0")
                 keys = data.keys()
                 for key in keys:
                     if key == '0':
                        key.pop() # tried to deleted delete the elements at first
```

<p>It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.</p>

<p>This is a simple version of what I am trying to do:</p>

<pre class="lang-py prettyprint-override"><code>[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]
</code>```

So basically the keys with value "0" get copied to a temp list of dictionaries.

答:
As I mentioned in a comment I'm not sure this will solve your problem, but based on the sample transformation you gave, here's one way to achieve it:</p>

```<code>LIST_IN = [{"name": {"book1": "0", "book2": "1", "book3": "0"}}]

def proccess(list_in):
    result = []

    for this_dict in list_in:
        for key in this_dict["name"]:
            if this_dict["name"][key] == "0":
                result.append({key: this_dict["name"][key]})

    return result

print(proccess(LIST_IN))
</code>```

Body:
I have been struggling to extract sub dictionaries where the value is "0" from a list of dictionaries and add them to temporary dictionaries.

I tried this:

new_users = [{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}]
    def approachA():
        for data in new_users:          # new_users is a list of nested dictionaries
            if data == '0':
                 print("found 0")
                 keys = data.keys()
                 for key in keys:
                     if key == '0':
                        key.pop() # tried to deleted delete the elements at first

It did not work for some reason, and I have been trying to do it for 2 hours so please do not ask questions not related to the problem.

This is a simple version of what I am trying to do:

[{'user1':{'book1':'0', 'book2':'4', 'book3':'1'}},{'user2':{'book1':'5', 'book2':'1', 'book3':'0'}}] -> [{'user1':{'book1':'0'}}, {'user2':{'book3':'0'}}]

So basically the keys with value "0" get copied to a temp list of dictionaries.

Body:
As I mentioned in a comment I'm not sure this will solve your problem, but based on the sample transformation you gave, here's one way to achieve it:

LIST_IN = [{"name": {"book1": "0", "book2": "1", "book3": "0"}}]

def proccess(list_in):
    result = []

    for this_dict in list_in:
        for key in this_dict["name"]:
            if this_dict["name"][key] == "0":
                result.append({key: this_dict["name"][key]})

    return result

print(proccess(LIST_IN))


问:
How to send confirmation mail to new email address in Laravel?
I have a form that can change current email address of a user. I want when user changes his current email address to a new email address to automatically sends confirmation mail to this new email address where user would confirm that email. How can that be done? Here is my code. Any help is appreciated.

UserProfileController.php

```<code>public function changeEmailAddress(UpdateEmailRequest $request)
{
    if ($request->new_email != $request->repeat_email)
        return response()->json(['status' => 'Emails do not match.'], 404);

    if ($request->new_email == $request->user()->email)
        return response()->json(['status' => 'Email cannot be the same as old email'], 404);

    if(sizeof(User::where('email','=',$request->new_email)->get()) > 0)
        return response()->json(['status' => 'Email already exists'], 404);

    $request->user()->email = $request->new_email;
    $request->user()->email_verified_at = null;
    $request->user()->save();

    return response()->json(['status' => 'success'], 200);
}
</code>```

index.blade.php

```<code><section data-edit="email" class="editEmail">
    <form action="{{ route('user.update.email') }}" method="POST" class="flex">
        @method('PATCH')
        @csrf
        <div class="form-group">
            <input type="text" placeholder="New Email Adress" name="new_email">
        </div>
        <div class="form-group">
            <input type="text" placeholder="Repeat Email Adress" name="repeat_email">
        </div>
        <div class="form-group">
            <button class="submit">BUTTON</button>
        </div>
    </form>
</section>
</code>```

web.php

```<code>Route::patch('/profile/change-email', 'UserProfileController@changeEmailAddress')-
 >name('user.update.email');
</code>```

UpdateEmailRequest.php

```<code>public function rules()
{
    return [
        'email' => ['string', 'email', 'max:255', 'unique:users,email'],
    ];
 }
</code>```

答:
To laravel  5.7+ implements MustVerifyEmail in your App\Models\User or App\User

```<code><?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}
</code>```

and in app/routes/web.php

Add such routes as email/verify and email/resend to the app:

```<code>Auth::routes(['verify' => true]);

</code>```

and simple in your method just call this:

```<code>$user->sendEmailVerificationNotification();
</code>```

Body:
I have a form that can change current email address of a user. I want when user changes his current email address to a new email address to automatically sends confirmation mail to this new email address where user would confirm that email. How can that be done? Here is my code. Any help is appreciated.

UserProfileController.php

public function changeEmailAddress(UpdateEmailRequest $request)
{
    if ($request->new_email != $request->repeat_email)
        return response()->json(['status' => 'Emails do not match.'], 404);

    if ($request->new_email == $request->user()->email)
        return response()->json(['status' => 'Email cannot be the same as old email'], 404);

    if(sizeof(User::where('email','=',$request->new_email)->get()) > 0)
        return response()->json(['status' => 'Email already exists'], 404);

    $request->user()->email = $request->new_email;
    $request->user()->email_verified_at = null;
    $request->user()->save();

    return response()->json(['status' => 'success'], 200);
}

index.blade.php

    <form action="{{ route('user.update.email') }}" method="POST" class="flex">
        @method('PATCH')
        @csrf

            <input type="text" placeholder="New Email Adress" name="new_email">

            <input type="text" placeholder="Repeat Email Adress" name="repeat_email">

            <button class="submit">BUTTON</button>

    </form>

web.php

Route::patch('/profile/change-email', 'UserProfileController@changeEmailAddress')-
 >name('user.update.email');

UpdateEmailRequest.php

public function rules()
{
    return [
        'email' => ['string', 'email', 'max:255', 'unique:users,email'],
    ];
 }

Body:
To laravel  5.7+ implements MustVerifyEmail in your App\Models\User or App\User

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements MustVerifyEmail
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password',
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];
}

and in app/routes/web.php

Add such routes as email/verify and email/resend to the app:

Auth::routes(['verify' => true]);

and simple in your method just call this:

$user->sendEmailVerificationNotification();


问:
PyCharm Running Out of Memory
I've recently started getting an out of memory error while using PyCharm 5.0.4
The message is:

There's not enough memory to perform the requested operation.
 Please increase Xmx setting and shutdown PyCharm for change to take effect.

I've already increased the value to 1024 MB, and to my knowledge nothing has changed in either my Python or system setups.

What exactly does the size of the Xmx memory manage, and how would I go about debugging what's causing the issue?

答: The issue for me was the css plugin installed in Pycharm. Removing it fixed the problem. To remove, go to the Project Interpreter in Pycharm preferences. </p>

Title: PyCharm Running Out of Memory


问:
Log4Net log showing up in console window
I have the opposite problem as most people do with Log4net. I have a basic rolling log appender, I use the INFO, WARN and ERROR levels in my code behind. I have debug turned off in the app.config. It STILL pushes the log data to the console window in addition to the rolling log appender.

How do I stop this behavior? It makes looking at the console window a nightmare.

My config:

<log4net debug="false">
  <appender name="RollingFileAppender"
            type="log4net.Appender.RollingFileAppender">
    <file type="log4net.Util.PatternString"
          value="milliondollars.log"/>
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <rollingStyle value="Composite"/>
    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true" />
      <levelMin value="INFO" />
      <levelMax value="FATAL" />
    </filter>
    <datePattern value="yyyyMMdd"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger: %message%newline" />
    </layout>
  </appender>
  <root>
    <level value="ALL" />
    <appender-ref ref="RollingFileAppender" />
  </root>
</log4net>
```

答:
Based on the additional information you provided, there are a couple things I can see.  First, you are logging all messages (including DEBUG messages).  You just aren't showing log4net debugging information.  As for why you are writing to the console window, I would suggest looking at the wrapper for your logger messages.  Maybe you are writing to the console there.

Also, walk through the execution of your program in debug mode.  See what line is writing to your console.


问:
what should be the parameters in residplot seaborn
I have made a simple linear regression model:

```<code>LR = LinearRegression()
kfold = model_selection.KFold(n_splits=10, random_state=12)
result_kfold = model_selection.cross_val_score(LR, X_train, Y_train, cv=kfold, scoring = 'r2')
print("Accuracy: %.2f%%" % (result_kfold.mean()*100.0))
LR.fit(X_train,Y_train)
Y_pred = LR.predict(X_test)
print("Y_pred:", Y_pred)
</code>```

i want to plot the residual errors. I've used 'residplot' for the same. But i'm not sure if i've passed the right arguements. According to the documentation, we've to use predictor variable and result/response variable.
Here's the code:

```<code>sns.set(style="whitegrid")
sns.residplot(Y_test, Y_pred, lowess=True, color="g")
</code>```

Can anyone please tell me if it is right...also what should be the labels of X and Y axis?

Thank You in advance for help

答:
You are plotting something very weird, so let's use an example dataset:

```<code>from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib. pyplot as plt
import seaborn as sns

iris = sns.load_dataset('iris')

X_train, X_test, Y_train, Y_test = train_test_split(iris.iloc[:,:3], iris.iloc[:,3],random_state=11)

LR = LinearRegression()
LR.fit(X_train,Y_train)
Y_pred = LR.predict(X_test)
</code>```

If you just want to plot the residuals, you can do:

```<code>sns.set(style="whitegrid")
fig, ax = plt.subplots(figsize =(5,5))
sns.regplot(x=Y_pred,y=Y_test-Y_pred,ax=ax,lowess=True)
ax.set(ylabel='residuals',xlabel='fitted values')
</code>```

What you are getting with sns.regplot() is the y variable regressed onto the x-variable and the residuals being plotted, which makes no sense in your case, and I illustrate below how the plot is obtained, first you fit the prediction (y variable) to actual (x variable), and get the residuals:

```<code>plotfit = LinearRegression()
plotfit.fit(Y_test.to_numpy().reshape(-1,1),Y_pred)
residual = Y_pred - plotfit.predict(Y_test.to_numpy().reshape(-1,1))
</code>```

Then plotting it gives you exactly the same thing as your sns.residplot:

```<code>sns.set(style="whitegrid")
fig, ax = plt.subplots(1,2,figsize =(10,5))

sns.residplot(Y_test,Y_pred,lowess=True, color="g",ax=ax[0])
ax[0].set_xlim(0,2.5)
sns.regplot(x=Y_test,y=residual,lowess=True)
ax[1].set_xlim(0,2.5)
</code>```

Body:
I have made a simple linear regression model:

LR = LinearRegression()
kfold = model_selection.KFold(n_splits=10, random_state=12)
result_kfold = model_selection.cross_val_score(LR, X_train, Y_train, cv=kfold, scoring = 'r2')
print("Accuracy: %.2f%%" % (result_kfold.mean()*100.0))
LR.fit(X_train,Y_train)
Y_pred = LR.predict(X_test)
print("Y_pred:", Y_pred)

i want to plot the residual errors. I've used 'residplot' for the same. But i'm not sure if i've passed the right arguements. According to the documentation, we've to use predictor variable and result/response variable.
Here's the code:

sns.set(style="whitegrid")
sns.residplot(Y_test, Y_pred, lowess=True, color="g")

Can anyone please tell me if it is right...also what should be the labels of X and Y axis?

Thank You in advance for help

Body:
You are plotting something very weird, so let's use an example dataset:

from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib. pyplot as plt
import seaborn as sns

iris = sns.load_dataset('iris')

X_train, X_test, Y_train, Y_test = train_test_split(iris.iloc[:,:3], iris.iloc[:,3],random_state=11)

LR = LinearRegression()
LR.fit(X_train,Y_train)
Y_pred = LR.predict(X_test)

If you just want to plot the residuals, you can do:

sns.set(style="whitegrid")
fig, ax = plt.subplots(figsize =(5,5))
sns.regplot(x=Y_pred,y=Y_test-Y_pred,ax=ax,lowess=True)
ax.set(ylabel='residuals',xlabel='fitted values')

What you are getting with sns.regplot() is the y variable regressed onto the x-variable and the residuals being plotted, which makes no sense in your case, and I illustrate below how the plot is obtained, first you fit the prediction (y variable) to actual (x variable), and get the residuals:

plotfit = LinearRegression()
plotfit.fit(Y_test.to_numpy().reshape(-1,1),Y_pred)
residual = Y_pred - plotfit.predict(Y_test.to_numpy().reshape(-1,1))

Then plotting it gives you exactly the same thing as your sns.residplot:

sns.set(style="whitegrid")
fig, ax = plt.subplots(1,2,figsize =(10,5))

sns.residplot(Y_test,Y_pred,lowess=True, color="g",ax=ax[0])
ax[0].set_xlim(0,2.5)
sns.regplot(x=Y_test,y=residual,lowess=True)
ax[1].set_xlim(0,2.5)


问:
Pushing element into an array wont update on the UI
I am trying to update an array after fetching the json data from the endpoint but i am not getting expected results on the front end.

```<code>export class LocationSectionComponent implements OnInit{

  myControl = new FormControl();
  options : string[] =  ['0089/PITT', '0085/CALI', '0090/MASS'];
  filteredOptions: Observable<string[]>;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );

      this.fetchData();
  }

  private _filter(value: string): string[] {
        const filterValue = value.toLowerCase();
        return this.options.filter(option => option.toLowerCase().includes(value));
      }

   private fetchData ()
   {
   this.http.get('http://localhost:9090/api/v1/facility/1')
   .subscribe(responseData => {
    const facilityOrigin = responseData.facilityNumber +"/"+ responseData.name;
    this.options.push(facilityOrigin);
    console.log(this.options);
    });
   }
</code>```

when I perform the push operation through fetchData() method gives me updated array like this

```<code>(4) ["0089/PITT", "0085/CALI", "0090/MASS", "89/PITT"]
0: "0089/PITT"
1: "0085/CALI"
2: "0090/MASS"
3: "89/PITT"
length: 4
__proto__: Array(0)
</code>```

but on the front end I can see only 3 options i.e ['0089/PITT', '0085/CALI', '0090/MASS']. How can fix this issue. Is this a scope issue or something else?

答:
you can try this:

```<code>this.options = [...this.options];  // after push
</code>```

If you have set ChangeDetectionStrategy.OnPush for your component, you can try to call this.cdr.detectChanges();

see: onpush-change-detection-how-it-works

Body:
I am trying to update an array after fetching the json data from the endpoint but i am not getting expected results on the front end.

export class LocationSectionComponent implements OnInit{

  myControl = new FormControl();
  options : string[] =  ['0089/PITT', '0085/CALI', '0090/MASS'];
  filteredOptions: Observable<string[]>;

  constructor(private http: HttpClient) {}

  ngOnInit() {
    this.filteredOptions = this.myControl.valueChanges
      .pipe(
        startWith(''),
        map(value => this._filter(value))
      );

      this.fetchData();
  }

  private _filter(value: string): string[] {
        const filterValue = value.toLowerCase();
        return this.options.filter(option => option.toLowerCase().includes(value));
      }

   private fetchData ()
   {
   this.http.get('http://localhost:9090/api/v1/facility/1')
   .subscribe(responseData => {
    const facilityOrigin = responseData.facilityNumber +"/"+ responseData.name;
    this.options.push(facilityOrigin);
    console.log(this.options);
    });
   }

when I perform the push operation through fetchData() method gives me updated array like this

(4) ["0089/PITT", "0085/CALI", "0090/MASS", "89/PITT"]
0: "0089/PITT"
1: "0085/CALI"
2: "0090/MASS"
3: "89/PITT"
length: 4
__proto__: Array(0)

but on the front end I can see only 3 options i.e ['0089/PITT', '0085/CALI', '0090/MASS']. How can fix this issue. Is this a scope issue or something else?

Body:
you can try this:

this.options = [...this.options];  // after push

If you have set ChangeDetectionStrategy.OnPush for your component, you can try to call this.cdr.detectChanges();

see: onpush-change-detection-how-it-works


问:
Lambda function errorMessage": "Cannot read property 'bucket' of undefined
I have a lambda function that is triggered whenever something is saved in my s3 bucket,

the aim is to read the metadata of a JSON file and insert rows in a dynamoDB table;

for instance
a training period starts on the june the 1st and end june 8th
and training days are Monday, Wednesday and Friday
thus the lambda should insert 4 rows ( 1st, 3rd, 5th, 8th of june)

so far only one row is inserted and then the error occurs and it crashes

The function is triggered well but this error message occurs sometimes.

```<code>{
    "errorType": "TypeError",
    "errorMessage": "Cannot read property 'bucket' of undefined",
    "stack": [
        "TypeError: Cannot read property 'bucket' of undefined",
        "    at Runtime.exports.handler (/var/task/index.js:26:44)",
        "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
    ]
}
</code>```

here is my function

```<code>let AWS = require('aws-sdk');
let s3 = new AWS.S3();
let moment = require('moment');
let uuid = require('node-uuid');

let apiSportmTrainingTableName = process.env.API_SPORTM_TRAININGTABLE_NAME
let dynamodb = new AWS.DynamoDB.DocumentClient();

exports.handler =  async (event, context) => {
  //eslint-disable-line
  const Bucket = await event.Records[0].s3.bucket.name;

  const Key = await event.Records[0].s3.object.key;
  const objectHead = await s3.headObject({Bucket, Key}).promise();

  let start = moment(new Date(objectHead.Metadata.trainingstart), "YYYY-MM-DD");
  let end = moment(new Date(objectHead.Metadata.trainingend), "YYYY-MM-DD");
  let days = JSON.parse("[" + objectHead.Metadata.trainingdays + "]");

  try {
    for (let m = moment(start); m.diff(end, 'days') <= 0; m.add(1, 'days')) {

      for (const e of days) {

        if (moment(m).day() === e) {
          let params = {
            TableName: apiSportmTrainingTableName,
            Item: {
              "id": uuid.v1(),
              "trainingDate": moment(m).format('YYYY-MM-DD'),
              "statut": true,
              "athleteCategory": objectHead.Metadata.trainingmembercategory,
              "trainingTime": objectHead.Metadata.trainingtime
            }
          };
          return await dynamodb.put(params).promise();
        }
      }
    }
  } catch (err) {
    console.error('Error', err);
    return;
  }
  context.done(null, 'Successfully processed DynamoDB record'); // SUCCESS with message
};

</code>```

when the event logs it looks like that

```<code>Records: [
    {
      eventVersion: '2.1',
      eventSource: 'aws:s3',
      awsRegion: 'us-east-1',
      eventTime: '2020-05-29T18:34:53.250Z',
      eventName: 'ObjectCreated:Put',
      userIdentity: [Object],
      requestParameters: [Object],
      responseElements: [Object],
      s3: [Object]
    }
  ]
}
```

that a part of logs it fails and then works and then it keeps trying and fail

[logs][1]

  [1]: https://i.stack.imgur.com/Sj5C7.png
```

答:
You are using return after inserting data into DynamoDB:

```<code>return await dynamodb.put(params).promise();
</code>```

This returns the result of the DynamoDB operations as the result of the Lambda function, which terminated the execution. This explains why only one record is inserted into DynamoDB. I'd try to remove the return and see if that also removes the error (best guess on my part: the returned value somehow causes another execution with it, but this time missing the S3 event, thus event.Records[0].s3 will be undefined).

Body:
I have a lambda function that is triggered whenever something is saved in my s3 bucket,

the aim is to read the metadata of a JSON file and insert rows in a dynamoDB table;

for instance
a training period starts on the june the 1st and end june 8th
and training days are Monday, Wednesday and Friday
thus the lambda should insert 4 rows ( 1st, 3rd, 5th, 8th of june)

so far only one row is inserted and then the error occurs and it crashes

The function is triggered well but this error message occurs sometimes.

{
    "errorType": "TypeError",
    "errorMessage": "Cannot read property 'bucket' of undefined",
    "stack": [
        "TypeError: Cannot read property 'bucket' of undefined",
        "    at Runtime.exports.handler (/var/task/index.js:26:44)",
        "    at Runtime.handleOnce (/var/runtime/Runtime.js:66:25)"
    ]
}

here is my function

let AWS = require('aws-sdk');
let s3 = new AWS.S3();
let moment = require('moment');
let uuid = require('node-uuid');

let apiSportmTrainingTableName = process.env.API_SPORTM_TRAININGTABLE_NAME
let dynamodb = new AWS.DynamoDB.DocumentClient();

exports.handler =  async (event, context) => {
  //eslint-disable-line
  const Bucket = await event.Records[0].s3.bucket.name;

  const Key = await event.Records[0].s3.object.key;
  const objectHead = await s3.headObject({Bucket, Key}).promise();

  let start = moment(new Date(objectHead.Metadata.trainingstart), "YYYY-MM-DD");
  let end = moment(new Date(objectHead.Metadata.trainingend), "YYYY-MM-DD");
  let days = JSON.parse("[" + objectHead.Metadata.trainingdays + "]");

  try {
    for (let m = moment(start); m.diff(end, 'days') <= 0; m.add(1, 'days')) {

      for (const e of days) {

        if (moment(m).day() === e) {
          let params = {
            TableName: apiSportmTrainingTableName,
            Item: {
              "id": uuid.v1(),
              "trainingDate": moment(m).format('YYYY-MM-DD'),
              "statut": true,
              "athleteCategory": objectHead.Metadata.trainingmembercategory,
              "trainingTime": objectHead.Metadata.trainingtime
            }
          };
          return await dynamodb.put(params).promise();
        }
      }
    }
  } catch (err) {
    console.error('Error', err);
    return;
  }
  context.done(null, 'Successfully processed DynamoDB record'); // SUCCESS with message
};

when the event logs it looks like that

Records: [
    {
      eventVersion: '2.1',
      eventSource: 'aws:s3',
      awsRegion: 'us-east-1',
      eventTime: '2020-05-29T18:34:53.250Z',
      eventName: 'ObjectCreated:Put',
      userIdentity: [Object],
      requestParameters: [Object],
      responseElements: [Object],
      s3: [Object]
    }
  ]
}
```

that a part of logs it fails and then works and then it keeps trying and fail

[logs][1]

  [1]: https://i.stack.imgur.com/Sj5C7.png

Body:
You are using return after inserting data into DynamoDB:

return await dynamodb.put(params).promise();

This returns the result of the DynamoDB operations as the result of the Lambda function, which terminated the execution. This explains why only one record is inserted into DynamoDB. I'd try to remove the return and see if that also removes the error (best guess on my part: the returned value somehow causes another execution with it, but this time missing the S3 event, thus event.Records[0].s3 will be undefined).


问:
No data received ERR_EMPTY_RESPONSE webpack
I am trying to run webpack-dev-server, but when I go to http://localhost:8080/ the browser returns

```<code>No data received
ERR_EMPTY_RESPONSE
</code>```

Solution

I was able to resolve this issue by explicitly telling webpack to use port 3000

```<code>webpack-dev-server --port 3000
</code>```

run on http://localhost:3000/

答:
This was happening on my laptop, and when I switched ports, it started working again.

I found there was a hung process still using the old port, but webpack/express didn't complain when it started up.

ps -ef | grep npm

Body:
I am trying to run webpack-dev-server, but when I go to http://localhost:8080/ the browser returns

No data received
ERR_EMPTY_RESPONSE

Solution

I was able to resolve this issue by explicitly telling webpack to use port 3000

webpack-dev-server --port 3000

run on http://localhost:3000/


问:
jQuery: on Clicking any Menu Link, Play Animation and Only Then Go to the Link's URL
When any of the menu links is clicked, I want to play a quick animation on the current page, and only then go to the url of the clicked link.

I would be grateful for the expertly help!

答:
Prevent the default behaviour, play your animation and then point the browser to the original destination.</p>

```<code>$('#menu a').click(function(event) {
    event.preventDefault();
    var href = this.href;

    $('#whatever').animate({
        top: '300px'
    }, 500,
    function() {
        window.location = href;
    });
});
</code>```

Body:
Prevent the default behaviour, play your animation and then point the browser to the original destination.

$('#menu a').click(function(event) {
    event.preventDefault();
    var href = this.href;

    $('#whatever').animate({
        top: '300px'
    }, 500,
    function() {
        window.location = href;
    });
});


问:
Sybase ASE : Table partitioning
I am working on partitioning a huge table in Sybase. The use case is, the table has grown over the years and the applications do not need data beyond let's say 6 months. So, I need to archive some of the rows. I am exploring the following approach:

Add date partitioning into table and partition the rows by day

Write a batch that executes every midnight and archives the partition that is more than 6 months old

Now, in order for me to do this, I need to partition the existing table and have a couple of questions (I am not a Sybase or a DB expert):

Range partitioning in Sybase comes closest to the approach I am trying to implement. However, it requires you to specify all the ranges upfront. So, if I want to create daily partition on rolling basis for a year, do I need to specify all the values up front?

Can I alter an existing table and add partitions or I need to create a new table?

答:
Partitioning is meant to:

Reduce time in maintenance tasks (dbcc, update statistics, and so on)

Savings in disk usage (i.e. use slow disks for cold data)

Achieve performance gains (with important previous considerations)

If you are in cases 1 or 2 the answer is:

To create a range partition you don't need to set an upper value; the upper value for the range is implicitly defined when you create the next partition.
The next partition can be defined at any time by means of alter table

If you are in case 3:

Be very careful defining the partition columns; ideally they must match the where clause of your queries. Use a meaningful global index, so that ASE is able to find the location of the rows in every partition. Use local indexes for the rest.

Title: Sybase ASE : Table partitioning


问:
multiplying a (N,N) matrix with a vector (V), so that the output is of the shape (N,N,V)
Hei there - I'm a python beginner and I'd like to figure out the following:

I want to multiply a matrix of shape (n,n) with a vector of shape (v), so that the output has the shape (n,n,v).

My code looks something like this but it's far from elegant.

```<code>def D(x,y,B,n):
    # shape of x,y is (n,n) # shape of B is (v)

    a = np.ndarray(shape = (n,n,1), dtype = float)
    b = np.ndarray(shape = (n,n,1), dtype = float)

    a = np.arctan2(y, x)*(B[0])/(2.*math.pi)
    b = np.arctan2(y, x)*(B[1])/(2.*math.pi)
    c, d = ...

    return np.asarray([a,b,c,d]).T
</code>```

x and y are the matrices of a meshgrid and represent a radius.

Any help is much appreciated! Thank you!!

答:
try using this, this is the fastest method i know

def D(x,y,B,n):

    M = np.arctan2(y, x)          # shape= [n, n]
    b = B / (2.*math.pi)          # shape= [v,]

    r = M[..., np.newaxis] * b

    return r                      # shape= [n, n, v]
```

the ... elipses represent all the axes of array and np.newaxis adds a new axis, so together A[..., np.newaxis] returns an array of shape [n, n, 1] which can be broadcasted with b

broadcasting an array of shape [n, n, 1] with an array of shape [v] produces an array of shape [n, n, v]

if A were of shape [a, b, c]. A[..., np.newaxis] would have changed it to [a, b, c, 1]

Body:
Hei there - I'm a python beginner and I'd like to figure out the following:

I want to multiply a matrix of shape (n,n) with a vector of shape (v), so that the output has the shape (n,n,v).

My code looks something like this but it's far from elegant.

def D(x,y,B,n):
    # shape of x,y is (n,n) # shape of B is (v)

    a = np.ndarray(shape = (n,n,1), dtype = float)
    b = np.ndarray(shape = (n,n,1), dtype = float)

    a = np.arctan2(y, x)*(B[0])/(2.*math.pi)
    b = np.arctan2(y, x)*(B[1])/(2.*math.pi)
    c, d = ...

    return np.asarray([a,b,c,d]).T

x and y are the matrices of a meshgrid and represent a radius.

Any help is much appreciated! Thank you!!

Body:
try using this, this is the fastest method i know

def D(x,y,B,n):

    M = np.arctan2(y, x)          # shape= [n, n]
    b = B / (2.*math.pi)          # shape= [v,]

    r = M[..., np.newaxis] * b

    return r                      # shape= [n, n, v]

the ... elipses represent all the axes of array and np.newaxis adds a new axis, so together A[..., np.newaxis] returns an array of shape [n, n, 1] which can be broadcasted with b

broadcasting an array of shape [n, n, 1] with an array of shape [v] produces an array of shape [n, n, v]

if A were of shape [a, b, c]. A[..., np.newaxis] would have changed it to [a, b, c, 1]


问:
Convert each prop of an object to an array of objects
Given this Object :

```<code>{
 name : 'whale'
 color : 'blue',
 size : 'xxl'
}
</code>```

How do i turn it into ?

```<code>[
  { name : 'whale' },
  { color : 'blue'},
  { size: 'xxl' }
]
</code>```

答:
Well i found a way after more deep tests </p>

```<code>Object.entries(myObject).map(([key, val]) => ({[key]: val}))
</code>```

Body:
Given this Object :

{
 name : 'whale'
 color : 'blue',
 size : 'xxl'
}

How do i turn it into ?

[
  { name : 'whale' },
  { color : 'blue'},
  { size: 'xxl' }
]

Body:
Well i found a way after more deep tests

Object.entries(myObject).map(([key, val]) => ({[key]: val}))


问:
How to use javascript libraries on a chromebook?
I'm attempting to code on a chromebook. Is there any way to download and use libraries like jQuery on a Chromebook? If anybody could help me, it would be much appreciated!</p>

答:
If you get an external hard or flash drive, you can put the libraries on there, along with the files.

But wait.

Hard drives can cost a lot of money, so another option is to download the libraries, then put the libraries in the same folder as the files, or vice versa.


问:
printing the sequence in different order
I am able to understand the logic here for the below pattern but not getting the way of implementation, please can someone help me here.

The pattern I want is like below, (in first column everything till 5, then second column after 5 leaving first and last row and so on. . )

```<code>1
2 6
3 7 9
4 8
5
</code>```

Body:
I am able to understand the logic here for the below pattern but not getting the way of implementation, please can someone help me here.

The pattern I want is like below, (in first column everything till 5, then second column after 5 leaving first and last row and so on. . )

1
2 6
3 7 9
4 8
5

Body:
Try this:

n = int(input())

for i in range(1, (n//2)+2):
    for j in range(i):
        print(i + ((n - 1) * j) - (j * (j - 1)) , end=' ')
    print()

for i in range((n//2)+2, n + 1):
    for j in range(n - i + 1):
        print(i + ((n - 1) * j) - (j * (j - 1)), end=' ')
    print()

Output:

n = 9
1
2 10
3 11 17
4 12 18 22
5 13 19 23 25
6 14 20 24
7 15 21
8 16
9

Logic

n = 9
1              |
2 10           |(10 - 2) = 8
3 11 17        |(11 - 3) = 8, (17 - 11) = 6
4 12 18 22     |(12 - 4) = 8, (18 - 12) = 6, (22 - 18) = 4
5 13 19 23 25  |(13 - 5) = 8, (19 - 13) = 6, (23 - 19) = 4, (25 - 23) = 2
6 14 20 24     |(14 - 6) = 8, (20 - 14) = 6, (24 - 20) = 4
7 15 21        |(15 - 7) = 8, (21 - 15) = 6
8 16           |(16 - 8) = 8
9              |

For example in line5

first number is 5 + ((n - 1) * 0) - (0 * -1) = 5

next value 5 + ((n - 1) * 1) - (1 * 0) = 13

next value 5 + ((n - 1) * 2) - (1 * 2) = 19

next value 5 + ((n - 1) * 3) - (2 * 3) = 23

next value 5 + ((n - 1) * 4) - (3 * 4) = 25

above 5 is i value and 0,1,2,3,4 are j values

generalised formula for calculating the value i + ((n - 1) * j) - (j * (j - 1))


问:
Ternary operator in perl yields unexpected result when assigning a variable in the statement
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

```<code>sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"
</code>```

however this one works:

```<code>sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);
</code>```

what is the real difference here?!

答:
If you write:

```<code>sub tester
{
   return ($_[0] < 10) ? "You're a young'un" : "You're an oldie";
}
</code>```

then you get the result you expect.

Body:
I'm trying to make a transition from php to perl and expectedly running into some weirdness.  I cannot understand why one version of my code works vs another.

This fails:

sub tester
{
$return;
($_[0] < 10) ? $return = "youre a youngin" : $return = "youre an old person";
return $return;
}

print "how old are you?";
$a = <>;
chomp $a;

print  tester($a);  #both result in "youre an old person"

however this one works:

sub tester
{
    return ($_[0] < 10) ? "youre a youngin" : "youre an old person";
}

print "how old are you?";
$a = <>;
chomp $a;
print  tester($a);

what is the real difference here?!

Body:
If you write:

sub tester
{
   return ($_[0] < 10) ? "You're a young'un" : "You're an oldie";
}

then you get the result you expect.


问:
Prevent printing of output in octave script without adding semicolons everywhere?
Octave by default prints the result of each assignment, which is quite useful on the terminal and can be quite useful for debugging data evaluation scripts. In order to suppress it,

However, it can also be a major annoyance when working on scripts, forgetting a semicolon, and suddenly having major lags in the GUI due to pages over pages of output for that 10000×10000 matrix.

Is there a way to instead suppress the output by default, and instead only echo of assignments, if an explicit trailing , is supplied?

答:
Yes, octave provides silent_functions.

It is false (i.e. 0) by default.

You can set it to 1 to make functions silent, i.e. any evaluations that do not have a semicolon inside the function will not be printed.

Note however, that what you describe, i.e. terminating with a comma, will not display output either when this is enabled. To display output intentionally from a function with this enabled, you will have to use the disp command.

From the docs:

```<code> -- silent_functions (NEW_VAL, "local")
 Query or set the internal variable that controls whether internal
 output from a function is suppressed.

 If this option is disabled, Octave will display the results
 produced by evaluating expressions within a function body that are
 not terminated with a semicolon.

 When called from inside a function with the "local" option, the
 variable is changed locally for the function and any subroutines it
 calls.  The original variable value is restored when exiting the
 function.
</code>```

PS. Note: this also works for scripts, but not for the main console window. Anything you don't terminate with a semicolon in the live console will be printed, regardless of this setting.

Body:
Yes, octave provides silent_functions.

It is false (i.e. 0) by default.

You can set it to 1 to make functions silent, i.e. any evaluations that do not have a semicolon inside the function will not be printed.

Note however, that what you describe, i.e. terminating with a comma, will not display output either when this is enabled. To display output intentionally from a function with this enabled, you will have to use the disp command.

From the docs:

 -- silent_functions (NEW_VAL, "local")
 Query or set the internal variable that controls whether internal
 output from a function is suppressed.

 If this option is disabled, Octave will display the results
 produced by evaluating expressions within a function body that are
 not terminated with a semicolon.

 When called from inside a function with the "local" option, the
 variable is changed locally for the function and any subroutines it
 calls.  The original variable value is restored when exiting the
 function.

PS. Note: this also works for scripts, but not for the main console window. Anything you don't terminate with a semicolon in the live console will be printed, regardless of this setting.


答:
You could map the entries of the object with new objects.

var data = { name : 'whale', color : 'blue', size : 'xxl' },
    result = Object
        .entries(data)
        .map(keyValue => Object.fromEntries([keyValue]));

console.log(result);```

Title: Convert each prop of an object to an array of objects