问:
Python function equivalent to R's `pretty()`?
I'm replicating some R code in Python.

I've tripped up on R's pretty().

All I need is pretty(x), where x is some numeric.

Roughly, the function "computes pretty breakpoints" as a sequence of several "round" values. I'm not sure there is a Python equivalent and I'm not having much luck with Google.

Edit: More specifically, this is the Description entry in he help page for pretty:

Description: Compute a sequence of about n+1 equally spaced ‘round’ values which cover the range of the values in x. The values are chosen so that they are 1, 2 or 5 times a power of 10.

I looked into R's pretty.default() to see what exactly R is doing with the function but it eventually uses .Internal() -- which usually leads to dark R magic. I thought I'd ask around before diving in.

Does anyone know if Python has something equivalent to R's pretty()?

答:
I thought that the psuedocode posted by Lewis Fogden looked familiar, and we indeed once coded that pseudocode in C++ for a plotting routine (to determine pretty axis labels). I quickly translated it to Python, not sure if this is similar to pretty() in R, but I hope it helps or is useful to anyone..

```<code>import numpy as np

def nicenumber(x, round):
    exp = np.floor(np.log10(x))
    f   = x / 10**exp

    if round:
        if f < 1.5:
            nf = 1.
        elif f < 3.:
            nf = 2.
        elif f < 7.:
            nf = 5.
        else:
            nf = 10.
    else:
        if f <= 1.:
            nf = 1.
        elif f <= 2.:
            nf = 2.
        elif f <= 5.:
            nf = 5.
        else:
            nf = 10.

    return nf * 10.**exp

def pretty(low, high, n):
    range = nicenumber(high - low, False)
    d     = nicenumber(range / (n-1), True)
    miny  = np.floor(low  / d) * d
    maxy  = np.ceil (high / d) * d
    return np.arange(miny, maxy+0.5*d, d)
</code>```

This produces for example:

```<code>pretty(0.5, 2.56, 10)
pretty(0.5, 25.6, 10)
pretty(0.5, 256, 10 )
pretty(0.5, 2560, 10)
</code>```

[ 0.5  1.   1.5  2.   2.5  3. ]

[ 0.   5.  10.  15.  20.  25.  30.]

[   0.   50.  100.  150.  200.  250.  300.]

[    0.   500.  1000.  1500.  2000.  2500.  3000.]

Body:
I thought that the psuedocode posted by Lewis Fogden looked familiar, and we indeed once coded that pseudocode in C++ for a plotting routine (to determine pretty axis labels). I quickly translated it to Python, not sure if this is similar to pretty() in R, but I hope it helps or is useful to anyone..

import numpy as np

def nicenumber(x, round):
    exp = np.floor(np.log10(x))
    f   = x / 10**exp

    if round:
        if f < 1.5:
            nf = 1.
        elif f < 3.:
            nf = 2.
        elif f < 7.:
            nf = 5.
        else:
            nf = 10.
    else:
        if f <= 1.:
            nf = 1.
        elif f <= 2.:
            nf = 2.
        elif f <= 5.:
            nf = 5.
        else:
            nf = 10.

    return nf * 10.**exp

def pretty(low, high, n):
    range = nicenumber(high - low, False)
    d     = nicenumber(range / (n-1), True)
    miny  = np.floor(low  / d) * d
    maxy  = np.ceil (high / d) * d
    return np.arange(miny, maxy+0.5*d, d)

This produces for example:

pretty(0.5, 2.56, 10)
pretty(0.5, 25.6, 10)
pretty(0.5, 256, 10 )
pretty(0.5, 2560, 10)

[ 0.5  1.   1.5  2.   2.5  3. ]

[ 0.   5.  10.  15.  20.  25.  30.]

[   0.   50.  100.  150.  200.  250.  300.]

[    0.   500.  1000.  1500.  2000.  2500.  3000.]


来源: stackexchange

问:
Why is the image not displaying
I have the webserver and the sql server working fin but when i run the file no image is displayed and characters like �})>�}(���>��j|��0�Ry>�s appear instead. What am i missing? the cobe below is part of the page.</p>

```<code>    <body>
         <?php
    $servername = "localhost";
    $user = "root";
    $passw = "Ajax3617";
    $dbname="sailingdb";
    // Create connection
    $conn = new mysqli($servername, $user, $passw, $dbname);

    $sql = "SELECT picturefile FROM pictures";
    $result = mysqli_query($conn,$sql);
    while ($row = mysqli_fetch_assoc($result))  {

echo '<img src="'.$row['picturefile'].'" width="175" height="200" />';

    } ?>
</body>
</html>
</code>```

答:
```<code>echo "<img src="'.$row['picturefile']."' >";
</code>```

should be replaced by

```<code>echo '<img src="'.$row['picturefile'].'" >';
</code>```

ContentLicense: CC BY-SA 3.0

Title: Why is the image not displaying

Body:
I have the webserver and the sql server working fin but when i run the file no image is displayed and characters like �})>�}(���>��j|��0�Ry>�s appear instead. What am i missing? the cobe below is part of the page.

         <?php
    $servername = "localhost";
    $user = "root";
    $passw = "Ajax3617";
    $dbname="sailingdb";
    // Create connection
    $conn = new mysqli($servername, $user, $passw, $dbname);

    $sql = "SELECT picturefile FROM pictures";
    $result = mysqli_query($conn,$sql);
    while ($row = mysqli_fetch_assoc($result))  {

echo '';

    } ?>

Body:
echo "<img src="'.$row['picturefile']."' >";

should be replaced by

echo '<img src="'.$row['picturefile'].'" >';


问:
MVC architecture control flow
I am a bit confused how the three components - Model, View, Controller - interact with each other in MVC architecture. Sometimes I feel I know how MVC works and sometimes I feel I don't know its inner working properly.

What I know about MVC architecture is -

User requests are intercepted by Controller whether it is a URL

request or any event raised by the user on the page.

Then controller processes the user input and talks to the Model.

Model prepares data and sends back to the Controller.

Finally, controller hands over data back to the view and is displayed to the user.

Here in my opinion, View never talks to the Model directly. The interaction between the View and Model will be handled by the Controller only.

So far so good!

But when I see diagrams like below then I get confused. In the below diagram, the left arrow shows that View component can also interact with the Model component.

Also in this code-project article, it is written that "A model is accessible by both controller and view" and "a view can use model to display data".

So kindly clarify whether a model is accessible only by the controller or by both the controller and the view. And if second one is also correct then in what situation this is possible. I work on ASP.NET MVC Framework and here any interaction is done through a controller object. I have never encountered a situation where a view directly talks to the model object.

答:
There's MVC, the pattern, and MVC, the web application framework developed by Microsoft and confusingly named after the pattern, so it's best to break those two out and discuss separately.

In MVC, the pattern, you'll find the following:

Model - Contains all the business logic for the application, including logic for how to "build" itself, whether via database queries or some other method.

View - provides a representation of the model for the UI

Controller - wires the model to the view

In MVC, the web application framework:

Model - There's not one. More appropriately, the model is probably some combination of one or more entity classes, a DAL layer and one or more view models.

View - Pretty much the same as MVC, the pattern

Controller - Wires the model to the view, but takes on much more responsibility as well. Could be responsible for querying entities from the database, mapping to view models, creating components for the view, etc.

Despite the name, the MVC framework only loosely implements the MVC pattern. However, in both, the Model is accessible by both the controller and the view, so your fundamental understanding there is flawed. In the case of the MVC framework, though, you could say that only the view model is accessible to the view. Since the "Model" in the MVC framework is not just one thing, there are constituent parts that should not be accessible by the view, namely: the DAL layer and potentially the entity, unless the entity is doing double duty as the view model, as well.

Title: MVC architecture control flow


问:
mysqldump unknown option no beep
I'm running MySQL 5.5 on Windows, attempting a mysqldump:

```<code> "C:\WebServer\MySQL Server 5.5\bin\mysqldump.exe" -u user -ppassword database > "C:\backup.sql"
</code>```

But get error:

mysqldump: unknown option '--no beep'

This is a pretty basic command, and works on two other development boxes, so not sure what is causing this?

答:
Deleting the no-beep option worked for me, but I had to change the my.ini file in my windows directory!
I'm using windows 10 by the way.

ContentLicense: CC BY-SA 4.0

Title: mysqldump unknown option no beep

Body:
I'm running MySQL 5.5 on Windows, attempting a mysqldump:

 "C:\WebServer\MySQL Server 5.5\bin\mysqldump.exe" -u user -ppassword database > "C:\backup.sql"

But get error:

mysqldump: unknown option '--no beep'

This is a pretty basic command, and works on two other development boxes, so not sure what is causing this?


问:
PowerShell script fails
I am trying to use the PowerShell script below with PSv5 to automate some manual processes but it keeps failing and I cannot figure out why. When I try to debug it in ISE, I get the following error and no output file is generated:

Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:15 char:53
+ $HeaderLine, ${$DestinationFile} = Get-Content -Path <<<<  $SourceFile.FullName
+ CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
```

<pre class="lang-bsh prettyprint-override"><code># BEGIN SCRIPT
#
# Collect all the files in the directory
$SoureFiles = Get-ChildItem -Path 'C:\raw' -Filter '*.txt'

# Create the destination file
$DestinationFile = (New-Item -Path 'c:\done' `
-Name ('CombinedSources-' + (Get-Date -Format 'ddMMMyyyy') + '.txt') `
-ItemType File -Force).FullName
$DestinationFile

# Loop source, files, remove header line, append to the destination file
ForEach ($SourceFile in $SoureFiles)
{
$HeaderLine, ${$DestinationFile} = Get-Content -Path $SourceFile.FullName
${$DestinationFile}`
| Out-File -FilePath $DestinationFile -Append
}

# Sort the Destination file content and replace with sorted unique lines
(Get-Content -Path $DestinationFile `
| Sort-Object { [string]$_.split(',')[1,2] } ) `
| Get-Unique `
| Out-File -FilePath $DestinationFile -Force
#
#END SCRIPT
</code>```

答:
This worked for me</p>

```<code># BEGIN SCRIPT
#
# Collect all the files in the directory
$SoureFiles = Get-ChildItem -Path 'C:\raw' -Filter '*.txt'

# Create the destination file
$DestinationFile = (New-Item -Path 'c:\done' -Name ('CombinedSources-' + (Get-Date -Format 'ddMMMyyyy') + '.txt') -ItemType File -Force).FullName

# Loop source, files, remove header line, append to the destination file
ForEach ($SourceFile in $SoureFiles)
{
   Get-Content -Path $SourceFile.FullName | Out-File -FilePath $DestinationFile -Append
}

(Get-Content -Path $DestinationFile | Sort-Object { [string]$_.split(',')[1,2] } ) | Get-Unique | Out-File -FilePath $DestinationFile -Force
</code>```

Title: PowerShell script fails

Body:
I am trying to use the PowerShell script below with PSv5 to automate some manual processes but it keeps failing and I cannot figure out why. When I try to debug it in ISE, I get the following error and no output file is generated:

Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:15 char:53
+ $HeaderLine, ${$DestinationFile} = Get-Content -Path <<<<  $SourceFile.FullName
+ CategoryInfo          : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand

# BEGIN SCRIPT
#
# Collect all the files in the directory
$SoureFiles = Get-ChildItem -Path 'C:\raw' -Filter '*.txt'

# Create the destination file
$DestinationFile = (New-Item -Path 'c:\done' `
-Name ('CombinedSources-' + (Get-Date -Format 'ddMMMyyyy') + '.txt') `
-ItemType File -Force).FullName
$DestinationFile

# Loop source, files, remove header line, append to the destination file
ForEach ($SourceFile in $SoureFiles)
{
$HeaderLine, ${$DestinationFile} = Get-Content -Path $SourceFile.FullName
${$DestinationFile}`
| Out-File -FilePath $DestinationFile -Append
}

# Sort the Destination file content and replace with sorted unique lines
(Get-Content -Path $DestinationFile `
| Sort-Object { [string]$_.split(',')[1,2] } ) `
| Get-Unique `
| Out-File -FilePath $DestinationFile -Force
#
#END SCRIPT

Body:
This worked for me

# BEGIN SCRIPT
#
# Collect all the files in the directory
$SoureFiles = Get-ChildItem -Path 'C:\raw' -Filter '*.txt'

# Create the destination file
$DestinationFile = (New-Item -Path 'c:\done' -Name ('CombinedSources-' + (Get-Date -Format 'ddMMMyyyy') + '.txt') -ItemType File -Force).FullName

# Loop source, files, remove header line, append to the destination file
ForEach ($SourceFile in $SoureFiles)
{
   Get-Content -Path $SourceFile.FullName | Out-File -FilePath $DestinationFile -Append
}

(Get-Content -Path $DestinationFile | Sort-Object { [string]$_.split(',')[1,2] } ) | Get-Unique | Out-File -FilePath $DestinationFile -Force


问:
php project works on linux server but not on windows
So I have two copies of exactly the same project. The configuration of the servers is the same. The script has to write some data to database and then redirect the user to the appropriate page with the header() function depending on the data written to the database.

It works fine on the Linux server, though in Windows it tries to redirect first, and then write to the database, which, of course, doesn't work, because there's no data written. If I comment out the header() function in the Windows version, it writes to the database, but doesn't do the redirection.

How can two exact scripts work so different?

Edit:

I'm not sure how do I show the code, since there's so much of it and it's so scattered. But basically, it's just a function that sets the header() and then the function that writes to db. And when it redirects, it should select the data that was written to the database and display it.

That's a very simplified version of it. Bear in mind, the header is set BEFORE the writing to the database. I believe this to be the culprit, but I didn't write the code, and I can't change the architecture of it, since it works perfectly on 2 Linux servers, I just don't understand how. I just need to make it work on the Windows server.

It makes the redirection ok, I mean it sends me to the link that it should send me to, but it doesn't write to the database. But it I comment out the header() part, it writes to the database, but doesn't make the redirection.

答:
The documentation for the header function states the following:

Note:

HTTP/1.1 requires an absolute URI as
  argument to » Location: including the
  scheme, hostname and absolute path,
  but some clients accept relative URIs.
  You can usually use
  $_SERVER['HTTP_HOST'],
  $_SERVER['PHP_SELF'] and dirname() to
  make an absolute URI from a relative
  one yourself:

Are you using a relative URL? It's possible that LAMP likes a relative URL more then WAMP does. It is a simple test, so worth a shot.

ContentLicense: CC BY-SA 2.5


问:
How do you turn off (or hide) the seconds y axis scale on a combination chart in openpyxl?
How do you turn off (or hide) the seconds y axis scale on a combination chart in openpyxl?

I can find the xml difference by comparing the before and after changes to hide the scale (I just change the excel file extension to '.zip' to access the xml):

```<code>    -<c:valAx>
<c:axId val="156672520"/>
-<c:scaling>
<c:orientation val="minMax"/>
</c:scaling>
<c:delete val="0"/>
<c:axPos val="r"/>
<c:majorGridlines/>
<c:numFmt sourceLinked="1" formatCode="0.0"/>
<c:majorTickMark val="out"/>
<c:minorTickMark val="none"/>
<c:tickLblPos val="none"/>     # this changes from 'nextTo'
<c:crossAx val="207247000"/>
<c:crosses val="max"/>
<c:crossBetween val="between"/>
</c:valAx>
</code>```

I've tried this (last few lines are the 'tickLblPos' ):

```<code>    mainchart = LineChart()
mainchart.style = 12
v2 = Reference(WorkSheetOne, min_col=1, min_row=2+CombBarLineDataOffsetFromTop, max_row=3+CombBarLineDataOffsetFromTop, max_col=13)
mainchart.add_data(v2, titles_from_data=True, from_rows=True)

mainchart.layout = Layout(
    ManualLayout(
    x=0.12, y=0.25, # position from the top
    h=0.9, w=0.75, # this is scaling the chart into the container
    xMode="edge",
    yMode="edge",
    )
)

mainchart.title = "Chart Title"

# Style the lines
s1 = mainchart.series[0]
#Marker type
s1.marker.symbol = "diamond" # triangle
s1.marker.size = 9
s1.marker.graphicalProperties.solidFill = "C00000" # Marker filling
s1.marker.graphicalProperties.line.solidFill = "000000" # Marker outline
s1.graphicalProperties.line.noFill = False
# Line color
s1.graphicalProperties.line.solidFill = "000000" # line color

s2 = mainchart.series[1]
s2.graphicalProperties.line.solidFill = "000000"
s2.graphicalProperties.line.dashStyle = "dash"

mainchart.dataLabels = DataLabelList()

mainchart.dataLabels.showVal = False
mainchart.dataLabels.dLblPos = 't'
mainchart.height = 15
mainchart.width = 39

#Create the Chart
chart2 = BarChart()
chart2.type = "col"
chart2.style = 10  # simple bar
chart2.y_axis.axId = 0

dataone = Reference(WorkSheetOne, min_col=2, min_row=CombBarLineDataOffsetFromTop+1, max_row=CombBarLineDataOffsetFromTop+1, max_col=13 )
doneseries = Series(dataone, title="Series Title")
chart2.append(doneseries)

cats = Reference(WorkSheetOne, min_col=2, min_row=CombBarLineDataOffsetFromTop, max_row=CombBarLineDataOffsetFromTop, max_col=13)
chart2.set_categories(cats)

# Set the series for the chart data
series3Total = chart2.series[0]
fill3Total =  PatternFillProperties(prst="pct5")
fill3Total.foreground = ColorChoice(srgbClr='996633') # brown
fill3Total.background = ColorChoice(srgbClr='996633')
series3Total.graphicalProperties.pattFill = fill3Total

chart2.dataLabels = DataLabelList()
chart2.dataLabels.showVal = False
chart2.shape = 2

mainchart.y_axis.crosses = "max"
mainchart.y_axis.tickLblPos = "none" # nextTo -- this doesn't work

mainchart += chart2

WorkSheetOne.add_chart(mainchart, 'A1')
</code>```

How can I translate the difference in the XML to an attribute with openpyxl?

答:
The problem here is with some of default values for some attributes which use 3-valued logic at times so that None != "none", ie. <c:tickLblPos /> != <c:tickLblPos val="none"/> because the default is "nextTo". This plays havoc with the Python semantics (3-valued logic is always wrong) where the default is not to set an attribute if the value is None in Python. This really only affects ChartML and I've added some logic to the descriptors for the relevant objects so that "none" will be written where required.

But this code isn't publicly available yet. Get in touch with my by e-mail if you'd like a preview.

Body:
How do you turn off (or hide) the seconds y axis scale on a combination chart in openpyxl?

I can find the xml difference by comparing the before and after changes to hide the scale (I just change the excel file extension to '.zip' to access the xml):

    -<c:valAx>
<c:axId val="156672520"/>
-<c:scaling>
<c:orientation val="minMax"/>
</c:scaling>
<c:delete val="0"/>
<c:axPos val="r"/>
<c:majorGridlines/>
<c:numFmt sourceLinked="1" formatCode="0.0"/>
<c:majorTickMark val="out"/>
<c:minorTickMark val="none"/>
<c:tickLblPos val="none"/>     # this changes from 'nextTo'
<c:crossAx val="207247000"/>
<c:crosses val="max"/>
<c:crossBetween val="between"/>
</c:valAx>

I've tried this (last few lines are the 'tickLblPos' ):

    mainchart = LineChart()
mainchart.style = 12
v2 = Reference(WorkSheetOne, min_col=1, min_row=2+CombBarLineDataOffsetFromTop, max_row=3+CombBarLineDataOffsetFromTop, max_col=13)
mainchart.add_data(v2, titles_from_data=True, from_rows=True)

mainchart.layout = Layout(
    ManualLayout(
    x=0.12, y=0.25, # position from the top
    h=0.9, w=0.75, # this is scaling the chart into the container
    xMode="edge",
    yMode="edge",
    )
)

mainchart.title = "Chart Title"

# Style the lines
s1 = mainchart.series[0]
#Marker type
s1.marker.symbol = "diamond" # triangle
s1.marker.size = 9
s1.marker.graphicalProperties.solidFill = "C00000" # Marker filling
s1.marker.graphicalProperties.line.solidFill = "000000" # Marker outline
s1.graphicalProperties.line.noFill = False
# Line color
s1.graphicalProperties.line.solidFill = "000000" # line color

s2 = mainchart.series[1]
s2.graphicalProperties.line.solidFill = "000000"
s2.graphicalProperties.line.dashStyle = "dash"

mainchart.dataLabels = DataLabelList()

mainchart.dataLabels.showVal = False
mainchart.dataLabels.dLblPos = 't'
mainchart.height = 15
mainchart.width = 39

#Create the Chart
chart2 = BarChart()
chart2.type = "col"
chart2.style = 10  # simple bar
chart2.y_axis.axId = 0

dataone = Reference(WorkSheetOne, min_col=2, min_row=CombBarLineDataOffsetFromTop+1, max_row=CombBarLineDataOffsetFromTop+1, max_col=13 )
doneseries = Series(dataone, title="Series Title")
chart2.append(doneseries)

cats = Reference(WorkSheetOne, min_col=2, min_row=CombBarLineDataOffsetFromTop, max_row=CombBarLineDataOffsetFromTop, max_col=13)
chart2.set_categories(cats)

# Set the series for the chart data
series3Total = chart2.series[0]
fill3Total =  PatternFillProperties(prst="pct5")
fill3Total.foreground = ColorChoice(srgbClr='996633') # brown
fill3Total.background = ColorChoice(srgbClr='996633')
series3Total.graphicalProperties.pattFill = fill3Total

chart2.dataLabels = DataLabelList()
chart2.dataLabels.showVal = False
chart2.shape = 2

mainchart.y_axis.crosses = "max"
mainchart.y_axis.tickLblPos = "none" # nextTo -- this doesn't work

mainchart += chart2

WorkSheetOne.add_chart(mainchart, 'A1')

How can I translate the difference in the XML to an attribute with openpyxl?


问:
Search within a big vector in C++
I have following vectors:

```<code>std::vector<A*> vec;
std::vector<std::pair<A*, A*>> vec_pair;
</code>```

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.

答:
I don't know yours exactly requirements but, if the order of element in vec_pair isn't important, I suppose you can substitute it with a std::multimap or, I suppose better, a std::unordered_multimap.

I mean (using a type A equal to int as example) that instead

```<code>   using A = int;

   std::vector<std::pair<A, A>> const vec_pair
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };
</code>```

you can use

```<code>   std::unordered_multimap<A, A> const cM
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };
</code>```

If you need that vec_pair is a vector of pairs, using the fact that vec_pair is constant (I understand correctly?) you can contruct a constant unordered multimap.

The advantage of this solution is that if you find that a key of the map isn't in vec, you can avoid the test for all the values with the same key.

More: if construct a set (or, better, an unordered_set) starting from vec (that is little, if I understand correctly, you can check the pairs as follows

```<code>   for ( auto ci = cM.cbegin() ; ci != cM.cend() ; )
    {
      auto val = ci->first;
      auto cnt = cM.count(val);

      if ( s.end() == s.find(val) )
       {
         for ( auto i = 0U ; i < cnt ; ++i )
            ++ci;
       }
      else for ( auto i = 0U ; i < cnt ; ++i, ++ci )
         if ( s.end() != s.find(ci->second) )
            std::cout << "- good for <" << val << ", " << ci->second
               << '>' << std::endl;
    }
</code>```

I know: isn't an elegant solution.

Another way is to use a combination of map and set (unorderd, better) and instead of

```<code>   std::vector<std::pair<A, A>> const vec_pair
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };
</code>```

use (or construct)

```<code>   std::unordered_map<A, std::unordered_set<A>> const cM
    { {1, {1, 2, 3, 4}}, {2, {1, 2, 3, 4}},
      {3, {1, 2, 3, 4}}, {4, {1, 2, 3, 4}} };
</code>```

In this case, the search part is more elegant (IMHO)

```<code>   for ( auto const & p : cM2 )
      if ( s.end() != s.find(p.first) )
         for ( auto const & sec : p.second )
            if ( s.end() != s.find(sec) )
            std::cout << "- good for <" << p.first << ", " << sec
               << '>' << std::endl;
</code>```

The following is a full compilable example for both solutions

```<code>#include <vector>
#include <utility>
#include <iostream>
#include <unordered_map>
#include <unordered_set>

int main()
 {
   using A = int;

   std::unordered_multimap<A, A> const cM
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };

   std::unordered_set<A> s { 4, 3 };

   for ( auto ci = cM.cbegin() ; ci != cM.cend() ; )
    {
      auto val = ci->first;
      auto cnt = cM.count(val);

      if ( s.end() == s.find(val) )
       {
         for ( auto i = 0U ; i < cnt ; ++i )
            ++ci;
       }
      else for ( auto i = 0U ; i < cnt ; ++i, ++ci )
         if ( s.end() != s.find(ci->second) )
            std::cout << "- good for <" << val << ", " << ci->second
               << '>' << std::endl;
    }

   std::unordered_map<A, std::unordered_set<A>> const cM2
    { {1, {1, 2, 3, 4}}, {2, {1, 2, 3, 4}},
      {3, {1, 2, 3, 4}}, {4, {1, 2, 3, 4}} };

   for ( auto const & p : cM2 )
      if ( s.end() != s.find(p.first) )
         for ( auto const & sec : p.second )
            if ( s.end() != s.find(sec) )
            std::cout << "- good for <" << p.first << ", " << sec
               << '>' << std::endl;
 }
</code>```

Title: Search within a big vector in C++

Body:
I have following vectors:

std::vector vec;
std::vector<std::pair> vec_pair;

vec_pair size is much more than vec size. I would like to find a pair within vec_pair which both members are inside vec.

contents of the vec_pair are constant. However after each iteration the contents of the vec will change and I would like to do the test again.

I know I can do a for loop and do the check. However considering size difference and recurrence of the job, I am looking for a smart and efficient way to do it.

Body:
I don't know yours exactly requirements but, if the order of element in vec_pair isn't important, I suppose you can substitute it with a std::multimap or, I suppose better, a std::unordered_multimap.

I mean (using a type A equal to int as example) that instead

   using A = int;

   std::vector<std::pair<A, A>> const vec_pair
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };

you can use

   std::unordered_multimap<A, A> const cM
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };

If you need that vec_pair is a vector of pairs, using the fact that vec_pair is constant (I understand correctly?) you can contruct a constant unordered multimap.

The advantage of this solution is that if you find that a key of the map isn't in vec, you can avoid the test for all the values with the same key.

More: if construct a set (or, better, an unordered_set) starting from vec (that is little, if I understand correctly, you can check the pairs as follows

   for ( auto ci = cM.cbegin() ; ci != cM.cend() ; )
    {
      auto val = ci->first;
      auto cnt = cM.count(val);

      if ( s.end() == s.find(val) )
       {
         for ( auto i = 0U ; i < cnt ; ++i )
            ++ci;
       }
      else for ( auto i = 0U ; i < cnt ; ++i, ++ci )
         if ( s.end() != s.find(ci->second) )
            std::cout << "- good for <" << val << ", " << ci->second
               << '>' << std::endl;
    }

I know: isn't an elegant solution.

Another way is to use a combination of map and set (unorderd, better) and instead of

   std::vector<std::pair<A, A>> const vec_pair
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };

use (or construct)

   std::unordered_map<A, std::unordered_set<A>> const cM
    { {1, {1, 2, 3, 4}}, {2, {1, 2, 3, 4}},
      {3, {1, 2, 3, 4}}, {4, {1, 2, 3, 4}} };

In this case, the search part is more elegant (IMHO)

   for ( auto const & p : cM2 )
      if ( s.end() != s.find(p.first) )
         for ( auto const & sec : p.second )
            if ( s.end() != s.find(sec) )
            std::cout << "- good for <" << p.first << ", " << sec
               << '>' << std::endl;

The following is a full compilable example for both solutions

#include <vector>
#include <utility>
#include <iostream>
#include <unordered_map>
#include <unordered_set>

int main()
 {
   using A = int;

   std::unordered_multimap<A, A> const cM
    { {1, 1}, {1, 2}, {1, 3}, {1, 4},
      {2, 1}, {2, 2}, {2, 3}, {2, 4},
      {3, 1}, {3, 2}, {3, 3}, {3, 4},
      {4, 1}, {4, 2}, {4, 3}, {4, 4} };

   std::unordered_set<A> s { 4, 3 };

   for ( auto ci = cM.cbegin() ; ci != cM.cend() ; )
    {
      auto val = ci->first;
      auto cnt = cM.count(val);

      if ( s.end() == s.find(val) )
       {
         for ( auto i = 0U ; i < cnt ; ++i )
            ++ci;
       }
      else for ( auto i = 0U ; i < cnt ; ++i, ++ci )
         if ( s.end() != s.find(ci->second) )
            std::cout << "- good for <" << val << ", " << ci->second
               << '>' << std::endl;
    }

   std::unordered_map<A, std::unordered_set<A>> const cM2
    { {1, {1, 2, 3, 4}}, {2, {1, 2, 3, 4}},
      {3, {1, 2, 3, 4}}, {4, {1, 2, 3, 4}} };

   for ( auto const & p : cM2 )
      if ( s.end() != s.find(p.first) )
         for ( auto const & sec : p.second )
            if ( s.end() != s.find(sec) )
            std::cout << "- good for <" << p.first << ", " << sec
               << '>' << std::endl;
 }


问:
c free() function question

Possible Duplicate:

  C programming : How does free know how much to free?

Hi,

when i have following code:

```<code>void *ptr = malloc(100); // alloc 100 bytes
// do sth
free(ptr);
</code>```

how does the free() function know how much space has to be freed?

thank you!

--

ok i have found other questions asking the same, please close - sorry

答:
It's implementation dependent but usually the underlying system mas a map of addresses to blocks and it knows the size from that memory map. </p>

<p>Here is the striped down code from glibc which shows it doing basically what what I just said. </p>

```<code>void fREe(Void_t* mem)
{
  arena *ar_ptr;
  mchunkptr p;
  if (__free_hook != NULL) {
    (*__free_hook)(mem, NULL);
  }

  if (mem == 0)                              /* free(0) has no effect */
    return;

  p = mem2chunk(mem);

  if (chunk_is_mmapped(p))                       /* release mmapped memory. */
  {
    munmap_chunk(p);
    return;
  }

  ar_ptr = arena_for_ptr(p);
  chunk_free(ar_ptr, p);
  (void)mutex_unlock(&ar_ptr->mutex);
}
</code>```

Title: c free() function question

Body:
Possible Duplicate:

  C programming : How does free know how much to free?

Hi,

when i have following code:

void *ptr = malloc(100); // alloc 100 bytes
// do sth
free(ptr);

how does the free() function know how much space has to be freed?

thank you!

--

ok i have found other questions asking the same, please close - sorry

Body:
It's implementation dependent but usually the underlying system mas a map of addresses to blocks and it knows the size from that memory map.

Here is the striped down code from glibc which shows it doing basically what what I just said.

void fREe(Void_t* mem)
{
  arena *ar_ptr;
  mchunkptr p;
  if (__free_hook != NULL) {
    (*__free_hook)(mem, NULL);
  }

  if (mem == 0)                              /* free(0) has no effect */
    return;

  p = mem2chunk(mem);

  if (chunk_is_mmapped(p))                       /* release mmapped memory. */
  {
    munmap_chunk(p);
    return;
  }

  ar_ptr = arena_for_ptr(p);
  chunk_free(ar_ptr, p);
  (void)mutex_unlock(&ar_ptr->mutex);
}


问:
Event Listeners not displaying in Chrome Devtools - Linux
Are there any settings or things that might block the event Listeners from displaying correctly in devtools?

Linux Mint 18.1 64-bit Chrome version: Version 58.0.3029.81 (64-bit)

答: Issue is fixed with latest version. 59.X</p>


问:
what is the best way of doing a remote development using PyCharm community version
PyCharm Professional has a nice feature of remote development -- developing codes on your local machine and running them on a remote server. Without PyCharm Professional, what would be a good way of mimicking this feature? I really like PyCharm so I won't give up for another IDE. I used to package the codes into an egg file and sftp it to a remove server but this is cumbersome, since I have to make the setup files, etc. </p>

<p>Thanks in advance for your suggestion. </p>

答:
use winscp to keep your remote directory in sync

install ssh

add external tool of "run remote" (I assume this is available)

ssh user@remote.com -t "cd /path/to/proj && python myproj.py"

if you have ssh keys setup it should just work ... if not you will probably be prompted for a password

Body:
PyCharm Professional has a nice feature of remote development -- developing codes on your local machine and running them on a remote server. Without PyCharm Professional, what would be a good way of mimicking this feature? I really like PyCharm so I won't give up for another IDE. I used to package the codes into an egg file and sftp it to a remove server but this is cumbersome, since I have to make the setup files, etc.

Thanks in advance for your suggestion.


问:
what's the best indexing for votes table?
Here is my query:

```<code>SELECT qa.id,
       qa.subject,
       qa.category cat,
       qa.keywords tags,
       qa.body_html,
       qa.amount,
       qa.visibility,
       qa.date_time,
       COALESCE(u.reputation, 'N') reputation,
       COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'unknown') name,
       COALESCE(u.avatar, 'anonymous.png') avatar,

  (SELECT COALESCE(sum(vv.value),0)
   FROM votes vv
   WHERE qa.id = vv.post_id
     AND 15 = vv.table_code) AS total_votes,

  (SELECT COALESCE(sum(vt.total_viewed),0)
   FROM viewed_total vt
   WHERE qa.id = vt.post_id
     AND 15 = vt.table_code
   LIMIT 1) AS total_viewed
FROM qanda qa
LEFT JOIN users u ON qa.author_id = u.id
AND qa.visibility = 1
WHERE qa.type = 0
ORDER BY qa.date_time DESC
LIMIT 0,
      11;
</code>```

And here is the result of EXPLAIN:

See? the last row (vv) doesn't benefit any index. Also here are the current indexes on the votes table:

Anyway, what's your suggestion? What index do I need to make the performance more better?

答:
I think you need to move qa.visibility = 1 from the LEFT JOIN..ON to the WHERE.  Once you have done that, have these indexes:

```<code>qanda:  INDEX(visibility, type, date_time)  -- date_time must be last
</code>```

This will completely handle the WHERE, ORDER BY and LIMIT -- this may be the biggest boost in performance.

```<code>vv and vt:  INDEX(post_id, table_code) -- in either order
</code>```

You seem to have (post_id, table_code, user_id).  If that is unique, then promote it to be the PRIMARY KEY and get rid of id; this will give an extra little boost.

I assume users has PRIMARY KEY(id)?

You don't need LIMIT 1 on the vt subquery.

If you need to discuss this further, please provide SHOW CREATE TABLE for each table.

Body:
Here is my query:

SELECT qa.id,
       qa.subject,
       qa.category cat,
       qa.keywords tags,
       qa.body_html,
       qa.amount,
       qa.visibility,
       qa.date_time,
       COALESCE(u.reputation, 'N') reputation,
       COALESCE(CONCAT(u.user_fname, ' ', u.user_lname), 'unknown') name,
       COALESCE(u.avatar, 'anonymous.png') avatar,

  (SELECT COALESCE(sum(vv.value),0)
   FROM votes vv
   WHERE qa.id = vv.post_id
     AND 15 = vv.table_code) AS total_votes,

  (SELECT COALESCE(sum(vt.total_viewed),0)
   FROM viewed_total vt
   WHERE qa.id = vt.post_id
     AND 15 = vt.table_code
   LIMIT 1) AS total_viewed
FROM qanda qa
LEFT JOIN users u ON qa.author_id = u.id
AND qa.visibility = 1
WHERE qa.type = 0
ORDER BY qa.date_time DESC
LIMIT 0,
      11;

And here is the result of EXPLAIN:

See? the last row (vv) doesn't benefit any index. Also here are the current indexes on the votes table:

Anyway, what's your suggestion? What index do I need to make the performance more better?

Body:
I think you need to move qa.visibility = 1 from the LEFT JOIN..ON to the WHERE.  Once you have done that, have these indexes:

qanda:  INDEX(visibility, type, date_time)  -- date_time must be last

This will completely handle the WHERE, ORDER BY and LIMIT -- this may be the biggest boost in performance.

vv and vt:  INDEX(post_id, table_code) -- in either order

You seem to have (post_id, table_code, user_id).  If that is unique, then promote it to be the PRIMARY KEY and get rid of id; this will give an extra little boost.

I assume users has PRIMARY KEY(id)?

You don't need LIMIT 1 on the vt subquery.

If you need to discuss this further, please provide SHOW CREATE TABLE for each table.


问:
Why is my code jumping out of a loop In php
I am writing a project on web scraping using simple HTML DOM parser. I scrape web pages from my database, extract contents and store then in database. The code is working fine with the first URL, but on the remaining URL it just break out of the loop. Below is my code.

```<code>include_once('Connections/elecom_connect.php');
include_once('dom/simple_html_dom.php');

mysqli_select_db($elecom_connect,$database_elecom_connect);
$sql = "SELECT * FROM link_data";
$result_links = array();
$result_cates = '';
$result_subs = '';
$result_names = '';
$num = -1;
$count = 0;

$img = '.image-wrapper img';
$brand = 'h2.title span.brand';
$name = 'h2.title span.name';
$price = 'span.price-box';
$link = 'section.products a.link';

$site = new simple_html_dom();

$query = mysqli_query($elecom_connect,$sql);

if (!$query){
    echo 'Database error: ' .    mysqli_error($elecom_connect);
}

while ($row = mysqli_fetch_array($query)) {
    $result_links[] =  $row;
}

foreach($result_links as $link){
    $var = $link['link'];
    if (!empty($var)) {
        var_dump($var);

        $site->load_file($var);
        if (!empty($site)) {
            $currentImg = $site->find($img);
            $currentBrand = $site->find($brand);
            $currentName = $site->find($name);
            $currentPrice = $site->find($price);
            $currentLink = $site->find($link);

            $rid = $link['id'];
            $rcates = $link['link_category'];
            $rsubs = $link['link_subcategory'];
            $rnames = $link['link_name'];
            if (!empty($currentImg)) {
                foreach($currentImg as $im){
                    $count++;

                    if($count % 2 == 0 && $count < 40){
                        $num++;

                        $cImg = $im->src;
                        $cBrand = "<p>".$currentBrand[$num]->plaintext."</p>";
                        $cName = "<p>".$currentName[$num]->plaintext."</p>";
                        $cPrice = "<p>".$currentPrice[$num]->plaintext."</p>";
                        //$cLink = $currentLink[$num]->href;

                        $content = file_get_contents($cImg);
                        //Store in the filesystem.
                        $save_path = "cachedPages/$rid.$num.jpg";
                        file_put_contents($save_path,$content);

                        $insertSQL = "INSERT INTO item_detail (item_name, item_brand, item_price, item_img, item_cate, item_sub_cate,filter_by) VALUES ('$cName', '$cBrand', '$cPrice','$save_path','$rcates','$rsubs','$rnames')";

                        mysqli_select_db($elecom_connect,$database_elecom_connect);
                        $Result1 = mysqli_query($elecom_connect,$insertSQL) or die(mysqli_error(          $elecom_connect));

                        echo 'Success';

                    }
                }
            }

        }
    }
    $site->clear();
}
</code>```

Here is the error code I get.

Fatal error: Uncaught Error: Call to a member function find() on null in dom/simple_html_dom.php:1113 Stack trace: #0

What should I do.?

答:
You replace the whole array for each row so only the last URL will ever be scraped.</p>

```<code>$result_links = array();
while ($row = mysqli_fetch_array($query))
{
    array_push($result_links, $row);
}
</code>```

Body:
I am writing a project on web scraping using simple HTML DOM parser. I scrape web pages from my database, extract contents and store then in database. The code is working fine with the first URL, but on the remaining URL it just break out of the loop. Below is my code.

include_once('Connections/elecom_connect.php');
include_once('dom/simple_html_dom.php');

mysqli_select_db($elecom_connect,$database_elecom_connect);
$sql = "SELECT * FROM link_data";
$result_links = array();
$result_cates = '';
$result_subs = '';
$result_names = '';
$num = -1;
$count = 0;

$img = '.image-wrapper img';
$brand = 'h2.title span.brand';
$name = 'h2.title span.name';
$price = 'span.price-box';
$link = 'section.products a.link';

$site = new simple_html_dom();

$query = mysqli_query($elecom_connect,$sql);

if (!$query){
    echo 'Database error: ' .    mysqli_error($elecom_connect);
}

while ($row = mysqli_fetch_array($query)) {
    $result_links[] =  $row;
}

foreach($result_links as $link){
    $var = $link['link'];
    if (!empty($var)) {
        var_dump($var);

        $site->load_file($var);
        if (!empty($site)) {
            $currentImg = $site->find($img);
            $currentBrand = $site->find($brand);
            $currentName = $site->find($name);
            $currentPrice = $site->find($price);
            $currentLink = $site->find($link);

            $rid = $link['id'];
            $rcates = $link['link_category'];
            $rsubs = $link['link_subcategory'];
            $rnames = $link['link_name'];
            if (!empty($currentImg)) {
                foreach($currentImg as $im){
                    $count++;

                    if($count % 2 == 0 && $count < 40){
                        $num++;

                        $cImg = $im->src;
                        $cBrand = "
".$currentBrand[$num]->plaintext."
";
                        $cName = "
".$currentName[$num]->plaintext."
";
                        $cPrice = "
".$currentPrice[$num]->plaintext."
";
                        //$cLink = $currentLink[$num]->href;

                        $content = file_get_contents($cImg);
                        //Store in the filesystem.
                        $save_path = "cachedPages/$rid.$num.jpg";
                        file_put_contents($save_path,$content);

                        $insertSQL = "INSERT INTO item_detail (item_name, item_brand, item_price, item_img, item_cate, item_sub_cate,filter_by) VALUES ('$cName', '$cBrand', '$cPrice','$save_path','$rcates','$rsubs','$rnames')";

                        mysqli_select_db($elecom_connect,$database_elecom_connect);
                        $Result1 = mysqli_query($elecom_connect,$insertSQL) or die(mysqli_error(          $elecom_connect));

                        echo 'Success';

                    }
                }
            }

        }
    }
    $site->clear();
}

Here is the error code I get.

Fatal error: Uncaught Error: Call to a member function find() on null in dom/simple_html_dom.php:1113 Stack trace: #0

What should I do.?

Body:
You replace the whole array for each row so only the last URL will ever be scraped.

$result_links = array();
while ($row = mysqli_fetch_array($query))
{
    array_push($result_links, $row);
}


问:
DocuSign API Explorer - Creating a draft envelope with a document and recipient
I am trying to create a a draft envelope with a document and a recipient through DocuSign API Explorer using my DocuSign Developer Sandbox account.

Despite a SUCCESS response, the actual envelope contains neither the document or the recipient I included in the Request. Where am I going wrong?

Here is the Request XML:

```<code><envelopeDefinition
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.docusign.com/restapi">
    <documents>
        <documentBase64><Base64BytesHere></documentBase64>
    </documents>
    <emailSubject>Test from API Explorer</emailSubject>
    <recipients>
        <signers>
            <email>nobody@nobody.com</email>
            <name>John Smith</name>
        </signers>
    </recipients>
    <status>created</status>
</envelopeDefinition>
</code>```

Here is the empty envelope screenshot

答:
You're missing some parameters for the document and recipient objects, for instance you need to add a documentId and documentName for the document in addition to the document bytes.

Here's what a full XML request should look like:

```<code><envelopeDefinition xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.docusign.com/restapi">
    <emailSubject>Test Subject</emailSubject>
    <documents>
      <document>
        <name>document.pdf</name>
        <documentId>1</documentId>
        <documentBase64><Base64BytesHere></documentBase64>
      </document>
    </documents>
    <recipients>
        <signers>
            <tabs>
                <signHereTabs>
                  <signHereTab>
                    <pageNumber>1</pageNumber>
                    <documentId>1</documentId>
                    <xPosition>100</xPosition>
                    <yPosition>100</yPosition>
                  </signHereTab>
                </signHereTabs>
            </tabs>
            <routingOrder>1</routingOrder>
            <recipientId>1</recipientId>
            <name>My Name</name>
            <email>email@email.com</email>
        </signers>
    </recipients>
    <status>created</status>
</envelopeDefinition>
</code>```

Body:
I am trying to create a a draft envelope with a document and a recipient through DocuSign API Explorer using my DocuSign Developer Sandbox account.

Despite a SUCCESS response, the actual envelope contains neither the document or the recipient I included in the Request. Where am I going wrong?

Here is the Request XML:

<envelopeDefinition
    xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.docusign.com/restapi">
    <documents>
        <documentBase64><Base64BytesHere></documentBase64>
    </documents>
    <emailSubject>Test from API Explorer</emailSubject>
    <recipients>
        <signers>
            <email>nobody@nobody.com</email>
            <name>John Smith</name>
        </signers>
    </recipients>
    <status>created</status>
</envelopeDefinition>

Here is the empty envelope screenshot

Body:
You're missing some parameters for the document and recipient objects, for instance you need to add a documentId and documentName for the document in addition to the document bytes.

Here's what a full XML request should look like:

<envelopeDefinition xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.docusign.com/restapi">
    <emailSubject>Test Subject</emailSubject>
    <documents>
      <document>
        <name>document.pdf</name>
        <documentId>1</documentId>
        <documentBase64>&lt;Base64BytesHere&gt;</documentBase64>
      </document>
    </documents>
    <recipients>
        <signers>
            <tabs>
                <signHereTabs>
                  <signHereTab>
                    <pageNumber>1</pageNumber>
                    <documentId>1</documentId>
                    <xPosition>100</xPosition>
                    <yPosition>100</yPosition>
                  </signHereTab>
                </signHereTabs>
            </tabs>
            <routingOrder>1</routingOrder>
            <recipientId>1</recipientId>
            <name>My Name</name>
            <email>email@email.com</email>
        </signers>
    </recipients>
    <status>created</status>
</envelopeDefinition>


问:
Code signing error: Doesn't match key pair in default keychain
*****Code Sign error: The identity 'iPhone Developer: XXXXXXXXXX' doesn't match any valid certificate/private key pair in the default keychain**.***

I am a member in developer profile, I have the provisioning profile installed, what must be the problem here?

Code Sign error: The identity 'iPhone Developer: XXXXXXXXXXXX' doesn't match any valid certificate/private key pair in the default keychain

What am I supposed to do? I already searched for a solution but still didn't find any.

答:
Just open a bash.

Go into the ProjectName*.xcodeproj* directory

And remove every *.mode1v3 and *.pbxuser file

Then start xcode again and you're lucky.

For my case it was like:

cd iCodeBrowser/iCodeBrowser.xcodeproj/

rm brandontrieb.*


问:
How to specify line breaks in a multi-line flexbox layout?
Is there a way to make a line break in multiple line flexbox?

For example to break after each 3rd item in this CodePen.

.container {
  background: tomato;
  display: flex;
  flex-flow: row wrap;
  align-content: space-between;
  justify-content: space-between;
}
.item {
  width: 100px;
  height: 100px;
  background: gold;
  border: 1px solid black;
  font-size: 30px;
  line-height: 100px;
  text-align: center;
  margin: 10px;
}
.item:nth-child(3n) {
  background: silver;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">3</div>
  <div class="item">4</div>
  <div class="item">5</div>
  <div class="item">6</div>
  <div class="item">7</div>
  <div class="item">8</div>
  <div class="item">9</div>
  <div class="item">10</div>
</div></code>```

Like

```<code>.item:nth-child(3n){
  /* line-break: after; */
}
</code>```

答:
.container {
  background: tomato;
  display: flex;
  flex-flow: row wrap;
  align-content: space-between;
  justify-content: space-between;
}

.item {
  width: 100px;
  height: 100px;
  background: gold;
  border: 1px solid black;
  font-size: 30px;
  line-height: 100px;
  text-align: center;
  margin: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div>
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
  </div>
  <div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
  </div>
  <div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
  </div>
  <div class="item">10</div>
</div></code>```

you could try wrapping the items in a dom element like here. with this you dont have to know a lot of css just having a good structure will solve the problem.

Body:
Is there a way to make a line break in multiple line flexbox?

For example to break after each 3rd item in this CodePen.

.container {
  background: tomato;
  display: flex;
  flex-flow: row wrap;
  align-content: space-between;
  justify-content: space-between;
}
.item {
  width: 100px;
  height: 100px;
  background: gold;
  border: 1px solid black;
  font-size: 30px;
  line-height: 100px;
  text-align: center;
  margin: 10px;
}
.item:nth-child(3n) {
  background: silver;
}

1

2

3

4

5

6

7

8

9

10

Like

.item:nth-child(3n){
  /* line-break: after; */
}

Body:
.container {
  background: tomato;
  display: flex;
  flex-flow: row wrap;
  align-content: space-between;
  justify-content: space-between;
}

.item {
  width: 100px;
  height: 100px;
  background: gold;
  border: 1px solid black;
  font-size: 30px;
  line-height: 100px;
  text-align: center;
  margin: 10px;
}

<div class="container">
  <div>
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
  </div>
  <div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
  </div>
  <div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
  </div>
  <div class="item">10</div>
</div>

you could try wrapping the items in a dom element like here. with this you dont have to know a lot of css just having a good structure will solve the problem.


问:
How to disable keyboard input in curses
I have some long running tasks and would like to disable the keyboard input during the procedure. After the keyboard is disabled, the keyboard inputs will be discarded automatically.

```<code>disable keyboard
running the task
enable keyboard
</code>```

Can I do this with python curses?

答: Well, there's no input until you ask for it, so there's no need to explicitly disable it. But, to flush the input queue before you start taking input again, just call curses.flushinp().

Title: How to disable keyboard input in curses

Body:
I have some long running tasks and would like to disable the keyboard input during the procedure. After the keyboard is disabled, the keyboard inputs will be discarded automatically.

disable keyboard
running the task
enable keyboard

Can I do this with python curses?


问:
Using PHP variable in SQL query
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)

```<code><?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>
</code>```

I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.

Thank you in advance.

Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:

```<code><?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>
</code>```

I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.

Thanks again.

答:
Do it like so </p>

```<code><?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
  $stmt->bind_param("s",$q);   // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
  $stmt->execute();
  $stmt->bind_result($col1,$col2,$col3,$col4);  // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
  $stmt->store_result();
  while($stmt->fetch()){   // fetch the results
    echo $col1;
  }
  $stmt->close();
}

?>
</code>```

Title: Using PHP variable in SQL query

Body:
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)

<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>

I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.

Thank you in advance.

Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:

<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>

I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.

Thanks again.

Body:
Do it like so

<?php
$q = 'mercy_west';
$query = "SELECT col1,col2,col3,col4 FROM database.table WHERE field_name = 'hospital_name' AND value = ?";
if($stmt = $db->query($query)){
  $stmt->bind_param("s",$q);   // s is for string, i for integer, number of these must match your ? marks in query. Then variable you're binding is the $q, Must match number of ? as well
  $stmt->execute();
  $stmt->bind_result($col1,$col2,$col3,$col4);  // Can initialize these above with $col1 = "", but these bind what you're selecting. If you select 5 times, must have 5 variables, and they go in in order. select id,name, bind_result($id,name)
  $stmt->store_result();
  while($stmt->fetch()){   // fetch the results
    echo $col1;
  }
  $stmt->close();
}

?>


问:
Why doesn't http_build_query work correctly?
Here is my code:

```<code>print_r(http_build_query(array_merge($_GET, array("param3"=>"baz"))));
</code>```

And here is the result:

```<code>o=newest&u=true¶m3=baz
</code>```

Well what's ¶? Why sometimes http_build_query doesn't put & between parameters?

And here is the result without http_build_query:

```<code>Array ( [o] => newest [u] => true [param3] => baz )
</code>```

答: So the representation of ¶ is & p a r a ;(html entity), when you use that name param3 it is interpreted to that symbol ¶ (Pilcrow Sign). That's why you see ¶m3=baz

Body:
Here is my code:

print_r(http_build_query(array_merge($_GET, array("param3"=>"baz"))));

And here is the result:

o=newest&u=true¶m3=baz

Well what's ¶? Why sometimes http_build_query doesn't put & between parameters?

And here is the result without http_build_query:

Array ( [o] => newest [u] => true [param3] => baz )


问:
Export reports via MHTML looks bad while sending it by mail
We’re creating some simple reports in SSRS that are being exported via Web Archive (MHTML) and pasted and sent by emails to the relevant subscribers.

These are mainly high level financial reports for the management.

My problem is when the data is exported from the report and pasted in the mail, the layout doesn’t look as good as in the report itself.

For example,

The pasted report data looks like:

```<code>December 13, 2010 (12:00:00 A.M. - 11:59:59 P.M.)

Total Video Revenues
$0.00

Completed Sessions
0

Non – completed Sessions
0

Cancelation
0
</code>```

Instead of looking like:

```<code>December 13, 2010 (12:00:00 A.M. - 11:59:59 P.M.)

Total Video Revenues       $0.00
Completed Sessions         0
Non – completed Sessions   0
Cancelation                0
</code>```

The only way I’ve managed to overcome this layout issue is by adding a header into the RDL layout and insert in the header a text box filled with WHITE text (which isn’t visible).

This fixes the issue and the report looks good in the mail.

What can I do ?

I believe that it’s a weird way to solve the issue…

Thanks in advance,

Roni Vered.

答:
Found the solution.

It appears that is a known issue which was fixed in one of the cumulative package updates of sp2.

http://support.microsoft.com/kb/935399.

A table in a report that is delivered by SQL Server 2005 Reporting Services with Service Pack 2 appears to be compressed when the report is opened in Outlook 2007

Body:
We’re creating some simple reports in SSRS that are being exported via Web Archive (MHTML) and pasted and sent by emails to the relevant subscribers.

These are mainly high level financial reports for the management.

My problem is when the data is exported from the report and pasted in the mail, the layout doesn’t look as good as in the report itself.

For example,

The pasted report data looks like:

December 13, 2010 (12:00:00 A.M. - 11:59:59 P.M.)

Total Video Revenues
$0.00

Completed Sessions
0

Non – completed Sessions
0

Cancelation
0

Instead of looking like:

December 13, 2010 (12:00:00 A.M. - 11:59:59 P.M.)

Total Video Revenues       $0.00
Completed Sessions         0
Non – completed Sessions   0
Cancelation                0

The only way I’ve managed to overcome this layout issue is by adding a header into the RDL layout and insert in the header a text box filled with WHITE text (which isn’t visible).

This fixes the issue and the report looks good in the mail.

What can I do ?

I believe that it’s a weird way to solve the issue…

Thanks in advance,

Roni Vered.


问:
Trouble with background position fixed on mobiles
Sorry in advandce, my english is poor... i'm going to try be clear.

I develop a website with a background picture fixed. Obviously background-position: fixed doesn't works on mobiles and IPAD!
So i've succeed to get around the problem as you can see in my code, ( picture display width and height 100% in background)
here's it:

```<code>  <body>
    <div class="container-fluid no-marge img-responsive">

    <img  src="crayons.jpg" class="bg-img" alt="">

    <div class="rowtitle col-md-12 outline">
      <h1>title</h1>
    </div>
        <h1 class="col-md-12 titre-accueil">Bienvenue</h1>
        <div class="row col-md-12 carousel-space">

        </div>
        <div class="row ">
            <div class="col-md-12 textePresentation ">
                <div class="col-md-offset-1 col-md-10 col-md-offset-1 ">
                    <h1 class="titre-qsn"><br>Qui sommes nous ?</h1><br><br><br>
                    <div class="col-md-4 "><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!</p>       <p>Lorem ibus porro? A vel, quam totam!</p>     <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!</p>  <br><br>
                    </div>
                    <div class="col-md-4"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!</p>        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!</p>      <p>tetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!</p><br><br>
                    </div>
                    <div class="col-md-4"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!</p>        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!</p><br><br>
                    </div>
                </div>
            </div>
        </div>

        <div id="footer" class="row footer col-lg-12 no-marge "><br>

        </div>
    </div><!--container-fluid-->

</body>
</code>```

and the css:

```<code>html
{
    height: 100%;
    width:100%;
}

body
{
 /* content: "";
  display: block;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -10;
  background: url('crayons.jpg') no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;*/
}

.rowtitle
{
  background-color: red;
}

.bg-img
{
  position: fixed;
  top: 0;
  left: 0;
  min-width: 100%;
  min-height: 100%;
  background: url('crayons.jpg');
  background-size: cover;
}

.titre-accueil
{
    margin-top: 50px;
    margin-bottom: 50px;
    width:100%;
    font-size: 3.8em;
    text-shadow: -1px -1px #eee, 1px 1px #888, -3px 0 4px #000;
    font-family:"Segoe print", Arial, Helvetica, sans-serif;
    color:white;
    font-weight:lighter;
    text-align:center;
    display:inline;
 }

.bandeau-carousel
{
    border: 35px solid rgba(255, 255, 255, .3);
    border-radius: 10px;
    padding: 0;
}

.textePresentation
{
    margin-top: 50px;
    width : 100%;
    background-color: rgb(235, 235, 235);
    box-shadow: 8px 8px 12px #aaa;
}

.carousel-space
{
    width:100%;
    height: 250px;
}

.footer
{
    /*padding-top: 50px;*/
    height: 200px;
    background-color: rgb(255, 73, 53);
    text-align: center;
    vertical-align: middle;
    margin: auto;
    position: relative;
}

.no-marge
{
    margin:0;
    padding:0;
}

.outline
{
  border: solid 3px red;
}
</code>```

The issue is that when i scroll the top menu ( nav-bar and title) down and we see the background. i want the background don't exceed the .

I think it's better with a screenshot :
illustration

Maybe someone had a solution to fix this problem ? or just improve the user experience about this.

Thank you very much !

答:
Try this:

```<code>  body{
    background-image: url('crayons.jpg');
    background-size: cover;
    background-repeat:no-repeat;
    background-position: center;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
    }
</code>```

Also you commented out (disabled) your body css code in your example by */
display block sets it as a block element and causes the body to fallow container rules instead of full page body rules.

Body:
Sorry in advandce, my english is poor... i'm going to try be clear.

I develop a website with a background picture fixed. Obviously background-position: fixed doesn't works on mobiles and IPAD!
So i've succeed to get around the problem as you can see in my code, ( picture display width and height 100% in background)
here's it:

title

Bienvenue

Qui sommes nous ?

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!

Lorem ibus porro? A vel, quam totam!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!

tetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates error libero repellendus ullam, deserunt vitae sint obcaecati asperiores, maiores culpa optio assumenda, mollitia repellat doloribus porro? A vel, quam totam!

and the css:

html
{
    height: 100%;
    width:100%;
}

body
{
 /* content: "";
  display: block;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -10;
  background: url('crayons.jpg') no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;*/
}

.rowtitle
{
  background-color: red;
}

.bg-img
{
  position: fixed;
  top: 0;
  left: 0;
  min-width: 100%;
  min-height: 100%;
  background: url('crayons.jpg');
  background-size: cover;
}

.titre-accueil
{
    margin-top: 50px;
    margin-bottom: 50px;
    width:100%;
    font-size: 3.8em;
    text-shadow: -1px -1px #eee, 1px 1px #888, -3px 0 4px #000;
    font-family:"Segoe print", Arial, Helvetica, sans-serif;
    color:white;
    font-weight:lighter;
    text-align:center;
    display:inline;
 }

.bandeau-carousel
{
    border: 35px solid rgba(255, 255, 255, .3);
    border-radius: 10px;
    padding: 0;
}

.textePresentation
{
    margin-top: 50px;
    width : 100%;
    background-color: rgb(235, 235, 235);
    box-shadow: 8px 8px 12px #aaa;
}

.carousel-space
{
    width:100%;
    height: 250px;
}

.footer
{
    /*padding-top: 50px;*/
    height: 200px;
    background-color: rgb(255, 73, 53);
    text-align: center;
    vertical-align: middle;
    margin: auto;
    position: relative;
}

.no-marge
{
    margin:0;
    padding:0;
}

.outline
{
  border: solid 3px red;
}

The issue is that when i scroll the top menu ( nav-bar and title) down and we see the background. i want the background don't exceed the .

I think it's better with a screenshot :
illustration

Maybe someone had a solution to fix this problem ? or just improve the user experience about this.

Thank you very much !

Body:
Try this:

  body{
    background-image: url('crayons.jpg');
    background-size: cover;
    background-repeat:no-repeat;
    background-position: center;
   -webkit-background-size: cover;
   -moz-background-size: cover;
   -o-background-size: cover;
    }

Also you commented out (disabled) your body css code in your example by */
display block sets it as a block element and causes the body to fallow container rules instead of full page body rules.


问:
Integrate Api.ai in already functioning Facebook Messenger Bot
I have already created a Facebook messenger bot without using any AI technology integration. Currently the bot simply replies from the limited conditions i have put.for eg, reply with time when someone types 'time', or greet when someone type 'Hi'. Now i want to Integrate Api.ai with the bot, most tutorial suggest to start a new page and integrate api there. PS : my current page is public.</p>

答:
You need to go to the Integration tab on API.ai and turn on the integration with Messenger and follow the steps.

Basically what will happen is that in the API.ai page, you will place the webhook url of your Messenger bot in the Fulfillment tab.

In your Facebook page (in the developer portal) you will place the API.ai url (the one that appears in the Integration of the API.ai bots.api.ai ... ) in the Webhook field (where your backend url used to be). This way, Facebook will make a request to API.ai, API.ai will make the natural language interpretation and call your backend.

You will have to change your backend to expect API.ai requests instead of Facebook requests.

There is a complete tutorial here.


问:
Does ArrayDeque implement the List interface, or Deque? Conflicting information from various sources
I'm currently taking an algorithms class online, and our textbook is Pat Morin's Open Data Structures.

In his discussion of ArrayDeque, Morin claims, "The ArrayDeque data structure allows for efficient addition and removal at both ends. This structure implements the List interface."  He then goes on to discuss a C++ implementation of the data structure, including the expected List methods:  get(i), set(i, x), add(i, x), and remove(i).

I found the author's treatment confusing, as I can't imagine how this implementation could be considered a Deque; it features insertion/deletion at any position, after all.

On the other hand, other resources indicate that ArrayDeque implements the Deque interface ("duh," right?).  In fact, this article claims, "the ArrayDeque is the array-based implementation of the Deque interface."  Furthermore, "the ArrayDeque, unlike the LinkedList, does not implement the List interface, and so we never think about using it for positional access."  This treatment makes perfect sense to me, and it seems to follow the consensus of the various articles I've found.

So is Morin's book just wrong, or am I missing something fundamental?

答:
From the Java docs

java.util

  Class ArrayDeque

  * java.lang.Object

  * * java.util.AbstractCollection

  * * * java.util.ArrayDeque

Type Parameters:

  E - the type of elements held in this collection

All Implemented Interfaces:

  Serializable, Cloneable, Iterable, Collection, Deque, Queue

ArrayDeque implements Iterable, Collection, Deque, and Queue (and Serializable, Cloneable); so no List, just Iterable.

In Morin's book, he is talking about writing your own ArrayDeque that has nothing to do with the Java implementation; and the auther is explaining that by using this underlying data-structure to implement an ArrayDeque, you can implement the List interface. (Key here, they are not saying that all ArrayDeque will implement List, because random access kinda messes with the whole 'que' part of the structure. But you CAN (and shouldn't))


问:
Heading changes font and position when not in full screen
I am making a website using HTML and CSS and the heading displays fine in full screen but when I make it half the screen size the header (h1) changes to the default font and aligns to the left instead of the center as it should.

Here is my HTML code:

```<code><!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
<title>Home page</title>
<link type="text/css" rel="stylesheet"
href="css/filesheet1.css"/>
</head>
<body>
<nav>
<ul>
<li><a href="index.html">Home page</a></li>
<li><a href="about us.html">About us</a></li>
<li><a href="our songs.html">Our songs</a></li>
<li><a href="see us play.html">See us play</a></li>
<li><a href="Contact us.html">Contact us</a></li>
<li><a href="merchandise.html">Merchandise</a></li>
<li><a href="playing a concert.html">Playing a concert</a></li>
</ul>
</nav>
<h1>Home</h1>
</body>
</html>
</code>```

Here is my CSS code (sorry if there's a lot as I have no idea whats causing this issue I have put it all there):

```<code>    /* set sizing to border box method */
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
/* set maximum and minimum widths for the body and centre within the viewport */
body {
text-align: center;
border: solid;
border-radius: 15px;
border-color: #CACFD2;
box-shadow: 0 0 100px 0 #888888;
background-color: #CACFD2;
font-family: 'Inconsolata', monospace;
margin-left: auto;
margin-right: auto;
max-width: 1024px;
min-width: 256px;
padding-top: 8px;
padding-bottom: 24px;
padding-left: 24px;
padding-right: 24px;
}
html, html body{
height: 100%;
}
html{
background-color: white;
}
/* header */
header{
}
header p {
float: left;
font-size: 16px;
font-weight: bold;
margin-top: 0px;
}
header h1 {
font-size: 16px;
text-align: center;
}
/* the menu */
nav ul {
text-align: center;
list-style-type: none;
background-color: none;
border: none;
font-family: 'Inconsolata', monospace;
font-weight: 400;
padding: 16px;
}
nav ul li {
display: inline;
border-right: 2px solid #111111;
padding-right: 8px;
padding-left: 8px;
}
nav ul li:last-child {
border-right: none;
}
nav ul li a {
text-decoration: none;
color: #111111;
}
nav li.selected{
color: #606060;
}
nav ul li a:hover {
font-weight: 900;
}
/* biographies */
section {
background-color: #FFFFFF;
margin-bottom: 24px;
min-height: 320px;
padding-left: 24px;
padding-right: 24px;
}
/* the aside */
aside {
}
/* footer */
footer {
}
footer p.copyright {
float: left;
margin-top: 0px;
}
footer p.contact {
text-align: right;
}

/* small images are set to 200px in height */
img.small {
float: left;
height: 200px;
margin-bottom: 24px;
margin-right: 24px;
}
/* medium images can be 50% of the container elementâ€™s width, up to 360px */
img.medium {
max-width: 360x;
width: 50%;
}
/* large images are 100% of the container elementâ€™s width */
img.large {
width: 100%;
}
/* add the same style of border to the elements which are to have borders */
section, img {
border: 2px solid #B1B1B1;
border-radius: 16px;
}
/* the bits that are specific to a wide viewport (over 56em) */
@media{
min-width: 900px
}
article {
float: left;
width: 66%;
}
aside {
float: left;
padding-left: 24px;
width: 34%;
}
footer {
clear: both;
}
h1{
text-align: center;
font-family: 'Inconsolata', monospace;
}
</code>```

答:
/* Styles go here */

/* set sizing to border box method */
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
/* set maximum and minimum widths for the body and centre within the viewport */
body {
text-align: center;
border: solid;
border-radius: 15px;
border-color: #CACFD2;
box-shadow: 0 0 100px 0 #888888;
background-color: #CACFD2;
font-family: 'Inconsolata', monospace;
margin-left: auto;
margin-right: auto;
max-width: 1024px;
min-width: 256px;
padding-top: 8px;
padding-bottom: 24px;
padding-left: 24px;
padding-right: 24px;
}
html, html body{
height: 100%;
}
html{
background-color: white;
}
/* header */
header{
}
header p {
float: left;
font-size: 16px;
font-weight: bold;
margin-top: 0px;
}
header h1 {
font-size: 16px;
text-align: center;
}
/* the menu */
nav ul {
text-align: center;
list-style-type: none;
background-color: none;
border: none;
font-family: 'Inconsolata', monospace;
font-weight: 400;
padding: 16px;
}
nav ul li {
display: inline;
border-right: 2px solid #111111;
padding-right: 8px;
padding-left: 8px;
}
nav ul li:last-child {
border-right: none;
}
nav ul li a {
text-decoration: none;
color: #111111;
}
nav li.selected{
color: #606060;
}
nav ul li a:hover {
font-weight: 900;
}
/* biographies */
section {
background-color: #FFFFFF;
margin-bottom: 24px;
min-height: 320px;
padding-left: 24px;
padding-right: 24px;
}
/* the aside */
aside {
}
/* footer */
footer {
}
footer p.copyright {
float: left;
margin-top: 0px;
}
footer p.contact {
text-align: right;
}

/* small images are set to 200px in height */
img.small {
float: left;
height: 200px;
margin-bottom: 24px;
margin-right: 24px;
}
/* medium images can be 50% of the container elementâ€™s width, up to 360px */
img.medium {
max-width: 360px;
width: 50%;
}
/* large images are 100% of the container elementâ€™s width */
img.large {
width: 100%;
}
/* add the same style of border to the elements which are to have borders */
section, img {
border: 2px solid #B1B1B1;
border-radius: 16px;
}
/* the bits that are specific to a wide viewport (over 56em) */
@media all and (min-width: 900px) {

}
article {
float: left;
width: 66%;
}
aside {
float: left;
padding-left: 24px;
width: 34%;
}
footer {
clear: both;
}
h1{
text-align: center;
font-family: 'Inconsolata', monospace;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
<title>Home page</title>
<link type="text/css" rel="stylesheet"
href="style.css"/>
</head>
<body>
<nav>
<ul>
<li>Home page</li>
<li>About us</li>
<li>Our songs</li>
<li>See us play</li>
<li>Contact us</li>
<li>Merchandise</li>
<li>Playing a concert</li>
</ul>
</nav>
<h1>Home</h1>
</body>
</html></code>```

This should work for you now.

Body:
I am making a website using HTML and CSS and the heading displays fine in full screen but when I make it half the screen size the header (h1) changes to the default font and aligns to the left instead of the center as it should.

Here is my HTML code:

<!DOCTYPE html>

<link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
<title>Home page</title>
<link type="text/css" rel="stylesheet"
href="css/filesheet1.css"/>

Home page

About us

Our songs

See us play

Contact us

Merchandise

Playing a concert

Home

Here is my CSS code (sorry if there's a lot as I have no idea whats causing this issue I have put it all there):

    /* set sizing to border box method */
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
/* set maximum and minimum widths for the body and centre within the viewport */
body {
text-align: center;
border: solid;
border-radius: 15px;
border-color: #CACFD2;
box-shadow: 0 0 100px 0 #888888;
background-color: #CACFD2;
font-family: 'Inconsolata', monospace;
margin-left: auto;
margin-right: auto;
max-width: 1024px;
min-width: 256px;
padding-top: 8px;
padding-bottom: 24px;
padding-left: 24px;
padding-right: 24px;
}
html, html body{
height: 100%;
}
html{
background-color: white;
}
/* header */
header{
}
header p {
float: left;
font-size: 16px;
font-weight: bold;
margin-top: 0px;
}
header h1 {
font-size: 16px;
text-align: center;
}
/* the menu */
nav ul {
text-align: center;
list-style-type: none;
background-color: none;
border: none;
font-family: 'Inconsolata', monospace;
font-weight: 400;
padding: 16px;
}
nav ul li {
display: inline;
border-right: 2px solid #111111;
padding-right: 8px;
padding-left: 8px;
}
nav ul li:last-child {
border-right: none;
}
nav ul li a {
text-decoration: none;
color: #111111;
}
nav li.selected{
color: #606060;
}
nav ul li a:hover {
font-weight: 900;
}
/* biographies */
section {
background-color: #FFFFFF;
margin-bottom: 24px;
min-height: 320px;
padding-left: 24px;
padding-right: 24px;
}
/* the aside */
aside {
}
/* footer */
footer {
}
footer p.copyright {
float: left;
margin-top: 0px;
}
footer p.contact {
text-align: right;
}

/* small images are set to 200px in height */
img.small {
float: left;
height: 200px;
margin-bottom: 24px;
margin-right: 24px;
}
/* medium images can be 50% of the container elementâ€™s width, up to 360px */
img.medium {
max-width: 360x;
width: 50%;
}
/* large images are 100% of the container elementâ€™s width */
img.large {
width: 100%;
}
/* add the same style of border to the elements which are to have borders */
section, img {
border: 2px solid #B1B1B1;
border-radius: 16px;
}
/* the bits that are specific to a wide viewport (over 56em) */
@media{
min-width: 900px
}
article {
float: left;
width: 66%;
}
aside {
float: left;
padding-left: 24px;
width: 34%;
}
footer {
clear: both;
}
h1{
text-align: center;
font-family: 'Inconsolata', monospace;
}

Body:
/* Styles go here */

/* set sizing to border box method */
html {
box-sizing: border-box;
}
*, *:before, *:after {
box-sizing: inherit;
}
/* set maximum and minimum widths for the body and centre within the viewport */
body {
text-align: center;
border: solid;
border-radius: 15px;
border-color: #CACFD2;
box-shadow: 0 0 100px 0 #888888;
background-color: #CACFD2;
font-family: 'Inconsolata', monospace;
margin-left: auto;
margin-right: auto;
max-width: 1024px;
min-width: 256px;
padding-top: 8px;
padding-bottom: 24px;
padding-left: 24px;
padding-right: 24px;
}
html, html body{
height: 100%;
}
html{
background-color: white;
}
/* header */
header{
}
header p {
float: left;
font-size: 16px;
font-weight: bold;
margin-top: 0px;
}
header h1 {
font-size: 16px;
text-align: center;
}
/* the menu */
nav ul {
text-align: center;
list-style-type: none;
background-color: none;
border: none;
font-family: 'Inconsolata', monospace;
font-weight: 400;
padding: 16px;
}
nav ul li {
display: inline;
border-right: 2px solid #111111;
padding-right: 8px;
padding-left: 8px;
}
nav ul li:last-child {
border-right: none;
}
nav ul li a {
text-decoration: none;
color: #111111;
}
nav li.selected{
color: #606060;
}
nav ul li a:hover {
font-weight: 900;
}
/* biographies */
section {
background-color: #FFFFFF;
margin-bottom: 24px;
min-height: 320px;
padding-left: 24px;
padding-right: 24px;
}
/* the aside */
aside {
}
/* footer */
footer {
}
footer p.copyright {
float: left;
margin-top: 0px;
}
footer p.contact {
text-align: right;
}

/* small images are set to 200px in height */
img.small {
float: left;
height: 200px;
margin-bottom: 24px;
margin-right: 24px;
}
/* medium images can be 50% of the container elementâ€™s width, up to 360px */
img.medium {
max-width: 360px;
width: 50%;
}
/* large images are 100% of the container elementâ€™s width */
img.large {
width: 100%;
}
/* add the same style of border to the elements which are to have borders */
section, img {
border: 2px solid #B1B1B1;
border-radius: 16px;
}
/* the bits that are specific to a wide viewport (over 56em) */
@media all and (min-width: 900px) {

}
article {
float: left;
width: 66%;
}
aside {
float: left;
padding-left: 24px;
width: 34%;
}
footer {
clear: both;
}
h1{
text-align: center;
font-family: 'Inconsolata', monospace;
}

<!DOCTYPE html>
<html>
<head>
<link href="https://fonts.googleapis.com/css?family=Inconsolata" rel="stylesheet">
<title>Home page</title>
<link type="text/css" rel="stylesheet"
href="style.css"/>
</head>
<body>
<nav>
<ul>
<li><a href="index.html">Home page</a></li>
<li><a href="about us.html">About us</a></li>
<li><a href="our songs.html">Our songs</a></li>
<li><a href="see us play.html">See us play</a></li>
<li><a href="Contact us.html">Contact us</a></li>
<li><a href="merchandise.html">Merchandise</a></li>
<li><a href="playing a concert.html">Playing a concert</a></li>
</ul>
</nav>
<h1>Home</h1>
</body>
</html>

This should work for you now.


问:
matching two points with minimum distance
I'm working on this problem:

There is a 3d binary matrix which i cluster with the kmeans algorithm in matlab;

After that i get a value C which contains the coordinates of the centroids of these clusters in an array, for example:

```<code> C=   30.0000   15.0000   48.5000

      100.2676   57.7382   80.7489

      57.5000   85.0000   35.0000

      27.5000   50.0000   69.5000
</code>```

(4 centroids: first one with coordinates (30,15,48,5))
where the rows represent the x,y and z coordinate of each centroid.

When I cluster another matrix I get a second value which also contains the coordinates of the second centroids.
now i have to match the centroids from first and second clustering which have minimum distance and create an output where i can see which centroids belong together.

I have tried it with pdist(X) and i get the distances pairwise of the coordinates but i can not match them together..

How to solve this, any idea?

答:
You should define more precisely what is "matching": should it be 1-to-1 or 1-to-many?

If it's 1-to-many (several centroids of C1 can be matched to the same centroid of C2) then using nearest-neighbors can help, see knnsearch.

If it's 1-to-1, then you'd have to use some greedy algorithm to map the closest centroids first (loop over the result of pdist2).

As for the plotting of the matches, it really depends on the nature of the data.
But one convenient way would be to do a PCA to go from 3D to 2D and then simply plot lines between centroids.

Body:
I'm working on this problem:

There is a 3d binary matrix which i cluster with the kmeans algorithm in matlab;

After that i get a value C which contains the coordinates of the centroids of these clusters in an array, for example:

 C=   30.0000   15.0000   48.5000

      100.2676   57.7382   80.7489

      57.5000   85.0000   35.0000

      27.5000   50.0000   69.5000

(4 centroids: first one with coordinates (30,15,48,5))
where the rows represent the x,y and z coordinate of each centroid.

When I cluster another matrix I get a second value which also contains the coordinates of the second centroids.
now i have to match the centroids from first and second clustering which have minimum distance and create an output where i can see which centroids belong together.

I have tried it with pdist(X) and i get the distances pairwise of the coordinates but i can not match them together..

How to solve this, any idea?


问:
MPI: Canceling Non-blocking Send
I'm using Open MPI library to implement the following algorithm: we have two processes p1 and p2. They're both executing some iterations and at the end of each iteration, they communicate their results. The problem is that the execution is not necessarily balanced, so p1 may execute 10 iterations in the time p2 executes 1. Even though, I want p2 to read the latest result from the last iteration executed by p1.

Thus, my idea is that p1 sends its results at each iteration. But, before sending the result from an iteration i, it should check if p2 actually read the information from iteration i-1. If not, it should cancel the previous send so that when p2 reads from p1, it will  read the most recent result.

Unfortunately, I'm not sure how to do that. I've tried using MPI_Cancel, as in the following code:

```<code>int main (int argc, char *argv[]){

    int myrank, numprocs;
    MPI_Status status;
    MPI_Request request;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

    if(myrank == 0){
        int send_buf = 1, flag;
        MPI_Isend(&send_buf, 1, MPI_INT, 1, 123, MPI_COMM_WORLD,
                  &request);
        MPI_Cancel(&request);
        MPI_Wait(&request, &status);
        MPI_Test_cancelled(&status, &flag);
        if (flag) printf("Send cancelled\n");
        else printf("Send NOT cancelled\n");
        send_buf = 2;
        MPI_Isend(&send_buf, 1, MPI_INT, 1, 123, MPI_COMM_WORLD,
                  &request);
    }
    else {
        sleep(5);
        int msg;
        MPI_Recv(&msg, 1, MPI_INT, 0, 123,
                 MPI_COMM_WORLD, &status);
        printf("%d\n", msg);
    }
    MPI_Finalize();

    return 0;
}
</code>```

But when I execute, it says that the send could not be cancelled and p2 prints 1 instead of 2.

I'd like to know if there's any way to achieve what I'm proposing or if there's an alternative to code the behaviour between p1 and p2.

答:
I would reverse the control of communications. Instead of p1 sending unnecessary messages that it has to cancel, p2 should signal that it is ready to receive a message, and p1 would send only then. In the meantime, p1 simply overwrites its send buffer with the latest results.

In (untested) code:

```<code>if ( rank == 0 )
{
    int ready;
    MPI_Request p2_request;
    MPI_Status p2_status;
    // initial request
    MPI_Irecv(&ready, 1, MPI_INT, 1, 123, MPI_COMM_WORLD, &p2_request);
    for (int i=0; true; i++)
    {
        sleep(1);
        MPI_Test(&p2_request, &ready, &p2_status);
        if ( ready )
        {
            // blocking send: p2 is ready to receive
            MPI_Send(&i, 1, MPI_INT, 1, 123, MPI_COMM_WORLD);
            // post new request
            MPI_Irecv(&ready, 1, MPI_INT, 1, 123, MPI_COMM_WORLD, &p2_request);
        }
    }
}
else
{
    int msg;
    MPI_Status status;
    while (true)
    {
        sleep(5);
        // actual message content doesn't matter, just let p1 know we're ready
        MPI_Send(&msg, 1, MPI_INT, 0, 123, MPI_COMM_WORLD);
        // receive message
        MPI_Recv(&msg, 1, MPI_INT, 0, 123, MPI_COMM_WORLD, &status);
    }
}
</code>```

Now like I said, that's untested code, but you can probably see what I'm getting at there. MPI_Cancel should only be used when things go horribly wrong: no message should be cancelled during normal execution.

Title: MPI: Canceling Non-blocking Send

Body:
I'm using Open MPI library to implement the following algorithm: we have two processes p1 and p2. They're both executing some iterations and at the end of each iteration, they communicate their results. The problem is that the execution is not necessarily balanced, so p1 may execute 10 iterations in the time p2 executes 1. Even though, I want p2 to read the latest result from the last iteration executed by p1.

Thus, my idea is that p1 sends its results at each iteration. But, before sending the result from an iteration i, it should check if p2 actually read the information from iteration i-1. If not, it should cancel the previous send so that when p2 reads from p1, it will  read the most recent result.

Unfortunately, I'm not sure how to do that. I've tried using MPI_Cancel, as in the following code:

int main (int argc, char *argv[]){

    int myrank, numprocs;
    MPI_Status status;
    MPI_Request request;

    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
    MPI_Comm_rank(MPI_COMM_WORLD, &myrank);

    if(myrank == 0){
        int send_buf = 1, flag;
        MPI_Isend(&send_buf, 1, MPI_INT, 1, 123, MPI_COMM_WORLD,
                  &request);
        MPI_Cancel(&request);
        MPI_Wait(&request, &status);
        MPI_Test_cancelled(&status, &flag);
        if (flag) printf("Send cancelled\n");
        else printf("Send NOT cancelled\n");
        send_buf = 2;
        MPI_Isend(&send_buf, 1, MPI_INT, 1, 123, MPI_COMM_WORLD,
                  &request);
    }
    else {
        sleep(5);
        int msg;
        MPI_Recv(&msg, 1, MPI_INT, 0, 123,
                 MPI_COMM_WORLD, &status);
        printf("%d\n", msg);
    }
    MPI_Finalize();

    return 0;
}

But when I execute, it says that the send could not be cancelled and p2 prints 1 instead of 2.

I'd like to know if there's any way to achieve what I'm proposing or if there's an alternative to code the behaviour between p1 and p2.

Body:
I would reverse the control of communications. Instead of p1 sending unnecessary messages that it has to cancel, p2 should signal that it is ready to receive a message, and p1 would send only then. In the meantime, p1 simply overwrites its send buffer with the latest results.

In (untested) code:

if ( rank == 0 )
{
    int ready;
    MPI_Request p2_request;
    MPI_Status p2_status;
    // initial request
    MPI_Irecv(&ready, 1, MPI_INT, 1, 123, MPI_COMM_WORLD, &p2_request);
    for (int i=0; true; i++)
    {
        sleep(1);
        MPI_Test(&p2_request, &ready, &p2_status);
        if ( ready )
        {
            // blocking send: p2 is ready to receive
            MPI_Send(&i, 1, MPI_INT, 1, 123, MPI_COMM_WORLD);
            // post new request
            MPI_Irecv(&ready, 1, MPI_INT, 1, 123, MPI_COMM_WORLD, &p2_request);
        }
    }
}
else
{
    int msg;
    MPI_Status status;
    while (true)
    {
        sleep(5);
        // actual message content doesn't matter, just let p1 know we're ready
        MPI_Send(&msg, 1, MPI_INT, 0, 123, MPI_COMM_WORLD);
        // receive message
        MPI_Recv(&msg, 1, MPI_INT, 0, 123, MPI_COMM_WORLD, &status);
    }
}

Now like I said, that's untested code, but you can probably see what I'm getting at there. MPI_Cancel should only be used when things go horribly wrong: no message should be cancelled during normal execution.