问:
Text data type Issue
I have this code below and when I run it, I get an error

Column "Orders.User_Memo1" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause

So then I add o.User_Memo1 (or simply remove CONVERT(VARCHAR(MAX)) and I get the following error message:

The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator

So I'm basically stuck, I'm getting errors no matter what I do, excluding it, including it, and including it with a CONVERT all give me errors.  What are my options?

```<code>SELECT
    CAST(o.OrderNo AS INT) AS [OrderNo],
    CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1,
    CHARINDEX('Pack',od.User_Memo1)+5, 8) AS DATE), 1) AS [Prod Due Date],
    o.User_Date1 AS [3 Week Ack Date],
    o.User_Date2 AS [1 Week Ack Date],
    CASE
       WHEN CONVERT(VARCHAR(MAX), o.User_Memo1) LIKE '%RDS%'
          THEN CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1, CHARINDEX('RSD', od.User_Memo1) + 4, 8) AS DATE), 1)
          ELSE NULL
    END AS [Revised Ship Date],
    d.ShipDate
FROM
    Orders o
JOIN
    OrderDet od ON o.OrderNo = od.OrderNo
LEFT JOIN
    DelTicket d ON o.OrderNo = d.OrderNo
WHERE
    CONVERT(VARCHAR(MAX), o.User_Memo1) IS NOT NULL
    AND SUBSTRING(o.User_Memo1, 1, 3) = 'Cut'
GROUP BY
    o.OrderNo,
    CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1, CHARINDEX('Pack', od.User_Memo1) + 5, 8) AS DATE), 1),
    o.User_Date1, o.User_Date2,
    CONVERT(VARCHAR(MAX), o.User_Memo1), CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1, CHARINDEX('RSD', od.User_Memo1) + 4, 8) AS DATE),
1),
    d.ShipDate
ORDER BY
    CAST(SUBSTRING(o.User_Memo1, CHARINDEX('Pack',o.User_Memo1) + 5, 8) AS DATETIME) DESC;
</code>```

答:
I think you are missing cast in your where clause. try changing it to this

```<code>AND CAST(Substring(o.user_memo1, 1, 3) as varchar(3)) = 'Cut'
</code>```

Complete Query

```<code>SELECT Cast(o.orderno AS INT) AS [OrderNo],
       CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1, Charindex('Pack', od.user_memo1) + 5, 8) AS  DATE), 1)    AS [Prod Due Date],
       o.user_date1                                                                                AS [3 Week Ack Date],
       o.user_date2                                                                                AS [1 Week Ack Date],
       CASE
         WHEN CONVERT(VARCHAR(max), o.user_memo1) LIKE '%RDS%'
         THEN CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1, Charindex('RSD', od.user_memo1) + 4, 8) AS DATE), 1)
         ELSE NULL
       END                                                                                AS [Revised Ship Date],
       d.shipdate
FROM orders o
JOIN orderdet od ON o.orderno = od.orderno
LEFT JOIN delticket d  ON o.orderno = d.orderno
WHERE  CONVERT(VARCHAR(max), o.user_memo1) IS NOT NULL
       AND  CAST(Substring(o.user_memo1, 1, 3) as varchar(3)) = 'Cut'
GROUP  BY o.orderno,
          CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1,  Charindex('Pack', od.user_memo1) + 5, 8) AS DATE), 1),
          o.user_date1,
          o.user_date2,
          CONVERT(VARCHAR(max), o.user_memo1),
          CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1,  Charindex('RSD', od.user_memo1) + 4, 8) AS  DATE), 1),
          d.shipdate
ORDER  BY Cast(Substring(o.user_memo1, Charindex('Pack', o.user_memo1) + 5, 8) AS DATETIME) DESC;
</code>```

Title: Text data type Issue

Body:
I have this code below and when I run it, I get an error

Column "Orders.User_Memo1" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause

So then I add o.User_Memo1 (or simply remove CONVERT(VARCHAR(MAX)) and I get the following error message:

The text, ntext, and image data types cannot be compared or sorted, except when using IS NULL or LIKE operator

So I'm basically stuck, I'm getting errors no matter what I do, excluding it, including it, and including it with a CONVERT all give me errors.  What are my options?

SELECT
    CAST(o.OrderNo AS INT) AS [OrderNo],
    CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1,
    CHARINDEX('Pack',od.User_Memo1)+5, 8) AS DATE), 1) AS [Prod Due Date],
    o.User_Date1 AS [3 Week Ack Date],
    o.User_Date2 AS [1 Week Ack Date],
    CASE
       WHEN CONVERT(VARCHAR(MAX), o.User_Memo1) LIKE '%RDS%'
          THEN CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1, CHARINDEX('RSD', od.User_Memo1) + 4, 8) AS DATE), 1)
          ELSE NULL
    END AS [Revised Ship Date],
    d.ShipDate
FROM
    Orders o
JOIN
    OrderDet od ON o.OrderNo = od.OrderNo
LEFT JOIN
    DelTicket d ON o.OrderNo = d.OrderNo
WHERE
    CONVERT(VARCHAR(MAX), o.User_Memo1) IS NOT NULL
    AND SUBSTRING(o.User_Memo1, 1, 3) = 'Cut'
GROUP BY
    o.OrderNo,
    CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1, CHARINDEX('Pack', od.User_Memo1) + 5, 8) AS DATE), 1),
    o.User_Date1, o.User_Date2,
    CONVERT(VARCHAR(MAX), o.User_Memo1), CONVERT(VARCHAR(MAX), CAST(SUBSTRING(od.User_Memo1, CHARINDEX('RSD', od.User_Memo1) + 4, 8) AS DATE),
1),
    d.ShipDate
ORDER BY
    CAST(SUBSTRING(o.User_Memo1, CHARINDEX('Pack',o.User_Memo1) + 5, 8) AS DATETIME) DESC;

Body:
I think you are missing cast in your where clause. try changing it to this

AND CAST(Substring(o.user_memo1, 1, 3) as varchar(3)) = 'Cut'

Complete Query

SELECT Cast(o.orderno AS INT) AS [OrderNo],
       CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1, Charindex('Pack', od.user_memo1) + 5, 8) AS  DATE), 1)    AS [Prod Due Date],
       o.user_date1                                                                                AS [3 Week Ack Date],
       o.user_date2                                                                                AS [1 Week Ack Date],
       CASE
         WHEN CONVERT(VARCHAR(max), o.user_memo1) LIKE '%RDS%'
         THEN CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1, Charindex('RSD', od.user_memo1) + 4, 8) AS DATE), 1)
         ELSE NULL
       END                                                                                AS [Revised Ship Date],
       d.shipdate
FROM orders o
JOIN orderdet od ON o.orderno = od.orderno
LEFT JOIN delticket d  ON o.orderno = d.orderno
WHERE  CONVERT(VARCHAR(max), o.user_memo1) IS NOT NULL
       AND  CAST(Substring(o.user_memo1, 1, 3) as varchar(3)) = 'Cut'
GROUP  BY o.orderno,
          CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1,  Charindex('Pack', od.user_memo1) + 5, 8) AS DATE), 1),
          o.user_date1,
          o.user_date2,
          CONVERT(VARCHAR(max), o.user_memo1),
          CONVERT(VARCHAR(max), Cast(Substring(od.user_memo1,  Charindex('RSD', od.user_memo1) + 4, 8) AS  DATE), 1),
          d.shipdate
ORDER  BY Cast(Substring(o.user_memo1, Charindex('Pack', o.user_memo1) + 5, 8) AS DATETIME) DESC;


来源: stackexchange

问:
BeautifulSoup find_all() returns no data
I am very new to Python. My recent project is scraping data from a betting website. What I want to scrape is the odds information from the webpage.

Here is my code

```<code>from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'http://bet.hkjc.com/default.aspx?url=football/odds/odds_allodds.aspx&lang=CH&tmatchid=120653'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")

page_soup.findAll("div",{"class":"oddsAll"})
</code>```

but the result return  [] , which is none

What should I do to make my code work?

答:
Updated the URL to be the page loaded from this page, using JavaScript, which contains the data and updated the tmatchid to be current 120998. Updated div to be tabe and the correct class.

```<code>from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'http://bet.hkjc.com/football/odds/odds_allodds.aspx?lang=CH&tmatchid=120998'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
tables = page_soup.findAll("table",{"class":"tOdds"})
for table in tables:
    print (table.text)
</code>```

Outputs:

```<code>燕豪芬青年隊(主隊勝) 和 烏德勒支青年隊(客隊勝)   1.53 4.00 4.60
  燕豪芬青年隊(主隊勝) 和 烏德勒支青年隊(客隊勝)   1.97 2.45 4.70
  燕豪芬青年隊[-1](主隊勝) 和 烏德勒支青年隊[+1](客隊勝)   2.45 3.60 2.26
  球數 大 細  [3/3.5]2.021.70
  球數 大 細   [1.5]2.191.60
     1.44    18.00    2.65
  0 1 2 3 4 5 6 7+   18.00 6.60 4.10 3.65 4.50 6.70 11.00 14.00
  單 雙   1.90 1.80
  主 主 主 和 和 和 客 客 客   主 和 客 主 和 客 主 和 客   2.30 14.00 34.00 4.70 6.50 10.50 19.00 14.00 7.50
</code>```

UPDATED in response to comment:

In this case you need the URL of the frame showing the data. You can do something like this:

```<code>import requests
from bs4 import BeautifulSoup
url = requests.get('http://football.hkjc.com/football/iframe/statistics/head-to-head/summary-iframe.aspx?ci=en-US')
soup = BeautifulSoup(url.content, 'lxml')
divs = soup.findAll('div', {'class':['win', 'draw', 'lose']})
for div in divs:
    print (div.get_text())
</code>```

Outputs:

```<code>18/03/2018 Italian Division 1 : Benevento 1-2 Cagliari
18/02/2018 Italian Division 1 : Benevento 3-2 Crotone
05/02/2018 Italian Division 1 : Benevento 0-2 Napoli
06/01/2018 Italian Division 1 : Benevento 3-2 Sampdoria
30/12/2017 Italian Division 1 : Benevento 1-0 Chievo
18/12/2017 Italian Division 1 : Benevento 1-2 SPAL
03/12/2017 Italian Division 1 : Benevento 2-2 AC Milan
19/11/2017 Italian Division 1 : Benevento 1-2 Sassuolo
29/10/2017 Italian Division 1 : Benevento 1-5 Lazio
22/10/2017 Italian Division 1 : Benevento 0-3 Fiorentina
31/03/2018 Italian Division 1 : Inter Milan 3-0 Verona
20/02/2018 Italian Division 1 : Lazio 2-0 Verona
11/02/2018 Italian Division 1 : Sampdoria 2-0 Verona
28/01/2018 Italian Division 1 : Fiorentina 1-4 Verona
06/01/2018 Italian Division 1 : Napoli 2-0 Verona
23/12/2017 Italian Division 1 : Udinese 4-0 Verona
14/12/2017 Italian Cup : AC Milan 3-0 Verona
10/12/2017 Italian Division 1 : SPAL 2-2 Verona
30/11/2017 Italian Cup : Chievo 1-1 Verona
26/11/2017 Italian Division 1 : Sassuolo 0-2 Verona
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am very new to Python. My recent project is scraping data from a betting website. What I want to scrape is the odds information from the webpage.

Here is my code

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

my_url = 'http://bet.hkjc.com/default.aspx?url=football/odds/odds_allodds.aspx&lang=CH&tmatchid=120653'

uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()

page_soup = soup(page_html, "html.parser")

page_soup.findAll("div",{"class":"oddsAll"})

but the result return  [] , which is none

What should I do to make my code work?

Body:
Updated the URL to be the page loaded from this page, using JavaScript, which contains the data and updated the tmatchid to be current 120998. Updated div to be tabe and the correct class.

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'http://bet.hkjc.com/football/odds/odds_allodds.aspx?lang=CH&tmatchid=120998'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, "html.parser")
tables = page_soup.findAll("table",{"class":"tOdds"})
for table in tables:
    print (table.text)

Outputs:

燕豪芬青年隊(主隊勝) 和 烏德勒支青年隊(客隊勝)   1.53 4.00 4.60
  燕豪芬青年隊(主隊勝) 和 烏德勒支青年隊(客隊勝)   1.97 2.45 4.70
  燕豪芬青年隊[-1](主隊勝) 和 烏德勒支青年隊[+1](客隊勝)   2.45 3.60 2.26
  球數 大 細  [3/3.5]2.021.70
  球數 大 細   [1.5]2.191.60
     1.44    18.00    2.65
  0 1 2 3 4 5 6 7+   18.00 6.60 4.10 3.65 4.50 6.70 11.00 14.00
  單 雙   1.90 1.80
  主 主 主 和 和 和 客 客 客   主 和 客 主 和 客 主 和 客   2.30 14.00 34.00 4.70 6.50 10.50 19.00 14.00 7.50

UPDATED in response to comment:

In this case you need the URL of the frame showing the data. You can do something like this:

import requests
from bs4 import BeautifulSoup
url = requests.get('http://football.hkjc.com/football/iframe/statistics/head-to-head/summary-iframe.aspx?ci=en-US')
soup = BeautifulSoup(url.content, 'lxml')
divs = soup.findAll('div', {'class':['win', 'draw', 'lose']})
for div in divs:
    print (div.get_text())

Outputs:

18/03/2018 Italian Division 1 : Benevento 1-2 Cagliari
18/02/2018 Italian Division 1 : Benevento 3-2 Crotone
05/02/2018 Italian Division 1 : Benevento 0-2 Napoli
06/01/2018 Italian Division 1 : Benevento 3-2 Sampdoria
30/12/2017 Italian Division 1 : Benevento 1-0 Chievo
18/12/2017 Italian Division 1 : Benevento 1-2 SPAL
03/12/2017 Italian Division 1 : Benevento 2-2 AC Milan
19/11/2017 Italian Division 1 : Benevento 1-2 Sassuolo
29/10/2017 Italian Division 1 : Benevento 1-5 Lazio
22/10/2017 Italian Division 1 : Benevento 0-3 Fiorentina
31/03/2018 Italian Division 1 : Inter Milan 3-0 Verona
20/02/2018 Italian Division 1 : Lazio 2-0 Verona
11/02/2018 Italian Division 1 : Sampdoria 2-0 Verona
28/01/2018 Italian Division 1 : Fiorentina 1-4 Verona
06/01/2018 Italian Division 1 : Napoli 2-0 Verona
23/12/2017 Italian Division 1 : Udinese 4-0 Verona
14/12/2017 Italian Cup : AC Milan 3-0 Verona
10/12/2017 Italian Division 1 : SPAL 2-2 Verona
30/11/2017 Italian Cup : Chievo 1-1 Verona
26/11/2017 Italian Division 1 : Sassuolo 0-2 Verona


问:
Smooth MultiPlayer movement
i am developing a multiplayer roleplaying game, (No, its not a mmorpg. ;)

My current setup is like this.

Client tells the server "I want to move forward"/"I want to move backwards", the server then updates your entity, and informs all clients in the area about the change. The server is also updating each entity every 20ms and sending updates every 100ms to the clients, these updates contains position, velocity, rotation etc.

So far so good, however i have nothing in store for smoothing the movement between the packets on the client side, and i must say, i can not get it working. I have been reading up on prediction, interpolation, deadreackoning but its all a big mess for me.

So right now i am just doing something like "Position = Packet.Position", which causes a very stuttering movement.

So, what i want help with is, how do i get a more smooth movement? Have been looking at the XNA Prediction Sample, but i could not get it right.

Thanks //F

答:
I solved it by running a ghost entity alongside with my main one.

The ghost will get updated every frame aswell, but whenever a packet comes in, his values are set to the values of the packet.

I then gradually tweak the real entity to where the ghost is.

ContentLicense: CC BY-SA 2.5

Title: Smooth MultiPlayer movement


问:
QNetworkReply returning incomplete XML data
I'm sending a HTTP GET request to a remote server. Using various parameters I define the content I'm interested in. In particular I make sure that output=xml is in the query since it makes the server return a reply as XML.

I have the following connections between my class HttpRetriever and the respective QNetworkReply and QNetworkAccessManager (for the QNetworkRequest see slotStartRequest()):

```<code>connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
        SLOT(slotErrorRequest(QNetworkReply::NetworkError)));
connect(this->reply, &QNetworkReply::finished, this, &HttpRetriever::slotFinishRequest);
connect(this->manager, &QNetworkAccessManager::finished, this->reply, &QNetworkReply::deleteLater);
connect(this->reply, &QIODevice::readyRead, this, &HttpRetriever::slotReadyReadRequest);
</code>```

The slots that are of interest here have the following declaration:

slotFinishRequest():

```<code>void HttpRetriever::slotFinishRequest()
{
    LOG(INFO) << "Finishing HTTP GET request from URL \"" << this->url.toString() << "\"";
    this->reply = Q_NULLPTR;

    // Reset validity of reply from a previous request
    this->validReply = false;
    // Skip validation if it's disabled
    if (!this->validateReply)
    {
        LOG(WARNING) << "Validation disabled. In order to enable it see the \"validate\" and \"validationMode\" in \"settings.ini\"";
        this->validReply = true;
    }
    else
    {
        // Validate reply
        this->validReply = validateReply();
    }

    if (!this->validReply)
    {
        return;
    }

    processReply(); // Parsing

    this->processingRequest = false;
}
</code>```

slotReadyReadRequest():

```<code>void HttpRetriever::slotReadyReadRequest()
{
    LOG(INFO) << "Received data from \"" << this->url.toString() << "\"";
    this->bufferReply = this->reply->readAll();
}
</code>```

Inside the slotFinishRequest() I call the processReply():

```<code>void HttpRetriever::processReply()
{
    LOG(INFO) << "Processing reply for request \"" << this->url.toString() << "\"";
    LOG(DEBUG) << QString(this->bufferReply);
    // Process the XML from the reply and extract necessary data

    QXmlStreamReader reader;
    reader.addData(this->bufferReply);

    // Read the XML reply and extract required data
    // TODO
    while (!reader.atEnd())
    {
        LOG(DEBUG) << "Reading XML element";
        reader.readNextStartElement();

        QXmlStreamAttributes attributes = reader.attributes();
        foreach (QXmlStreamAttribute attrib, attributes)
        {
            LOG(DEBUG) << attrib.name();
        }
    }
    if (reader.hasError())
    {
        LOG(ERROR) << "Encountered error while parsing XML data:" << reader.errorString();
    }

    LOG(INFO) << "Sending data to data fusion handler";
    // TODO
}
</code>```

I trigger the HTTP get request through the following slot:

```<code>void HttpRetriever::slotStartRequest(quint32 id)
{
    if (this->processingRequest)
    {
        this->reply->abort();
    }

    this->processingRequest = false;

    // The first request also instantiates the manager. If the slot is called after the instance of HafasHttpRetriever
    // is moved to a new thread this will ensure proper parenting
    if (!this->manager)
    {
        this->manager = new QNetworkAccessManager(this);
    }

    quint32 requestId = generateRequestId(stopId);
    if (!this->url.hasQuery())
    {
        LOG(WARNING) << "Attempting to start request without parameters";
    }

    // Part of the filters applied to the request to reduce the data received (for more see slotSetRequestParams())
    QUrlQuery query(this->url.query());
    query.addQueryItem("input", QString::number(requestId));
    // TODO Add more filters; see documentation

    this->url.setQuery(query);

    LOG(INFO) << "Requesting data from \"" << this->url.toString() << "\" with request ID:" << requestId;

    QNetworkRequest request(this->url);
    this->reply = this->manager->get(request);

    // Establish connections from/to the reply and the network access manager
    connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
            SLOT(slotErrorRequest(QNetworkReply::NetworkError)));
    connect(this->reply, &QNetworkReply::finished, this, &HttpRetriever::slotFinishRequest);
    connect(this->manager, &QNetworkAccessManager::finished, this->reply, &QNetworkReply::deleteLater);
    connect(this->reply, &QIODevice::readyRead, this, &HttpRetriever::slotReadyReadRequest);
}
</code>```

As you can see so far I have laid down the foundation for the network communication between my class and the server and I am yet to start working on the parsing of the XML reply and extracting the information I need from it.

The problem is that I am getting (very, very often) either

Encountered error while parsing XML data: Start tag expected.

or

Encountered error while parsing XML data: Premature end of document

in my processReply() function. This happens every time I get a large reply (a couple of hundreds up to a couple of thousands of lines). It never happens when I get a small one (30-40 lines give or take).

So the issue is obviously somewhere in the amount of data I am receiving, the way it is put together by the QNetworkAccessManager (or whichever Qt component in all this buffers the received chunks of data) and/or perhaps the way I have setup the instances of the network-related components in my class. I also have to make an important note here namely that in my browser (latest Firefox with the HttpRequester add-on) I am always receiving the complete XML no matter how large it is. So this seems to be a problem exclusive to my application and has nothing to do with the network settings on my system.

答:
Since @Marco didn't write the answer...

The problem was that I was rewriting my buffer all the time by assigning the result from QNetworkReply::readAll(). As suggested using QByteArray::append() solves the problem.

In order to prevent a possible issue from this solution namely that you keep appending with each and every next reply you get, QByteArray::clear() needs to be called at some point for example when the finished() signal is emitted. Of course one needs to first process its contents before flushing it down the drain.

Body:
I'm sending a HTTP GET request to a remote server. Using various parameters I define the content I'm interested in. In particular I make sure that output=xml is in the query since it makes the server return a reply as XML.

I have the following connections between my class HttpRetriever and the respective QNetworkReply and QNetworkAccessManager (for the QNetworkRequest see slotStartRequest()):

connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
        SLOT(slotErrorRequest(QNetworkReply::NetworkError)));
connect(this->reply, &QNetworkReply::finished, this, &HttpRetriever::slotFinishRequest);
connect(this->manager, &QNetworkAccessManager::finished, this->reply, &QNetworkReply::deleteLater);
connect(this->reply, &QIODevice::readyRead, this, &HttpRetriever::slotReadyReadRequest);

The slots that are of interest here have the following declaration:

slotFinishRequest():

void HttpRetriever::slotFinishRequest()
{
    LOG(INFO) << "Finishing HTTP GET request from URL \"" << this->url.toString() << "\"";
    this->reply = Q_NULLPTR;

    // Reset validity of reply from a previous request
    this->validReply = false;
    // Skip validation if it's disabled
    if (!this->validateReply)
    {
        LOG(WARNING) << "Validation disabled. In order to enable it see the \"validate\" and \"validationMode\" in \"settings.ini\"";
        this->validReply = true;
    }
    else
    {
        // Validate reply
        this->validReply = validateReply();
    }

    if (!this->validReply)
    {
        return;
    }

    processReply(); // Parsing

    this->processingRequest = false;
}

slotReadyReadRequest():

void HttpRetriever::slotReadyReadRequest()
{
    LOG(INFO) << "Received data from \"" << this->url.toString() << "\"";
    this->bufferReply = this->reply->readAll();
}

Inside the slotFinishRequest() I call the processReply():

void HttpRetriever::processReply()
{
    LOG(INFO) << "Processing reply for request \"" << this->url.toString() << "\"";
    LOG(DEBUG) << QString(this->bufferReply);
    // Process the XML from the reply and extract necessary data

    QXmlStreamReader reader;
    reader.addData(this->bufferReply);

    // Read the XML reply and extract required data
    // TODO
    while (!reader.atEnd())
    {
        LOG(DEBUG) << "Reading XML element";
        reader.readNextStartElement();

        QXmlStreamAttributes attributes = reader.attributes();
        foreach (QXmlStreamAttribute attrib, attributes)
        {
            LOG(DEBUG) << attrib.name();
        }
    }
    if (reader.hasError())
    {
        LOG(ERROR) << "Encountered error while parsing XML data:" << reader.errorString();
    }

    LOG(INFO) << "Sending data to data fusion handler";
    // TODO
}

I trigger the HTTP get request through the following slot:

void HttpRetriever::slotStartRequest(quint32 id)
{
    if (this->processingRequest)
    {
        this->reply->abort();
    }

    this->processingRequest = false;

    // The first request also instantiates the manager. If the slot is called after the instance of HafasHttpRetriever
    // is moved to a new thread this will ensure proper parenting
    if (!this->manager)
    {
        this->manager = new QNetworkAccessManager(this);
    }

    quint32 requestId = generateRequestId(stopId);
    if (!this->url.hasQuery())
    {
        LOG(WARNING) << "Attempting to start request without parameters";
    }

    // Part of the filters applied to the request to reduce the data received (for more see slotSetRequestParams())
    QUrlQuery query(this->url.query());
    query.addQueryItem("input", QString::number(requestId));
    // TODO Add more filters; see documentation

    this->url.setQuery(query);

    LOG(INFO) << "Requesting data from \"" << this->url.toString() << "\" with request ID:" << requestId;

    QNetworkRequest request(this->url);
    this->reply = this->manager->get(request);

    // Establish connections from/to the reply and the network access manager
    connect(this->reply, SIGNAL(error(QNetworkReply::NetworkError)), this,
            SLOT(slotErrorRequest(QNetworkReply::NetworkError)));
    connect(this->reply, &QNetworkReply::finished, this, &HttpRetriever::slotFinishRequest);
    connect(this->manager, &QNetworkAccessManager::finished, this->reply, &QNetworkReply::deleteLater);
    connect(this->reply, &QIODevice::readyRead, this, &HttpRetriever::slotReadyReadRequest);
}

As you can see so far I have laid down the foundation for the network communication between my class and the server and I am yet to start working on the parsing of the XML reply and extracting the information I need from it.

The problem is that I am getting (very, very often) either

Encountered error while parsing XML data: Start tag expected.

or

Encountered error while parsing XML data: Premature end of document

in my processReply() function. This happens every time I get a large reply (a couple of hundreds up to a couple of thousands of lines). It never happens when I get a small one (30-40 lines give or take).

So the issue is obviously somewhere in the amount of data I am receiving, the way it is put together by the QNetworkAccessManager (or whichever Qt component in all this buffers the received chunks of data) and/or perhaps the way I have setup the instances of the network-related components in my class. I also have to make an important note here namely that in my browser (latest Firefox with the HttpRequester add-on) I am always receiving the complete XML no matter how large it is. So this seems to be a problem exclusive to my application and has nothing to do with the network settings on my system.


问:
How to combine two regex using AND operator
I have a dilemma in using regex as I am very new in using this:

I have the URL below:

```<code>var url = https://website.com/something-here/page.html?p=null#confirmation?order=123
</code>```

My expected result is:

```<code>/something-here/page.html #confirmation
</code>```

It could be a space or a comma or simply combine the two(/something-here/page.html#confirmation)

I can do this using two regex below:

```<code>var a= url.match(/som([^#]+).html/)[0];

var b= url.match(/#([^#]+).tion/)[0];

console.log(a,b);
</code>```

But I would like to have it done as a single regex with the same result.

答:
Aside the fact that your example url is malformed (you have two search params), therefore not very suitable to work with -  I have e proposition:

Why not use the URL object and its properties?

```<code>url = new URL("https://website.com/something-here/page.html?p=null#confirmation?order=123");
</code>```

and precisely grab the properties with explicit syntax as in:

url.pathname; >> "something-here/page.html"

url.hash; >> "#confirmation?order=123"

But in case you explicitly need a RegExp variant

here is one

var url = "https://website.com/something-here/page.html?p=null#confirmation?order=123";
var match =  url.match(/\/som.*?html|\#.*?tion/g);

console.log(match.join(" "));```

Body:
I have a dilemma in using regex as I am very new in using this:

I have the URL below:

var url = https://website.com/something-here/page.html?p=null#confirmation?order=123

My expected result is:

/something-here/page.html #confirmation

It could be a space or a comma or simply combine the two(/something-here/page.html#confirmation)

I can do this using two regex below:

var a= url.match(/som([^#]+).html/)[0];

var b= url.match(/#([^#]+).tion/)[0];

console.log(a,b);

But I would like to have it done as a single regex with the same result.

Body:
Aside the fact that your example url is malformed (you have two search params), therefore not very suitable to work with -  I have e proposition:

Why not use the URL object and its properties?

url = new URL("https://website.com/something-here/page.html?p=null#confirmation?order=123");

and precisely grab the properties with explicit syntax as in:

url.pathname; >> "something-here/page.html"

url.hash; >> "#confirmation?order=123"

But in case you explicitly need a RegExp variant

here is one

var url = "https://website.com/something-here/page.html?p=null#confirmation?order=123";
var match =  url.match(/\/som.*?html|\#.*?tion/g);

console.log(match.join(" "));


问:
How do I get a JQuery object inside a template literal?
So often I have a JQuery object such as

```<code>var element = $('<h1>Title</h1>');
</code>```

I will make some operations on it, and later, I want to embed it inside of a template literal, so it displays as if it were using the $().append from jquery. Here is my attempt

```<code>var secondElement = $(`<div><div>${element}</div></div>`);
$('#someRandomDiv').append(secondElement);
</code>```

This, as expected, outputs

```<code><div><div>[Object object]</div></div>
</code>```

as it is referencing an object, not actually the HTML of the element. However I want it to be .

```<code><div><div><h1>Title</h1></div</div>
</code>```

Is there a way of doing this? Optimally it would still use the template literals, and of course, it is best if it uses native js/jquery functionality, rather than workarounds.

答:
Use jQuery methods instead

var element = $('
Title
');

var secondElement = $(`<div>`).append(element).wrap(`<div>`).parent();

console.log(secondElement[0].outerHTML)
// Logs:

Title

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Body:
So often I have a JQuery object such as

var element = $('
Title
');

I will make some operations on it, and later, I want to embed it inside of a template literal, so it displays as if it were using the $().append from jquery. Here is my attempt

var secondElement = $(`<div><div>${element}</div></div>`);
$('#someRandomDiv').append(secondElement);

This, as expected, outputs

[Object object]

as it is referencing an object, not actually the HTML of the element. However I want it to be .

Title
</div

Is there a way of doing this? Optimally it would still use the template literals, and of course, it is best if it uses native js/jquery functionality, rather than workarounds.

Body:
Use jQuery methods instead

var element = $('<h1>Title</h1>');

var secondElement = $(`<div>`).append(element).wrap(`<div>`).parent();

console.log(secondElement[0].outerHTML)
// Logs: <div><div><h1>Title</h1></div></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
getting selected check box value in Mvc asp.net
I had displayed check box in a list and i want to access that which check box is selected or not and want to call controller action where i select option from dropdown list</p>

```<code><div id="pnlSent" style="display: none">
            <%= Html.DropDownList("select","msgtype") %>
            <% foreach (Usp_GetUserMessagesResult w in (List<Usp_GetUserMessagesResult>)ViewData["UListM"])
               { %>
                <li>
            <div class="question-info">

                <input id="Checkbox1" type="checkbox" onclick="function() { alert("df") ; } "  />

                <div class="views count"><span></span></div>
                <div class="question">
                    <div class="meta">Subject:  <%= w.Subject %></div>
                    <div class="meta">To: <%= w.Username  %></div>
                    <h3 class="title"><%= Html.Encode(w.Mesg)%></h3>
                </div>
            </div>
        </li>
            <% } %>

    </div>
</code>```

答:
If you're planning to submit this form, and do anything with the checkbox values on the server side, you'll want to give them name and value attributes (and the name should be the same for each checkbox in the group). The checkbox helper that TStamper mentioned takes care of that for you.

If you just want a client action to happen when the checkbox is ticked or unticked, you can do something like this (I'm assuming that these objects have some kind of key field; I'm calling it MessageID):

```<code><script type="text/javascript">
function handleCheckbox( theBox ) {
  if( theBox.checked) {
    // do checked stuff
  }
  else {
    // do un-checked stuff
  }
}
</script>

...

<input type="checkbox" value="<%= w.MessageID %>" onclick="handleCheckbox(this)"  />
</code>```

Please note that id values are required to be unique within an HTML document. So creating lots of checkboxes with the ID "Checkbox1" is not a good idea. (If that input element were runat="server", then .NET would generate a unique HTML id from the WebForms ID.

OwnerDisplayName: avinash mahajan

LastEditorDisplayName: Fabian Steeg

Body:
I had displayed check box in a list and i want to access that which check box is selected or not and want to call controller action where i select option from dropdown list

            <%= Html.DropDownList("select","msgtype") %>
            <% foreach (Usp_GetUserMessagesResult w in (List<Usp_GetUserMessagesResult>)ViewData["UListM"])
               { %>

                <input id="Checkbox1" type="checkbox" onclick="function() { alert("df") ; } "  />

Subject:  <%= w.Subject %>

To: <%= w.Username  %>

<%= Html.Encode(w.Mesg)%>

            <% } %>

Body:
If you're planning to submit this form, and do anything with the checkbox values on the server side, you'll want to give them name and value attributes (and the name should be the same for each checkbox in the group). The checkbox helper that TStamper mentioned takes care of that for you.

If you just want a client action to happen when the checkbox is ticked or unticked, you can do something like this (I'm assuming that these objects have some kind of key field; I'm calling it MessageID):

<script type="text/javascript">
function handleCheckbox( theBox ) {
  if( theBox.checked) {
    // do checked stuff
  }
  else {
    // do un-checked stuff
  }
}
</script>

...

<input type="checkbox" value="<%= w.MessageID %>" onclick="handleCheckbox(this)"  />

Please note that id values are required to be unique within an HTML document. So creating lots of checkboxes with the ID "Checkbox1" is not a good idea. (If that input element were runat="server", then .NET would generate a unique HTML id from the WebForms ID.

OwnerDisplayName: Sixten Otto


问:
wpf print / print preview usercontrol
I have to print to specified printer (price-label printer) some data.
Data looks like ean13 barcode, price, item's title, etc

I have a few settings what to print in each case.
What I want:

create usercontrol (WPF) with 2 columns. left column for print preview, and right column for settings (checkboxes, textboxes).

is user changes settings, print preview updates.

What approach should I use, to do it most right way?
Now printing routine looks like:

```<code>private void DrawOnGraphics(Graphics graphics)
{
    using (var shF = new Font("Arial", 10, FontStyle.Bold))
    {
        graphics.DrawImage(_barcode, new Point(0, 0));
// etc...
}
</code>```

I think it's not very good code but it works here:

```<code>var pDoc = new PrintDocument();
pDoc.PrintPage += (a, e) =>
                              {
                                  DrawOnGraphics(e.Graphics);
                                  e.HasMorePages = false;
                              };
pDoc.Print();
</code>```

Can I create one 'rendering routine' for both actions: print and printpreview?
Thanks.
How can it be done? Should I use in XAML for print preview

```<code><Image Source="{Binding Path=PrintPreviewImage}" />
</code>```

or? :)

Main question is: how to draw own things (text, images, etc) for print and printpreview in WPF.

答:
I tried this approach:

in ViewModel, I have public property PrintPreview (of type Grid)

in XAML i have

```<code><ContentPresenter Content="{Binding Path=PrintPreview}" />
</code>```

each of settings are binded to ViewModel properties

in private function I contruct PrintPreview property like this:

PrintPreview.Children.Clear();
var title = new TextBlock { ... };
PrintPreview.Children.Add(title); //etc.

I have "Print" method, that is binded to button "Print" in view:

```<code>PrintQueue pq = new PrintServer().GetPrintQueues(new[]
                                                     {
                                                         EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections
                                                     }).FirstOrDefault(tmp => tmp.FullName.Contains("MyPrintername"));

if (pq == null)
{
    MessageBox.Show("Please, setup printer");
    return;
}

var pt = new PrintTicket();
// setting printticket
pt.PageMediaSize = new PageMediaSize(FromMMtoPx(96, WidthInMm), FromMMtoPx(96, HeightInMm));
pt.CopyCount = Copies;
pt.PageResolution = new PageResolution(203, 203);
pt.PageOrientation = PageOrientation.Portrait;
pt.PageBorderless = PageBorderless.Borderless;

var pDoc = new System.Windows.Controls.PrintDialog();
pDoc.PrintQueue = pq;
pDoc.PrintTicket = pt;

// scale for whole printer page:

var capabilities = pDoc.PrintQueue.GetPrintCapabilities(pDoc.PrintTicket);
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / PrintPreview.ActualWidth, capabilities.PageImageableArea.ExtentHeight / PrintPreview.ActualHeight);

PrintPreview.LayoutTransform = new ScaleTransform(scale, scale);
var sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
PrintPreview.Measure(sz);
PrintPreview.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
pDoc.PrintVisual(PrintPreview, "MyPrint");
</code>```

It works, but I don't really know, is that good approach or not.

Title: wpf print / print preview usercontrol

Body:
I have to print to specified printer (price-label printer) some data.
Data looks like ean13 barcode, price, item's title, etc

I have a few settings what to print in each case.
What I want:

create usercontrol (WPF) with 2 columns. left column for print preview, and right column for settings (checkboxes, textboxes).

is user changes settings, print preview updates.

What approach should I use, to do it most right way?
Now printing routine looks like:

private void DrawOnGraphics(Graphics graphics)
{
    using (var shF = new Font("Arial", 10, FontStyle.Bold))
    {
        graphics.DrawImage(_barcode, new Point(0, 0));
// etc...
}

I think it's not very good code but it works here:

var pDoc = new PrintDocument();
pDoc.PrintPage += (a, e) =>
                              {
                                  DrawOnGraphics(e.Graphics);
                                  e.HasMorePages = false;
                              };
pDoc.Print();

Can I create one 'rendering routine' for both actions: print and printpreview?
Thanks.
How can it be done? Should I use in XAML for print preview

<Image Source="{Binding Path=PrintPreviewImage}" />

or? :)

Main question is: how to draw own things (text, images, etc) for print and printpreview in WPF.

Body:
I tried this approach:

in ViewModel, I have public property PrintPreview (of type Grid)

in XAML i have

<ContentPresenter Content="{Binding Path=PrintPreview}" />

each of settings are binded to ViewModel properties

in private function I contruct PrintPreview property like this:

PrintPreview.Children.Clear();
var title = new TextBlock { ... };
PrintPreview.Children.Add(title); //etc.

I have "Print" method, that is binded to button "Print" in view:

PrintQueue pq = new PrintServer().GetPrintQueues(new[]
                                                     {
                                                         EnumeratedPrintQueueTypes.Local, EnumeratedPrintQueueTypes.Connections
                                                     }).FirstOrDefault(tmp => tmp.FullName.Contains("MyPrintername"));

if (pq == null)
{
    MessageBox.Show("Please, setup printer");
    return;
}

var pt = new PrintTicket();
// setting printticket
pt.PageMediaSize = new PageMediaSize(FromMMtoPx(96, WidthInMm), FromMMtoPx(96, HeightInMm));
pt.CopyCount = Copies;
pt.PageResolution = new PageResolution(203, 203);
pt.PageOrientation = PageOrientation.Portrait;
pt.PageBorderless = PageBorderless.Borderless;

var pDoc = new System.Windows.Controls.PrintDialog();
pDoc.PrintQueue = pq;
pDoc.PrintTicket = pt;

// scale for whole printer page:

var capabilities = pDoc.PrintQueue.GetPrintCapabilities(pDoc.PrintTicket);
double scale = Math.Min(capabilities.PageImageableArea.ExtentWidth / PrintPreview.ActualWidth, capabilities.PageImageableArea.ExtentHeight / PrintPreview.ActualHeight);

PrintPreview.LayoutTransform = new ScaleTransform(scale, scale);
var sz = new Size(capabilities.PageImageableArea.ExtentWidth, capabilities.PageImageableArea.ExtentHeight);
PrintPreview.Measure(sz);
PrintPreview.Arrange(new Rect(new Point(capabilities.PageImageableArea.OriginWidth, capabilities.PageImageableArea.OriginHeight), sz));
pDoc.PrintVisual(PrintPreview, "MyPrint");

It works, but I don't really know, is that good approach or not.


问:
How to insert user email after Sheets cell is edited
Working on a sheet that when the user edits a cell (example C3), it will insert his/her email (name).  Have a scrip that does work for only one column ("C"), but when moved to another sheet or column ("5 or E") it gives “Error – you do not have permission to call getActiveUser (line 41)".

Because it does work once, not sure what I am missing or why the same script wont work at all on another sheet. Thanks for any assistance.

```<code>function onEdit() {
 var s = SpreadsheetApp.getActiveSheet();
 if( s.getName() == "Sheet1" ) { //checks that we're on the correct sheet
   var r = s.getActiveCell();
    var email = Session.getActiveUser().getEmail();
   Logger.log(email);
   if( r.getColumn() == 3 ) { //checks the C column
    var nextCell = r.offset(0, 1);
   nextCell.setValue(email);
  if( r.getColumn() == 5 ) { //checks the E column
   var nextCell = r.offset(0, 1);
  if( nextCell.getValue() !== '' ) //is empty?
 nextCell.setValue(email);
   }
  }
 }
</code>```

答:
Make sure you are the owner of the spreadsheet and you have granted the necessary permission to run the script.</p>

```<code>function onEdit() {
    var s = SpreadsheetApp.getActiveSheet();
    if (s.getName() == "Sheet2") { //checks that we're on the correct sheet
        var r = s.getActiveCell();
        var email = Session.getActiveUser().getEmail();
        if (r.getColumn() == 3) { //checks the C column
            var nextCell = r.offset(0, 1);
            nextCell.setValue(email);
        }
        if (r.getColumn() == 5) { //checks the E column
            var nextCell = r.offset(0, 1);
            Logger.log(nextCell.getValue());
            if (nextCell.getValue() == '') //is empty?
                nextCell.setValue(email);
        }
    }
}
</code>```

Body:
Working on a sheet that when the user edits a cell (example C3), it will insert his/her email (name).  Have a scrip that does work for only one column ("C"), but when moved to another sheet or column ("5 or E") it gives “Error – you do not have permission to call getActiveUser (line 41)".

Because it does work once, not sure what I am missing or why the same script wont work at all on another sheet. Thanks for any assistance.

function onEdit() {
 var s = SpreadsheetApp.getActiveSheet();
 if( s.getName() == "Sheet1" ) { //checks that we're on the correct sheet
   var r = s.getActiveCell();
    var email = Session.getActiveUser().getEmail();
   Logger.log(email);
   if( r.getColumn() == 3 ) { //checks the C column
    var nextCell = r.offset(0, 1);
   nextCell.setValue(email);
  if( r.getColumn() == 5 ) { //checks the E column
   var nextCell = r.offset(0, 1);
  if( nextCell.getValue() !== '' ) //is empty?
 nextCell.setValue(email);
   }
  }
 }

Body:
Make sure you are the owner of the spreadsheet and you have granted the necessary permission to run the script.

function onEdit() {
    var s = SpreadsheetApp.getActiveSheet();
    if (s.getName() == "Sheet2") { //checks that we're on the correct sheet
        var r = s.getActiveCell();
        var email = Session.getActiveUser().getEmail();
        if (r.getColumn() == 3) { //checks the C column
            var nextCell = r.offset(0, 1);
            nextCell.setValue(email);
        }
        if (r.getColumn() == 5) { //checks the E column
            var nextCell = r.offset(0, 1);
            Logger.log(nextCell.getValue());
            if (nextCell.getValue() == '') //is empty?
                nextCell.setValue(email);
        }
    }
}


问:
Secure Websocket (wss) Handshake does not happen using Stunnel
We have made an application that using websockets. We have built our own websocket server in PHP and use Stunnel for using secure websockets. We use Amazon EC2 Medium Server

Every thing was working fine till last week when suddenly the chrome browser started showing failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET. The connection also has stopped happening on Firefox.

However at time the wss connection does happen. Its like may be after 4 or 5 times when we refresh the page, the wss connection happens once.

We have analysed the issue and below are the things we have observed :

In STUNNEL :

When a new SSL session is created, everything works fine. Below is the log

```<code>2014.12.05 05:56:08 LOG7[13990:140019053639616]: Service [websockets] accepted (FD=14) from 115.111.211.142:60018
2014.12.05 05:56:08 LOG7[13990:140019053496064]: Service [websockets] started
2014.12.05 05:56:08 LOG5[13990:140019053496064]: Service [websockets] accepted connection from 115.111.211.142:60018
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): before/accept initialization
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SNI: no virtual services defined
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read client hello B
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write server hello A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write certificate A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write key exchange A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write server done A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 flush data
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read client key exchange A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read finished A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write session ticket A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write change cipher spec A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write finished A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 flush data
2014.12.05 05:56:08 LOG7[13990:140019053496064]:   10 items in the session cache
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 client connects (SSL_connect())
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 client connects that finished
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 client renegotiations requested
2014.12.05 05:56:08 LOG7[13990:140019053496064]: 1138 server connects (SSL_accept())
2014.12.05 05:56:08 LOG7[13990:140019053496064]: 1087 server connects that finished
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 server renegotiations requested
2014.12.05 05:56:08 LOG7[13990:140019053496064]:  558 session cache hits
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 external session cache hits
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 session cache misses
2014.12.05 05:56:08 LOG7[13990:140019053496064]:  132 session cache timeouts
2014.12.05 05:56:08 LOG6[13990:140019053496064]: SSL accepted: new session negotiated
2014.12.05 05:56:08 LOG6[13990:140019053496064]: Negotiated TLSv1/SSLv3 ciphersuite: DHE-RSA-AES128-SHA (128-bit encryption)
2014.12.05 05:56:08 LOG6[13990:140019053496064]: Compression: null, expansion: null
2014.12.05 05:56:08 LOG6[13990:140019053496064]: connect_blocking: connecting 127.0.0.1:9000
2014.12.05 05:56:08 LOG7[13990:140019053496064]: connect_blocking: s_poll_wait 127.0.0.1:9000: waiting 10 seconds
2014.12.05 05:56:08 LOG5[13990:140019053496064]: connect_blocking: connected 127.0.0.1:9000
2014.12.05 05:56:08 LOG5[13990:140019053496064]: Service [websockets] connected remote server from 127.0.0.1:18479
</code>```

However when the a session is reused, the connection is closed from the PHP websocket. below is the log

```<code>2014.12.05 05:56:08 LOG7[13990:140019053496064]: Remote socket (FD=15) initialized
2014.12.05 05:56:39 LOG6[13990:140019053496064]: Read socket closed (readsocket)
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Sending close_notify alert
2014.12.05 05:56:39 LOG7[13990:140019053496064]: SSL alert (write): warning: close notify
2014.12.05 05:56:39 LOG6[13990:140019053496064]: SSL_shutdown successfully sent close_notify alert
2014.12.05 05:56:39 LOG3[13990:140019053496064]: transfer: s_poll_wait: TIMEOUTclose exceeded: closing
2014.12.05 05:56:39 LOG5[13990:140019053496064]: Connection closed: 988 byte(s) sent to SSL, 873 byte(s) sent to socket
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Remote socket (FD=15) closed
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Local socket (FD=14) closed
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Service [websockets] finished (3 left)
2014.12.05 05:56:43 LOG7[13990:140019053639616]: Service [websockets] accepted (FD=14) from 115.111.211.142:60045
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Service [websockets] started
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Service [websockets] accepted connection from 115.111.211.142:60045
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): before/accept initialization
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SNI: no virtual services defined
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read client hello B
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write server hello A
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write change cipher spec A
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write finished A
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 flush data
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read finished A
2014.12.05 05:56:43 LOG7[13990:140019053496064]:   10 items in the session cache
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 client connects (SSL_connect())
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 client connects that finished
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 client renegotiations requested
2014.12.05 05:56:43 LOG7[13990:140019053496064]: 1139 server connects (SSL_accept())
2014.12.05 05:56:43 LOG7[13990:140019053496064]: 1088 server connects that finished
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 server renegotiations requested
2014.12.05 05:56:43 LOG7[13990:140019053496064]:  559 session cache hits
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 external session cache hits
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 session cache misses
2014.12.05 05:56:43 LOG7[13990:140019053496064]:  132 session cache timeouts
2014.12.05 05:56:43 LOG6[13990:140019053496064]: SSL accepted: previous session reused
2014.12.05 05:56:43 LOG6[13990:140019053496064]: connect_blocking: connecting 127.0.0.1:9000
2014.12.05 05:56:43 LOG7[13990:140019053496064]: connect_blocking: s_poll_wait 127.0.0.1:9000: waiting 10 seconds
2014.12.05 05:56:43 LOG5[13990:140019053496064]: connect_blocking: connected 127.0.0.1:9000
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Service [websockets] connected remote server from 127.0.0.1:18480
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Remote socket (FD=15) initialized
2014.12.05 05:56:43 LOG6[13990:140019053496064]: Read socket closed (readsocket)
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Sending close_notify alert
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Read socket error: Broken pipe (32)
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Connection reset: 0 byte(s) sent to SSL, 516 byte(s) sent to socket
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Remote socket (FD=15) closed
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Local socket (FD=14) closed
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Service [websockets] finished (3 left)
</code>```

In our PHP WebSocket Server :

When the session reuse happens the WebSocket server just gets string 'G' as the data and nothing else so the handshake fails. However when a new session is create in the Stunnel, the handshake works fine.

It would be great if someone could help us out.

What have we done to solve this issue till now :

Disabled SSL Cache in Apache. ISSUE STILL THERE

Used Session Cache setting in stunnel. ISSUE STILL THERE. Also we dont have a clear understanding on the Session cache setting and how to disable it.

What we plan to do next

Recompile STUNNEL and try to disable SSL cache from the code.

Stop using STUNNEL and find out how to establish SSL Connection in PHP. Got something like stream_context_create to create these connections. However still we have to see the details of stream_context_create

Move everything to a new server and see where the issue.

Hope I have made things clear. Awaiting for replies. Thanks!

答: Read 1 byte off the stream first, then do a full read (concatenating the 1 byte to the full read). The "G" is most likely the first byte of a "GET". I'm not sure what causes it, but I experienced this recently.</p>

Body:
We have made an application that using websockets. We have built our own websocket server in PHP and use Stunnel for using secure websockets. We use Amazon EC2 Medium Server

Every thing was working fine till last week when suddenly the chrome browser started showing failed: Error during WebSocket handshake: net::ERR_CONNECTION_RESET. The connection also has stopped happening on Firefox.

However at time the wss connection does happen. Its like may be after 4 or 5 times when we refresh the page, the wss connection happens once.

We have analysed the issue and below are the things we have observed :

In STUNNEL :

When a new SSL session is created, everything works fine. Below is the log

2014.12.05 05:56:08 LOG7[13990:140019053639616]: Service [websockets] accepted (FD=14) from 115.111.211.142:60018
2014.12.05 05:56:08 LOG7[13990:140019053496064]: Service [websockets] started
2014.12.05 05:56:08 LOG5[13990:140019053496064]: Service [websockets] accepted connection from 115.111.211.142:60018
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): before/accept initialization
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SNI: no virtual services defined
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read client hello B
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write server hello A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write certificate A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write key exchange A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write server done A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 flush data
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read client key exchange A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read finished A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write session ticket A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write change cipher spec A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write finished A
2014.12.05 05:56:08 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 flush data
2014.12.05 05:56:08 LOG7[13990:140019053496064]:   10 items in the session cache
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 client connects (SSL_connect())
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 client connects that finished
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 client renegotiations requested
2014.12.05 05:56:08 LOG7[13990:140019053496064]: 1138 server connects (SSL_accept())
2014.12.05 05:56:08 LOG7[13990:140019053496064]: 1087 server connects that finished
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 server renegotiations requested
2014.12.05 05:56:08 LOG7[13990:140019053496064]:  558 session cache hits
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 external session cache hits
2014.12.05 05:56:08 LOG7[13990:140019053496064]:    0 session cache misses
2014.12.05 05:56:08 LOG7[13990:140019053496064]:  132 session cache timeouts
2014.12.05 05:56:08 LOG6[13990:140019053496064]: SSL accepted: new session negotiated
2014.12.05 05:56:08 LOG6[13990:140019053496064]: Negotiated TLSv1/SSLv3 ciphersuite: DHE-RSA-AES128-SHA (128-bit encryption)
2014.12.05 05:56:08 LOG6[13990:140019053496064]: Compression: null, expansion: null
2014.12.05 05:56:08 LOG6[13990:140019053496064]: connect_blocking: connecting 127.0.0.1:9000
2014.12.05 05:56:08 LOG7[13990:140019053496064]: connect_blocking: s_poll_wait 127.0.0.1:9000: waiting 10 seconds
2014.12.05 05:56:08 LOG5[13990:140019053496064]: connect_blocking: connected 127.0.0.1:9000
2014.12.05 05:56:08 LOG5[13990:140019053496064]: Service [websockets] connected remote server from 127.0.0.1:18479

However when the a session is reused, the connection is closed from the PHP websocket. below is the log

2014.12.05 05:56:08 LOG7[13990:140019053496064]: Remote socket (FD=15) initialized
2014.12.05 05:56:39 LOG6[13990:140019053496064]: Read socket closed (readsocket)
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Sending close_notify alert
2014.12.05 05:56:39 LOG7[13990:140019053496064]: SSL alert (write): warning: close notify
2014.12.05 05:56:39 LOG6[13990:140019053496064]: SSL_shutdown successfully sent close_notify alert
2014.12.05 05:56:39 LOG3[13990:140019053496064]: transfer: s_poll_wait: TIMEOUTclose exceeded: closing
2014.12.05 05:56:39 LOG5[13990:140019053496064]: Connection closed: 988 byte(s) sent to SSL, 873 byte(s) sent to socket
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Remote socket (FD=15) closed
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Local socket (FD=14) closed
2014.12.05 05:56:39 LOG7[13990:140019053496064]: Service [websockets] finished (3 left)
2014.12.05 05:56:43 LOG7[13990:140019053639616]: Service [websockets] accepted (FD=14) from 115.111.211.142:60045
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Service [websockets] started
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Service [websockets] accepted connection from 115.111.211.142:60045
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): before/accept initialization
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SNI: no virtual services defined
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read client hello B
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write server hello A
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write change cipher spec A
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 write finished A
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 flush data
2014.12.05 05:56:43 LOG7[13990:140019053496064]: SSL state (accept): SSLv3 read finished A
2014.12.05 05:56:43 LOG7[13990:140019053496064]:   10 items in the session cache
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 client connects (SSL_connect())
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 client connects that finished
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 client renegotiations requested
2014.12.05 05:56:43 LOG7[13990:140019053496064]: 1139 server connects (SSL_accept())
2014.12.05 05:56:43 LOG7[13990:140019053496064]: 1088 server connects that finished
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 server renegotiations requested
2014.12.05 05:56:43 LOG7[13990:140019053496064]:  559 session cache hits
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 external session cache hits
2014.12.05 05:56:43 LOG7[13990:140019053496064]:    0 session cache misses
2014.12.05 05:56:43 LOG7[13990:140019053496064]:  132 session cache timeouts
2014.12.05 05:56:43 LOG6[13990:140019053496064]: SSL accepted: previous session reused
2014.12.05 05:56:43 LOG6[13990:140019053496064]: connect_blocking: connecting 127.0.0.1:9000
2014.12.05 05:56:43 LOG7[13990:140019053496064]: connect_blocking: s_poll_wait 127.0.0.1:9000: waiting 10 seconds
2014.12.05 05:56:43 LOG5[13990:140019053496064]: connect_blocking: connected 127.0.0.1:9000
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Service [websockets] connected remote server from 127.0.0.1:18480
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Remote socket (FD=15) initialized
2014.12.05 05:56:43 LOG6[13990:140019053496064]: Read socket closed (readsocket)
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Sending close_notify alert
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Read socket error: Broken pipe (32)
2014.12.05 05:56:43 LOG5[13990:140019053496064]: Connection reset: 0 byte(s) sent to SSL, 516 byte(s) sent to socket
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Remote socket (FD=15) closed
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Local socket (FD=14) closed
2014.12.05 05:56:43 LOG7[13990:140019053496064]: Service [websockets] finished (3 left)

In our PHP WebSocket Server :

When the session reuse happens the WebSocket server just gets string 'G' as the data and nothing else so the handshake fails. However when a new session is create in the Stunnel, the handshake works fine.

It would be great if someone could help us out.

What have we done to solve this issue till now :

Disabled SSL Cache in Apache. ISSUE STILL THERE

Used Session Cache setting in stunnel. ISSUE STILL THERE. Also we dont have a clear understanding on the Session cache setting and how to disable it.

What we plan to do next

Recompile STUNNEL and try to disable SSL cache from the code.

Stop using STUNNEL and find out how to establish SSL Connection in PHP. Got something like stream_context_create to create these connections. However still we have to see the details of stream_context_create

Move everything to a new server and see where the issue.

Hope I have made things clear. Awaiting for replies. Thanks!


问:
Pre-serializing some fields of a proto message
Suppose I have a proto structure that looks like the following:

```<code>message TMessage {
    optional TDictionary dictionary = 1;
    optional int specificField1 = 2;
    optional TOtherMessage specificField2 = 3;
    ...
}
</code>```

Suppose I am using C++. This is the message stub that is used in the master process to send information to the bunch of the nodes using the network. In particular, the dictionary field is 1) pretty heavy 2) common for all the serialized messages, and all the following specific fields are filled with the relatively small information specific to the destination node.

Of course, dictionary is built only once, but it comes out that the major part of running time is spent while serializing the common dictionary part again and again for each new node.

Obvious optimization would be to pre-serialize dictionary into the byte string and put it into the TMessage as a bytes field, but this looks a bit nasty to me.

Am I right that there is no built-in way to pre-serialize a message field without ruining the message structure? It sounds like an idea for a good plugin for proto compiler.

答:
Protobuf is designed such that concatenation === composition, at least for the root message. That means that you can serialize an object with just the dictionary, and snapshot the bytes somewhere. Now for each of the real messages you can paste down that snapshot, and then serialize an object with just the other fields - just whack it straight after: no additional syntax is required. This is semantically identical to serializing them all at the same time. In fact, since it will retain the field order, it should actually be identical bytes too.

It helps that you used "optional" throughout :)

Body:
Suppose I have a proto structure that looks like the following:

message TMessage {
    optional TDictionary dictionary = 1;
    optional int specificField1 = 2;
    optional TOtherMessage specificField2 = 3;
    ...
}

Suppose I am using C++. This is the message stub that is used in the master process to send information to the bunch of the nodes using the network. In particular, the dictionary field is 1) pretty heavy 2) common for all the serialized messages, and all the following specific fields are filled with the relatively small information specific to the destination node.

Of course, dictionary is built only once, but it comes out that the major part of running time is spent while serializing the common dictionary part again and again for each new node.

Obvious optimization would be to pre-serialize dictionary into the byte string and put it into the TMessage as a bytes field, but this looks a bit nasty to me.

Am I right that there is no built-in way to pre-serialize a message field without ruining the message structure? It sounds like an idea for a good plugin for proto compiler.


问:
Sampling with weight for 1 number
I want to sample from a big pool of numbers e.g. -2000:5000.

I would like thought to set the weight for a certain number to 80%.

Everything other possibility should be equal for every other number.

Doing this for a small sample is easy:

sample(-2:2, 10, replace = TRUE, prob=c(0.05, 0.05, 0.80, 0.05, 0.05))

this would output:

[1]  0  0  0  0  0 -1  0  0  0  0

How can I do this for a big range of numbers?

答:
You only need to run a separate vector with all the probabilities. Take on the account that when you create the probabilities vector, you can use a logic test to define "p1 = 0.8" if it is my desired number and "p2 = 0.2/n" in any other case. The code run as follows:

```<code>n <- 37 # your num
x <- -100:1000 # your sequence
probs <- ifelse(x == n, 0.8, (1 - 0.8) /length(x) ) # determine probabilities taking on account they have to add up to 1
sum(probs)
sample(x = x, size = 1000, prob = probs)
</code>```

Let me know if it helps.

Title: Sampling with weight for 1 number

Body:
You only need to run a separate vector with all the probabilities. Take on the account that when you create the probabilities vector, you can use a logic test to define "p1 = 0.8" if it is my desired number and "p2 = 0.2/n" in any other case. The code run as follows:

n <- 37 # your num
x <- -100:1000 # your sequence
probs <- ifelse(x == n, 0.8, (1 - 0.8) /length(x) ) # determine probabilities taking on account they have to add up to 1
sum(probs)
sample(x = x, size = 1000, prob = probs)

Let me know if it helps.


问:
php email attachment
i am using this script for the email attachment but when i execute the form on my server it shows to warning

Warning: fread(): supplied argument is not a valid stream resource

Warning: fclose(): supplied argument is not a valid stream resource

pls help

答:
I used phpmailer class. Its very simple.

procedure- http://www.phpexpertsforum.com/how-to-add-doc-file-as-attachment-to-sending-mail-from-php-t649.html

Title: php email attachment


问:
Android studio: changing imageview weekly
I am trying to obtain create an app on Android Studio that displays an image on the main activity.  This image will change weekly.  I understand that this cannot be done by updating the application on a weekly basis.  How can I display an image and change it on a weekly basis without having to re-release the application?</p>

答:
Just host your image on the web. Use Picasso OR Glide to load in your app.

```<code> Picasso.with(context)
.load("imageURL") //new imageURL should same as the previous
.into(imageView)
</code>```

You can update your image at any time on the web. Changes will automatically update to your app.

Body:
Just host your image on the web. Use Picasso OR Glide to load in your app.

 Picasso.with(context)
.load("imageURL") //new imageURL should same as the previous
.into(imageView)

You can update your image at any time on the web. Changes will automatically update to your app.


问:
How to read more than one csv files from the command line in python3?
So I append all the files from command line to a list and then I have

```<code>filenames =['file1.csv', 'try.csv', 'new.csv']
</code>```

I now want to access file1.csv first check some conditions, if they don't satisfy, then check the next file until then do.
Any help?

答:
Just use a simple for-loop and a with statement:

```<code>import csv

filenames =['file1.csv', 'try.csv', 'new.csv']
for file in fienames:
    with open(file, 'r') as f:
         for row in csv.reader(f):
             #do something (check user input whatever...)
</code>```

Body:
So I append all the files from command line to a list and then I have

filenames =['file1.csv', 'try.csv', 'new.csv']

I now want to access file1.csv first check some conditions, if they don't satisfy, then check the next file until then do.
Any help?

Body:
Just use a simple for-loop and a with statement:

import csv

filenames =['file1.csv', 'try.csv', 'new.csv']
for file in fienames:
    with open(file, 'r') as f:
         for row in csv.reader(f):
             #do something (check user input whatever...)


问:
Universe Dictionary ITem multipart key, second part is multi-valued
Trying to use

```<code>TRANS(SPEC.ORDR,@ID:"*":@RECORD<27,@CNT>,27,'X')
</code>```

Universe is returning an error message on @CNT, assuming not used in our Universe flavour, anyone know what the actual trans code would be?

答:
I just realized that the CATS is base so this should work for you. A similarly built I-Descriptor on my system certainly does the concatenation correctly, but I don't have an easy to find example to test the TRANS on top. It does bring back the expected number of blanks based the on the 'X'.

```<code>TRANS(SPEC.ORDR,SUBR('-CATS',REUSE(@ID:'*'),@RECORD<27>),27,'X')
</code>```

Good luck

Body:
Trying to use

TRANS(SPEC.ORDR,@ID:"*":@RECORD<27,@CNT>,27,'X')

Universe is returning an error message on @CNT, assuming not used in our Universe flavour, anyone know what the actual trans code would be?

Body:
I just realized that the CATS is base so this should work for you. A similarly built I-Descriptor on my system certainly does the concatenation correctly, but I don't have an easy to find example to test the TRANS on top. It does bring back the expected number of blanks based the on the 'X'.

TRANS(SPEC.ORDR,SUBR('-CATS',REUSE(@ID:'*'),@RECORD<27>),27,'X')

Good luck


问:
Image exceeding parent size
I want to center and restrict an image

I have an outer container and an image-container which has display: inline-block; to have the same size as the image (required, will contain draggable items)

But the image keeps exceeding the height: 100%;

Is there a workaround to get the desired result (as in the screenshot)

.container {
  width: 300px;
  height: 100px;
  background: red;
  text-align: center;
}

.image-container {
  display: inline-block;
  background: #0f0;
  outline: 5px solid #00f;
  max-width: 100%;
  max-height: 100%;

}

.main-image {
  max-width: 100%;
  max-height: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="image-container">
    <img class="main-image" src="http://via.placeholder.com/400x400" />
  </div>
</div></code>```

fiddle

答:
I ended up using absolute positioning on the image-container to collapse it to the size of the child. this requires position: relative on the parent container. overflow: hidden is added here to fix slight offset due to the transform on image-container.

```<code>.container {
  width: 300px;
  height: 100px;
  background: red;
  position: relative;
  overflow: hidden;
}
</code>```

position, top, left, and transform are set here to center the image-container vertically and horizontally in the parent container.

```<code>.image-container {
  background: green;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</code>```

max-width and max-height need to match the parent container's width and height.

```<code>.main-image {
  max-width: 300px;
  max-height: 100px;
}
</code>```

fiddle

Title: Image exceeding parent size

Body:
I want to center and restrict an image

I have an outer container and an image-container which has display: inline-block; to have the same size as the image (required, will contain draggable items)

But the image keeps exceeding the height: 100%;

Is there a workaround to get the desired result (as in the screenshot)

.container {
  width: 300px;
  height: 100px;
  background: red;
  text-align: center;
}

.image-container {
  display: inline-block;
  background: #0f0;
  outline: 5px solid #00f;
  max-width: 100%;
  max-height: 100%;

}

.main-image {
  max-width: 100%;
  max-height: 100%;
}

fiddle

Body:
I ended up using absolute positioning on the image-container to collapse it to the size of the child. this requires position: relative on the parent container. overflow: hidden is added here to fix slight offset due to the transform on image-container.

.container {
  width: 300px;
  height: 100px;
  background: red;
  position: relative;
  overflow: hidden;
}

position, top, left, and transform are set here to center the image-container vertically and horizontally in the parent container.

.image-container {
  background: green;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

max-width and max-height need to match the parent container's width and height.

.main-image {
  max-width: 300px;
  max-height: 100px;
}

fiddle


问:
Enumerate all possible distributions of n balls into k boxes
The exact problem i am referring to and the number of distributions for the  problem is computed here. I am interested in knowing those distributions explicitly.

For example, there are 5 balls and 3 boxes: one distribution is 2 balls in box 1, 2 in box 2, 1 in box 3 referred to as, say 221. Now i want to list all such possible distributions: -

212

131

104

.
.
.

One way is that i run the matlab command: perms([0,0,0,0,0,1,1,1]). This essentially generates all permutations of 5 balls and 2 sticks. but there is massive over-counting as the command perms does not recognize identical objects.

答:
You can use unique() to get rid of identical rows generated by perms():

```<code>A = unique(perms([0,0,0,0,0,1,1,1]), 'rows');
% `A` will contain all combinations, not permutations, of [0,0,0,0,0,1,1,1]
</code>```

Body:
You can use unique() to get rid of identical rows generated by perms():

A = unique(perms([0,0,0,0,0,1,1,1]), 'rows');
% `A` will contain all combinations, not permutations, of [0,0,0,0,0,1,1,1]


问:
In React, how to grab custom data when options are selected in <select> elements
I have a <select> element that displays a list of Countries.

When the user selects one, the selected value is a name, like "Canada" but I need to make a query that uses the serial number we use for Canada.

How do I get that serial number out of the stateless functional select component and into the parent container?

Here is the relevant code:

dumb component

```<code>const GeoSelect = function selectFromGeoTree({ ... }) {
  ...
  return (
    <select
      id={name}
      className={maybeHasError}
      name={name}
      onChange={onChange}
      {...input}
    >
      <option
        value={0}
        className="edit_empty"
      >
        {placeholder}
      </option>
      {options && options.map(opt => (
        <option
          key={opt.serialNumber}
          value={opt.label}
          className="edit_filled"
          id={opt.id}
        >
          {opt.label}
        </option>
      ))}
    </select>
  )
}
</code>```

container

```<code><Field
  label="Country"
  component={FormSelectFromObject}
  name="country"
  placeholder="Select Country"
  options={this.state.countries}
  onChange={e => console.log('ON SELECT', e.target)}
  required
/>
</code>```

I am looking to do as concisely as possible something like:

```<code>onChange={(id) => this.getRegions(id)}
</code>```

to make a query that gets a list based on that ID.

The data structure that goes into the <select> element looks like this:

```<code>this.state.countries = [
  { id: '9s87f698d7f', label: 'Canada' },
  { id: 'dsei487g4e4', label: 'USA' },
]
</code>```

How do I get that ID back up into the parent when the user selects one of the options?

My leading thought so far is to do something like this:

```<code>onChange={(e) => {
  const { id } = this.state.countries.find(country => country.label === e.target.value)
  this.getRegionsById(id)
}}
</code>```

答: I would set your option value to the serial number you need. Then onchange for the select element get e.target.value, which should be the serial number.</p>

Body:
I have a <select> element that displays a list of Countries.

When the user selects one, the selected value is a name, like "Canada" but I need to make a query that uses the serial number we use for Canada.

How do I get that serial number out of the stateless functional select component and into the parent container?

Here is the relevant code:

dumb component

const GeoSelect = function selectFromGeoTree({ ... }) {
  ...
  return (
    <select
      id={name}
      className={maybeHasError}
      name={name}
      onChange={onChange}
      {...input}
    >
      <option
        value={0}
        className="edit_empty"
      >
        {placeholder}
      </option>
      {options && options.map(opt => (
        <option
          key={opt.serialNumber}
          value={opt.label}
          className="edit_filled"
          id={opt.id}
        >
          {opt.label}
        </option>
      ))}
    </select>
  )
}

container

<Field
  label="Country"
  component={FormSelectFromObject}
  name="country"
  placeholder="Select Country"
  options={this.state.countries}
  onChange={e => console.log('ON SELECT', e.target)}
  required
/>

I am looking to do as concisely as possible something like:

onChange={(id) => this.getRegions(id)}

to make a query that gets a list based on that ID.

The data structure that goes into the <select> element looks like this:

this.state.countries = [
  { id: '9s87f698d7f', label: 'Canada' },
  { id: 'dsei487g4e4', label: 'USA' },
]

How do I get that ID back up into the parent when the user selects one of the options?

My leading thought so far is to do something like this:

onChange={(e) => {
  const { id } = this.state.countries.find(country => country.label === e.target.value)
  this.getRegionsById(id)
}}


问:
Importing 3ds Max OBJ using C++
I have created a an OBJ loader that can import .OBJ files that were exported from 3DS Max into my simple OpenGL viewer / app. At the heart of this was a Vector3.h written with the help of some tutorials.

It worked great on a couple models I used, but the one I want to work with has something different that wasn't accounted for. It has 4 points in its vertices instead of 3. Here is a sample of a line I am working with:

```<code>g Box02
usemtl Wood_Bark
s 4
f 1/1/1 2/2/1 3/3/1 4/4/2
f 4/1/3 3/2/3 5/3/3
</code>```

The first 'f' line has 4 vertices I am interested in. My Vertex3.h takes X, Y, Z. In the other models I had, all lines were like the second 'f' line, with only 3 elements. I am getting a vertex out of range, so when I went to check where it was happening, I saw it was on this line, so I assumed because there is more data on the line that can be handled. Here is the entire Vertex3.h

http://pastebin.com/dgGSBSFe

And this is the line of code that fails. vertices is a Vector3.

```<code>tempVertices.push_back ( vertices[--vertex] );
</code>```

My question is, what is the 4th point? How would you account for that in something like my Vector3.h file? Seems like I need to create a Vector4.h, and ignore the 4th var if there is only 3 on the line. But I would like to know more about what I am dealing with, and any tips on how to do it. Is the 4th element an alpha or something? How should it be used, or should it be used at all in my calculations in Vector3.h?

答: Why don't you export as triangles only? Convert to EMesh in 3ds max, make all edges visible, export. Or simply use the appropriate OBJ export option.</p>

Title: Importing 3ds Max OBJ using C++

Body:
I have created a an OBJ loader that can import .OBJ files that were exported from 3DS Max into my simple OpenGL viewer / app. At the heart of this was a Vector3.h written with the help of some tutorials.

It worked great on a couple models I used, but the one I want to work with has something different that wasn't accounted for. It has 4 points in its vertices instead of 3. Here is a sample of a line I am working with:

g Box02
usemtl Wood_Bark
s 4
f 1/1/1 2/2/1 3/3/1 4/4/2
f 4/1/3 3/2/3 5/3/3

The first 'f' line has 4 vertices I am interested in. My Vertex3.h takes X, Y, Z. In the other models I had, all lines were like the second 'f' line, with only 3 elements. I am getting a vertex out of range, so when I went to check where it was happening, I saw it was on this line, so I assumed because there is more data on the line that can be handled. Here is the entire Vertex3.h

http://pastebin.com/dgGSBSFe

And this is the line of code that fails. vertices is a Vector3.

tempVertices.push_back ( vertices[--vertex] );

My question is, what is the 4th point? How would you account for that in something like my Vector3.h file? Seems like I need to create a Vector4.h, and ignore the 4th var if there is only 3 on the line. But I would like to know more about what I am dealing with, and any tips on how to do it. Is the 4th element an alpha or something? How should it be used, or should it be used at all in my calculations in Vector3.h?


问:
Make: Utilizing VPATH to compile and link files with a different extension
I have a somewhat odd Make case that I'm struggling to figure out. I have a C++ project I'm starting with some .cpp files, and I need to compile some source files from multiple remote directories that are utilized by several applications. This is not ideal, but this is the legacy directory/compilation structure my dev group utilizes.

Other projects utilize VPATH to accomplish this. However, they end up hardcoding the list of required objects that get linked, and this approach does not seem elegant or flexible to me. I want to dynamically compile and link everything in. Another potential complication is that some of these remote VPATH directories have files with .c extensions (even though these compile as C++) rather than .cpp.

My current solution:

```<code># Directory for object files
OBJ_DIR = build

CPPSRC := $(wildcard *.cpp)
CSRC   := $(wildcard *.c)
OBJ    := $(CSRC:%.c=$(OBJ_DIR)/%.o) $(CPPSRC:%.cpp=$(OBJ_DIR)/%.o)

# Directory for output binaries
BIN_DIR = bin

# Name of binary executable
OUTPUT = foo

# VPATH allows you to specify other directories to search for prereqs in
VPATH = /one/remote/dir /another/remote/dir

# 'make all'
all: $(BIN_DIR)/$(OUTPUT)

# 'make clean'
clean:
    @rm -rf $(BIN_DIR)
    @rm -rf $(OBJ_DIR)

$(OBJ_DIR)/%.o: %.cpp
    @mkdir -p $(OBJ_DIR)
    $(CXX) -c $< -o $@

$(OBJ_DIR)/%.o: %.c
    @mkdir -p $(OBJ_DIR)
    $(CXX) -c $< -o $@

$(BIN_DIR)/$(OUTPUT): $(OBJ)
    @mkdir -p $(BIN_DIR)
    $(CXX) -g -ansi -Wall -Werror -o $@ $(OBJ)
</code>```

The result is that everything gets compiled and linked in EXCEPT the files in my VPATH directories. I suspect this may be because once my $(OBJ) prereq is being evaluated, none of the resulting objects themselves are located in the VPATH, just the source files.

Is there a better approach I can take? I do not easily have the ability to change the contents of these remote VPATH directories, because they are used by many different applications with different owners.

答:
Looking at:

```<code>CPPSRC := $(wildcard *.cpp)
CSRC   := $(wildcard *.c)
OBJ    := $(CSRC:%.c=$(OBJ_DIR)/%.o) $(CPPSRC:%.cpp=$(OBJ_DIR)/%.o)

$(BIN_DIR)/$(OUTPUT): $(OBJ)
</code>```

The first line says, get all the files in my current directory that match the pattern *.cpp.  The second line says, get all the files in my current directory that match the pattern *.c.  The third line says, convert all these source files into object file names in the $(OBJ_DIR) directory.

The last line says, when you want to build $(BIN_DIR)/$(OUTPUT), make sure to build all those object files first.

Nowhere have you told make that it should build any object files for sources that it might find anywhere else (such as, for example, /one/remote/dir or /another/remote/dir).  So why should it try to build them?

You'll have to have make go looking for those files and add them to your object list.

You could try something like this:

```<code>VPATH = /one/remote/dir /another/remote/dir
OBJ += $(patsubst %,$(OBJ_DIR)/%.o,$(notdir $(basename $(wildcard $(addsuffix /*.cpp,$(VPATH)) $(addsuffix /*.c,$(VPATH))))))
</code>```

This adds the /*.cpp and /*.c suffixes to each directory in $(VPATH), then does a wildcard to get all matching files, then takes the basename (removing the .cpp and .c suffix), then removes the directory path, then converts each base filename to prepend with $(OBJ_DIR) and add .o to the end.

Of course, if you have two files with the same base name anywhere in your system you're out of luck and you'll have to do something more complex, preserving the directory structure for example.

Body:
I have a somewhat odd Make case that I'm struggling to figure out. I have a C++ project I'm starting with some .cpp files, and I need to compile some source files from multiple remote directories that are utilized by several applications. This is not ideal, but this is the legacy directory/compilation structure my dev group utilizes.

Other projects utilize VPATH to accomplish this. However, they end up hardcoding the list of required objects that get linked, and this approach does not seem elegant or flexible to me. I want to dynamically compile and link everything in. Another potential complication is that some of these remote VPATH directories have files with .c extensions (even though these compile as C++) rather than .cpp.

My current solution:

# Directory for object files
OBJ_DIR = build

CPPSRC := $(wildcard *.cpp)
CSRC   := $(wildcard *.c)
OBJ    := $(CSRC:%.c=$(OBJ_DIR)/%.o) $(CPPSRC:%.cpp=$(OBJ_DIR)/%.o)

# Directory for output binaries
BIN_DIR = bin

# Name of binary executable
OUTPUT = foo

# VPATH allows you to specify other directories to search for prereqs in
VPATH = /one/remote/dir /another/remote/dir

# 'make all'
all: $(BIN_DIR)/$(OUTPUT)

# 'make clean'
clean:
    @rm -rf $(BIN_DIR)
    @rm -rf $(OBJ_DIR)

$(OBJ_DIR)/%.o: %.cpp
    @mkdir -p $(OBJ_DIR)
    $(CXX) -c $< -o $@

$(OBJ_DIR)/%.o: %.c
    @mkdir -p $(OBJ_DIR)
    $(CXX) -c $< -o $@

$(BIN_DIR)/$(OUTPUT): $(OBJ)
    @mkdir -p $(BIN_DIR)
    $(CXX) -g -ansi -Wall -Werror -o $@ $(OBJ)

The result is that everything gets compiled and linked in EXCEPT the files in my VPATH directories. I suspect this may be because once my $(OBJ) prereq is being evaluated, none of the resulting objects themselves are located in the VPATH, just the source files.

Is there a better approach I can take? I do not easily have the ability to change the contents of these remote VPATH directories, because they are used by many different applications with different owners.

Body:
Looking at:

CPPSRC := $(wildcard *.cpp)
CSRC   := $(wildcard *.c)
OBJ    := $(CSRC:%.c=$(OBJ_DIR)/%.o) $(CPPSRC:%.cpp=$(OBJ_DIR)/%.o)

$(BIN_DIR)/$(OUTPUT): $(OBJ)

The first line says, get all the files in my current directory that match the pattern *.cpp.  The second line says, get all the files in my current directory that match the pattern *.c.  The third line says, convert all these source files into object file names in the $(OBJ_DIR) directory.

The last line says, when you want to build $(BIN_DIR)/$(OUTPUT), make sure to build all those object files first.

Nowhere have you told make that it should build any object files for sources that it might find anywhere else (such as, for example, /one/remote/dir or /another/remote/dir).  So why should it try to build them?

You'll have to have make go looking for those files and add them to your object list.

You could try something like this:

VPATH = /one/remote/dir /another/remote/dir
OBJ += $(patsubst %,$(OBJ_DIR)/%.o,$(notdir $(basename $(wildcard $(addsuffix /*.cpp,$(VPATH)) $(addsuffix /*.c,$(VPATH))))))

This adds the /*.cpp and /*.c suffixes to each directory in $(VPATH), then does a wildcard to get all matching files, then takes the basename (removing the .cpp and .c suffix), then removes the directory path, then converts each base filename to prepend with $(OBJ_DIR) and add .o to the end.

Of course, if you have two files with the same base name anywhere in your system you're out of luck and you'll have to do something more complex, preserving the directory structure for example.


答:
Very simple ... sort of.

```<code>function alloc(balls, boxes):

    if boxes = 1
        return [balls]
    else
       for n in range 0:balls
           return alloc(balls-n, boxes-1)
</code>```

That's the basic recursion logic: pick each possible quantity of balls, then recur on the remaining balls and one box fewer.

The list-gluing methods will be language-dependent; I leave them as an exercise for the student.

Title: Enumerate all possible distributions of n balls into k boxes

Body:
The exact problem i am referring to and the number of distributions for the  problem is computed here. I am interested in knowing those distributions explicitly.

For example, there are 5 balls and 3 boxes: one distribution is 2 balls in box 1, 2 in box 2, 1 in box 3 referred to as, say 221. Now i want to list all such possible distributions: -

212

131

104

.
.
.

One way is that i run the matlab command: perms([0,0,0,0,0,1,1,1]). This essentially generates all permutations of 5 balls and 2 sticks. but there is massive over-counting as the command perms does not recognize identical objects.

Body:
Very simple ... sort of.

function alloc(balls, boxes):

    if boxes = 1
        return [balls]
    else
       for n in range 0:balls
           return alloc(balls-n, boxes-1)

That's the basic recursion logic: pick each possible quantity of balls, then recur on the remaining balls and one box fewer.

The list-gluing methods will be language-dependent; I leave them as an exercise for the student.


问:
devise vs. devise_token_auth: How to handle authentication for both a web app and API
I'm writing an application that will primarily be accessed via API, but will also have views for editing via web app.

I would like to create a User model with authentication and authorization across both platforms.

I'm having trouble understanding the relationship between the devise and devise_token_auth libraries, other than that the former is recommended for most rails apps and the latter is great for API-only authentication.

For my case, what is the appropriate library to use, or should I be using both? Should I be generating the User model via devise and then adding the token auth to it? Do both systems use different authentication schemes? I'm just trying to understand why devise_token_auth exists apart from devise.

I'm also just a bit confused about the added complexity of token-based authentication. What would be wrong with simply having the users be registered and managed through devise, generating an API secret key for them, and then having them sign their API requests with that. Why the need for token based auth in the API?

答:
devise_token_auth is an advanced method of API authentication which may, or may not, be overkill for your application. Essentially, a new token is generated for each API request.

Depending on what your needs are, you may be fine with token-based authentication, or perhaps even HTTP Basic auth, which devise supports out of the box.


问:
Why does this output 10 for each loop? Isn't int a value type?
I was browsing through some C# examples and came upon this:

```<code>using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}
</code>```

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

```<code>int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);
</code>```

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.

答:
What you have is a closure.  It's when you make an anonymous function and use locally-scoped variables in it.

It doesn't make a copy of those variables.  It uses those variables.  Since you're increased i all the way up to 10, those anonymous functions will run using the same variable i.

If you want it to actually count to 10, you can make a new variable for the closure.

```<code>var j = i;
printers.Add(delegate { var d = j; Console.WriteLine(d); });
</code>```

See this question for more info:
What are 'closures' in .NET?

Body:
I was browsing through some C# examples and came upon this:

using System;
using System.Collections.Generic;

namespace ConsoleApp1
{
    class Program
    {
        delegate void Printer();

        static void Main()
        {
            List<Printer> printers = new List<Printer>();

            for (int i = 0; i < 10; i++)
            {
                printers.Add(delegate { var d = i; Console.WriteLine(d); });
            }

            foreach (var printer in printers)
            {
                printer();
            }
            Console.ReadLine();
        }
    }
}

I expected this to output 0 through 9, since an int is a value type and d should be set to whatever i is at that time.

However, this outputs 10 ten times.

Why is this? Is the int not a reference instead inside the delegate?

Note: I am not trying to solve a problem here, just understand how this works, in a way that is re-applicable.

Edit: Example of my confusion

int i = 9;
int d = 8;
d = i;
i++;
Console.WriteLine(d);

This would show that i is passed as a value, and not a reference. I expected the same inside the closure, but was surprised.

Thanks for the comments, I understand more now, the code in the delegate isn't executed till after and it uses i that exists outside of it in a generic class made by the compiler?

In javascript this same kind of code outputs 1-9, which is what I expected in C#. https://jsfiddle.net/L21xLaq0/2/.

Body:
What you have is a closure.  It's when you make an anonymous function and use locally-scoped variables in it.

It doesn't make a copy of those variables.  It uses those variables.  Since you're increased i all the way up to 10, those anonymous functions will run using the same variable i.

If you want it to actually count to 10, you can make a new variable for the closure.

var j = i;
printers.Add(delegate { var d = j; Console.WriteLine(d); });

See this question for more info:
What are 'closures' in .NET?