问:
c++ - Using zlib with const data
To compress/decompress data with zlib , first I need to set up a struct called z_stream.
z_stream has two non-const pointers called next_in and next_out.

If I want to do a function like this:

```<code>void ungzip(std::vector<unsigned char>& dst,const std::vector<unsigned char>& src)
{
  z_stream strm;
  // more code
}
</code>```

and other like,

```<code>void gzip  (std::vector<unsigned char>& dst,const std::vector<unsigned char>& src);
</code>```

What I should do?

Copy src in a local std::vector<unsigned char>

```<code>std::vector<unsigned char> tmp(src);
</code>```

and use it as source or setting pointer like this , strm.next_in = const_cast<char*>(&src[0])?

Does zlib keep input data?

答:
Probably the cleanest way would be to just define ZLIB_CONST when compiling so that the input pointer is defined to be a const unsigned char * instead.

Note however that simply casting away const-ness is indeed going to work (it's legal if the character being pointed to is not actually constant).
The code for this should be:

```<code>strm.next_in = (unsigned char *)&src[0];
</code>```

or the uglier const_cast variant if you are into that kind of things.

Note that default in zlib is NOT to have ZLIB_CONST defined and if you want to use a precompiled zlib binary the casting solution is the best option. You should go for the ZLIB_CONST solution only if you're compiling yourself the library too with the same define(1).

(1) Giving the compiler an header with different semantic meaning is a bad idea - and a formal breaking of C++ standard rules - and it could - at least in theory - create protability problems.

With X86 architecture this is probably not the case and the library compiled with or without ZLIB_CONST would end up with the exact same bytes; however there are also different architectures.

For example I've been working with CPUs in which there were different pointer registers for different alignments. In that CPUs reading say an integer from an address that wasn't a multiple or 4 was an error generating an hardware trap (moreover something that at the time surprised me is that the error was triggered even by just assigning the pointer a non-aligned address, even if that misaligned address was never used for reading or writing).

With that compiler I didn't check (I was working only on high-level software) but I wouldn't be surprised if the system ABI specifed that a function void foo(char *) and void bar(int *) would have to receive the parameter in different registers.

More to the point, I never worked with but I can imagine may exist CPUs or VMs for which certain registers (let's name one as RW0) can be used for reading/writing operations and other registers (e.g. R0) can be used only for reading.
With such an architecture the ABI may specify that the first parameter of type const char * must be passed in R0 and the first parameter of type char * must be passed in RW0 instead.

If this is the case compiling a library with a function void foo(char *p){...} and then compiling the calling code using as declaration void foo(const char *p); would actually end up passing the address in the wrong register!

Title: c++ - Using zlib with const data

Body:
To compress/decompress data with zlib , first I need to set up a struct called z_stream.
z_stream has two non-const pointers called next_in and next_out.

If I want to do a function like this:

void ungzip(std::vector<unsigned char>& dst,const std::vector<unsigned char>& src)
{
  z_stream strm;
  // more code
}

and other like,

void gzip  (std::vector<unsigned char>& dst,const std::vector<unsigned char>& src);

What I should do?

Copy src in a local std::vector<unsigned char>

std::vector<unsigned char> tmp(src);

and use it as source or setting pointer like this , strm.next_in = const_cast<char*>(&src[0])?

Does zlib keep input data?

Body:
Probably the cleanest way would be to just define ZLIB_CONST when compiling so that the input pointer is defined to be a const unsigned char * instead.

Note however that simply casting away const-ness is indeed going to work (it's legal if the character being pointed to is not actually constant).
The code for this should be:

strm.next_in = (unsigned char *)&src[0];

or the uglier const_cast variant if you are into that kind of things.

Note that default in zlib is NOT to have ZLIB_CONST defined and if you want to use a precompiled zlib binary the casting solution is the best option. You should go for the ZLIB_CONST solution only if you're compiling yourself the library too with the same define(1).

(1) Giving the compiler an header with different semantic meaning is a bad idea - and a formal breaking of C++ standard rules - and it could - at least in theory - create protability problems.

With X86 architecture this is probably not the case and the library compiled with or without ZLIB_CONST would end up with the exact same bytes; however there are also different architectures.

For example I've been working with CPUs in which there were different pointer registers for different alignments. In that CPUs reading say an integer from an address that wasn't a multiple or 4 was an error generating an hardware trap (moreover something that at the time surprised me is that the error was triggered even by just assigning the pointer a non-aligned address, even if that misaligned address was never used for reading or writing).

With that compiler I didn't check (I was working only on high-level software) but I wouldn't be surprised if the system ABI specifed that a function void foo(char *) and void bar(int *) would have to receive the parameter in different registers.

More to the point, I never worked with but I can imagine may exist CPUs or VMs for which certain registers (let's name one as RW0) can be used for reading/writing operations and other registers (e.g. R0) can be used only for reading.
With such an architecture the ABI may specify that the first parameter of type const char * must be passed in R0 and the first parameter of type char * must be passed in RW0 instead.

If this is the case compiling a library with a function void foo(char *p){...} and then compiling the calling code using as declaration void foo(const char *p); would actually end up passing the address in the wrong register!


来源: stackexchange

问:
How to get return values from http post method in Angular2?
I have a requirement where I need to make a http post method request to a Web API i.e. save some data entered by the user. The Web API would return some values as a result and this result would be used for some UI logic.

I tried making the http post in synchronous way, but it doesn't work properly as expected.

Angular2 component calls this service to save the data:-

```<code>public SaveCubeReport(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
    {
        var result = this.SaveData(userName, cubeReport, APIServiceURL).subscribe(
            data => {
                console.log(data);
            });

        console.log(result);
}
</code>```

Http post method call is as follows:-

```<code>SaveData(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
{
    var temp = this._http.post(APIServiceURL, JSON.stringify(cubeReport), { headers: ContentHeaders })
        .map((res: Response) => res.json())
        .do(() => {
            console.log('request finished');
        });
    return res;
}
</code>```

Parent component where the angular2-modal popup is invoked.

```<code>var dialog = this.modal.open(SaveCubeReport, overlayConfigFactory(
{
    ReportName: this.ReportItem.rpt_name,
    ReportDescription: this.ReportItem.rpt_description,
    Application: this.ReportItem.application_name,
    Owner: this.ReportItem.owner,
    CubeId: this.CubeId,
    ReportId: this.ReportItem.rpt_id,
    ReportJson: JSON.stringify(this.getState())
}, BSModalContext));

dialog
.then((d) => d.result)
.then((r) => {
    // success
    console.log("Dialog ended with success: ", r);
    this.RefreshReportListDropdown(r);
}, (error) => {
    // failure
    console.log("Dialog ended with failure: ", error);
});
</code>```

function from where the service call is made

```<code>RefreshReportListDropdown(savedReportName: any)
{
    this._ClientAPIService.GetCubeReportsListByCubeWithEmptyRecord(this._SessionService.LoggedInUser, this._SessionService.SelectedApplication, this.cubeName, this._SessionService.ClientAPIServiceURL)
        .subscribe(
        (res) => {
            this.cubeReportList = res; //This result should contain all records including the recently saved data from the popup
            ....
        }
    );
}
</code>```

All my request are made a asynch requests i.e. it doesn't wait to get the return values.
What is the mistake here?

答:
Return the result of http.post call in the SaveData method.

```<code>SaveData(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
{
    return this._http.post(APIServiceURL, JSON.stringify(cubeReport), { headers: ContentHeaders })
        .map((res: Response) => res.json())
        .do(() => {
            console.log('request finished');
        });
}
</code>```

After this your subscribe in your consumer component will work correctly.

ContentLicense: CC BY-SA 3.0

Body:
I have a requirement where I need to make a http post method request to a Web API i.e. save some data entered by the user. The Web API would return some values as a result and this result would be used for some UI logic.

I tried making the http post in synchronous way, but it doesn't work properly as expected.

Angular2 component calls this service to save the data:-

public SaveCubeReport(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
    {
        var result = this.SaveData(userName, cubeReport, APIServiceURL).subscribe(
            data => {
                console.log(data);
            });

        console.log(result);
}

Http post method call is as follows:-

SaveData(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
{
    var temp = this._http.post(APIServiceURL, JSON.stringify(cubeReport), { headers: ContentHeaders })
        .map((res: Response) => res.json())
        .do(() => {
            console.log('request finished');
        });
    return res;
}

Parent component where the angular2-modal popup is invoked.

var dialog = this.modal.open(SaveCubeReport, overlayConfigFactory(
{
    ReportName: this.ReportItem.rpt_name,
    ReportDescription: this.ReportItem.rpt_description,
    Application: this.ReportItem.application_name,
    Owner: this.ReportItem.owner,
    CubeId: this.CubeId,
    ReportId: this.ReportItem.rpt_id,
    ReportJson: JSON.stringify(this.getState())
}, BSModalContext));

dialog
.then((d) => d.result)
.then((r) => {
    // success
    console.log("Dialog ended with success: ", r);
    this.RefreshReportListDropdown(r);
}, (error) => {
    // failure
    console.log("Dialog ended with failure: ", error);
});

function from where the service call is made

RefreshReportListDropdown(savedReportName: any)
{
    this._ClientAPIService.GetCubeReportsListByCubeWithEmptyRecord(this._SessionService.LoggedInUser, this._SessionService.SelectedApplication, this.cubeName, this._SessionService.ClientAPIServiceURL)
        .subscribe(
        (res) => {
            this.cubeReportList = res; //This result should contain all records including the recently saved data from the popup
            ....
        }
    );
}

All my request are made a asynch requests i.e. it doesn't wait to get the return values.
What is the mistake here?

Body:
Return the result of http.post call in the SaveData method.

SaveData(userName: any, cubeReport: CubeReportViewModel, APIServiceURL: any)
{
    return this._http.post(APIServiceURL, JSON.stringify(cubeReport), { headers: ContentHeaders })
        .map((res: Response) => res.json())
        .do(() => {
            console.log('request finished');
        });
}

After this your subscribe in your consumer component will work correctly.


问:
Convert U1 array to int in Python
I have the following array "class_id"

```<code>array([[array(['2'],
  dtype='<U1')],
   [array(['3'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   ...,
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')]], dtype=object)
</code>```

When I'm using the function:

class_id.astype(int)

I get the following error:

```<code>   ValueError: setting an array element with a sequence.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-124-3ad39bf87e7d> in <module>()
----> 1 class_id.astype(int)
ValueError: setting an array element with a sequence.
</code>```

I would like to get the following array:

```<code>array([[1],
   [2],
   [1],
   ...,
   [1],
   [1],
   [1]])
</code>```

Which function should I use?

Title: Convert U1 array to int in Python

Body:
I have the following array "class_id"

array([[array(['2'],
  dtype='<U1')],
   [array(['3'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   ...,
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')],
   [array(['2'],
  dtype='<U1')]], dtype=object)

When I'm using the function:

class_id.astype(int)

I get the following error:

   ValueError: setting an array element with a sequence.
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-124-3ad39bf87e7d> in <module>()
----> 1 class_id.astype(int)
ValueError: setting an array element with a sequence.

I would like to get the following array:

array([[1],
   [2],
   [1],
   ...,
   [1],
   [1],
   [1]])

Which function should I use?

Body:
To recreate your array, I have to use:

array = np.array
In [460]: alist = [[array(['2'],
     ...:   dtype='<U1')],
     ...:    [array(['3'],
     ...:   dtype='<U1')],
     ...:    [array(['2'],
     ...:   dtype='<U1')],
     ...:    [array(['2'],
     ...:   dtype='<U1')],
     ...:    [array(['2'],
     ...:   dtype='<U1')],
     ...:    [array(['2'],
     ...:   dtype='<U1')]]
In [461]: arr = np.zeros((6,1), dtype=object)
In [462]: arr[:,0] = alist
In [463]: arr
Out[463]:
array([[[array(['2'],
      dtype='<U1')]],
       [[array(['3'],
      dtype='<U1')]],
       [[array(['2'],
      dtype='<U1')]],
       [[array(['2'],
      dtype='<U1')]],
       [[array(['2'],
      dtype='<U1')]],
       [[array(['2'],
      dtype='<U1')]]], dtype=object)

A simple copy n paste strips out the inner array definitions:

array([[['2']],    # (6,1,1) shape

       [['3']],
       ...
       [['2']]], dtype=object)

Removing one level of [] with arr[:,0], I can join the arrays with concatenate, and easily convert the U1 array to int with one call to astype.

In [464]: np.concatenate(arr[:,0])
Out[464]:
array([['2'],
       ['3'],
       ['2'],
       ['2'],
       ['2'],
       ['2']],
      dtype='<U1')
In [465]: np.concatenate(arr[:,0]).astype(int)
Out[465]:
array([[2],
       [3],
       [2],
       [2],
       [2],
       [2]])


问:
How do I install Python(x,y) for linux (Elementary OS)?
I'm kinda noob in Linux, and in my class they asked us to install Python(x,y) but I've just recently moved from Windows to Linux. So I read this webpage and followed the steps: https://launchpad.net/~pythonxy/+archive/ubuntu/pythonxy-stable

But then I saw many tutorials on how to install Linux packages and they told that to install a Linux package (ppa) after adding the package to my system and updating it I had to use the next command line:

```<code>sudo apt install "name of package"
</code>```

The problem is that I don't know the name of the package for Python(x,y) and I can't find it any where. Does someone knows the name of the package or knows an alternative way to install it. I'm using Elementary OS.

答: If you are doing in through PPAs, install it with sudo apt install python-xy-meta-current.

Body:
I'm kinda noob in Linux, and in my class they asked us to install Python(x,y) but I've just recently moved from Windows to Linux. So I read this webpage and followed the steps: https://launchpad.net/~pythonxy/+archive/ubuntu/pythonxy-stable

But then I saw many tutorials on how to install Linux packages and they told that to install a Linux package (ppa) after adding the package to my system and updating it I had to use the next command line:

sudo apt install "name of package"

The problem is that I don't know the name of the package for Python(x,y) and I can't find it any where. Does someone knows the name of the package or knows an alternative way to install it. I'm using Elementary OS.


问:
Creating a graph based on input from a file in tkinter
I have a GUI where the user loads a log file and can view the log file on a frame with the warnings and errors in the file highlighted.

I am also trying to visualize the data of this file by creating a graph that contains the ids and time stamps from this log file that the user selected. I have been able to create a graph separately using matplotlib and it displays the graph using plt.show().

But I have trouble embedding it in my tkinter gui. I have tried many things but have only been able to get the axes and not the actual bar graph. When the user selects the file to load, the log file comes up etc but in the canvas area only the axes show up and no plot.

Here is part of my code:

```<code>import matplotlib

matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import \
    FigureCanvasTkAgg,NavigationToolbar2TkAgg

from matplotlib.figure import Figure

import matplotlib.pyplot as plt

from tkinter import *

from tkinter import ttk

from tkinter.filedialog import askopenfilename

link,warn_list,frame_id, timeStamp=[[] for _ in range(4)]

root= Tk()

Title=root.title("Tool")

label=ttk.Label(root, text="Welcome",foreground='purple',font=("Times 20 bold italic"))

label.pack()

frame1=ttk.LabelFrame(root,labelanchor=NW,height=500,width=500,text='Static Information')

frame1.pack(fill=BOTH,expand=True)

text_static=Text(frame1,width=45, height=15,bg='lightgray')

text_static.pack(side=LEFT,fill=BOTH)

def loadfile():

    filename=askopenfilename(parent=root,filetypes=(("Text File","*.txt"),  ("All Files","*.*")),title='Choose a file')
    with open(filename, 'r')as log:
        for num,line in enumerate(log,1):
            if line.find("cam_req_mgr_process_sof")!=-1:
                    line=line.split()
                    frame_id.append(line [-1])
                    timeStamp.append(line[3].replace(":", ""))

menu=Menu(root)
root.config(menu=menu)

file=Menu(menu)

file.add_command(label='Load', command=loadfile)

file.add_command(label='Exit',command=root.destroy)

menu.add_cascade(label='Select an option:', menu=file)

def graph():

    fig=plt.Figure()
    x=frame_id #can use x=range(1,38)
    y=[1]*len(x)

    ax=fig.add_subplot(111)
    ax.bar(x,y,width=0.5, color='lightgreen')
    return fig

plot=graph()

canvas=FigureCanvasTkAgg(plot,frame1)

canvas.get_tk_widget().pack()

toolbar=NavigationToolbar2TkAgg(canvas,frame1)

toolbar.update()

canvas._tkcanvas.pack()

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

see the result here

答:
The graph drawing almost works ! But not by loading a file. The problem is you don't update the canvas with the new set of data, and you don't cast them into numbers (float ? integers ?)

You kinda reach the limit of a functional approach to design this tool, because you need to refer i.e. to frame_id and canvas inside functions. 1 or 2 classes could solve this more easily.

As a quick fix i suggest this function :

```<code>def loadfile():
    global frame_id   # reach outside scope to use frame_id
    frame_id = []
    filename=askopenfilename(parent=root,
                             filetypes=(("Text File","*.txt"),
                                        ("All Files","*.*")),
                             title='Choose a file')
    with open(filename, 'r')as log:
        for num,line in enumerate(log,1):
            if line.find("cam_req_mgr_process_sof")!=-1:
                    line=line.split()
                    frame_id.append(float(line [-1])) # cast to float
                    timeStamp.append(line[3].replace(":", ""))
    newplot = graph()
    newplot.canvas = canvas
    canvas.figure = newplot
    canvas.draw()
</code>```

Body:
I have a GUI where the user loads a log file and can view the log file on a frame with the warnings and errors in the file highlighted.

I am also trying to visualize the data of this file by creating a graph that contains the ids and time stamps from this log file that the user selected. I have been able to create a graph separately using matplotlib and it displays the graph using plt.show().

But I have trouble embedding it in my tkinter gui. I have tried many things but have only been able to get the axes and not the actual bar graph. When the user selects the file to load, the log file comes up etc but in the canvas area only the axes show up and no plot.

Here is part of my code:

import matplotlib

matplotlib.use('TkAgg')

from matplotlib.backends.backend_tkagg import \
    FigureCanvasTkAgg,NavigationToolbar2TkAgg

from matplotlib.figure import Figure

import matplotlib.pyplot as plt

from tkinter import *

from tkinter import ttk

from tkinter.filedialog import askopenfilename

link,warn_list,frame_id, timeStamp=[[] for _ in range(4)]

root= Tk()

Title=root.title("Tool")

label=ttk.Label(root, text="Welcome",foreground='purple',font=("Times 20 bold italic"))

label.pack()

frame1=ttk.LabelFrame(root,labelanchor=NW,height=500,width=500,text='Static Information')

frame1.pack(fill=BOTH,expand=True)

text_static=Text(frame1,width=45, height=15,bg='lightgray')

text_static.pack(side=LEFT,fill=BOTH)

def loadfile():

    filename=askopenfilename(parent=root,filetypes=(("Text File","*.txt"),  ("All Files","*.*")),title='Choose a file')
    with open(filename, 'r')as log:
        for num,line in enumerate(log,1):
            if line.find("cam_req_mgr_process_sof")!=-1:
                    line=line.split()
                    frame_id.append(line [-1])
                    timeStamp.append(line[3].replace(":", ""))

menu=Menu(root)
root.config(menu=menu)

file=Menu(menu)

file.add_command(label='Load', command=loadfile)

file.add_command(label='Exit',command=root.destroy)

menu.add_cascade(label='Select an option:', menu=file)

def graph():

    fig=plt.Figure()
    x=frame_id #can use x=range(1,38)
    y=[1]*len(x)

    ax=fig.add_subplot(111)
    ax.bar(x,y,width=0.5, color='lightgreen')
    return fig

plot=graph()

canvas=FigureCanvasTkAgg(plot,frame1)

canvas.get_tk_widget().pack()

toolbar=NavigationToolbar2TkAgg(canvas,frame1)

toolbar.update()

canvas._tkcanvas.pack()

root.mainloop()

see the result here

Body:
The graph drawing almost works ! But not by loading a file. The problem is you don't update the canvas with the new set of data, and you don't cast them into numbers (float ? integers ?)

You kinda reach the limit of a functional approach to design this tool, because you need to refer i.e. to frame_id and canvas inside functions. 1 or 2 classes could solve this more easily.

As a quick fix i suggest this function :

def loadfile():
    global frame_id   # reach outside scope to use frame_id
    frame_id = []
    filename=askopenfilename(parent=root,
                             filetypes=(("Text File","*.txt"),
                                        ("All Files","*.*")),
                             title='Choose a file')
    with open(filename, 'r')as log:
        for num,line in enumerate(log,1):
            if line.find("cam_req_mgr_process_sof")!=-1:
                    line=line.split()
                    frame_id.append(float(line [-1])) # cast to float
                    timeStamp.append(line[3].replace(":", ""))
    newplot = graph()
    newplot.canvas = canvas
    canvas.figure = newplot
    canvas.draw()


问:
Progress while deserializing JSON
I'm deserializing a huge JSON (1.4 GB) via a stream, because I don't want to load the whole content into memory in advance just for parsing. That's working fine, but it takes ~80 seconds, so I want to display a progress.

```<code>public JObject DeserializeViaStream(string filename)
{
    object obj;
    var serializer = new JsonSerializer();
    using (var sr = new StreamReader(new FileStream(filename, FileMode.Open)))
    {
        using (var jsonTextReader = new JsonTextReader(sr))
        {
            obj = serializer.Deserialize(jsonTextReader);
        }
    }
    return (JObject) obj;
}
</code>```

I have not yet tried but only one idea: I could implement my own stream reader which keep track of the bytes being read and comparing that to the file length.

Is there a built-in option or easier way to do this?

答:
I ended up using the idea I had. Luckily there's already a ProgressStream available by Mel Green (archive.org). The original URL is no longer available.

Please note:

this approach may not work for all situations and with all libraries forever. This is due to the fact that the Seek() operation provides random access, and someone could read the file multiple times.

I can't post the source code here, because it was released under an unclear license.

Title: Progress while deserializing JSON

Body:
I'm deserializing a huge JSON (1.4 GB) via a stream, because I don't want to load the whole content into memory in advance just for parsing. That's working fine, but it takes ~80 seconds, so I want to display a progress.

public JObject DeserializeViaStream(string filename)
{
    object obj;
    var serializer = new JsonSerializer();
    using (var sr = new StreamReader(new FileStream(filename, FileMode.Open)))
    {
        using (var jsonTextReader = new JsonTextReader(sr))
        {
            obj = serializer.Deserialize(jsonTextReader);
        }
    }
    return (JObject) obj;
}

I have not yet tried but only one idea: I could implement my own stream reader which keep track of the bytes being read and comparing that to the file length.

Is there a built-in option or easier way to do this?

ContentLicense: CC BY-SA 4.0


问:
Zscore Normalize column in Dataframe using groupby
I have a dataframe representing customers orders with many columns, two of those being 'user_id' and 'dollar'.

for example :

```<code>    user_id   dollar
0  1  0.34592  5
1  1  0.02857  7
2  1  0.26672  6
3  1  0.34592  5
4  1  0.02857  9
5  1  0.26672  10
6  1  0.34592  6
      [...]
7  40  0.02857  20
8  40  0.26672  19
9  40  0.34592  8
10 40  0.02857  18
11 40  0.26672  26
</code>```

I want to normalize the value of dollar with respect to the other values in each users row. I want the following result for the previous example:

```<code> user_id   dollar norm_dollar
0  1  0.34592  5  -1.02774024
1  1  0.02857  7  0.07905694
2  1  0.26672  6  -0.47434165
3  1  0.34592  5  -1.02774024
4  1  0.02857  9  1.18585412
5  1  0.26672  10  1.73925271
6  1  0.34592  6  -0.47434165
      [...]
7  40  0.02857  20  0.7787612
8  40  0.26672  19  0.57109154
9  40  0.34592  8   -1.71327463
10 40  0.02857  18  0.36342189
</code>```

EDIT:

I would like each results to be normalized wrt each user individually and not the values of the whole column, so for example  with user2,[20,19,8,18] should be normalized as if the mean is the mean of user2 orders, here for example the mean is 16,25 and not the mean of the whole dataframe column.

I know how to do it with one user:

```<code>user1 = data.loc[data['user_id']==1]
data.loc[data['user_id']==1]['norm_dollar'] = sp.stats.mstats.zscore(user1['dollar'])
</code>```

I tried to do it this way for all the users:

```<code>data.dollar.div(sp.stats.mstats.zscore(data.groupby('user_id').dollar))
</code>```

But I got an error, do you have any idea on how to proceed?

Thank you

答:
Different ways to do this—like joining the groupby dataframe back to the original—but I'm starting to like the use of transform for stuff like this.

The syntax is still verbose, but I think it's more readable than the join method.

```<code>df['norm_dollar'] = (df['dollar']
                        - df.groupby('user_id')['dollar'].transform(np.mean)) \
                        / df.groupby('user_id')['dollar'].transform(np.std)
</code>```

If you need to specify degrees of freedom on np.std, you can turn that into

```<code>lambda x: np.std(x, ddof=n)
</code>```

Body:
I have a dataframe representing customers orders with many columns, two of those being 'user_id' and 'dollar'.

for example :

    user_id   dollar
0  1  0.34592  5
1  1  0.02857  7
2  1  0.26672  6
3  1  0.34592  5
4  1  0.02857  9
5  1  0.26672  10
6  1  0.34592  6
      [...]
7  40  0.02857  20
8  40  0.26672  19
9  40  0.34592  8
10 40  0.02857  18
11 40  0.26672  26

I want to normalize the value of dollar with respect to the other values in each users row. I want the following result for the previous example:

 user_id   dollar norm_dollar
0  1  0.34592  5  -1.02774024
1  1  0.02857  7  0.07905694
2  1  0.26672  6  -0.47434165
3  1  0.34592  5  -1.02774024
4  1  0.02857  9  1.18585412
5  1  0.26672  10  1.73925271
6  1  0.34592  6  -0.47434165
      [...]
7  40  0.02857  20  0.7787612
8  40  0.26672  19  0.57109154
9  40  0.34592  8   -1.71327463
10 40  0.02857  18  0.36342189

EDIT:

I would like each results to be normalized wrt each user individually and not the values of the whole column, so for example  with user2,[20,19,8,18] should be normalized as if the mean is the mean of user2 orders, here for example the mean is 16,25 and not the mean of the whole dataframe column.

I know how to do it with one user:

user1 = data.loc[data['user_id']==1]
data.loc[data['user_id']==1]['norm_dollar'] = sp.stats.mstats.zscore(user1['dollar'])

I tried to do it this way for all the users:

data.dollar.div(sp.stats.mstats.zscore(data.groupby('user_id').dollar))

But I got an error, do you have any idea on how to proceed?

Thank you

Body:
Different ways to do this—like joining the groupby dataframe back to the original—but I'm starting to like the use of transform for stuff like this.

The syntax is still verbose, but I think it's more readable than the join method.

df['norm_dollar'] = (df['dollar']
                        - df.groupby('user_id')['dollar'].transform(np.mean)) \
                        / df.groupby('user_id')['dollar'].transform(np.std)

If you need to specify degrees of freedom on np.std, you can turn that into

lambda x: np.std(x, ddof=n)


问:
Kernel address poising by clearing upper bits?
Is there some mechanism in Linux which is poisoning addresses by zeroing upper 16 bits?

I am debugging a kernel crash on an Intel x86-64 machine.  The instruction which is causing the crash tries to access an address of 0x880139f3da00:

```<code>crash> bt
R10: 0000000000000001  R11: 0000000000000001  R12: 0000880139f3da00
                                              ~~~~~~~~~~~~~~~~~~~~~

crash> p arp_tbl.nht->hash_buckets[255]
$66 = (struct neighbour *) 0x880139f3da00

crash> p *arp_tbl.nht->hash_buckets[255]
Cannot access memory at address 0x880139f3da00
</code>```

The hash_buckets table is valid:

```<code>crash> p arp_tbl.nht->hash_buckets[253]
$70 = (struct neighbour *) 0xffff88007325ae00
$71 = {
  next = 0x0,
  tbl = 0xffffffff81abbf20 <arp_tbl>,
</code>```

Setting upper word to 0xffff makes the address valid and returns a valid data structure:

```<code>crash> p *((struct neighbour *)0xffff880139f3da00)
$73 = {
  next = 0xffff88006de69a00,
  tbl = 0xffffffff81abbf20 <arp_tbl>,
  ... rest looks reasonable too ...
</code>```

Structure is updated by RCU operations (e.g. very likely by these in neigh_flush_dev()).  So, what could be the reason that the address becomes invalid in such a way?

I can exclude hardware defects (seen on two machines and with different addresses).  Systems are running CentOS 7 with kernel 3.10.0-514.6.1.el7.centos.plus.x86_64 till  3.10.0-514.21.2.el7.centos.plus.x86_64.

Update

From another crash dump, I see an skb of an IPv6 packet with

```<code>crash> p *((struct sk_buff *)0xffff880070e25e00)
$57 = {
  transport_header = 54,
  network_header = 14,
  mac_header = 0,
  ...
  head = 0xffff880138e28000 "",
  data = 0xffff880138e2800e "`",
  ...
}
</code>```

This crashes when writing the first 0x8 bytes in

#define HH_DATA_MOD 16

static inline int neigh_hh_output(const struct hh_cache *hh, struct sk_buff *skb)
{
                if (likely(hh_len <= HH_DATA_MOD)) {
                        memcpy(skb->data - HH_DATA_MOD, hh->hh_data, HH_DATA_MOD);   <<<<<
```

This  would explain why two bytes are overridden (16 - 14).

答:
can you inspect the memory location this address was read from? typically such a "partial zero" read is a result of memset being run on the area. after this cpu triggered a crash there was possibly enough time for whoever else was modifying the area to finish zeroing and possibly even fill it with other data.

so far there is no reason to suspect rcu plays any role here

this is most definitely not "poisoning" done by the kernel (it would be quite weird to do it in this way). however, if the crash is reproducible (you say it occurred on at least 2 different machines?) then running a debug kernel may be of help, especially with slab debug enabled.

Body:
Is there some mechanism in Linux which is poisoning addresses by zeroing upper 16 bits?

I am debugging a kernel crash on an Intel x86-64 machine.  The instruction which is causing the crash tries to access an address of 0x880139f3da00:

crash> bt
R10: 0000000000000001  R11: 0000000000000001  R12: 0000880139f3da00
                                              ~~~~~~~~~~~~~~~~~~~~~

crash> p arp_tbl.nht->hash_buckets[255]
$66 = (struct neighbour *) 0x880139f3da00

crash> p *arp_tbl.nht->hash_buckets[255]
Cannot access memory at address 0x880139f3da00

The hash_buckets table is valid:

crash> p arp_tbl.nht->hash_buckets[253]
$70 = (struct neighbour *) 0xffff88007325ae00
$71 = {
  next = 0x0,
  tbl = 0xffffffff81abbf20 <arp_tbl>,

Setting upper word to 0xffff makes the address valid and returns a valid data structure:

crash> p *((struct neighbour *)0xffff880139f3da00)
$73 = {
  next = 0xffff88006de69a00,
  tbl = 0xffffffff81abbf20 <arp_tbl>,
  ... rest looks reasonable too ...

Structure is updated by RCU operations (e.g. very likely by these in neigh_flush_dev()).  So, what could be the reason that the address becomes invalid in such a way?

I can exclude hardware defects (seen on two machines and with different addresses).  Systems are running CentOS 7 with kernel 3.10.0-514.6.1.el7.centos.plus.x86_64 till  3.10.0-514.21.2.el7.centos.plus.x86_64.

Update

From another crash dump, I see an skb of an IPv6 packet with

crash> p *((struct sk_buff *)0xffff880070e25e00)
$57 = {
  transport_header = 54,
  network_header = 14,
  mac_header = 0,
  ...
  head = 0xffff880138e28000 "",
  data = 0xffff880138e2800e "`",
  ...
}

This crashes when writing the first 0x8 bytes in

#define HH_DATA_MOD 16

static inline int neigh_hh_output(const struct hh_cache *hh, struct sk_buff *skb)
{
                if (likely(hh_len <= HH_DATA_MOD)) {
                        memcpy(skb->data - HH_DATA_MOD, hh->hh_data, HH_DATA_MOD);   <<<<<

This  would explain why two bytes are overridden (16 - 14).


问:
How to use virtualenv in makefile
I want to perform several operations while working on a specified virtualenv.

For example command

```<code>make install
</code>```

would be equivalent to

```<code>source path/to/virtualenv/bin/activate
pip install -r requirements.txt
</code>```

Is it possible?

答:
You should use this, it's functional for me at moment.</p>

```<code>report.ipynb : merged.ipynb
    ( bash -c "source ${HOME}/anaconda3/bin/activate py27; which -a python; \
        jupyter nbconvert \
        --to notebook \
        --ExecutePreprocessor.kernel_name=python2 \
        --ExecutePreprocessor.timeout=3000 \
        --execute merged.ipynb \
        --output=$< $<" )
</code>```

Title: How to use virtualenv in makefile

Body:
I want to perform several operations while working on a specified virtualenv.

For example command

make install

would be equivalent to

source path/to/virtualenv/bin/activate
pip install -r requirements.txt

Is it possible?

Body:
You should use this, it's functional for me at moment.

report.ipynb : merged.ipynb
    ( bash -c "source ${HOME}/anaconda3/bin/activate py27; which -a python; \
        jupyter nbconvert \
        --to notebook \
        --ExecutePreprocessor.kernel_name=python2 \
        --ExecutePreprocessor.timeout=3000 \
        --execute merged.ipynb \
        --output=$< $<" )


问:
Non-symbolic derivative at all sample points including boundary points
Suppose I have a vector t = [0 0.1 0.9 1 1.4], and a vector x  = [1 3 5 2 3]. How can I compute the derivative of x with respect to time that has the same length as the original vectors?

I should not use any symbolic operations. The command diff(x)./diff(t) does not produce a vector of the same length. Should I first interpolate the x(t) function and then take its derivative?

答:
Different approaches exist to calculate the derivative at the same points as your initial data:

Finite differences: Use a central difference scheme at your inner points and a forward/backward scheme at your first/last point

or

Curve fitting: Fit a curve through your points, calculate the derivative of this fitted function and sample them at the same points as the original data. Typical fitting functions are polynomials or spline functions.

Note that the curve fitting approach gives better results, but needs more tuning options and is slower (~100x).

Demonstration

As an example, I will calculate the derivative of a sine function:

```<code>t = 0:0.1:1;
y = sin(t);
</code>```

Its exact derivative is well known:

```<code>dy_dt_exact = cos(t);
</code>```

The derivative can approximately been calculated as:

Finite differences:

```<code>dy_dt_approx = zeros(size(y));
dy_dt_approx(1) = (y(2) - y(1))/(t(2) - t(1)); % forward difference
dy_dt_approx(end) = (y(end) - y(end-1))/(t(end) - t(end-1)); % backward difference
dy_dt_approx(2:end-1) = (y(3:end) - y(1:end-2))./(t(3:end) - t(1:end-2)); % central difference
</code>```

or

Polynomial fitting:

```<code>p = polyfit(t,y,5); % fit fifth order polynomial
dp = polyder(p); % calculate derivative of polynomial
</code>```

The results can be visualised as follows:

```<code>figure('Name', 'Derivative')
hold on
plot(t, dy_dt_exact, 'DisplayName', 'eyact');
plot(t, dy_dt_approx, 'DisplayName', 'finite difference');
plot(t, polyval(dp, t), 'DisplayName', 'polynomial');
legend show

figure('Name', 'Error')
hold on
plot(t, abs(dy_dt_approx - dy_dt_exact)/max(dy_dt_exact), 'DisplayName', 'finite difference');
plot(t, abs(polyval(dp, t) - dy_dt_exact)/max(dy_dt_exact), 'DisplayName', 'polynomial');
legend show
</code>```

The first graph shows the derivatives itself and the second graph plots the relative errors made by both methods.

Discussion

One clearly sees that the curve fitting method gives better results than the finite differences, but it is ~100x slower. The curve fitting methods has a relative error of order 10^-5. Note that the finite differences approach becomes better when your data is sampled more densely or you use a higher order scheme. The disadvantage of the curve fitting approach is that one has to choose a good polynomial order. Spline functions may be better suited in general.

A 10x faster sampled dataset, i.e. t = 0:0.01:1;, results in the following graphs:

Body:
Different approaches exist to calculate the derivative at the same points as your initial data:

Finite differences: Use a central difference scheme at your inner points and a forward/backward scheme at your first/last point

or

Curve fitting: Fit a curve through your points, calculate the derivative of this fitted function and sample them at the same points as the original data. Typical fitting functions are polynomials or spline functions.

Note that the curve fitting approach gives better results, but needs more tuning options and is slower (~100x).

Demonstration

As an example, I will calculate the derivative of a sine function:

t = 0:0.1:1;
y = sin(t);

Its exact derivative is well known:

dy_dt_exact = cos(t);

The derivative can approximately been calculated as:

Finite differences:

dy_dt_approx = zeros(size(y));
dy_dt_approx(1) = (y(2) - y(1))/(t(2) - t(1)); % forward difference
dy_dt_approx(end) = (y(end) - y(end-1))/(t(end) - t(end-1)); % backward difference
dy_dt_approx(2:end-1) = (y(3:end) - y(1:end-2))./(t(3:end) - t(1:end-2)); % central difference

or

Polynomial fitting:

p = polyfit(t,y,5); % fit fifth order polynomial
dp = polyder(p); % calculate derivative of polynomial

The results can be visualised as follows:

figure('Name', 'Derivative')
hold on
plot(t, dy_dt_exact, 'DisplayName', 'eyact');
plot(t, dy_dt_approx, 'DisplayName', 'finite difference');
plot(t, polyval(dp, t), 'DisplayName', 'polynomial');
legend show

figure('Name', 'Error')
hold on
plot(t, abs(dy_dt_approx - dy_dt_exact)/max(dy_dt_exact), 'DisplayName', 'finite difference');
plot(t, abs(polyval(dp, t) - dy_dt_exact)/max(dy_dt_exact), 'DisplayName', 'polynomial');
legend show

The first graph shows the derivatives itself and the second graph plots the relative errors made by both methods.

Discussion

One clearly sees that the curve fitting method gives better results than the finite differences, but it is ~100x slower. The curve fitting methods has a relative error of order 10^-5. Note that the finite differences approach becomes better when your data is sampled more densely or you use a higher order scheme. The disadvantage of the curve fitting approach is that one has to choose a good polynomial order. Spline functions may be better suited in general.

A 10x faster sampled dataset, i.e. t = 0:0.01:1;, results in the following graphs:


问:
HTML5 acronym tag replacement using jQuery
Using jQuery, how would you replace every <acronym> tag with ?

答:
```<code>$('acronym').each(function() {
  $(this).replaceWith('<abbr>' + $(this).html() + '</abbr>');
});
</code>```

ContentLicense: CC BY-SA 2.5


问:
Allign image and text
I have text "Helloooooooooooooooo" at the bottom of the image but the image should be in the center of text.

Expected output:

```<code>            IMG
Hellooooooooooooooooooooooooooo
</code>```

Currently wrong output:

```<code>IMG
Helloooooooooooooooooooooooooooooo
</code>```

What can I try?

  Hellooooooooooooooooooooooooooooooooooooooooooooo.

```

答:
text-align: center will center an img. Add that to the parent, and add display: inline-block if you want the parent on the left side of the screen contained to the max width of either the text or the img. Or remove it if you want the parent to occupy the full width of the container and the text/img centered relative to that width.

  Hellooooooooooooooooooooooooooooooooooooooooooooo.

```

Title: Allign image and text

Body:
I have text "Helloooooooooooooooo" at the bottom of the image but the image should be in the center of text.

Expected output:

            IMG
Hellooooooooooooooooooooooooooo

Currently wrong output:

IMG
Helloooooooooooooooooooooooooooooo

What can I try?

  Hellooooooooooooooooooooooooooooooooooooooooooooo.

Body:
text-align: center will center an img. Add that to the parent, and add display: inline-block if you want the parent on the left side of the screen contained to the max width of either the text or the img. Or remove it if you want the parent to occupy the full width of the container and the text/img centered relative to that width.

<div style="text-align: center; display: inline-block;">
  <img style="vertical-align:middle" src="https://placehold.it/60x60"><br>
  <span style="">Hellooooooooooooooooooooooooooooooooooooooooooooo.</span>
</div>


问:
Ruby: how to erase the " in the string-keys when return a hash
I'm trying to return a hash, of which the keys are strings and the values are arrays, by adding elements into value-arrays, for example:

```<code>    {"Fixnum"=>[1, 8], "Hash"=>[{7=>"einzeln", 5=>[13]}]}
</code>```

But I want to erase " in the keys, like so:

```<code>    {Fixnum=>[1, 8], Hash=>[{7=>"einzeln", 5=>[13]}]}
</code>```

Obviously I can't simply use .delete('"') because then the " with einzeln will be gone too. I've also tried freezing the .to_s form of the elements when adding them to value-arrays, and then use .delete, but it didn't work. I also didn't find anyway to iterate or grab the keys and use .delete directly on the keys, because the keys are frozen.

Is there anyway to do this?

答:
The hash keys don't actually have double quotes ("), you see them because the keys are strings and ruby will show all strings enclosed between double quotes; so you won't be able (nor need) to remove them.

What you could do is use symbols instead of strings for the hash keys (which is pretty much Ruby best practice).

For that you could either create the hash with symbols, like this:

```<code>my_hash = {Fixnum: [1, 8], Hash: [{7=>"einzeln", 5=>[13]}]}
#=> {:Fixnum=>[1, 8], :Hash=>[{7=>"einzeln", 5=>[13]}]}
</code>```

If you have no control over the keys of the hash, you can convert the keys to symbols, like this:

```<code>my_hash = {"Fixnum"=>[1, 8], "Hash"=>[{7=>"einzeln", 5=>[13]}]}

Hash[my_hash.map{ |k, v| [k.to_sym, v] }]
#=> {:Fixnum=>[1, 8], :Hash=>[{7=>"einzeln", 5=>[13]}]}
</code>```

Or, as pointed out by mu is too short, you could use Fixnum and Hash classes as keys, like so:

```<code>my_hash = {Fixnum => [1, 8], Hash => [{7=>"einzeln", 5=>[13]}]}
#=> {Fixnum=>[1, 8], Hash=>[{7=>"einzeln", 5=>[13]}]}
</code>```

Again, if you don't have control over the keys of the hash, you can convert the keys to their classes, like this1:

```<code>my_hash = {"Fixnum"=>[1, 8], "Hash"=>[{7=>"einzeln", 5=>[13]}]}

Hash[my_hash.map{ |k, v| [eval(k.to_s), v] }]
#=> {Fixnum=>[1, 8], Hash=>[{7=>"einzeln", 5=>[13]}]}
</code>```

1 Keep in mind that using eval is only recommended when you have complete trust/control over the values passed to it.

Body:
I'm trying to return a hash, of which the keys are strings and the values are arrays, by adding elements into value-arrays, for example:

    {"Fixnum"=>[1, 8], "Hash"=>[{7=>"einzeln", 5=>[13]}]}

But I want to erase " in the keys, like so:

    {Fixnum=>[1, 8], Hash=>[{7=>"einzeln", 5=>[13]}]}

Obviously I can't simply use .delete('"') because then the " with einzeln will be gone too. I've also tried freezing the .to_s form of the elements when adding them to value-arrays, and then use .delete, but it didn't work. I also didn't find anyway to iterate or grab the keys and use .delete directly on the keys, because the keys are frozen.

Is there anyway to do this?

Body:
The hash keys don't actually have double quotes ("), you see them because the keys are strings and ruby will show all strings enclosed between double quotes; so you won't be able (nor need) to remove them.

What you could do is use symbols instead of strings for the hash keys (which is pretty much Ruby best practice).

For that you could either create the hash with symbols, like this:

my_hash = {Fixnum: [1, 8], Hash: [{7=>"einzeln", 5=>[13]}]}
#=> {:Fixnum=>[1, 8], :Hash=>[{7=>"einzeln", 5=>[13]}]}

If you have no control over the keys of the hash, you can convert the keys to symbols, like this:

my_hash = {"Fixnum"=>[1, 8], "Hash"=>[{7=>"einzeln", 5=>[13]}]}

Hash[my_hash.map{ |k, v| [k.to_sym, v] }]
#=> {:Fixnum=>[1, 8], :Hash=>[{7=>"einzeln", 5=>[13]}]}

Or, as pointed out by mu is too short, you could use Fixnum and Hash classes as keys, like so:

my_hash = {Fixnum => [1, 8], Hash => [{7=>"einzeln", 5=>[13]}]}
#=> {Fixnum=>[1, 8], Hash=>[{7=>"einzeln", 5=>[13]}]}

Again, if you don't have control over the keys of the hash, you can convert the keys to their classes, like this1:

my_hash = {"Fixnum"=>[1, 8], "Hash"=>[{7=>"einzeln", 5=>[13]}]}

Hash[my_hash.map{ |k, v| [eval(k.to_s), v] }]
#=> {Fixnum=>[1, 8], Hash=>[{7=>"einzeln", 5=>[13]}]}

1 Keep in mind that using eval is only recommended when you have complete trust/control over the values passed to it.


问:
Need Help to create a folder with Timestamp using EST Timezone With DST(DaylightSavingTime)
i tried with below code , when i use ${build.time}， it create one hr behind as DST is on now. I want created with exact time.

```<code><plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>3.0.0</version>
  <executions>
    <execution>
      <id>timestamp-property</id>
      <phase>validate</phase>
      <goals>
        <goal>timestamp-property</goal>
      </goals>
      <configuration>
        <name>build.time</name>
        <pattern>MM-dd-YYYY-hh-mm-SS</pattern>
        <locale>en_US</locale>
        <timezone>EST</timezone>
      </configuration>
    </execution>
  </executions>
</plugin>
</code>```

答:
If you want it to adjust for DST, don't use EST, use America/New_York.

For historical reasons, the JDK doesn't apply daylight savings time adjustments to EST (although it does to other timezone abbreviations like PST).

You are better off just avoiding three-letter timezone abbreviations entirely, they are ambiguous. From the Javadoc:

For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such as "PST", "CTT", "AST") are also supported. However, their use is deprecated because the same abbreviation is often used for multiple time zones (for example, "CST" could be U.S. "Central Standard Time" and "China Standard Time"), and the Java platform can then only recognize one of them.

Body:
i tried with below code , when i use ${build.time}， it create one hr behind as DST is on now. I want created with exact time.

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>build-helper-maven-plugin</artifactId>
  <version>3.0.0</version>
  <executions>
    <execution>
      <id>timestamp-property</id>
      <phase>validate</phase>
      <goals>
        <goal>timestamp-property</goal>
      </goals>
      <configuration>
        <name>build.time</name>
        <pattern>MM-dd-YYYY-hh-mm-SS</pattern>
        <locale>en_US</locale>
        <timezone>EST</timezone>
      </configuration>
    </execution>
  </executions>
</plugin>


问:
How to update date in table based on two criteria from a select
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like</p>

```<code>UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)
</code>```

答:
The simplest method is to join these two tables in an UPDATE statement.

Try the following:

```<code>UPDATE [Table A]
SET DATE = GETDATE()
FROM [Table A] a
INNER JOIN [Table B] b on a.userid = b.userid and a.planName = b.planName
</code>```

Body:
I need to update a date in one table based on if an userID and planName are returned from a select off a different table.
Something like

UPDATE Table A
SET DATE = GETDATE()
WHERE userid AND planName IN (SELECT userid, planName From Table B)

Body:
The simplest method is to join these two tables in an UPDATE statement.

Try the following:

UPDATE [Table A]
SET DATE = GETDATE()
FROM [Table A] a
INNER JOIN [Table B] b on a.userid = b.userid and a.planName = b.planName


问:
How do I use a for loop in JavaScript to add all positive integers to 'sum'?
```<code>var n = 25;
</code>```

Declare a new variable named "sum" initialized to 0. Be sure to use the "var" keyword.

Use a for loop to add every positive integer less than n to sum.

Come up with a solution that works for all values of n.

Above are the conditions of the code to be written. Below is what I have written. However, I keep getting an error stating "the sum of all integers less than 2 is 1". Is there something wrong with my code, or am I approaching this from the wrong angle?

```<code>var sum = 0;
for (i = 0; i <= n; i++) {
  if (i % 2 == 0) {
    sum += i;
  } else {
    sum = sum;
  }
}
</code>```

答:
You don't need the conditions in the for loop. Seems those are for conditions where you want even/odd numbers. And you should iterate over indexes 1 to n-1, i.e., up to but not including n, or i < n. Also notice you were asked to sum the positive numbers only. Technically you shouldn't sum 0 in the start, mean you should start at i = 1. However, mathematically speaking, this last thing doesn't actually change the result.

```<code>var n = 25;
var sum = 0;
for (i = 1; i < n; i++) {
    sum += i;
}
</code>```

An alternative is also:

```<code>var n = 25;
sum = Array.from(new Array(n), (x, i) => i).reduce((a, b) => a + b, 0);
</code>```

However, IMO it's too "fancy" and not as readable, and technically sums with zero in the start.

Body:
var n = 25;

Declare a new variable named "sum" initialized to 0. Be sure to use the "var" keyword.

Use a for loop to add every positive integer less than n to sum.

Come up with a solution that works for all values of n.

Above are the conditions of the code to be written. Below is what I have written. However, I keep getting an error stating "the sum of all integers less than 2 is 1". Is there something wrong with my code, or am I approaching this from the wrong angle?

var sum = 0;
for (i = 0; i <= n; i++) {
  if (i % 2 == 0) {
    sum += i;
  } else {
    sum = sum;
  }
}

Body:
You don't need the conditions in the for loop. Seems those are for conditions where you want even/odd numbers. And you should iterate over indexes 1 to n-1, i.e., up to but not including n, or i < n. Also notice you were asked to sum the positive numbers only. Technically you shouldn't sum 0 in the start, mean you should start at i = 1. However, mathematically speaking, this last thing doesn't actually change the result.

var n = 25;
var sum = 0;
for (i = 1; i < n; i++) {
    sum += i;
}

An alternative is also:

var n = 25;
sum = Array.from(new Array(n), (x, i) => i).reduce((a, b) => a + b, 0);

However, IMO it's too "fancy" and not as readable, and technically sums with zero in the start.


问:
Python AWS Boto URL Connection Error
I'm trying to create an AWS machine learning model in Python BOTO:

```<code>import boto3
from boto3.session import Session
import uuid

session = Session(aws_access_key_id='...', aws_secret_access_key='...', region_name='us-west-1')
client = session.client('machinelearning')

response = client.create_ml_model(
    MLModelId=str(uuid.uuid4()),
    MLModelName='banking',
    MLModelType='BINARY',
    TrainingDataSourceId='...',
)
</code>```

However, I'm getting the following error:

botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://machinelearning.us-west-1.amazonaws.com/"

I don't believe the region_name is the problem. Could this be a permission problem?

答: Actually the region is the issue. Amazon Machine Learning is only available currently in the Virginia and Ireland regions as per documentation

Title: Python AWS Boto URL Connection Error

Body:
I'm trying to create an AWS machine learning model in Python BOTO:

import boto3
from boto3.session import Session
import uuid

session = Session(aws_access_key_id='...', aws_secret_access_key='...', region_name='us-west-1')
client = session.client('machinelearning')

response = client.create_ml_model(
    MLModelId=str(uuid.uuid4()),
    MLModelName='banking',
    MLModelType='BINARY',
    TrainingDataSourceId='...',
)

However, I'm getting the following error:

botocore.exceptions.EndpointConnectionError: Could not connect to the endpoint URL: "https://machinelearning.us-west-1.amazonaws.com/"

I don't believe the region_name is the problem. Could this be a permission problem?


问:
How many formats of mail client's address book?
I want to develop a library to handle mail client’s address book. And, I know Microsoft Outlook’s address book’s format is *.pst. What about Mozilla thunderbird or others?</p>

答:
PST isn't address book, it's archived email.

You could start by reading the source of Apache Tika which handles some formats.


问:
Force focus on input-field on click with angularjs
I have a text-box to show a input field on click and  hide it on blur. The problem is when the input is shown, it is not auto-focused. The blur only works if you click the text-box, then click the input. But when you click the text-box once and go somewhere else, you can still see the input. Is it possible to auto-focus the input field on click? or maybe there is a better way to do this?

```<code><div data-ng-init="editMode = false">
    <p data-ng-show="!editMode" data-ng-click="editMode = true">{{color}}</p>
    <span data-ng-show="editMode">
       <input data-ng-blur="editMode = false" data-ng-model="color">
    </span>
  </div>
</code>```

Thanks in advance for your help!

答:
I would suggest maybe making some light use of jquery. Call a function from ng-click, which executes jquery to do an auto-focus, like so:</p>

```<code>$("#textInputId").focus();
</code>```

Body:
I have a text-box to show a input field on click and  hide it on blur. The problem is when the input is shown, it is not auto-focused. The blur only works if you click the text-box, then click the input. But when you click the text-box once and go somewhere else, you can still see the input. Is it possible to auto-focus the input field on click? or maybe there is a better way to do this?

{{color}}

       <input data-ng-blur="editMode = false" data-ng-model="color">

Thanks in advance for your help!

Body:
I would suggest maybe making some light use of jquery. Call a function from ng-click, which executes jquery to do an auto-focus, like so:

$("#textInputId").focus();


问:
Include unrelated table in Linq to entity query
I have the following simplified setup:

```<code>Public User
{

  //Primary key
  public int Id {get;set;}

  public string Name {get; set;}
}

Public UserInfo
{

  //Primary key
  public int Id {get;set;}

  //Foreign key to user table
  public int userKey {get; set;}
}
</code>```

The relationship between the tables is one user to Many userInfo

I am trying to select from the user table and include the userInfo table.

I cannot do this:

```<code>var users = Context.user.Include(u => u.userInfos);
</code>```

as there is no reference to the UserInfo table from the user table.

I can do this:

```<code>context.userInfo.include(x => x.user)
</code>```

but if there are no corresponding entries in the userInfo table, this will not return any results, which is not what I want. Also, this will return one row for each userInfo, whereas I want one row for user, with a list of userInfo as a parameter.

Similarly I could join the tables like this:

```<code>var users = from us in Context.user
    join inf in Context.userInfo
    on us.Id equals inf.userKey
    select new //etc
</code>```

But this will also return one row per userInfo entry, the same problem as above.

To summarise, is there a way of including this table to produce a result in the same way as the include function does.

I know I could adjust my setup to all me to include this, but that is not what I am asking here.

I suspect this cannot be done, but from all my googling so far I have not been able to find a definitive answer....

答:
I want one row for user, with a list of userInfo as a parameter

I assume you mean a list of userInfo as a property. My understanding of what you ask it that you're just looking for:

```<code>var users = from us in Context.user
    join inf in Context.userInfo
        on us.Id equals inf.userKey into infg
    select new
    {
        User = us,
        UserInfos = infg
    };
</code>```

join ... into amounts to a GroupJoin, i.e. a user entity joined with a group of userinfos.

Better still is to use a navigation property user.userInfos (reluctantly following your naming convention):

```<code>var users = Context.user.Include(u => u.userInfos);
</code>```

Body:
I have the following simplified setup:

Public User
{

  //Primary key
  public int Id {get;set;}

  public string Name {get; set;}
}

Public UserInfo
{

  //Primary key
  public int Id {get;set;}

  //Foreign key to user table
  public int userKey {get; set;}
}

The relationship between the tables is one user to Many userInfo

I am trying to select from the user table and include the userInfo table.

I cannot do this:

var users = Context.user.Include(u => u.userInfos);

as there is no reference to the UserInfo table from the user table.

I can do this:

context.userInfo.include(x => x.user)

but if there are no corresponding entries in the userInfo table, this will not return any results, which is not what I want. Also, this will return one row for each userInfo, whereas I want one row for user, with a list of userInfo as a parameter.

Similarly I could join the tables like this:

var users = from us in Context.user
    join inf in Context.userInfo
    on us.Id equals inf.userKey
    select new //etc

But this will also return one row per userInfo entry, the same problem as above.

To summarise, is there a way of including this table to produce a result in the same way as the include function does.

I know I could adjust my setup to all me to include this, but that is not what I am asking here.

I suspect this cannot be done, but from all my googling so far I have not been able to find a definitive answer....

Body:
I want one row for user, with a list of userInfo as a parameter

I assume you mean a list of userInfo as a property. My understanding of what you ask it that you're just looking for:

var users = from us in Context.user
    join inf in Context.userInfo
        on us.Id equals inf.userKey into infg
    select new
    {
        User = us,
        UserInfos = infg
    };

join ... into amounts to a GroupJoin, i.e. a user entity joined with a group of userinfos.

Better still is to use a navigation property user.userInfos (reluctantly following your naming convention):

var users = Context.user.Include(u => u.userInfos);


答:
it is just as simple as this, remember to use var in the for loop. </p>

```<code>    var n = 25;
    var sum = 0;
    for (var i = 0; i < n; i++) {
        sum += i;
    }
</code>```

Title: How do I use a for loop in JavaScript to add all positive integers to 'sum'?

Body:
it is just as simple as this, remember to use var in the for loop.

    var n = 25;
    var sum = 0;
    for (var i = 0; i < n; i++) {
        sum += i;
    }


答:
Here's another option...</p>

```<code>IF OBJECT_ID('tempdb..#Article', 'U') IS NOT NULL
DROP TABLE #Article;

CREATE TABLE #Article (
    Article INT NOT NULL,
    Location CHAR(6) NOT NULL,
    Existance INT NOT NULL
    );

IF OBJECT_ID('tempdb..#Counts', 'U') IS NOT NULL
DROP TABLE #Counts;

CREATE TABLE #Counts (
    Article INT NOT NULL,
    Location CHAR(6) NOT NULL,
    Quantity INT NOT NULL
    );

INSERT #Article(Article, Location, Existance) VALUES
    (200116, 'cc3111', 1), (200116, 'ee3091', 1);

INSERT #Counts(Article, Location, Quantity) VALUES
    (200116, 'cc3111', 10), (200116, 'EE3091', 8),
    (200116, 'EE2102', 5), (200116, 'DD5131', 10);

SELECT * FROM #Article a;
SELECT * FROM #Counts c;

--=====================================================

SELECT
    Article = COALESCE(a.Article, c.Article),
    Location = COALESCE(a.Location, c.Location),
    Existance = COALESCE(a.Existance, 0),
    Quantity = COALESCE(c.Quantity, 0),
    DIF =  COALESCE(c.Quantity, 0) - COALESCE(a.Existance, 0)
FROM
    #Article a
    FULL JOIN #Counts c
        ON a.Article = c.Article
        AND a.Location = c.Location;
</code>```

Title: Bring information from 2 tables and put it in the same column

Body:
I have this table of articles

---------------------------------------------
|   Article   |   Location    | existence   |
---------------------------------------------
|     200116    |   cc3111      |   1       |
---------------------------------------------
|     200116    |   ee3091      |       1   |
---------------------------------------------

And this count table

----------------------------------------------------
|   Article   |   Location     |   Quantity      |
----------------------------------------------------
|     200116    |   cc3111       |   10            |
----------------------------------------------------
|     200116    |   EE3091       |   8             |
----------------------------------------------------
|     200116    |   EE2102       |   5             |
----------------------------------------------------
|     200116    |   DD5131       |   7             |
----------------------------------------------------

What I'm trying to do is give me one result like the next.

--------------------------------------------------------------------------
|   Article   |   Location    | Existence      |  Quantity |   DIF      |
--------------------------------------------------------------------------
|     200116  |   CC3111      |     1          |     10    |     9       |
--------------------------------------------------------------------------
|     200116  |   EE3091      |     1          |     8     |      7      |
--------------------------------------------------------------------------
|     200116  |   DD5131      |     0          |    7      |     7       |
--------------------------------------------------------------------------
|     200116  |   EE2102      |     0          |    5      |     5      |
----------------------------- -------------------------------------------

But without doing it with a Union since then I have to make another query, I just do not know how to join it without usingUnion.

-SOME HELP TO PERFORM THIS QUERY

-I do not know how to add the location in the same column

Body:
Here's another option...

IF OBJECT_ID('tempdb..#Article', 'U') IS NOT NULL
DROP TABLE #Article;

CREATE TABLE #Article (
    Article INT NOT NULL,
    Location CHAR(6) NOT NULL,
    Existance INT NOT NULL
    );

IF OBJECT_ID('tempdb..#Counts', 'U') IS NOT NULL
DROP TABLE #Counts;

CREATE TABLE #Counts (
    Article INT NOT NULL,
    Location CHAR(6) NOT NULL,
    Quantity INT NOT NULL
    );

INSERT #Article(Article, Location, Existance) VALUES
    (200116, 'cc3111', 1), (200116, 'ee3091', 1);

INSERT #Counts(Article, Location, Quantity) VALUES
    (200116, 'cc3111', 10), (200116, 'EE3091', 8),
    (200116, 'EE2102', 5), (200116, 'DD5131', 10);

SELECT * FROM #Article a;
SELECT * FROM #Counts c;

--=====================================================

SELECT
    Article = COALESCE(a.Article, c.Article),
    Location = COALESCE(a.Location, c.Location),
    Existance = COALESCE(a.Existance, 0),
    Quantity = COALESCE(c.Quantity, 0),
    DIF =  COALESCE(c.Quantity, 0) - COALESCE(a.Existance, 0)
FROM
    #Article a
    FULL JOIN #Counts c
        ON a.Article = c.Article
        AND a.Location = c.Location;


问:
How to use wsHttpBinding with Message security through a load balancer
I have a load-balanced service that uses Message security:

```<code><wsHttpBinding>
  <binding>
    <security mode="Message">
      <message clientCredentialType="Windows" establishSecurityContext="false" />
    </security>
  </binding>
</wsHttpBinding>
</code>```

All of my calls to this service open and close their own channel, so there's no benefit to establishing a security context.

I am calling the service with a WSHttpBinding that matches the service config:

```<code>ws.Security.Mode = SecurityMode.Message;
ws.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
ws.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
ws.Security.Message.EstablishSecurityContext = false;
</code>```

This works sometimes, but sometimes I get errors such as

The security context token is expired or is not valid. The message was not processed.

or

The request for security token has invalid or malformed elements.

I finally found that setting EstablishSecurityContext to false doesn't actually prevent security context tokens from being used.  Our load balancer doesn't currently use sticky sessions, and I'm trying to avoid going that route.

I did find that I should be able to set NegotiateServiceCredential to false on the client to allow for the load balancer without sticky sessions.  My service is already running under an AD account, and I can see it in the WSDL:

```<code><Upn>User@Domain</Upn>
</code>```

However, when I try to add the service identity to my client

```<code>EndpointIDentity.CreateUpnIdentity("User@Domain")
</code>```

I get the following error:

Authenticating to a service running under a user account which requires Kerberos multilegs, is not supported.

How do I get past this to be able to make a call to my service through the load balancer?

答:
According to the documentation for NegotiateServiceCredential, you must run the service using an SPN identity instead of UPN:

If this property is set to false, and the binding is configured to use
  Windows as a client credential type, the service account must be
  associated with a Service Principal Name (SPN). To do this, run the
  service under the NETWORK SERVICE account, or LOCAL SYSTEM account.
  Alternatively, use the SetSpn.exe tool to create an SPN for the
  service account. In either case, the client must use the correct SPN
  in the <servicePrincipalName> element, or by using the EndpointAddress
  constructor.

Once you configure the SPN that your service is running under, your WSDL should display SPN instead of UPN, then you'll have to modify your client such that: EndpointIdentity.CreateSpnIdentity("service_spn_name")

Update:

The following command should properly configure the SPN:

setspn -A YourSvc/host.server.com domain\AppPoolAcccountName

YourSvc = a name identifying your svc

host.server.com = fully qualified hostname of the server your service is hosted on

See docs for setspn

Body:
I have a load-balanced service that uses Message security:

<wsHttpBinding>
  <binding>
    <security mode="Message">
      <message clientCredentialType="Windows" establishSecurityContext="false" />
    </security>
  </binding>
</wsHttpBinding>

All of my calls to this service open and close their own channel, so there's no benefit to establishing a security context.

I am calling the service with a WSHttpBinding that matches the service config:

ws.Security.Mode = SecurityMode.Message;
ws.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
ws.Security.Message.ClientCredentialType = MessageCredentialType.Windows;
ws.Security.Message.EstablishSecurityContext = false;

This works sometimes, but sometimes I get errors such as

The security context token is expired or is not valid. The message was not processed.

or

The request for security token has invalid or malformed elements.

I finally found that setting EstablishSecurityContext to false doesn't actually prevent security context tokens from being used.  Our load balancer doesn't currently use sticky sessions, and I'm trying to avoid going that route.

I did find that I should be able to set NegotiateServiceCredential to false on the client to allow for the load balancer without sticky sessions.  My service is already running under an AD account, and I can see it in the WSDL:

<Upn>User@Domain</Upn>

However, when I try to add the service identity to my client

EndpointIDentity.CreateUpnIdentity("User@Domain")

I get the following error:

Authenticating to a service running under a user account which requires Kerberos multilegs, is not supported.

How do I get past this to be able to make a call to my service through the load balancer?


问:
Android - Preference onCreateView attrs.getAttributeCount()
How do I get the "max" attribute during onCreateView()?
If I can get attrs.getAttributeCount() to work that would solve my problem.

```<code><?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:title="@string/livewallpaper_settings"
        android:key="livewallpaper_settings"
    >
        <com.example.myapp.SeekBarPreference1
            android:persistent="true"
            android:key="keyItems"
            android:title="Items"
            android:defaultValue="50"
            android:max="200" />
        <com.example.myapp.SeekBarPreference1
            android:persistent="true"
            android:key="keyItemsTwo"
            android:title="Items Two"
            android:defaultValue="5"
            android:max="10" />
    </PreferenceScreen>
</code>```

Here is the simplified class. XmlPullParser does not return anything to parse.

```<code>    public final class SeekBarPreference1 extends Preference implements OnSeekBarChangeListener {

        private static int _maxValue = 0;
        private int _currentValue = 0;
        private TextView _value;
        private SharedPreferences _preferences;

        public SeekBarPreference1(Context context, AttributeSet attrs) {
            super(context, attrs);
            _preferences = PreferenceManager.getDefaultSharedPreferences(context);

            //
            // These values are correct
            //
            Log.d("PREFS", " ");
            Log.d("PREFS", "SeekBarPreference1");
            Log.d("PREFS", "Key: " + getKey());
            Log.d("PREFS", "AttrCount: " + attrs.getAttributeCount());
            Log.d("PREFS", "####");
        }

        @Override
        protected View onCreateView(ViewGroup parent) {

            XmlPullParser attrs = parent.getResources().getXml(R.xml.livewallpaper_settings);

            Log.d("PREFS", " ");
            Log.d("PREFS", "onCreateView");
            Log.d("PREFS", "Key: " + getKey()); // Correct key is output
            Log.d("PREFS", "AttrCount: " + attrs.getAttributeCount()); // -1
            Log.d("PREFS", "####");

        }
}
</code>```

Log output

```<code>SeekBarPreference1
Key: keyItems
AttrCount: 7
####

SeekBarPreference1
Key: keyItemsTwo
AttrCount: 7
####

onCreateView
Key: keyItems
AttrCount: -1
####

onCreateView
Key: keyItemsTwo
AttrCount: -1
####
</code>```

It seems to me that if I can get the correct key, title, summery, etc. (from onCreateView) there should be a simple way to get other attributes.?

If I try and store the attributes from SeekBarPreference1(), they are lost as soon as onCreateView() is called.

Summery: get the attributes from the current "this" onCreateView();

答:
I got it figured out.

```<code>public SeekBarPreference1(Context context, AttributeSet attrs) {
    super(context, attrs);
    _preferences = PreferenceManager.getDefaultSharedPreferences(context);

    // Save your shared prefs here
    // I saved the seekbar max && current value
    // Something like below
    for (int i = 0; i < attrs.getAttributeCount(); i++) {
        if (attrs.getAttributeName(i).equals("max"))
            _preferences.edit().putString(getKey() +"Max", ""+
                    attrs.getAttributeValue(i)).commit();
    }
}
</code>```

Then retrieve the data onCreateView()

```<code>protected View onCreateView(ViewGroup parent) {

    // Retrieve the data
    // Now you will always have the correct data
    _maxValue = Integer.parseInt(_preferences.getString(getKey() +"Max", ""));

}
</code>```

Now I can use the same class multiple times, finally...

Body:
How do I get the "max" attribute during onCreateView()?
If I can get attrs.getAttributeCount() to work that would solve my problem.

<?xml version="1.0" encoding="utf-8"?>
    <PreferenceScreen
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:title="@string/livewallpaper_settings"
        android:key="livewallpaper_settings"
    >
        <com.example.myapp.SeekBarPreference1
            android:persistent="true"
            android:key="keyItems"
            android:title="Items"
            android:defaultValue="50"
            android:max="200" />
        <com.example.myapp.SeekBarPreference1
            android:persistent="true"
            android:key="keyItemsTwo"
            android:title="Items Two"
            android:defaultValue="5"
            android:max="10" />
    </PreferenceScreen>

Here is the simplified class. XmlPullParser does not return anything to parse.

    public final class SeekBarPreference1 extends Preference implements OnSeekBarChangeListener {

        private static int _maxValue = 0;
        private int _currentValue = 0;
        private TextView _value;
        private SharedPreferences _preferences;

        public SeekBarPreference1(Context context, AttributeSet attrs) {
            super(context, attrs);
            _preferences = PreferenceManager.getDefaultSharedPreferences(context);

            //
            // These values are correct
            //
            Log.d("PREFS", " ");
            Log.d("PREFS", "SeekBarPreference1");
            Log.d("PREFS", "Key: " + getKey());
            Log.d("PREFS", "AttrCount: " + attrs.getAttributeCount());
            Log.d("PREFS", "####");
        }

        @Override
        protected View onCreateView(ViewGroup parent) {

            XmlPullParser attrs = parent.getResources().getXml(R.xml.livewallpaper_settings);

            Log.d("PREFS", " ");
            Log.d("PREFS", "onCreateView");
            Log.d("PREFS", "Key: " + getKey()); // Correct key is output
            Log.d("PREFS", "AttrCount: " + attrs.getAttributeCount()); // -1
            Log.d("PREFS", "####");

        }
}

Log output

SeekBarPreference1
Key: keyItems
AttrCount: 7
####

SeekBarPreference1
Key: keyItemsTwo
AttrCount: 7
####

onCreateView
Key: keyItems
AttrCount: -1
####

onCreateView
Key: keyItemsTwo
AttrCount: -1
####

It seems to me that if I can get the correct key, title, summery, etc. (from onCreateView) there should be a simple way to get other attributes.?

If I try and store the attributes from SeekBarPreference1(), they are lost as soon as onCreateView() is called.

Summery: get the attributes from the current "this" onCreateView();

Body:
I got it figured out.

public SeekBarPreference1(Context context, AttributeSet attrs) {
    super(context, attrs);
    _preferences = PreferenceManager.getDefaultSharedPreferences(context);

    // Save your shared prefs here
    // I saved the seekbar max && current value
    // Something like below
    for (int i = 0; i < attrs.getAttributeCount(); i++) {
        if (attrs.getAttributeName(i).equals("max"))
            _preferences.edit().putString(getKey() +"Max", ""+
                    attrs.getAttributeValue(i)).commit();
    }
}

Then retrieve the data onCreateView()

protected View onCreateView(ViewGroup parent) {

    // Retrieve the data
    // Now you will always have the correct data
    _maxValue = Integer.parseInt(_preferences.getString(getKey() +"Max", ""));

}

Now I can use the same class multiple times, finally...


问:
Using sed to extract element content of an XML file
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<Header>
<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>
</Header>
<Body>
</Body>
</Envelope>
</code>```

so i want to get

```<code><EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</code>```

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

```<code>sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt
</code>```

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

答:
For your "last try without such ...", grep approach:

```<code>grep -Poz '<Transport_key>\s*\K[\s\S]*(?=</Transport_key>)' test.txt
</code>```

The output:

```<code><EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</code>```

For your further proper tries, xmlstarlet approach:

```<code>xmlstarlet sel -t -c '//Transport_key/*' -n test.txt
</code>```

Body:
Well, using sed I'm trying to extract everything between <Transport_key> and </Transport_key> from input files like this:

<?xml version="1.0" encoding="utf-8"?>
<Envelope xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">

<Security>
<Transport_key>
<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>
</Transport_key>
</Security>

</Envelope>

so i want to get

<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>

regardless of any optional newlines between elements. I just want the text between the two strings unmodified, even if the input is a single big line.

I tried with

sed -e "s@.*<Transport_key>\(.*\)</Transport_key>.*@\1@" test.txt

but in the meantime I learned, that sed is taking inputs line per line and it cannot work.

Is there a solution for that?

Body:
For your "last try without such ...", grep approach:

grep -Poz '<Transport_key>\s*\K[\s\S]*(?=</Transport_key>)' test.txt

The output:

<EncryptedKey Id="TK" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p" />
<CipherData>
<CipherValue>pifKajuAK8FKwqLEhKIP4x5V5XUQyrwhpA</CipherValue>
</CipherData>
</EncryptedKey>

For your further proper tries, xmlstarlet approach:

xmlstarlet sel -t -c '//Transport_key/*' -n test.txt


问:
'NSInternalInconsistencyException', reason: 'attempt to insert row 0 into section 0, but there are only 0 sections after the update'
I am making an iOS app but I keep getting this error:

```<code>'NSInternalInconsistencyException', reason: 'attempt to insert row 0 into section 0, but there are only 0 sections after the update'
</code>```

I have researched this question for 2 days now but I don't know what's wrong. I am putting my code down below.

```<code>import UIKit
import FirebaseDatabase
import FirebaseAuth

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var databaseRef = Database.database().reference()
var loggedInUser:AnyObject?
var loggedInUserData:NSDictionary?

@IBOutlet weak var aivLoading: UIActivityIndicatorView!

@IBOutlet weak var homeTableView: UITableView!

var posts = [NSDictionary]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.loggedInUser = Auth.auth().currentUser

    self.databaseRef.child("users").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in

        self.loggedInUserData = snapshot.value as? NSDictionary
        self.databaseRef.child("posts").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot: DataSnapshot) in

            self.posts.insert(snapshot.value as! NSDictionary, at: 0)
            self.homeTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic)
            self.aivLoading.stopAnimating()
        }){(error) in
            ProgressHUD.showError("There was an error, try again")
        }
    }

    self.homeTableView.rowHeight = UITableViewAutomaticDimension
    self.homeTableView.estimatedRowHeight = 140

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: HomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
    let post = posts[(self.posts.count-1) - (indexPath.row)]["text"] as! String

    cell.configure("Anonymous", post: post)
    return cell
}

}
</code>```

In my code, it refers to a dequeueReusableCell, with the identifier HomeTableViewCell, which is a Swift file. Here is the code for that Swift file:

```<code>import UIKit
import FirebaseDatabase
import Firebase
import FirebaseAuth

class HomeTableViewCell: UITableViewCell {

    @IBOutlet weak var nameConstant: UILabel!
    @IBOutlet weak var post: UITextView!

    override open func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    open func configure(_ nameConstant: String, post: String)  {
        self.post.text = post
        self.nameConstant.text = "Anonymous"
    }

}
</code>```

I know there are similar questions to mine but a lot of those are in Objective-C. I've looked at the Swift ones too but they don't help.

If anyone has any ideas to fix this that would be great. Thanks in advance!

答:
In your code you're always returning 1 for number of rows. But i guess you should be returning posts.count right? Every time you insertRows(at:... the table checks consistency through the delegate. There's also something weird, you're appending to your list (self.posts.append(snapshot.value as! NSDictionary)) but then you're inserting row 0-0?, I'll assume you want to insert new post to the top. Moreover if you have just one section, you don't need to implement the method.

So here's the code (I'm assuming the firebase and cell configuration code is correct):

```<code>import UIKit
import FirebaseDatabase
import FirebaseAuth

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var databaseRef = Database.database().reference()
var loggedInUser:AnyObject?
var loggedInUserData:NSDictionary?

@IBOutlet weak var aivLoading: UIActivityIndicatorView!

@IBOutlet weak var homeTableView: UITableView!

var posts = [NSDictionary]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.loggedInUser = Auth.auth().currentUser

    self.databaseRef.child("users").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in

        self.loggedInUserData = snapshot.value as? NSDictionary
        self.databaseRef.child("posts").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot: DataSnapshot) in

            self.posts.insert(snapshot.value as! NSDictionary, at: 0)
            self.homeTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic)
            self.aivLoading.stopAnimating()
        }){(error) in
            ProgressHUD.showError("There was an error, try again")
        }
    }

    self.homeTableView.rowHeight = UITableViewAutomaticDimension
    self.homeTableView.estimatedRowHeight = 140

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: HomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
    let post = posts[(self.posts.count-1) - (indexPath.row)]["text"] as! String

    cell.configure("Anonymous", post: post)
    return cell
}

}
</code>```

I hope it fixes your problem ;)

Body:
I am making an iOS app but I keep getting this error:

'NSInternalInconsistencyException', reason: 'attempt to insert row 0 into section 0, but there are only 0 sections after the update'

I have researched this question for 2 days now but I don't know what's wrong. I am putting my code down below.

import UIKit
import FirebaseDatabase
import FirebaseAuth

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var databaseRef = Database.database().reference()
var loggedInUser:AnyObject?
var loggedInUserData:NSDictionary?

@IBOutlet weak var aivLoading: UIActivityIndicatorView!

@IBOutlet weak var homeTableView: UITableView!

var posts = [NSDictionary]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.loggedInUser = Auth.auth().currentUser

    self.databaseRef.child("users").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in

        self.loggedInUserData = snapshot.value as? NSDictionary
        self.databaseRef.child("posts").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot: DataSnapshot) in

            self.posts.insert(snapshot.value as! NSDictionary, at: 0)
            self.homeTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic)
            self.aivLoading.stopAnimating()
        }){(error) in
            ProgressHUD.showError("There was an error, try again")
        }
    }

    self.homeTableView.rowHeight = UITableViewAutomaticDimension
    self.homeTableView.estimatedRowHeight = 140

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: HomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
    let post = posts[(self.posts.count-1) - (indexPath.row)]["text"] as! String

    cell.configure("Anonymous", post: post)
    return cell
}

}

In my code, it refers to a dequeueReusableCell, with the identifier HomeTableViewCell, which is a Swift file. Here is the code for that Swift file:

import UIKit
import FirebaseDatabase
import Firebase
import FirebaseAuth

class HomeTableViewCell: UITableViewCell {

    @IBOutlet weak var nameConstant: UILabel!
    @IBOutlet weak var post: UITextView!

    override open func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    open func configure(_ nameConstant: String, post: String)  {
        self.post.text = post
        self.nameConstant.text = "Anonymous"
    }

}

I know there are similar questions to mine but a lot of those are in Objective-C. I've looked at the Swift ones too but they don't help.

If anyone has any ideas to fix this that would be great. Thanks in advance!

Body:
In your code you're always returning 1 for number of rows. But i guess you should be returning posts.count right? Every time you insertRows(at:... the table checks consistency through the delegate. There's also something weird, you're appending to your list (self.posts.append(snapshot.value as! NSDictionary)) but then you're inserting row 0-0?, I'll assume you want to insert new post to the top. Moreover if you have just one section, you don't need to implement the method.

So here's the code (I'm assuming the firebase and cell configuration code is correct):

import UIKit
import FirebaseDatabase
import FirebaseAuth

class HomeViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var databaseRef = Database.database().reference()
var loggedInUser:AnyObject?
var loggedInUserData:NSDictionary?

@IBOutlet weak var aivLoading: UIActivityIndicatorView!

@IBOutlet weak var homeTableView: UITableView!

var posts = [NSDictionary]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.loggedInUser = Auth.auth().currentUser

    self.databaseRef.child("users").child(self.loggedInUser!.uid).observeSingleEvent(of: .value) { (snapshot: DataSnapshot) in

        self.loggedInUserData = snapshot.value as? NSDictionary
        self.databaseRef.child("posts").child(self.loggedInUser!.uid).observe(.childAdded, with: { (snapshot: DataSnapshot) in

            self.posts.insert(snapshot.value as! NSDictionary, at: 0)
            self.homeTableView.insertRows(at: [IndexPath(row: 0, section: 0)], with: UITableViewRowAnimation.automatic)
            self.aivLoading.stopAnimating()
        }){(error) in
            ProgressHUD.showError("There was an error, try again")
        }
    }

    self.homeTableView.rowHeight = UITableViewAutomaticDimension
    self.homeTableView.estimatedRowHeight = 140

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell: HomeTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeTableViewCell", for: indexPath) as! HomeTableViewCell
    let post = posts[(self.posts.count-1) - (indexPath.row)]["text"] as! String

    cell.configure("Anonymous", post: post)
    return cell
}

}

I hope it fixes your problem ;)


问:
Padding and show only the last N characters of a masked/password/secret variable's value
I want to prompt a user to enter a secret value (for ex: password variable, credit card, some key/token) and would like to see if there's a way to show the last N (lets say 4 characters) of that variable's value.

Ex:
Enter your credit card# : 1234567898765432

I can use wrappers for ex stty -echo/echo to hide what user will enter or use read -s variable and it'll hide the values but what I'd like is to show only last N (for ex: 4) characters of this variable i.e.
if I say $ echo $mySecretVariable (not sure if I really have to write a function) then it will echo the value as: ************5432 or your token key value last 4 ends with *******************C5fx something like that where all the characters will be padded with a * and only the last N will be shown.

答:
You can use this bash function for masking all but last 4 characters:

```<code>mask() {
   local r="${1?needs an argument}"
   if ((${#r} > 4)); then
      r="${r:0: -4}"
      echo "${r//?/*}${1: -4}"
   else
      echo "$r"
   fi
}
</code>```

Then use it as:

```<code>mask 1234567898765432
************5432

mask 123
123

mask 123456
**3456
</code>```

Body:
You can use this bash function for masking all but last 4 characters:

mask() {
   local r="${1?needs an argument}"
   if ((${#r} > 4)); then
      r="${r:0: -4}"
      echo "${r//?/*}${1: -4}"
   else
      echo "$r"
   fi
}

Then use it as:

mask 1234567898765432
************5432

mask 123
123

mask 123456
**3456