问:
Connection Error stockPortfolio::getReturns
I'm running a portfolio optimization and to do that I want to download historical stock data using the stockPortfolio package. I ran the below code, which should generate the pricing data from Yahoo Finance. Instead, I'm getting an error:

```<code>```{r}
stocks <- c("AAPL")
getReturns(ticker = stocks, freq = "year")
```
</code>```

Here's the traceback:

```<code>Error in file(file, "rt") : cannot open the connection
4.file(file, "rt")
3.read.table(file = file, header = header, sep = sep, quote = quote, dec = dec, fill = fill, comment.char = comment.char, ...)
2.read.delim(URL, TRUE, sep = ",")
1.getReturns(ticker = stocks, freq = "year")
</code>```

Looking around other threads, I can't find a great answer. I have the latest version of R and updating my proxy settings doesn't do anything.

答:
getReturns doesn't work anymore because Yahoo Finance has discontinued the service on which most functions fetching data from Yahoo rely (similar problems for get.hist.quote from tseries or getSymbols from quantmod). I guess this is the same issue.

Instead, you can just download the data from Yahoo manually and import it with read.csv. Alternatively, you could get the (daily) data from google with getSymbols:

```<code>    library(quantmod)
    S <- getSymbols("AAPL", src = 'google', auto.assign = FALSE, from = "2004-01-01", to = "2016-12-31")
</code>```

Body:
I'm running a portfolio optimization and to do that I want to download historical stock data using the stockPortfolio package. I ran the below code, which should generate the pricing data from Yahoo Finance. Instead, I'm getting an error:

```{r}
stocks <- c("AAPL")
getReturns(ticker = stocks, freq = "year")
```

Here's the traceback:

Error in file(file, "rt") : cannot open the connection
4.file(file, "rt")
3.read.table(file = file, header = header, sep = sep, quote = quote, dec = dec, fill = fill, comment.char = comment.char, ...)
2.read.delim(URL, TRUE, sep = ",")
1.getReturns(ticker = stocks, freq = "year")

Looking around other threads, I can't find a great answer. I have the latest version of R and updating my proxy settings doesn't do anything.

Body:
getReturns doesn't work anymore because Yahoo Finance has discontinued the service on which most functions fetching data from Yahoo rely (similar problems for get.hist.quote from tseries or getSymbols from quantmod). I guess this is the same issue.

Instead, you can just download the data from Yahoo manually and import it with read.csv. Alternatively, you could get the (daily) data from google with getSymbols:

    library(quantmod)
    S <- getSymbols("AAPL", src = 'google', auto.assign = FALSE, from = "2004-01-01", to = "2016-12-31")


来源: stackexchange

问:
SELECT TOP N with UNION and ORDER BY
Given the example below, why does using using UNION ALL with two SELECT TOP 5 statements in Query 2 below seemingly not respect the ORDER BY clause?

Query 1 returns the expected results but does not include the required union.
Query 2 demonstrates the unexpected behavior.
Query 3 is the workaround I'm currently using to get the desired results.

```<code>CREATE TABLE #T1 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);
CREATE TABLE #T2 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);

INSERT INTO #T1([Description], [Inactive]) VALUES ('One', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Two', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Three', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Four', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Five', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Six', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Seven', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Eight', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Nine', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Ten', 0);

-- Query 1, works as expected giving all 4 records with Inactive = 0 plus one more
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
ORDER BY [Inactive], [Description];

-- Query 2, does not work as expected, as only 2 of the Inactive = 0 records are present
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
UNION ALL
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T2
ORDER BY [Inactive], [Description];

-- Query 3, Workaround to produce desired results
WITH T1 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T1
    ORDER BY [Inactive], [Description]
),
T2 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T2
    ORDER BY [Inactive], [Description]
)
SELECT [ID], [Description], [Inactive] FROM T1
UNION ALL
SELECT [ID], [Description], [Inactive] FROM T2
ORDER BY [Inactive], [Description];

DROP TABLE #T1;
DROP TABLE #T2;
</code>```

Obviously, the workaround is working for me but I'd like to understand why Query 2 does not do what I expected it to.  In case you're wondering why I am bothering with the empty table #T2, the results are actually limited by a WHERE clause in my production example - however leaving it empty here serves the purpose of providing a comparable example without bothering to populate it.

If you do populate #T2 with the following, I find the results to be just as strange - Query 2 only gives four results with Inactive = 0.

```<code>INSERT INTO #T2([Description], [Inactive]) VALUES ('Eleven', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twelve', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Thirteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fourteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fifteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Sixteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Seventeen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Eighteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Nineteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twenty', 0);
</code>```

I have run this script with the same results on SQL Server 2014 and SQL Server 2008 R2.

答:
You should move the whole UNION ALL within a subquery:

```<code>SELECT *
FROM (SELECT TOP 5 [ID], [Description], [Inactive]
      FROM #T1
      ORDER BY [Inactive], [Description]
      UNION ALL
      SELECT TOP 5 [ID], [Description], [Inactive]
      FROM #T2
      ORDER BY [Inactive], [Description]) T3
ORDER BY [Inactive], [Description];
GO
</code>```

```
ID | Description | Inactive
-: | :---------- | :-------
 4 | Four        | False
 6 | Six         | False
10 | Ten         | False
 2 | Two         | False
 8 | Eight       | True
```

ContentLicense: CC BY-SA 3.0

Title: SELECT TOP N with UNION and ORDER BY

Body:
Given the example below, why does using using UNION ALL with two SELECT TOP 5 statements in Query 2 below seemingly not respect the ORDER BY clause?

Query 1 returns the expected results but does not include the required union.
Query 2 demonstrates the unexpected behavior.
Query 3 is the workaround I'm currently using to get the desired results.

CREATE TABLE #T1 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);
CREATE TABLE #T2 ([ID] int IDENTITY(1,1), [Description] varchar(100), [Inactive] bit);

INSERT INTO #T1([Description], [Inactive]) VALUES ('One', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Two', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Three', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Four', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Five', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Six', 0);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Seven', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Eight', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Nine', 1);
INSERT INTO #T1([Description], [Inactive]) VALUES ('Ten', 0);

-- Query 1, works as expected giving all 4 records with Inactive = 0 plus one more
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
ORDER BY [Inactive], [Description];

-- Query 2, does not work as expected, as only 2 of the Inactive = 0 records are present
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T1
UNION ALL
SELECT TOP 5 [ID], [Description], [Inactive]
FROM #T2
ORDER BY [Inactive], [Description];

-- Query 3, Workaround to produce desired results
WITH T1 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T1
    ORDER BY [Inactive], [Description]
),
T2 AS (
    SELECT TOP 5 [ID], [Description], [Inactive]
    FROM #T2
    ORDER BY [Inactive], [Description]
)
SELECT [ID], [Description], [Inactive] FROM T1
UNION ALL
SELECT [ID], [Description], [Inactive] FROM T2
ORDER BY [Inactive], [Description];

DROP TABLE #T1;
DROP TABLE #T2;

Obviously, the workaround is working for me but I'd like to understand why Query 2 does not do what I expected it to.  In case you're wondering why I am bothering with the empty table #T2, the results are actually limited by a WHERE clause in my production example - however leaving it empty here serves the purpose of providing a comparable example without bothering to populate it.

If you do populate #T2 with the following, I find the results to be just as strange - Query 2 only gives four results with Inactive = 0.

INSERT INTO #T2([Description], [Inactive]) VALUES ('Eleven', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twelve', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Thirteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fourteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Fifteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Sixteen', 0);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Seventeen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Eighteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Nineteen', 1);
INSERT INTO #T2([Description], [Inactive]) VALUES ('Twenty', 0);

I have run this script with the same results on SQL Server 2014 and SQL Server 2008 R2.

Body:
You should move the whole UNION ALL within a subquery:

SELECT *
FROM (SELECT TOP 5 [ID], [Description], [Inactive]
      FROM #T1
      ORDER BY [Inactive], [Description]
      UNION ALL
      SELECT TOP 5 [ID], [Description], [Inactive]
      FROM #T2
      ORDER BY [Inactive], [Description]) T3
ORDER BY [Inactive], [Description];
GO

ID | Description | Inactive
-: | :---------- | :-------
 4 | Four        | False
 6 | Six         | False
10 | Ten         | False
 2 | Two         | False
 8 | Eight       | True


问:
How do I configure crafter profile client and crafter profile admin console with non-default crafter profile URL?
The default configuration of crafter profile is http://localhost:8080/crafter-profile for Crafter Profile Client and Crafter Profile Admin Console. I have installed Crafter Profile on port 7070 and updated the following property in the extension folder:

/shared/classes/crafter/engine/extension/server-config.properties

crafter.profile.rest.client.url.base=http://localhost:7070/crafter-profile

But both instances are still looking for crafter-profile at port 8080.

[WARN] 2017-06-07 13:16:23,158 [ajp-nio-7009-exec-71] [rest.RestTemplate] | GET request for "http://localhost:8080/crafter-profile/api/1/profile/by_ticket.json?accessTokenId=b4d44030-d0af-11e3-9c1a-0800200c

2017-06-07_13:17:11.085 [http-nio-7070-exec-62] WARN  o.c.commons.rest.RestTemplate - GET request for "http://localhost:8080/crafter-profile/api/1/tenant/all.json?accessTokenId=e8f5170c-877b-416f-b70f-4b09772f8e2d" resulted in 404 (); invoking error handler

答:
For Crafter-Profile-Admin console that property (crafter.profile.rest.client.url.base) should be in this file
crafter/profile/management/extension/server-config.properties under tomcat shared folder.

When using the crafter-profile-client in spring context you should make sure that your spring context read a property file which and override of the key


问:
DirectX : Write to texture with Compute Shader
I'm trying to write in a texture with compute shader in HLSL.

Creation of the texture :

```<code>D3D11_TEXTURE2D_DESC textureDesc;
ZeroMemory(&textureDesc, sizeof(textureDesc));
textureDesc.Width = 512;
textureDesc.Height = 512;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = 0;
m_tex = 0;
hr = device->CreateTexture2D(&textureDesc, 0, &m_tex);
</code>```

Creation of the UAV :

```<code>D3D11_UNORDERED_ACCESS_VIEW_DESC descUAV;
ZeroMemory(&descUAV, sizeof(descUAV));
descUAV.Format = DXGI_FORMAT_UNKNOWN;
descUAV.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
descUAV.Texture2D.MipSlice = 0;
hr = device->CreateUnorderedAccessView(m_tex, &descUAV, &m_uavAccess);
</code>```

Creation of the SRV (to see the texture) :`

```<code>D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = textureDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = 1;
hr = device->CreateShaderResourceView(m_tex, &srvDesc, &m_srvTexOutput);
</code>```

The shader :

```<code>RWTexture2D<float4> gOutput : register(u0);

[numthreads(16, 16, 1)]
void main(int3 dispatchThreadID : SV_DispatchThreadID) // Thread ID
{
    gOutput[dispatchThreadID.xy] = float4(0.0f, 1.0f, 0.0f, 1.0f);
}
</code>```

The problem is that the texture is always black (the compute shader doesn't write to the texture).

Thanks for your help ! :D

答:
The problem is that I bound an UAV and a SRV on the same texture.

I resolved the problem creating two textures : one bound to an UAV and another bound to a SRV.

The compute shader write on the UAV and, each frame, I copy the data on the SRV with deviceContext->CopyResource(m_texSRV, m_texUAV);

The problem now is the performance, CopyResource is a costly operation. Does it have an other solution less expensive ?

Thanks for your help ! :D

Body:
I'm trying to write in a texture with compute shader in HLSL.

Creation of the texture :

D3D11_TEXTURE2D_DESC textureDesc;
ZeroMemory(&textureDesc, sizeof(textureDesc));
textureDesc.Width = 512;
textureDesc.Height = 512;
textureDesc.MipLevels = 1;
textureDesc.ArraySize = 1;
textureDesc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT;
textureDesc.SampleDesc.Count = 1;
textureDesc.SampleDesc.Quality = 0;
textureDesc.Usage = D3D11_USAGE_DEFAULT;
textureDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_UNORDERED_ACCESS;
textureDesc.CPUAccessFlags = 0;
textureDesc.MiscFlags = 0;
m_tex = 0;
hr = device->CreateTexture2D(&textureDesc, 0, &m_tex);

Creation of the UAV :

D3D11_UNORDERED_ACCESS_VIEW_DESC descUAV;
ZeroMemory(&descUAV, sizeof(descUAV));
descUAV.Format = DXGI_FORMAT_UNKNOWN;
descUAV.ViewDimension = D3D11_UAV_DIMENSION_TEXTURE2D;
descUAV.Texture2D.MipSlice = 0;
hr = device->CreateUnorderedAccessView(m_tex, &descUAV, &m_uavAccess);

Creation of the SRV (to see the texture) :`

D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
srvDesc.Format = textureDesc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MostDetailedMip = 0;
srvDesc.Texture2D.MipLevels = 1;
hr = device->CreateShaderResourceView(m_tex, &srvDesc, &m_srvTexOutput);

The shader :

RWTexture2D<float4> gOutput : register(u0);

[numthreads(16, 16, 1)]
void main(int3 dispatchThreadID : SV_DispatchThreadID) // Thread ID
{
    gOutput[dispatchThreadID.xy] = float4(0.0f, 1.0f, 0.0f, 1.0f);
}

The problem is that the texture is always black (the compute shader doesn't write to the texture).

Thanks for your help ! :D


问:
How to change axis values in Matlab (imhist command)
```<code>%boat_image&histogram
subplot(1,2,1)
imshow(I01);
subplot(1,2,2)
imhist(I01);
saveas( gcf, 'boat_image&histogram', 'jpg' );
</code>```

I want to cover all y values. How can I change the axis values in terms of the covering maximum value?

after adding following commands, I recieved a different histogram below.

```<code>%boat_image&histogram
subplot(1,2,1)
imshow(I02);
subplot(1,2,2)
[cts,x] = imhist(I02);
stem(cts,x);
ylim([0,max(x)]);
saveas( gcf, 'boat_image&histogram_', 'jpg' );
</code>```

after switch:

```<code>%boat_image&histogram
 subplot(1,2,1)
    imshow(I02);
    subplot(1,2,2)
    [x,cts] = imhist(I02);
    stem(x,cts);
    ylim([0,max(x)]);
    saveas( gcf, 'boat_image&histogram_', 'jpg' );
</code>```

after correct switch :)

```<code>%boat_image&histogram
subplot(1,2,1)
imshow(I02);
subplot(1,2,2)
[cts,x] = imhist(I02);
stem(x,cts);
ylim([0,max(cts)]);
saveas( gcf, 'boat_image&histogram__', 'jpg' );
</code>```

It was added;

There is a big visual gap both first histogram and the last one.

答:
You could probably use

```<code>ylim([0,max_val])
</code>```

where max_val is the greatest y-value you want to have displayed.

You could even do that directly using

```<code>h = hist(your_data);
ylim([0,max(h)]);
</code>```

Alternatively when using imhist you can use the stem command:

```<code>[cts,x] = imhist(img);
stem(x,cts);
ylim([0,max(cts)]);
</code>```

Body:
%boat_image&histogram
subplot(1,2,1)
imshow(I01);
subplot(1,2,2)
imhist(I01);
saveas( gcf, 'boat_image&histogram', 'jpg' );

I want to cover all y values. How can I change the axis values in terms of the covering maximum value?

after adding following commands, I recieved a different histogram below.

%boat_image&histogram
subplot(1,2,1)
imshow(I02);
subplot(1,2,2)
[cts,x] = imhist(I02);
stem(cts,x);
ylim([0,max(x)]);
saveas( gcf, 'boat_image&histogram_', 'jpg' );

after switch:

%boat_image&histogram
 subplot(1,2,1)
    imshow(I02);
    subplot(1,2,2)
    [x,cts] = imhist(I02);
    stem(x,cts);
    ylim([0,max(x)]);
    saveas( gcf, 'boat_image&histogram_', 'jpg' );

after correct switch :)

%boat_image&histogram
subplot(1,2,1)
imshow(I02);
subplot(1,2,2)
[cts,x] = imhist(I02);
stem(x,cts);
ylim([0,max(cts)]);
saveas( gcf, 'boat_image&histogram__', 'jpg' );

It was added;

There is a big visual gap both first histogram and the last one.

Body:
You could probably use

ylim([0,max_val])

where max_val is the greatest y-value you want to have displayed.

You could even do that directly using

h = hist(your_data);
ylim([0,max(h)]);

Alternatively when using imhist you can use the stem command:

[cts,x] = imhist(img);
stem(x,cts);
ylim([0,max(cts)]);


问:
Pass in any number of arguments into a Javascript function
I want to be able to pass in any number of arguments into a function and then be able to use those arguments later. I know I can pass in default arguments but I don't know what to declare in my function.

For example,

```<code>function test(????) {
  console.log(a)
  console.log(b)
  console.log(c)
}

test(a="a", b="b", c="c")
</code>```

I'm also challenged by being given this function and to make as little changes to the var declarations as much as possible. So here, variables, a, b, and c are declared and I'm not able to edit these variables. I should be able to pass in arguments that will then know to assign itself to these variables.

```<code>function test(???) {
  var a,b,c
  if (a>b){
    c = a + b
  }
}

test(a=2,b=3)
</code>```

答:
you could pass in an object or an array:</p>

```<code>function test1([a, b, c]) {
   // ...
}
test1([1, 2, 3]);

function test2({ a, b, c }) {
   // ...
}
test2({ a: 1, b: 2, c: 3 });
</code>```

Body:
I want to be able to pass in any number of arguments into a function and then be able to use those arguments later. I know I can pass in default arguments but I don't know what to declare in my function.

For example,

function test(????) {
  console.log(a)
  console.log(b)
  console.log(c)
}

test(a="a", b="b", c="c")

I'm also challenged by being given this function and to make as little changes to the var declarations as much as possible. So here, variables, a, b, and c are declared and I'm not able to edit these variables. I should be able to pass in arguments that will then know to assign itself to these variables.

function test(???) {
  var a,b,c
  if (a>b){
    c = a + b
  }
}

test(a=2,b=3)

Body:
you could pass in an object or an array:

function test1([a, b, c]) {
   // ...
}
test1([1, 2, 3]);

function test2({ a, b, c }) {
   // ...
}
test2({ a: 1, b: 2, c: 3 });


问:
How to produce an ordered sequence of vertices of polygon from a discretized cellular representation of polygon
Here is the cellular representation of polygon shown:-

Here is the extracted polygon shown.

We are given the input as a matrix polM that stores 1 for pink cells and 2 for yellow cells. From the yellow colored cells we want to create a polygon. This is also done using below code derived from here.

```<code>clear;
close all;
A=ones(25,25);
indices=[64,65,88,89,90,91,111,112,113,114,115,116,117,135,136,137,138,139,140,141,142,143,158,159,160,161,162,163,164,165,166,167,168,169,182,183,184,185,186,187,188,189,190,191,192,193,194,195,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,282,283,284,285,286,287,288,289,290,291,292,293,294,295,307,308,309,310,311,314,315,316,317,318,319,320,341,342,343,344,345,367,368,369,393,394];
A(indices)=2;

figure
hold on
axis equal
axis ij
xx=10:20:500;
yy=10:20:500;
imagesc(xx,yy,A);
colormap([1.0000         0    0.7931;
    1.0000    0.8276         0]);
rt=[0,500];
gcs=0:20:500;
gds=ones(size(rt,2),size(gcs,2));
gds = bsxfun(@times,gds,gcs);
plot(rt,gds,'Color','k','LineStyle','-');
plot(gds,rt,'Color','k','LineStyle','-');
axis([0 350 100 450])

A=A-1;
% we identify patterns with edges over 2x2 patches, describing with
% the first 4 binary values what pixels are set, and with the next 2
% the edge with 2 indices over the 2x2 patch
patterns = [
    0,1,0,1,  3,4 % vertical edge at rhe right
    1,0,1,0,  1,2 % vertical edge at the left
    0,0,1,1,  2,4 % horizontal edge at the bottom
    1,1,0,0,  1,3 % horizontal edge at the top
    1,0,0,1,  1,4 % diagonal edge
    0,1,1,0,  2,3 % diagonal edge
    1,0,1,1,  1,4 % diagonal edge, extra pixel set
    1,1,0,1,  1,4 % diagonal edge, extra pixel set
    1,1,1,0,  2,3 % diagonal edge, extra pixel set
    0,1,1,1,  2,3 % diagonal edge, extra pixel set
    ];

% 2x2 patches (matrix form)
P00 = A(1:end-1,1:end-1);
P10 = A(2:end,1:end-1);
P01 = A(1:end-1,2:end);
P11 = A(2:end,2:end);

% edge unique identifier using powers of 2
id = @(p00,p01,p10,p11) 1*p00 + 2*p10 + 4*p01 + 8*p11;
P = id(P00,P01,P10,P11); % vectorized pattern identification

% edges
e0 = []; % from (i,j)
e1 = []; % to (i,j)
for i = 1:size(patterns, 1) % small loop over the 10 patterns
    p = patterns(i, :);
    E = (P == id(p(1),p(2),p(3),p(4))); % pattern search, vectorized
    [c,r] = ind2sub(size(E), find(E));
    [c0,r0] = ind2sub([2,2], p(5));
    [c1,r1] = ind2sub([2,2], p(6));
    e0 = [e0; c+c0, r+r0];
    e1 = [e1; c+c1, r+r1];
end

X = [e0(:,2) e1(:,2)]';
Y = size(A,1) - [e0(:,1) e1(:,1)]';

figure
hold on
axis equal
axis ij
X=X*20;
Y=Y*20; Y=500-Y;
plot(X, Y, '.-')
axis([0 350 100 450])
</code>```

But the output of this code which represents the polygon is given by arrays X and Y. I want to express the output in nx2 matrix form where all rows represent a vertex if the final polygon and the vertices are in a clockwise or counter clockwise order starting from the first vertex. There are methods here that can post-process a jumbled sequence of vertices to an ordered sequence but i want an algorithm to determine the polygonal vertices from input matrix polM in an ordered sequence only. SO input is polM and output is a nx2 matrix of polygon vertices in either cw or ccw order only.

Can someone suggest an efficient change to the algorithm?

EDIT:

If you add this piece of code assuming ordered result is already coming you get error:-

```<code>newp=[X(1,:)',Y(1,:)'];
figure
hold on
axis([0 350 100 450])
axis equal
axis ij
line(newp(:,1), newp(:,2));
</code>```

Basically i want to resolve this error.

答:
X and Y are both 2xn matrices specifying n unordered vertexes, i.e. a line should be drawn between [X(1, i) Y(1, i)] and [X(2, i) Y(2, i)] for every i=1:n. Because all the vertexes are connected, every point should occur twice in these X and Y matrices. Therefore, one can start at an arbitrary point on the polygon and search the next point iteratively. This can be done as follows:

% XY_from: a `nx2` matrix containing all starting points
% with a third column indicating if this vertex is already used
XY_from = [X(1, :)' Y(1, :)' zeros(size(X, 2), 1)];
XY_to = [X(2, :)' Y(2, :)' zeros(size(X, 2), 1)]; % similar matrix for destination points
new_poly = zeros(size(X, 2)+1, 2); % allocate output space
new_poly(1, :) = XY_from(1, 1:2); % select an arbitrary starting point
for i=2:size(new_poly, 1)
  index = find(all([new_poly(i-1, :) 0] == XY_from, 2), 1); % search the previous (unused) point in the starting points
  if isempty(index)
    index = find(all([new_poly(i-1, :) 0] == XY_to, 2), 1); % if no point was found, search it in the destination points
    new_poly(i, :) = XY_from(index, 1:2); % add the new point (corresponding with the found destination point)
  else
    new_poly(i, :) = XY_to(index, 1:2); % add the new point (corresponding with the found start point)
  end
  XY_from(index, 3) = 1; % indicate that this start point is used
  XY_to(index, 3) = 1; % indicate that this destination point is used
end

hold on
plot(new_poly(:, 1), new_poly(:, 2), '--k', 'LineWidth', 2); % plot on top of the polygon
```

Body:
Here is the cellular representation of polygon shown:-

Here is the extracted polygon shown.

We are given the input as a matrix polM that stores 1 for pink cells and 2 for yellow cells. From the yellow colored cells we want to create a polygon. This is also done using below code derived from here.

clear;
close all;
A=ones(25,25);
indices=[64,65,88,89,90,91,111,112,113,114,115,116,117,135,136,137,138,139,140,141,142,143,158,159,160,161,162,163,164,165,166,167,168,169,182,183,184,185,186,187,188,189,190,191,192,193,194,195,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,282,283,284,285,286,287,288,289,290,291,292,293,294,295,307,308,309,310,311,314,315,316,317,318,319,320,341,342,343,344,345,367,368,369,393,394];
A(indices)=2;

figure
hold on
axis equal
axis ij
xx=10:20:500;
yy=10:20:500;
imagesc(xx,yy,A);
colormap([1.0000         0    0.7931;
    1.0000    0.8276         0]);
rt=[0,500];
gcs=0:20:500;
gds=ones(size(rt,2),size(gcs,2));
gds = bsxfun(@times,gds,gcs);
plot(rt,gds,'Color','k','LineStyle','-');
plot(gds,rt,'Color','k','LineStyle','-');
axis([0 350 100 450])

A=A-1;
% we identify patterns with edges over 2x2 patches, describing with
% the first 4 binary values what pixels are set, and with the next 2
% the edge with 2 indices over the 2x2 patch
patterns = [
    0,1,0,1,  3,4 % vertical edge at rhe right
    1,0,1,0,  1,2 % vertical edge at the left
    0,0,1,1,  2,4 % horizontal edge at the bottom
    1,1,0,0,  1,3 % horizontal edge at the top
    1,0,0,1,  1,4 % diagonal edge
    0,1,1,0,  2,3 % diagonal edge
    1,0,1,1,  1,4 % diagonal edge, extra pixel set
    1,1,0,1,  1,4 % diagonal edge, extra pixel set
    1,1,1,0,  2,3 % diagonal edge, extra pixel set
    0,1,1,1,  2,3 % diagonal edge, extra pixel set
    ];

% 2x2 patches (matrix form)
P00 = A(1:end-1,1:end-1);
P10 = A(2:end,1:end-1);
P01 = A(1:end-1,2:end);
P11 = A(2:end,2:end);

% edge unique identifier using powers of 2
id = @(p00,p01,p10,p11) 1*p00 + 2*p10 + 4*p01 + 8*p11;
P = id(P00,P01,P10,P11); % vectorized pattern identification

% edges
e0 = []; % from (i,j)
e1 = []; % to (i,j)
for i = 1:size(patterns, 1) % small loop over the 10 patterns
    p = patterns(i, :);
    E = (P == id(p(1),p(2),p(3),p(4))); % pattern search, vectorized
    [c,r] = ind2sub(size(E), find(E));
    [c0,r0] = ind2sub([2,2], p(5));
    [c1,r1] = ind2sub([2,2], p(6));
    e0 = [e0; c+c0, r+r0];
    e1 = [e1; c+c1, r+r1];
end

X = [e0(:,2) e1(:,2)]';
Y = size(A,1) - [e0(:,1) e1(:,1)]';

figure
hold on
axis equal
axis ij
X=X*20;
Y=Y*20; Y=500-Y;
plot(X, Y, '.-')
axis([0 350 100 450])

But the output of this code which represents the polygon is given by arrays X and Y. I want to express the output in nx2 matrix form where all rows represent a vertex if the final polygon and the vertices are in a clockwise or counter clockwise order starting from the first vertex. There are methods here that can post-process a jumbled sequence of vertices to an ordered sequence but i want an algorithm to determine the polygonal vertices from input matrix polM in an ordered sequence only. SO input is polM and output is a nx2 matrix of polygon vertices in either cw or ccw order only.

Can someone suggest an efficient change to the algorithm?

EDIT:

If you add this piece of code assuming ordered result is already coming you get error:-

newp=[X(1,:)',Y(1,:)'];
figure
hold on
axis([0 350 100 450])
axis equal
axis ij
line(newp(:,1), newp(:,2));

Basically i want to resolve this error.


问:
Get commit message in Git hook
I would like to check the commit message before Git commit.

I use a pre-commit hook to do that, but I couldn't find the way to get the commit message in the .git/pre-commit script.
How could I get it?

答:
I implemented this in the commit-msg hook. See the documentation.

```<code>commit-msg

This hook is invoked by git commit, and can be bypassed with the --no-verify option.
It takes a single parameter, the name of the file that holds the proposed commit log message.
Exiting with a non-zero status causes the git commit to abort.
</code>```

Under my_git_project/.git/hooks, I added the file commit-msg (has to be this name). I added the following Bash contents inside this file which did the validation.

#!/usr/bin/env bash
INPUT_FILE=$1
START_LINE=`head -n1 $INPUT_FILE`
PATTERN="^(MYPROJ)-[[:digit:]]+: "
if ! [[ "$START_LINE" =~ $PATTERN ]]; then
  echo "Bad commit message, see example: MYPROJ-123: commit message"
  exit 1
fi
```

ContentLicense: CC BY-SA 4.0

Title: Get commit message in Git hook

Body:
I implemented this in the commit-msg hook. See the documentation.

commit-msg

This hook is invoked by git commit, and can be bypassed with the --no-verify option.
It takes a single parameter, the name of the file that holds the proposed commit log message.
Exiting with a non-zero status causes the git commit to abort.

Under my_git_project/.git/hooks, I added the file commit-msg (has to be this name). I added the following Bash contents inside this file which did the validation.

#!/usr/bin/env bash
INPUT_FILE=$1
START_LINE=`head -n1 $INPUT_FILE`
PATTERN="^(MYPROJ)-[[:digit:]]+: "
if ! [[ "$START_LINE" =~ $PATTERN ]]; then
  echo "Bad commit message, see example: MYPROJ-123: commit message"
  exit 1
fi


问:
Sending a file to a server using sockets in Python
Mainpage displays my front page and upload is supposed to display the page
where you enter the file you wish to store with the server

```<code>def upload():
        path_name = raw_input("Enter your file directory")
        open_file = open(path_name,'rb').read()
        name_split = path_name.split("\\")[-1].split('.')
        at = 1

        s.send("SAVE-"+username+"\\"+"".join(name_split[:-1])+"."+str(at)+"."+name_split[-1]+"-")

        while open_file:
            current = open_file[:1024]
            print current
            open_file = open_file[1024:]
            s.send(current)

def mainpage():
        global R2
        R2=Tk()
        gg="white"
        g="blue"
        R2.geometry('720x720')
        R2.title(username + " Dropbox")
        R2.resizable(width=False,height=False)
        logoutbt= Button(R2,text="Logout",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=deslogout)
        upload = Button(R2,text="Upload",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desupload)
        retrieve = Button(R2,text="Retreive",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desretreive)
        logoutbt.place(x = 220,y = 500)
        retrieve.place(x = 350,y = 500)
        upload.place(x = 480,y = 500)
        R2.mainloop()
        open(path_name,'rb').close()
</code>```

Now when I add the command mainpage() to return back to to my main page after sending the file to the server,the server gets stuck in an infinite loop

```<code>ServerCode

if message[0] == "SAVE":
                    if not os.path.exists("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0]):
                        os.makedirs("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0])
                    file =open("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+ message[1],"wb")
                    content = ""
                    while True:
                        data = current_socket.recv(1024)
                        if not data:
                            break
                        content += data

                    file.write(content)
                    file.close()
</code>```

The file reaches the server fine when I don't try to return, but the moment I add that one extra line, the server doesn't exit its loop where it receives all the file content. Also,if I try to get a response from the server when it's done writing all the data down, the client and the server get stuck.

答:
Python's socket.recv(...) inherits semantics from Unix recv(2) function, and as stated in recv(2) man:

If no messages are available at the socket, the receive calls wait  for a  message  to arrive, unless the socket is nonblocking

Therefore, since current_socket is blocking, your server just hangs on the line data = current_socket.recv(1024) infinitely right after the whole file has been read to the content variable until the socket on the client becomes properly closed.

To avoid that:

On the client side send your file size in bytes before sending any of its contents:

```<code>import struct

...

file_len_bytes = pack('!i', len(open_file))
s.send(file_len_bytes)

while open_file:
    ....
</code>```

On the server side read your file size and then use it to check whether the whole file has been read:

```<code>import struct

...

file_len_bytes = ""
while len(file_len_bytes) < 4:
    file_len_bytes += client.recv(1)
file_len = struct.unpack("!i", file_len_bytes[:4])[0]

content = ""
bytes_read = 0
while bytes_read < file_len:
    data = current_socket.recv(1024)
    bytes_read += len(data)
    content += data
</code>```

Body:
Mainpage displays my front page and upload is supposed to display the page
where you enter the file you wish to store with the server

def upload():
        path_name = raw_input("Enter your file directory")
        open_file = open(path_name,'rb').read()
        name_split = path_name.split("\\")[-1].split('.')
        at = 1

        s.send("SAVE-"+username+"\\"+"".join(name_split[:-1])+"."+str(at)+"."+name_split[-1]+"-")

        while open_file:
            current = open_file[:1024]
            print current
            open_file = open_file[1024:]
            s.send(current)

def mainpage():
        global R2
        R2=Tk()
        gg="white"
        g="blue"
        R2.geometry('720x720')
        R2.title(username + " Dropbox")
        R2.resizable(width=False,height=False)
        logoutbt= Button(R2,text="Logout",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=deslogout)
        upload = Button(R2,text="Upload",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desupload)
        retrieve = Button(R2,text="Retreive",width=10,height=2,bg=g,fg=gg,font="5",relief=RAISED,overrelief=RIDGE,command=desretreive)
        logoutbt.place(x = 220,y = 500)
        retrieve.place(x = 350,y = 500)
        upload.place(x = 480,y = 500)
        R2.mainloop()
        open(path_name,'rb').close()

Now when I add the command mainpage() to return back to to my main page after sending the file to the server,the server gets stuck in an infinite loop

ServerCode

if message[0] == "SAVE":
                    if not os.path.exists("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0]):
                        os.makedirs("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+message[1].split("\\")[0])
                    file =open("C:\Heights\Documents\Projects\HomeWork\Project\Server1\\Files\\"+ message[1],"wb")
                    content = ""
                    while True:
                        data = current_socket.recv(1024)
                        if not data:
                            break
                        content += data

                    file.write(content)
                    file.close()

The file reaches the server fine when I don't try to return, but the moment I add that one extra line, the server doesn't exit its loop where it receives all the file content. Also,if I try to get a response from the server when it's done writing all the data down, the client and the server get stuck.

Body:
Python's socket.recv(...) inherits semantics from Unix recv(2) function, and as stated in recv(2) man:

If no messages are available at the socket, the receive calls wait  for a  message  to arrive, unless the socket is nonblocking

Therefore, since current_socket is blocking, your server just hangs on the line data = current_socket.recv(1024) infinitely right after the whole file has been read to the content variable until the socket on the client becomes properly closed.

To avoid that:

On the client side send your file size in bytes before sending any of its contents:

import struct

...

file_len_bytes = pack('!i', len(open_file))
s.send(file_len_bytes)

while open_file:
    ....

On the server side read your file size and then use it to check whether the whole file has been read:

import struct

...

file_len_bytes = ""
while len(file_len_bytes) < 4:
    file_len_bytes += client.recv(1)
file_len = struct.unpack("!i", file_len_bytes[:4])[0]

content = ""
bytes_read = 0
while bytes_read < file_len:
    data = current_socket.recv(1024)
    bytes_read += len(data)
    content += data


问:
PowerPivot relations witht the same columns from 2 excels
How do I powerpivot 2 excel files with the exact same column information.  It comes from 2 different production machines and the information is the same.  There is just too many columns (same) and rows to just copy and paste and put in to a pivot table.  I got an error message "the relationship cannot be created because each column contains duplicate values.</p>

答: You could use Power Query to append the two tables and load that appended table into the data model. Relationships don't work for that kind of scenario.</p>


问:
Disable mouse hover on click
I have box which flips on hover. You can check here.
http://rehabhousedeals.com/shortcode/

I have add red icon on top right corner on other side of box.
I want as user will click on this icon box should flip back.
Actually this is for mobile view. User should be able to flip back on front side by clicking this icon.
Here are container class with hover effect in my css.

```<code>.card-container:not(.manual-flip):hover .card,
.card-container.hover.manual-flip .card{
    -webkit-transform: rotateY( 180deg );
-moz-transform: rotateY( 180deg );
 -o-transform: rotateY( 180deg );
    transform: rotateY( 180deg );
}

.card-container.static:hover .card,
.card-container.static.hover .card {
    -webkit-transform: none;
-moz-transform: none;
 -o-transform: none;
    transform: none;
}
</code>```

Kindly help me get this.

答:
If I understand your question correctly I may have a solution. I'm not sure if this can be done in css alone, but in JavaScript you can simply add a class on hover and remove it when the icon is clicked

something like this

```<code> box.addEventListener('mouseenter', function() {
   this.classList.add('boxHover');
 });
</code>```

and remove it when the icon is clicked

```<code>icon.addEventListener('click', function() {
  box.classList.remove('boxHover');
});
</code>```

Here is an example
https://jsfiddle.net/vqk8Ld46/

Title: Disable mouse hover on click

Body:
I have box which flips on hover. You can check here.
http://rehabhousedeals.com/shortcode/

I have add red icon on top right corner on other side of box.
I want as user will click on this icon box should flip back.
Actually this is for mobile view. User should be able to flip back on front side by clicking this icon.
Here are container class with hover effect in my css.

.card-container:not(.manual-flip):hover .card,
.card-container.hover.manual-flip .card{
    -webkit-transform: rotateY( 180deg );
-moz-transform: rotateY( 180deg );
 -o-transform: rotateY( 180deg );
    transform: rotateY( 180deg );
}

.card-container.static:hover .card,
.card-container.static.hover .card {
    -webkit-transform: none;
-moz-transform: none;
 -o-transform: none;
    transform: none;
}

Kindly help me get this.

Body:
If I understand your question correctly I may have a solution. I'm not sure if this can be done in css alone, but in JavaScript you can simply add a class on hover and remove it when the icon is clicked

something like this

 box.addEventListener('mouseenter', function() {
   this.classList.add('boxHover');
 });

and remove it when the icon is clicked

icon.addEventListener('click', function() {
  box.classList.remove('boxHover');
});

Here is an example
https://jsfiddle.net/vqk8Ld46/


问:
Python: How to combine two SQL queries
As I have limited knowledge about Python how can I crate in Python one query  which will contains both from below where second will be queried for when first will return not results (no email address returned)

Code blow

```<code>bits = sys.argv[1].split('@')
if len(bits) != 2:
    sys.exit(0)

cur.execute("SELECT email FROM notifications WHERE diraddr = %s", (sys.argv[1],))
cur.execute("SELECT email FROM users WHERE (username LIKE %s) AND (domain LIKE %s) and notifications = 'Y'", (bits[0], bits[1]))
</code>```

I have tried to do IF...ELSE for email return results from  first SQL query but it looks like can be done in one query without IF...ELSE statement.

答:
Can you be more specific with the question when you say COMBINE.

From what I understand from the code is that you will you be getting an email id as input (as argument)?

You will split that email id and store username and domain name as 2 list elements. If the first query do not return any result(querying notification table) , then you want to execute another query(on users table) using the element in the list?

If above scenario is true, then use a simple if else logic to check if the first query is returning any result.If it is not returning anything, then execute the 2nd query in the else part.

Title: Python: How to combine two SQL queries

Body:
As I have limited knowledge about Python how can I crate in Python one query  which will contains both from below where second will be queried for when first will return not results (no email address returned)

Code blow

bits = sys.argv[1].split('@')
if len(bits) != 2:
    sys.exit(0)

cur.execute("SELECT email FROM notifications WHERE diraddr = %s", (sys.argv[1],))
cur.execute("SELECT email FROM users WHERE (username LIKE %s) AND (domain LIKE %s) and notifications = 'Y'", (bits[0], bits[1]))

I have tried to do IF...ELSE for email return results from  first SQL query but it looks like can be done in one query without IF...ELSE statement.


问:
What is the appropriate way to delete a service in Service Fabric?
I have an application running in service fabric.  One of the services that compose the application is a stateful service that only has a run method. It queries other services, does some record keeping as it goes, and then produces an output.  Upon successful completion of the work, it saves the output to Blob Storage and then deletes itself.  I use this for on demand elastic compute around reporting.

If I call into the ServiceManager service to delete the service itself, it appears to deadlock.  This makes sense to me, since the call is likely awaiting the run method's completion before returning to the caller (in this case the caller is in the run method itself so it is effectively awaiting itself).  My next approach was to essentially ignore a Task to asynchronously delete the service like so:

```<code>protected override async Task RunAsync(CancellationToken can)
{

    //do work as described above

    Task ignored = Task.Factory.Run(async ()=>{
       await s_FabricClient.ServiceManager.DeleteServiceAsync(/*blah blah*/);
    }
    await Task.Delay(30000);
}
</code>```

What is the appropriate way to delete a service, when I know the service should under all circumstances be deleted. I would like to avoid a 'manager' service which tracks these things, because right now they are very well self contained.

答:
You can remove the service by using powershell command
Remove-ServiceFabricService
Please have a look here for documentation
https://learn.microsoft.com/en-us/powershell/module/servicefabric/Remove-ServiceFabricService?view=azureservicefabricps

The deadlock issue could be due to your code does not check for cancellation token. The idea is when you stop tell service fabric to stop a service cancellation token should be passed into your code. If you code dont check for the token then service fabric can not gracefully stop the service. This is the bit

```<code>  //do work as described above
</code>```

Body:
I have an application running in service fabric.  One of the services that compose the application is a stateful service that only has a run method. It queries other services, does some record keeping as it goes, and then produces an output.  Upon successful completion of the work, it saves the output to Blob Storage and then deletes itself.  I use this for on demand elastic compute around reporting.

If I call into the ServiceManager service to delete the service itself, it appears to deadlock.  This makes sense to me, since the call is likely awaiting the run method's completion before returning to the caller (in this case the caller is in the run method itself so it is effectively awaiting itself).  My next approach was to essentially ignore a Task to asynchronously delete the service like so:

protected override async Task RunAsync(CancellationToken can)
{

    //do work as described above

    Task ignored = Task.Factory.Run(async ()=>{
       await s_FabricClient.ServiceManager.DeleteServiceAsync(/*blah blah*/);
    }
    await Task.Delay(30000);
}

What is the appropriate way to delete a service, when I know the service should under all circumstances be deleted. I would like to avoid a 'manager' service which tracks these things, because right now they are very well self contained.

Body:
You can remove the service by using powershell command
Remove-ServiceFabricService
Please have a look here for documentation
https://learn.microsoft.com/en-us/powershell/module/servicefabric/Remove-ServiceFabricService?view=azureservicefabricps

The deadlock issue could be due to your code does not check for cancellation token. The idea is when you stop tell service fabric to stop a service cancellation token should be passed into your code. If you code dont check for the token then service fabric can not gracefully stop the service. This is the bit

  //do work as described above


问:
Datagrid paging align right
I have a datagrid and I set up the paging based on how many rows there are like this

```<code>With dgBookings
    .AllowPaging = True
    .PagerStyle.Mode = PagerMode.NumericPages
    .PagerStyle.PageButtonCount = 5
    .PageSize = 5
   End With
</code>```

Is there a way to set the horizontal-align in the code too I tried adding this

```<code>    .PagerStyle.HorizontalAlign = Right
</code>```

and I get this error

```<code>Argument not specified for parameter 'Length' of 'Public Function Right(str As String, Length As Integer) As String'.
</code>```

Any ideas?

Thanks

答:
It should be

```<code>.PagerStyle.HorizontalAlign = HorizontalAlign.Right
</code>```

You need to indicate that it's an enumerator value.

ContentLicense: CC BY-SA 2.5

Title: Datagrid paging align right

Body:
I have a datagrid and I set up the paging based on how many rows there are like this

With dgBookings
    .AllowPaging = True
    .PagerStyle.Mode = PagerMode.NumericPages
    .PagerStyle.PageButtonCount = 5
    .PageSize = 5
   End With

Is there a way to set the horizontal-align in the code too I tried adding this

    .PagerStyle.HorizontalAlign = Right

and I get this error

Argument not specified for parameter 'Length' of 'Public Function Right(str As String, Length As Integer) As String'.

Any ideas?

Thanks

Body:
It should be

.PagerStyle.HorizontalAlign = HorizontalAlign.Right

You need to indicate that it's an enumerator value.


问:
Find a distance between point clouds efficiently
I have 2 point clouds (a set of points in 3D space) and an iterative algorithm. One of the clouds (let's call it A) is constant on each iteration and another (call it B(i)) is slightly different on each iteration (it means that B(i+1) differs from B(i) only in a few points). On every iteration i for each point from A my algorithm should find closest point from B(i).

My question is: how can I compute these distances in a fastest way possible?

Here is what I've already tried:

Brute force computing (compute all distances for each pair of points from A and B(i)) - absolutely inefficient.

On each iteration build a KD-tree for B(i) and then find closest points for each point from A - faster then brute force, but still computationally expensive (because I should rebuild KD-tree on each iteration).

It seems like I should utilize a fact that B(i) and B(i+1) differs only slightly from each other, but I still can't come up with a good solution. Thank you in advance.

答:
For each point in A, keep a record of which point was closest in the previous iteration B(i).

At iteration i+1, make a list of each point in B that was deleted or changed between i and i+1, and also each new point in B.

For each point in A:

If the previous closest point in B was not changed or removed, then you only need to compute the distance from A to the closest of the new points in B(i+1) and check against the previous closest in B(i).

If the previous closest point in B(i) was changed or removed, then you need to compute the closest distance from A to any of the points in B(i+1)

You can use a KD-tree or whatever spatial data structure you like to speed this up, but the optimization comes from the first case. Note that a KD-tree allows removal so you don't need to rebuild the whole thing from scratch each iteration.


问:
Short-circuit evaluation evaluating if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
The program is posted below:

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

int main(void)
{
    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);

    if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
        printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
}
</code>```

I understand the first printf statement but in the 2nd if statement I do not understand what it would evaluate when there is only one equal sign instead of two.

The output is :

```<code>        a = 0, b = 0, c = 32767, d = -341260496
        a = 4, b = 0, c = 32767, d = -341260496
</code>```

So the 2nd if statement ended up being true but how?

I thought one equal sign would be assigning a value to the variables.

答:
I do not understand what if would evaluate when there is only one equal sign instead of two.

One equal sign makes it an assignment. Hence, a=4 evaluates to 4, which is interpreted as "true" by the logical "OR" operator ||. At this point no further evaluation is happening due to short-circuiting, so the remaining variables retain the values that they have prior to the if statement.

Note: Printing unassigned variables causes undefined behavior. You should change the declaration line as follows:

```<code>int a = 0, b = 0, c = 0, d = 0;
</code>```

Body:
The program is posted below:

#include <stdio.h>

int main(void)
{
    int a, b, c, d;

    printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);

    if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )
        printf("a = %d, b = %d, c = %d, d = %d\n", a, b, c, d);
}

I understand the first printf statement but in the 2nd if statement I do not understand what it would evaluate when there is only one equal sign instead of two.

The output is :

        a = 0, b = 0, c = 32767, d = -341260496
        a = 4, b = 0, c = 32767, d = -341260496

So the 2nd if statement ended up being true but how?

I thought one equal sign would be assigning a value to the variables.

Body:
I do not understand what if would evaluate when there is only one equal sign instead of two.

One equal sign makes it an assignment. Hence, a=4 evaluates to 4, which is interpreted as "true" by the logical "OR" operator ||. At this point no further evaluation is happening due to short-circuiting, so the remaining variables retain the values that they have prior to the if statement.

Note: Printing unassigned variables causes undefined behavior. You should change the declaration line as follows:

int a = 0, b = 0, c = 0, d = 0;


答:
Given your example:

```<code>$ awk -F, '{print $6}' file
Basildon
Parkville
Astoria
Echuca
Cahaba Heights
Mickleton
Peoria
Martin
Tel Aviv
Chatou
</code>```

Or with cut:

```<code>$ cut -d, -f 6 file
# same output
</code>```

Or, for all fields up to and including the 6th:

```<code>$ awk 'BEGIN{FS=OFS=","} {for (i=1;i<=6;i++) printf "%s%s", $i, i==6 ? ORS : OFS}' file
</code>```

Or, cut version:

```<code>$ cut -d, -f-6 file
</code>```

Title: Bash cut .csv files

Body:
I'm working with a sample .csv file

my.csv:

1/2/09 6:17,Product1,1200,Mastercard,carolina,Basildon,England,United Kingdom,1/2/09 6:00,1/2/09 6:08,51.5,-1.1166667
1/2/09 4:53,Product1,1200,Visa,Betina,Parkville                   ,MO,United States,1/2/09 4:42,1/2/09 7:49,39.195,-94.68194
1/2/09 13:08,Product1,1200,Mastercard,Federica e Andrea,Astoria                     ,OR,United States,1/1/09 16:21,1/3/09 12:32,46.18806,-123.83
1/3/09 14:44,Product1,1200,Visa,Gouya,Echuca,Victoria,Australia,9/25/05 21:13,1/3/09 14:22,-36.1333333,144.75
1/4/09 12:56,Product2,3600,Visa,Gerd W ,Cahaba Heights              ,AL,United States,11/15/08 15:47,1/4/09 12:45,33.52056,-86.8025
1/4/09 13:19,Product1,1200,Visa,LAURENCE,Mickleton                   ,NJ,United States,9/24/08 15:19,1/4/09 13:04,39.79,-75.23806
1/4/09 20:11,Product1,1200,Mastercard,Fleur,Peoria                      ,IL,United States,1/3/09 9:38,1/4/09 19:45,40.69361,-89.58889
1/2/09 20:09,Product1,1200,Mastercard,adam,Martin                      ,TN,United States,1/2/09 17:43,1/4/09 20:01,36.34333,-88.85028
1/4/09 13:17,Product1,1200,Mastercard,Renee Elisabeth,Tel Aviv,Tel Aviv,Israel,1/4/09 13:03,1/4/09 22:10,32.0666667,34.7666667
1/4/09 14:11,Product1,1200,Visa,Aidan,Chatou,Ile-de-France,France,6/3/08 4:22,1/5/09 1:17,48.8833333,2.15

I'm trying to print out data using cut -d"," -f-6 my.csv but this only prints the first row:

1/2/09 6:17,Product1,1200,Mastercard,carolina,Basildon

How do I get cut to print the entries of every row matching the delimiter/field?

Body:
Given your example:

$ awk -F, '{print $6}' file
Basildon
Parkville
Astoria
Echuca
Cahaba Heights
Mickleton
Peoria
Martin
Tel Aviv
Chatou

Or with cut:

$ cut -d, -f 6 file
# same output

Or, for all fields up to and including the 6th:

$ awk 'BEGIN{FS=OFS=","} {for (i=1;i<=6;i++) printf "%s%s", $i, i==6 ? ORS : OFS}' file

Or, cut version:

$ cut -d, -f-6 file


答:
So the 2nd if statement ended up being true but how?

In C, assignments are also a sort of expression that evaluate to some value. The value is (in most situations) the right hand side of the assignment.

In this case, (a = 4) evaluates to 4, which is true in the world of C, thus short-circuiting the entire condition and skipping the assignments for b, c and d. Which is why only a is initialised while the others retain their junk values.

Title: Short-circuit evaluation evaluating if( (a = 4) || (b = 6) || (c = 7) || (d = 8) )


问:
Dynamic restrictions in SQLAlchemy Core query
I want to write a query where I can dynamically pass various restrictions to SQLA Core.  For example, I want to be able to specify on a SELECT query WHERE color = 'blue' or not specify that, dynamically. It might be nice to pass in a {'color': 'blue'} restrictions-dict, or maybe there's a more standard way.

I have read the tutorial and API documentation, but I'm wondering:

What would be an idiomatic contract for dynamic restrictions in SQLA Core, and how would it be implemented?

答:
You can build your query dynamically without any problem. For instance, you can do:

```<code>query = select([table])
for key, value in params.iteritems():
    query = query.where(table.columns[key] == value)

print conn.execute(query).fetchall()
</code>```

where params is just a dictionary of restrictions such as {'column': 'value'}. This will produce a query in which all the where clauses are chained with AND. Of course, if you need more complex where clauses the construction of the query can be a bit more difficult.

A working example:

```<code>from sqlalchemy import select
from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer
from sqlalchemy.schema import MetaData, Table

# create engine and connection
DB_URI = "mysql+mysqldb://username:password@127.0.0.1:3306/database?charset=utf8mb4"
engine = create_engine(DB_URI, convert_unicode=True, echo=False)
conn = engine.connect()

# create table
metadata = MetaData()
pieces_table = Table('pieces', metadata,
    Column('id', Integer, primary_key=True),
    Column('size', String(60)),
    Column('color', String(60)),
)
metadata.create_all(engine)

# insert data
conn.execute(pieces_table.insert(), [
    {'size': 'small', 'color': 'blue'},
    {'size': 'large', 'color': 'blue'},
    {'size': 'small', 'color': 'red'},
])

# query data

def build_query(table, params):
    query = select([table])
    for key, value in params.iteritems():
        query = query.where(table.columns[key] == value)
    return query

params = {
    'size': 'large',
    'color': 'blue',
}
query = build_query(pieces_table, params)
print conn.execute(query).fetchall()
</code>```

Body:
You can build your query dynamically without any problem. For instance, you can do:

query = select([table])
for key, value in params.iteritems():
    query = query.where(table.columns[key] == value)

print conn.execute(query).fetchall()

where params is just a dictionary of restrictions such as {'column': 'value'}. This will produce a query in which all the where clauses are chained with AND. Of course, if you need more complex where clauses the construction of the query can be a bit more difficult.

A working example:

from sqlalchemy import select
from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer
from sqlalchemy.schema import MetaData, Table

# create engine and connection
DB_URI = "mysql+mysqldb://username:password@127.0.0.1:3306/database?charset=utf8mb4"
engine = create_engine(DB_URI, convert_unicode=True, echo=False)
conn = engine.connect()

# create table
metadata = MetaData()
pieces_table = Table('pieces', metadata,
    Column('id', Integer, primary_key=True),
    Column('size', String(60)),
    Column('color', String(60)),
)
metadata.create_all(engine)

# insert data
conn.execute(pieces_table.insert(), [
    {'size': 'small', 'color': 'blue'},
    {'size': 'large', 'color': 'blue'},
    {'size': 'small', 'color': 'red'},
])

# query data

def build_query(table, params):
    query = select([table])
    for key, value in params.iteritems():
        query = query.where(table.columns[key] == value)
    return query

params = {
    'size': 'large',
    'color': 'blue',
}
query = build_query(pieces_table, params)
print conn.execute(query).fetchall()


问:
Towers of Hanoi with Stacks Java
I am working on a Towers of Hanoi problem in Java.  I chose to use Stacks as the pegs and have everything working except for the move method.  I have the specification and a JUnit test class and am currently passing 6 of the 7 tests but am failing on the move test.  The specs are as follows:

Here is my Towers class:

```<code>package edu.metrostate.ics240.p2.towers;
import java.util.Stack;

public class Towers {
    private static final int DEFAULT_SIZE = 5;
    private static final int MAX_SIZE = 64;
    private static final int MIN_PEG = 1;
    private static final int MAX_PEG = 3;
    private static Stack<Integer>[] tower = new Stack[4];
    private int numOfRings;

public Towers(int n) {
    if (n < 1 || n > MAX_SIZE)
        throw new IllegalArgumentException(
                String.format("Number of rings (%s) cannot be less than 1 or exceed 64 ", n));
    numOfRings = n;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = 1; i <= numOfRings; i++)
        tower[1].push(i);
}
public Towers() {
    numOfRings = DEFAULT_SIZE;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = 1; i <= numOfRings; i++)
        tower[1].push(i);
}

private static void pegCheck(int pegNumber){
    if (pegNumber < MIN_PEG || pegNumber > MAX_PEG)
        throw new IllegalArgumentException(
                String.format("Peg number (%s) cannot be less than 1 or exceed 3 ", pegNumber));
}
public int getRingCount(int pegNumber) {
    pegCheck(pegNumber);

    switch (pegNumber) {
    case 1:
        if (tower[1].isEmpty())
            return 0;
        else
            return tower[1].size();
    case 2:
        if (tower[2].isEmpty())
            return 0;
        else
            return tower[2].size();
    case 3:
        if (tower[3].isEmpty())
            return 0;
        else
            return tower[3].size();
    default:
        return 0;
    }
}
public int getTopDiameter(int pegNumber) {
    pegCheck(pegNumber);

    switch (pegNumber) {
    case 1:
        if(getRingCount(1) > 0){
            return tower[1].get(tower[1].peek() - tower[1].size());
        }else
            return 0;
    case 2:
        if(getRingCount(2) > 0){
            return tower[2].get(tower[2].peek() - tower[2].size());
        }else
            return 0;
    case 3:
        if(getRingCount(3) > 0){
            return tower[3].get(tower[3].peek() - tower[3].size());
        }else
            return 0;
    default:
        return 0;
    }
}
public boolean move(int startPeg, int endPeg) {
    pegCheck(startPeg);
    pegCheck(endPeg);
    Stack<Integer> startTower = tower[startPeg];
    Stack<Integer> endTower = tower[endPeg];

    if (getRingCount(startPeg) > 0 && endPeg != startPeg && getRingCount(endPeg) > 0 && getTopDiameter(startPeg) < getTopDiameter(endPeg)) {
        int topRing = startTower.pop();
        endTower.push(topRing);
        return true;
    }else
        return false;
}
}
</code>```

and finally the JUnit test(s):

```<code>import static org.junit.Assert.*;
import org.junit.Test;
import edu.metrostate.ics240.p2.towers.*;
import java.util.Random;

public class TowersTest {
    private static final int MAX_NUM_RINGS = 64;
    private static final long SEED = 20170604001L;
    private static final Random RAND = new Random(SEED);

@Test
public void testDefaultConstruction() {
    Towers t = new Towers();
    assertEquals(5, t.getRingCount(1));
    assertEquals(0, t.getRingCount(2));
    assertEquals(0, t.getRingCount(3));

    assertEquals(1, t.getTopDiameter(1));
    assertEquals(0, t.getTopDiameter(2));
    assertEquals(0, t.getTopDiameter(3));
}

@Test
public void testConstruction() {
    int numRings = RAND.nextInt(MAX_NUM_RINGS);
    Towers t = new Towers(numRings);
    assertEquals(numRings, t.getRingCount(1));
    assertEquals(0, t.getRingCount(2));
    assertEquals(0, t.getRingCount(3));

    assertEquals(1, t.getTopDiameter(1));
    assertEquals(0, t.getTopDiameter(2));
    assertEquals(0, t.getTopDiameter(3));
}

@Test
public void testMove() {
    int numRings = RAND.nextInt(64);

    Towers t = new Towers(numRings);

    assertTrue(t.move(1, 2));
    assertEquals(numRings - 1, t.getRingCount(1));
    assertEquals(1, t.getRingCount(2));
    assertEquals(0, t.getRingCount(3));

    assertEquals(2, t.getTopDiameter(1));
    assertEquals(1, t.getTopDiameter(2));
    assertEquals(0, t.getTopDiameter(3));

    assertTrue(t.move(1, 3));
    assertEquals(numRings - 2, t.getRingCount(1));
    assertEquals(1, t.getRingCount(2));
    assertEquals(1, t.getRingCount(3));

    assertEquals(3, t.getTopDiameter(1));
    assertEquals(1, t.getTopDiameter(2));
    assertEquals(2, t.getTopDiameter(3));
}

@Test
public void testInvalidConstructor(){
    Towers t = null;
    try {
        t = new Towers(0); // illegal value
        fail("Expected exception");
    } catch (IllegalArgumentException iae) {
        // expected
    }

    try {
        t = new Towers(MAX_NUM_RINGS + 1); // illegal value
        fail("Expected exception");
    } catch (IllegalArgumentException iae) {
        // expected
    }
}
@Test
public void testPreconditionGetRingCount() {
    Towers t = new Towers();
    try {
        t.getRingCount(0);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
    try {
        t.getRingCount(4);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
}

@Test
public void testPreconditionTopRing() {
    Towers t = new Towers();
    try {
        t.getTopDiameter(0);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
    try {
        t.getTopDiameter(4);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
}

@Test
public void testIllegalMoves(){
    Towers t = new Towers();

    t.move(1, 2);
    t.move(1, 3);

    assertFalse(t.move(1, 1)); // can't move to itself
    assertFalse(t.move(1, 2)); // moving larger ring to smaller
    assertFalse(t.move(1, 3)); // moving larger ring to smaller
    assertFalse(t.move(3, 2));
}
}
</code>```

I think I know where my issue lies.  The precondition of getTopDiameter() returns the top ring size if getRingCount(pegNum) > 0 but returns 0 if the stack is empty or there are no rings on the peg.  Since tower[1] is the only peg that gets initialized with rings and the other two do not, getTopDiameter() returns 0 since there are no rings currently on tower[2] and tower[3].  In the move() method one of the preconditions requires that getTopdiameter(startPeg) be less than getTopDiamater(endPeg) but if the endPeg was initialized with 0 rings and is therefore empty, getTopDiamater(endPeg) returns 0 which is obviously not less than 1 in this case.  I just cannot figure this bit out.  Any help is greatly appreciated, thank you in advance!

UPDATE
revised code that is passing all test cases:

```<code>package edu.metrostate.ics240.p2.towers;

import java.util.Stack;

public class Towers {
    private static final int DEFAULT_SIZE = 5;
    private static final int MAX_SIZE = 64;
    private static final int MIN_PEG = 1;
    private static final int MAX_PEG = 3;
    @SuppressWarnings("unchecked")
    private static Stack<Integer>[] tower = new Stack[4];
    private int numOfRings;

public Towers(int n) {
    if (n < 1 || n > MAX_SIZE)
        throw new IllegalArgumentException(
                String.format("Number of rings (%s) cannot be less than 1 or exceed 64 ", n));
    numOfRings = n;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = numOfRings; i >= 1; i--)
        tower[1].push(i);
}

public Towers() {
    numOfRings = DEFAULT_SIZE;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = numOfRings; i >= 1; i--)
        tower[1].push(i);
}

private static void pegCheck(int pegNumber) {
    if (pegNumber < MIN_PEG || pegNumber > MAX_PEG)
        throw new IllegalArgumentException(
                String.format("Peg number (%s) cannot be less than 1 or exceed 3 ", pegNumber));
}

public int getRingCount(int pegNumber) {
    pegCheck(pegNumber);
    if (tower[pegNumber].isEmpty()) {
        return 0;
    } else
        return tower[pegNumber].size();
}

public int getTopDiameter(int pegNumber) {
    pegCheck(pegNumber);
    if (getRingCount(pegNumber) > 0) {
        return tower[pegNumber].get(tower[pegNumber].size() - 1);
    }
    return 0;
}

public boolean move(int startPeg, int endPeg) {
    pegCheck(startPeg);
    pegCheck(endPeg);

    if (endPeg != startPeg) {
        if (getRingCount(startPeg) > 0) {
            if (getRingCount(endPeg) == 0 || getTopDiameter(startPeg) < getTopDiameter(endPeg)) {
                int topRing = tower[startPeg].pop();
                tower[endPeg].push(topRing);
                return true;
            }

        }
    }
    return false;
}
}
</code>```

答:
You say:

In the move() method one of the preconditions requires that getTopdiameter(startPeg) be less than getTopDiamater(endPeg) but if the endPeg was initialized with 0 rings and is therefore empty, getTopDiamater(endPeg) returns 0 which is obviously not less than 1 in this case

But if you read the preconditions in the image you provide - it is stating that getTopdiameter(startPeg) be less than getTopDiamater(endPeg) if endPeg has at least one ring so to write this as conditions you need

```<code>getRingCount(endPeg) > 0 && getTopdiameter(startPeg) < getTopDiamater(endPeg))
</code>```

-- Edit --

You need to separate the conditions into different if statements (or have and or condition also) to handle the case when the towers have no pegs - currently with your conditions as is, it fails on the first move as the condition getRingCount(endPeg) > 0 will be false. If getRingCount == 0 then you can just do the move without needing to check if the diameters are compatible. For readability I would suggest you separate your conditions out initially - you can always combine them as required later - something like this pseudo code

```<code>if not same peg
   if start peg has rings
      if end peg is empty or (end peg has rings and diameters are compatible)
          do move and return true
 return false
</code>```

Title: Towers of Hanoi with Stacks Java

Body:
I am working on a Towers of Hanoi problem in Java.  I chose to use Stacks as the pegs and have everything working except for the move method.  I have the specification and a JUnit test class and am currently passing 6 of the 7 tests but am failing on the move test.  The specs are as follows:

Here is my Towers class:

package edu.metrostate.ics240.p2.towers;
import java.util.Stack;

public class Towers {
    private static final int DEFAULT_SIZE = 5;
    private static final int MAX_SIZE = 64;
    private static final int MIN_PEG = 1;
    private static final int MAX_PEG = 3;
    private static Stack<Integer>[] tower = new Stack[4];
    private int numOfRings;

public Towers(int n) {
    if (n < 1 || n > MAX_SIZE)
        throw new IllegalArgumentException(
                String.format("Number of rings (%s) cannot be less than 1 or exceed 64 ", n));
    numOfRings = n;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = 1; i <= numOfRings; i++)
        tower[1].push(i);
}
public Towers() {
    numOfRings = DEFAULT_SIZE;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = 1; i <= numOfRings; i++)
        tower[1].push(i);
}

private static void pegCheck(int pegNumber){
    if (pegNumber < MIN_PEG || pegNumber > MAX_PEG)
        throw new IllegalArgumentException(
                String.format("Peg number (%s) cannot be less than 1 or exceed 3 ", pegNumber));
}
public int getRingCount(int pegNumber) {
    pegCheck(pegNumber);

    switch (pegNumber) {
    case 1:
        if (tower[1].isEmpty())
            return 0;
        else
            return tower[1].size();
    case 2:
        if (tower[2].isEmpty())
            return 0;
        else
            return tower[2].size();
    case 3:
        if (tower[3].isEmpty())
            return 0;
        else
            return tower[3].size();
    default:
        return 0;
    }
}
public int getTopDiameter(int pegNumber) {
    pegCheck(pegNumber);

    switch (pegNumber) {
    case 1:
        if(getRingCount(1) > 0){
            return tower[1].get(tower[1].peek() - tower[1].size());
        }else
            return 0;
    case 2:
        if(getRingCount(2) > 0){
            return tower[2].get(tower[2].peek() - tower[2].size());
        }else
            return 0;
    case 3:
        if(getRingCount(3) > 0){
            return tower[3].get(tower[3].peek() - tower[3].size());
        }else
            return 0;
    default:
        return 0;
    }
}
public boolean move(int startPeg, int endPeg) {
    pegCheck(startPeg);
    pegCheck(endPeg);
    Stack<Integer> startTower = tower[startPeg];
    Stack<Integer> endTower = tower[endPeg];

    if (getRingCount(startPeg) > 0 && endPeg != startPeg && getRingCount(endPeg) > 0 && getTopDiameter(startPeg) < getTopDiameter(endPeg)) {
        int topRing = startTower.pop();
        endTower.push(topRing);
        return true;
    }else
        return false;
}
}

and finally the JUnit test(s):

import static org.junit.Assert.*;
import org.junit.Test;
import edu.metrostate.ics240.p2.towers.*;
import java.util.Random;

public class TowersTest {
    private static final int MAX_NUM_RINGS = 64;
    private static final long SEED = 20170604001L;
    private static final Random RAND = new Random(SEED);

@Test
public void testDefaultConstruction() {
    Towers t = new Towers();
    assertEquals(5, t.getRingCount(1));
    assertEquals(0, t.getRingCount(2));
    assertEquals(0, t.getRingCount(3));

    assertEquals(1, t.getTopDiameter(1));
    assertEquals(0, t.getTopDiameter(2));
    assertEquals(0, t.getTopDiameter(3));
}

@Test
public void testConstruction() {
    int numRings = RAND.nextInt(MAX_NUM_RINGS);
    Towers t = new Towers(numRings);
    assertEquals(numRings, t.getRingCount(1));
    assertEquals(0, t.getRingCount(2));
    assertEquals(0, t.getRingCount(3));

    assertEquals(1, t.getTopDiameter(1));
    assertEquals(0, t.getTopDiameter(2));
    assertEquals(0, t.getTopDiameter(3));
}

@Test
public void testMove() {
    int numRings = RAND.nextInt(64);

    Towers t = new Towers(numRings);

    assertTrue(t.move(1, 2));
    assertEquals(numRings - 1, t.getRingCount(1));
    assertEquals(1, t.getRingCount(2));
    assertEquals(0, t.getRingCount(3));

    assertEquals(2, t.getTopDiameter(1));
    assertEquals(1, t.getTopDiameter(2));
    assertEquals(0, t.getTopDiameter(3));

    assertTrue(t.move(1, 3));
    assertEquals(numRings - 2, t.getRingCount(1));
    assertEquals(1, t.getRingCount(2));
    assertEquals(1, t.getRingCount(3));

    assertEquals(3, t.getTopDiameter(1));
    assertEquals(1, t.getTopDiameter(2));
    assertEquals(2, t.getTopDiameter(3));
}

@Test
public void testInvalidConstructor(){
    Towers t = null;
    try {
        t = new Towers(0); // illegal value
        fail("Expected exception");
    } catch (IllegalArgumentException iae) {
        // expected
    }

    try {
        t = new Towers(MAX_NUM_RINGS + 1); // illegal value
        fail("Expected exception");
    } catch (IllegalArgumentException iae) {
        // expected
    }
}
@Test
public void testPreconditionGetRingCount() {
    Towers t = new Towers();
    try {
        t.getRingCount(0);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
    try {
        t.getRingCount(4);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
}

@Test
public void testPreconditionTopRing() {
    Towers t = new Towers();
    try {
        t.getTopDiameter(0);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
    try {
        t.getTopDiameter(4);
        fail("Exception expected");
    } catch (IllegalArgumentException iae) {
        // expected
    }
}

@Test
public void testIllegalMoves(){
    Towers t = new Towers();

    t.move(1, 2);
    t.move(1, 3);

    assertFalse(t.move(1, 1)); // can't move to itself
    assertFalse(t.move(1, 2)); // moving larger ring to smaller
    assertFalse(t.move(1, 3)); // moving larger ring to smaller
    assertFalse(t.move(3, 2));
}
}

I think I know where my issue lies.  The precondition of getTopDiameter() returns the top ring size if getRingCount(pegNum) > 0 but returns 0 if the stack is empty or there are no rings on the peg.  Since tower[1] is the only peg that gets initialized with rings and the other two do not, getTopDiameter() returns 0 since there are no rings currently on tower[2] and tower[3].  In the move() method one of the preconditions requires that getTopdiameter(startPeg) be less than getTopDiamater(endPeg) but if the endPeg was initialized with 0 rings and is therefore empty, getTopDiamater(endPeg) returns 0 which is obviously not less than 1 in this case.  I just cannot figure this bit out.  Any help is greatly appreciated, thank you in advance!

UPDATE
revised code that is passing all test cases:

package edu.metrostate.ics240.p2.towers;

import java.util.Stack;

public class Towers {
    private static final int DEFAULT_SIZE = 5;
    private static final int MAX_SIZE = 64;
    private static final int MIN_PEG = 1;
    private static final int MAX_PEG = 3;
    @SuppressWarnings("unchecked")
    private static Stack<Integer>[] tower = new Stack[4];
    private int numOfRings;

public Towers(int n) {
    if (n < 1 || n > MAX_SIZE)
        throw new IllegalArgumentException(
                String.format("Number of rings (%s) cannot be less than 1 or exceed 64 ", n));
    numOfRings = n;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = numOfRings; i >= 1; i--)
        tower[1].push(i);
}

public Towers() {
    numOfRings = DEFAULT_SIZE;
    tower[1] = new Stack<Integer>();
    tower[2] = new Stack<Integer>();
    tower[3] = new Stack<Integer>();
    for (int i = numOfRings; i >= 1; i--)
        tower[1].push(i);
}

private static void pegCheck(int pegNumber) {
    if (pegNumber < MIN_PEG || pegNumber > MAX_PEG)
        throw new IllegalArgumentException(
                String.format("Peg number (%s) cannot be less than 1 or exceed 3 ", pegNumber));
}

public int getRingCount(int pegNumber) {
    pegCheck(pegNumber);
    if (tower[pegNumber].isEmpty()) {
        return 0;
    } else
        return tower[pegNumber].size();
}

public int getTopDiameter(int pegNumber) {
    pegCheck(pegNumber);
    if (getRingCount(pegNumber) > 0) {
        return tower[pegNumber].get(tower[pegNumber].size() - 1);
    }
    return 0;
}

public boolean move(int startPeg, int endPeg) {
    pegCheck(startPeg);
    pegCheck(endPeg);

    if (endPeg != startPeg) {
        if (getRingCount(startPeg) > 0) {
            if (getRingCount(endPeg) == 0 || getTopDiameter(startPeg) < getTopDiameter(endPeg)) {
                int topRing = tower[startPeg].pop();
                tower[endPeg].push(topRing);
                return true;
            }

        }
    }
    return false;
}
}

Body:
You say:

In the move() method one of the preconditions requires that getTopdiameter(startPeg) be less than getTopDiamater(endPeg) but if the endPeg was initialized with 0 rings and is therefore empty, getTopDiamater(endPeg) returns 0 which is obviously not less than 1 in this case

But if you read the preconditions in the image you provide - it is stating that getTopdiameter(startPeg) be less than getTopDiamater(endPeg) if endPeg has at least one ring so to write this as conditions you need

getRingCount(endPeg) > 0 && getTopdiameter(startPeg) < getTopDiamater(endPeg))

-- Edit --

You need to separate the conditions into different if statements (or have and or condition also) to handle the case when the towers have no pegs - currently with your conditions as is, it fails on the first move as the condition getRingCount(endPeg) > 0 will be false. If getRingCount == 0 then you can just do the move without needing to check if the diameters are compatible. For readability I would suggest you separate your conditions out initially - you can always combine them as required later - something like this pseudo code

if not same peg
   if start peg has rings
      if end peg is empty or (end peg has rings and diameters are compatible)
          do move and return true
 return false


问:
Multiple DKIM signatures in message?
I'm checking my postfix setup with mail-server.net. I have SPF, DKIM, and DMARC setup and working. However, mail-server.net is claiming I have 2 DKIM signatures in a single message. How is this possible? Here's what my DNS records looks like:

Name    Value   TTL Options
v=spf1 mx -all  Default Edit | Remove

201705._domainkey   v=DKIM1; h=sha256; k=rsa; s=email; p=MIIBIjANBgk...

_adsp._domainkey    dkim=all

_dmarc  v=DMARC1;p=quarantine;sp=quarantine;adkim=r;aspf=r;fo=1;rf=afrf;rua=mailto:alescher@adventurecatsnw.com

As you can see, I've only included one DKIM signature key in the txt record. I'm using opendkim as the DKIM signer. I've only one key in the key.table record and one entry in the signing.table record. Does anyone have any ideas as to what could be the issue?

答:
I have the same problem (not solved yet) but I think it has to do with SpamAssassin.

It looks like the DKIM signature is added before and after SpamAssassin filter.

```<code>my mailheader
Return-Path: <info@mydomain>
X-Original-To: info@mydomain
Delivered-To: info@mydomain
Received: by mail.mydomain (Postfix, from userid 1001)
    id 2D776B7CA; Wed,  7 Jun 2017 23:15:02 +0200 (CEST)
DKIM-Filter: OpenDKIM Filter v2.11.0 mail.mydomain 2D776B7CA
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain;
    etc.
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
    hostname.mydomain
X-Spam-Level:
X-Spam-Status: No, score=-0.9 required=3.0 tests=ALL_TRUSTED,DKIM_SIGNED,
    HTML_MESSAGE,T_DKIM_INVALID,URIBL_BLOCKED autolearn=no autolearn_force=no
    version=3.4.0
Received: from [mylocalip] (myprovider [myip])
    by mail.mydomain (Postfix) with ESMTPSA id BB..
    for <info@mydomain>; Wed,  7 Jun 2017 23:15:01 +0200 (CEST)
DKIM-Filter: OpenDKIM Filter v2.11.0 mail.mydomain BB..
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain;
    etc.
</code>```

cat /var/log/maillog | grep "DKIM-Signature field added"

```<code>Jun  8 00:02:34 host opendkim[762]: BCD70B75A: DKIM-Signature field added (s=default, d=mydomain)
Jun  8 00:02:34 host opendkim[762]: F3341B7CA: DKIM-Signature field added (s=default, d=mydomain)
</code>```

check this answer:
https://serverfault.com/questions/475416/is-there-a-reason-why-dkim-signs-every-mail-twice

Title: Multiple DKIM signatures in message?

Body:
I have the same problem (not solved yet) but I think it has to do with SpamAssassin.

It looks like the DKIM signature is added before and after SpamAssassin filter.

my mailheader
Return-Path: <info@mydomain>
X-Original-To: info@mydomain
Delivered-To: info@mydomain
Received: by mail.mydomain (Postfix, from userid 1001)
    id 2D776B7CA; Wed,  7 Jun 2017 23:15:02 +0200 (CEST)
DKIM-Filter: OpenDKIM Filter v2.11.0 mail.mydomain 2D776B7CA
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain;
    etc.
X-Spam-Checker-Version: SpamAssassin 3.4.0 (2014-02-07) on
    hostname.mydomain
X-Spam-Level:
X-Spam-Status: No, score=-0.9 required=3.0 tests=ALL_TRUSTED,DKIM_SIGNED,
    HTML_MESSAGE,T_DKIM_INVALID,URIBL_BLOCKED autolearn=no autolearn_force=no
    version=3.4.0
Received: from [mylocalip] (myprovider [myip])
    by mail.mydomain (Postfix) with ESMTPSA id BB..
    for <info@mydomain>; Wed,  7 Jun 2017 23:15:01 +0200 (CEST)
DKIM-Filter: OpenDKIM Filter v2.11.0 mail.mydomain BB..
DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/simple; d=mydomain;
    etc.

cat /var/log/maillog | grep "DKIM-Signature field added"

Jun  8 00:02:34 host opendkim[762]: BCD70B75A: DKIM-Signature field added (s=default, d=mydomain)
Jun  8 00:02:34 host opendkim[762]: F3341B7CA: DKIM-Signature field added (s=default, d=mydomain)

check this answer:
https://serverfault.com/questions/475416/is-there-a-reason-why-dkim-signs-every-mail-twice