问:
Loop through records and increment value in vba access
I'm trying to loop through records in a table with part no's and with matching part no's, increment a value in the pos field. I asked a question earlier(Object variable or With block variable not set Access vba) with the same project but for a different step of the process (running a query). I haven't found a question that addresses this problem in Access yet, but I have taken some pointers from this question: Code to loop through all records in MS Access . Now, I'm trying to write the code to loop through the records and increment the value in the pos field.

The query that will run:

```<code>SELECT CTOL.ID, CTOL.BOM_PART_NAME, CTOL.CII, CTOL.[PART FIND NO], CTOL.CSN, CTOL.AFS, CTOL.EQP_POS_CD, CTOL.LCN, CTOL.POS_CT, CTOL.SERIAL_NO, CTOL.PART_NO_LLP, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO], [CTOL_Asbuilt].[PW-PART-NO]
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];
</code>```

Code so far (credit to Kostas K for helping me on the other question):

```<code>Option Compare Database
Option Explicit

'Const adOpenStatic = 3
'Const adLockOptimistic = 3

Function queryDatabase()

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdf As QueryDef
'Dim rsQuery As DAO.Recordset
Dim rows As Variant

Dim part_find_no() As String
Dim eqp_pos() As Integer
'Dim strSQL As String

Dim i As Integer
Dim j As Integer
'Set objConnection = CurrentDb.OpenRecordset("CTOL")

Set db = CurrentDb

Set qdf = db.QueryDefs("SicrProcess")

Set rs = qdf.OpenRecordset(dbOpenDynaset)

If rs.EOF Then GoTo Leave
rs.MoveLast
rs.MoveFirst

For i = 1 To rs.RecordCount
    Debug.Print rs.Fields("PART FIND NO") & " " & rs.Fields("EQP_POS_CD")
    rs.MoveNext
Next i

Leave:
    On Error Resume Next
    rs.Close
    Set rs = Nothing
    qdf.Close
    Set qdf = Nothing
    Set db = Nothing
    On Error GoTo 0
    Exit Function

ErrProc:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Function
</code>```

The two fields I want to loop through are PART FIND NO in the CTOL table and EQP_POS_CD in the CTOL table. The value in EQP_POS_CD should be incremented by 1 if the last PART FIND NO is identical to the current no. The result set should contain the other fields selected in the query as well. Is there anything else I need to add to get it output? Right now, I'm not too concerned as to how it's output, whether in a window or in datasheet format (though I would appreciate pointers on this if anyone knows). Any pointers on how to accomplish this? Also, if there's anything I'm missing in my question that's important, or if there's something I could do better when posting a question, I'm open to discussing it. I'm also open to discussion of how to approach the problem. Thanks!

答:
Possibly:</p>

```<code>SELECT CTOL.*, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO], [CTOL_Asbuilt].[PW-PART-NO],
DCount("*", "CTOL", "[Part Find No]=" & [Part Find No] & " AND ID<" & [ID])+1 AS Seq
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];
</code>```

Body:
I'm trying to loop through records in a table with part no's and with matching part no's, increment a value in the pos field. I asked a question earlier(Object variable or With block variable not set Access vba) with the same project but for a different step of the process (running a query). I haven't found a question that addresses this problem in Access yet, but I have taken some pointers from this question: Code to loop through all records in MS Access . Now, I'm trying to write the code to loop through the records and increment the value in the pos field.

The query that will run:

SELECT CTOL.ID, CTOL.BOM_PART_NAME, CTOL.CII, CTOL.[PART FIND NO], CTOL.CSN, CTOL.AFS, CTOL.EQP_POS_CD, CTOL.LCN, CTOL.POS_CT, CTOL.SERIAL_NO, CTOL.PART_NO_LLP, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO], [CTOL_Asbuilt].[PW-PART-NO]
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];

Code so far (credit to Kostas K for helping me on the other question):

Option Compare Database
Option Explicit

'Const adOpenStatic = 3
'Const adLockOptimistic = 3

Function queryDatabase()

Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim qdf As QueryDef
'Dim rsQuery As DAO.Recordset
Dim rows As Variant

Dim part_find_no() As String
Dim eqp_pos() As Integer
'Dim strSQL As String

Dim i As Integer
Dim j As Integer
'Set objConnection = CurrentDb.OpenRecordset("CTOL")

Set db = CurrentDb

Set qdf = db.QueryDefs("SicrProcess")

Set rs = qdf.OpenRecordset(dbOpenDynaset)

If rs.EOF Then GoTo Leave
rs.MoveLast
rs.MoveFirst

For i = 1 To rs.RecordCount
    Debug.Print rs.Fields("PART FIND NO") & " " & rs.Fields("EQP_POS_CD")
    rs.MoveNext
Next i

Leave:
    On Error Resume Next
    rs.Close
    Set rs = Nothing
    qdf.Close
    Set qdf = Nothing
    Set db = Nothing
    On Error GoTo 0
    Exit Function

ErrProc:
    MsgBox Err.Description, vbCritical
    Resume Leave
End Function

The two fields I want to loop through are PART FIND NO in the CTOL table and EQP_POS_CD in the CTOL table. The value in EQP_POS_CD should be incremented by 1 if the last PART FIND NO is identical to the current no. The result set should contain the other fields selected in the query as well. Is there anything else I need to add to get it output? Right now, I'm not too concerned as to how it's output, whether in a window or in datasheet format (though I would appreciate pointers on this if anyone knows). Any pointers on how to accomplish this? Also, if there's anything I'm missing in my question that's important, or if there's something I could do better when posting a question, I'm open to discussing it. I'm also open to discussion of how to approach the problem. Thanks!

Body:
Possibly:

SELECT CTOL.*, [CTOL_Asbuilt].[PART-SN], [CTOL_Asbuilt].[PART-ATA-NO], [CTOL_Asbuilt].[PW-PART-NO],
DCount("*", "CTOL", "[Part Find No]=" & [Part Find No] & " AND ID<" & [ID])+1 AS Seq
FROM CTOL LEFT JOIN [CTOL_Asbuilt] ON CTOL.[PART FIND NO] = [CTOL_Asbuilt].[PART-ATA-NO];


来源: stackexchange

问:
Set a custom style to tags recognized by Html.fromHtml()
In Android, when setting html formatted text in a TextView using Html.fromHtml(), text styling is applied to e.g. the h1 heading tag. The style Android uses does not fit with the style of my app.

Is it possible to apply custom text styles / formatting to the recognized html tags?

So that e.g. all h1 tags are styled in the same custom way?

答: You can add custom style attributes to your texviews but you cannot override the HTML tags, those tags are predefined standards and cannot be changed.</p>

ContentLicense: CC BY-SA 3.0


问:
Monogame What's the new code for monogame for GraphicsDevice
I follow a tutorial, but I notice this problem:

```<code>GraphicsDevice.RenderState.CullMode = CullMode.None;

        GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);
</code>```

This code is missing in monogame, What should I do?
This is the complete code of the tutorial:

```<code> protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        GraphicsDevice.RenderState.CullMode = CullMode.None;

        GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);

        BasicEffect effect = new BasicEffect(GraphicsDevice, null);
        effect.World = Matrix.Identity;
        effect.View = camera.viewMatrix;
        effect.Projection = camera.projectionMatrix;

        effect.VertexColorEnabled = true;

        effect.Begin();
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Begin();
            GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, verts, 0, 2);
            pass.End();
        }
        effect.End();

        base.Draw(gameTime);
    }
</code>```

Thank you.

答:
I think you might want to use a RasterizerState. RenderState was discontinued in XNA 4.0, I think.

GraphicsDevice.RasterizerState = RasterizerState.CullNone;

And look at this blog post: https://blogs.msdn.microsoft.com/shawnhar/2010/04/19/vertex-data-in-xna-game-studio-4-0/

It covers changes to vertex declarations in XNA 4.0

Body:
I follow a tutorial, but I notice this problem:

GraphicsDevice.RenderState.CullMode = CullMode.None;

        GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);

This code is missing in monogame, What should I do?
This is the complete code of the tutorial:

 protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.CornflowerBlue);
        GraphicsDevice.RenderState.CullMode = CullMode.None;

        GraphicsDevice.VertexDeclaration = new VertexDeclaration(GraphicsDevice, VertexPositionColor.VertexElements);

        BasicEffect effect = new BasicEffect(GraphicsDevice, null);
        effect.World = Matrix.Identity;
        effect.View = camera.viewMatrix;
        effect.Projection = camera.projectionMatrix;

        effect.VertexColorEnabled = true;

        effect.Begin();
        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
        {
            pass.Begin();
            GraphicsDevice.DrawUserPrimitives(PrimitiveType.TriangleStrip, verts, 0, 2);
            pass.End();
        }
        effect.End();

        base.Draw(gameTime);
    }

Thank you.


问:
Create index to speed up query with inner join
I am using MS SQL and have two tables: Products (ProdID, some other fields) and ProdCat (ID, ProdID, CategoryID) which determines which Product belongs to which category.

And I am making select like

```<code>SELECT TOP (8) ProdID, Description, Image
FROM  Products INNER JOIN ProdCat ON ProdCat.ProdID = Products.ProdID
WHERE  Products.Active=1 AND ProdCat.CategoryID = 123 Order by ProdCat.sorting, Products.ProdID
</code>```

Products table has more than 50.000 and ProdCat table has more than 150.000 records and the query is slow.

Can you please advise how to create index to speed up this query?

Thanks.

答:
ProdCat (ID, ProdID, CategoryID)

Why is there an ID column?  That doesn't seem helpful.

In a many-to-many linking table like this you need to be able to efficiently get all the CategoryIDs for a single ProdID, and get all the ProdID for a single Category.

Your query is a case-in-point of why.  If Products.Active has low cardinality, the query may start there, and look up the categories for each Active product, or it might start with Category=123 and then find all the products.

Then this table should have a clustered PK on (ProdID,CategoryID) and a non-clustered index on (CategoryID) (or vice versa).

Body:
I am using MS SQL and have two tables: Products (ProdID, some other fields) and ProdCat (ID, ProdID, CategoryID) which determines which Product belongs to which category.

And I am making select like

SELECT TOP (8) ProdID, Description, Image
FROM  Products INNER JOIN ProdCat ON ProdCat.ProdID = Products.ProdID
WHERE  Products.Active=1 AND ProdCat.CategoryID = 123 Order by ProdCat.sorting, Products.ProdID

Products table has more than 50.000 and ProdCat table has more than 150.000 records and the query is slow.

Can you please advise how to create index to speed up this query?

Thanks.


问:
DirectX Screen Capture - Desktop Duplication API - limited frame rate of AcquireNextFrame
I'm trying to use Windows Desktop Duplication API to capture the screen and save the raw output to a video. I'm using AcquireNextFrame with a very high timeout value (999ms). This way I should get every new frame from windows as soon as it at has one, which naturally should be at 60fps anyway. I end up getting sequences where everything looks good (frame 6-11), and then sequences where things look bad (frame 12-14). If I check AccumulatedFrames

```<code>lFrameInfo.AccumulatedFrames
</code>```

the value is often 2 or higher. From my understanding, this means windows is saying "hey hold up, I don't have a frame for you yet", because calls to AcquireNextFrame take so long. But once windows does finally give me a frame, it is saying "hey you were actually too slow and ended up missing a frame". If i could somehow get these frames I think I would be getting 60hz.

This can be further clarified with logging:

```<code>I0608 10:40:16.964375  4196 window_capturer_dd.cc:438] 206 - Frame 6 start acquire
I0608 10:40:16.973867  4196 window_capturer_dd.cc:451] 216 - Frame 6 acquired
I0608 10:40:16.981364  4196 window_capturer_dd.cc:438] 223 - Frame 7 start acquire
I0608 10:40:16.990864  4196 window_capturer_dd.cc:451] 233 - Frame 7 acquired
I0608 10:40:16.998364  4196 window_capturer_dd.cc:438] 240 - Frame 8 start acquire
I0608 10:40:17.007876  4196 window_capturer_dd.cc:451] 250 - Frame 8 acquired
I0608 10:40:17.015393  4196 window_capturer_dd.cc:438] 257 - Frame 9 start acquire
I0608 10:40:17.023905  4196 window_capturer_dd.cc:451] 266 - Frame 9 acquired
I0608 10:40:17.032411  4196 window_capturer_dd.cc:438] 274 - Frame 10 start acquire
I0608 10:40:17.039912  4196 window_capturer_dd.cc:451] 282 - Frame 10 acquired
I0608 10:40:17.048925  4196 window_capturer_dd.cc:438] 291 - Frame 11 start acquire
I0608 10:40:17.058428  4196 window_capturer_dd.cc:451] 300 - Frame 11 acquired
I0608 10:40:17.065943  4196 window_capturer_dd.cc:438] 308 - Frame 12 start acquire
I0608 10:40:17.096945  4196 window_capturer_dd.cc:451] 336 - Frame 12 acquired
I0608 10:40:17.098947  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 12
I0608 10:40:17.101444  4196 window_capturer_dd.cc:438] 343 - Frame 13 start acquire
I0608 10:40:17.128958  4196 window_capturer_dd.cc:451] 368 - Frame 13 acquired
I0608 10:40:17.130957  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 13
I0608 10:40:17.135459  4196 window_capturer_dd.cc:438] 377 - Frame 14 start acquire
I0608 10:40:17.160959  4196 window_capturer_dd.cc:451] 399 - Frame 14 acquired
I0608 10:40:17.162958  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 14
</code>```

Frame 6-11 look good, the acquires are roughly 17ms apart. Frame 12 should be acquired at (300+17=317ms). Frame 12 starts waiting at 308, but doesn't get anything until 336ms. Windows didn't have anything for me until the frame after (300+17+17~=336ms). Okay sure maybe windows just missed a frame, but when I finally get it, I can check AccumulatedFrames and its value was 2 (meaning I missed a frame because I waited too long before calling AcquireNextFrame). In my understanding, it only makes sense for AccumulatedFrames to be larger than 1 if AcquireNextFrame returns immediately.

Furthermore, I can use PresentMon while my capture software is running. The logs show MsBetweenDisplayChange for every frame, which is fairly steady at 16.666ms (with a couple outliers, but much less than my capture software is seeing).

These people (1, 2) seem to have been able to get 60fps, so I'm wondering what I am doing incorrectly.

My code is based on this:

```<code>int main() {
    int FPS = 60;
    int video_length_sec = 5;

    int total_frames = FPS * video_length_sec;
    for (int i = 0; i < total_frames; i++) {
        if(!CaptureSingleFrame()){
            i--;
        }
    }
}

ComPtr<ID3D11Device> lDevice;
ComPtr<ID3D11DeviceContext> lImmediateContext;
ComPtr<IDXGIOutputDuplication> lDeskDupl;
ComPtr<ID3D11Texture2D> lAcquiredDesktopImage;
ComPtr<ID3D11Texture2D> lGDIImage;
ComPtr<ID3D11Texture2D> lDestImage;
DXGI_OUTPUT_DESC lOutputDesc;
DXGI_OUTDUPL_DESC lOutputDuplDesc;
D3D11_TEXTURE2D_DESC desc;

// Driver types supported
D3D_DRIVER_TYPE gDriverTypes[] = {
    D3D_DRIVER_TYPE_HARDWARE
};
UINT gNumDriverTypes = ARRAYSIZE(gDriverTypes);

// Feature levels supported
D3D_FEATURE_LEVEL gFeatureLevels[] = {
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_1
};
UINT gNumFeatureLevels = ARRAYSIZE(gFeatureLevels);

bool Init() {
    int lresult(-1);

    D3D_FEATURE_LEVEL lFeatureLevel;

    HRESULT hr(E_FAIL);

    // Create device
    for (UINT DriverTypeIndex = 0; DriverTypeIndex < gNumDriverTypes; ++DriverTypeIndex)
    {
        hr = D3D11CreateDevice(
            nullptr,
            gDriverTypes[DriverTypeIndex],
            nullptr,
            0,
            gFeatureLevels,
            gNumFeatureLevels,
            D3D11_SDK_VERSION,
            &lDevice,
            &lFeatureLevel,
            &lImmediateContext);

        if (SUCCEEDED(hr))
        {
            // Device creation success, no need to loop anymore
            break;
        }

        lDevice.Reset();

        lImmediateContext.Reset();
    }

    if (FAILED(hr))
        return false;

    if (lDevice == nullptr)
        return false;

    // Get DXGI device
    ComPtr<IDXGIDevice> lDxgiDevice;
    hr = lDevice.As(&lDxgiDevice);

    if (FAILED(hr))
        return false;

    // Get DXGI adapter
    ComPtr<IDXGIAdapter> lDxgiAdapter;
    hr = lDxgiDevice->GetParent(
        __uuidof(IDXGIAdapter), &lDxgiAdapter);

    if (FAILED(hr))
        return false;

    lDxgiDevice.Reset();

    UINT Output = 0;

    // Get output
    ComPtr<IDXGIOutput> lDxgiOutput;
    hr = lDxgiAdapter->EnumOutputs(
        Output,
        &lDxgiOutput);

    if (FAILED(hr))
        return false;

    lDxgiAdapter.Reset();

    hr = lDxgiOutput->GetDesc(
        &lOutputDesc);

    if (FAILED(hr))
        return false;

    // QI for Output 1
    ComPtr<IDXGIOutput1> lDxgiOutput1;
    hr = lDxgiOutput.As(&lDxgiOutput1);

    if (FAILED(hr))
        return false;

    lDxgiOutput.Reset();

    // Create desktop duplication
    hr = lDxgiOutput1->DuplicateOutput(
        lDevice.Get(), //TODO what im i doing here
        &lDeskDupl);

    if (FAILED(hr))
        return false;

    lDxgiOutput1.Reset();

    // Create GUI drawing texture
    lDeskDupl->GetDesc(&lOutputDuplDesc);
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    desc.ArraySize = 1;
    desc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_RENDER_TARGET;
    desc.MiscFlags = D3D11_RESOURCE_MISC_GDI_COMPATIBLE;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;

    hr = lDevice->CreateTexture2D(&desc, NULL, &lGDIImage);

    if (FAILED(hr))
        return false;

    if (lGDIImage == nullptr)
        return false;

    // Create CPU access texture
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    std::cout << desc.Width << "x" << desc.Height << "\n\n\n";
    desc.ArraySize = 1;
    desc.BindFlags = 0;
    desc.MiscFlags = 0;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
    desc.Usage = D3D11_USAGE_STAGING;

    return true;
}

void WriteFrameToCaptureFile(ID3D11Texture2D* texture) {

    D3D11_MAPPED_SUBRESOURCE* pRes = new D3D11_MAPPED_SUBRESOURCE;
    UINT subresource = D3D11CalcSubresource(0, 0, 0);

    lImmediateContext->Map(texture, subresource, D3D11_MAP_READ_WRITE, 0, pRes);

    void* d = pRes->pData;
    char* data = reinterpret_cast<char*>(d);

    // writes data to file
    WriteFrameToCaptureFile(data, 0);
}

bool CaptureSingleFrame()
{
    HRESULT hr(E_FAIL);
    ComPtr<IDXGIResource> lDesktopResource = nullptr;
    DXGI_OUTDUPL_FRAME_INFO lFrameInfo;
    ID3D11Texture2D* currTexture;

    hr = lDeskDupl->AcquireNextFrame(
        999,
        &lFrameInfo,
        &lDesktopResource);

    if (FAILED(hr)) {
        LOG(INFO) << "Failed to acquire new frame";
        return false;
    }

    if (lFrameInfo.LastPresentTime.HighPart == 0) {
        // not interested in just mouse updates, which can happen much faster than 60fps if you really shake the mouse
        hr = lDeskDupl->ReleaseFrame();
        return false;
    }

    int accum_frames = lFrameInfo.AccumulatedFrames;
    if (accum_frames > 1 && current_frame != 1) {
        // TOO MANY OF THESE is the problem
        // especially after having to wait >17ms in AcquireNextFrame()
    }

    // QI for ID3D11Texture2D
    hr = lDesktopResource.As(&lAcquiredDesktopImage);

    // Copy image into a newly created CPU access texture
    hr = lDevice->CreateTexture2D(&desc, NULL, &currTexture);
    if (FAILED(hr))
        return false;
    if (currTexture == nullptr)
        return false;

    lImmediateContext->CopyResource(currTexture, lAcquiredDesktopImage.Get());

    writer_thread->Schedule(
        FROM_HERE, [this, currTexture]() {
        WriteFrameToCaptureFile(currTexture);
    });
    pending_write_counts_++;

    hr = lDeskDupl->ReleaseFrame();

    return true;
}
</code>```

**EDIT - According to my measurements, you must call AcquireNextFrame() before the frame will actually appear by about ~10ms, or windows will fail to acquire it and get you the next one. Every time my recording program takes more than 7 ms to wrap around (after acquiring frame i until calling AcquireNextFrame() on i+1), frame i+1 is missed.

***EDIT - Heres a screenshot of GPU View showing what I'm talking about. The first 6 frames process in no time, then the 7th frame takes 119ms. The long rectangle beside "capture_to_argb.exe" corresponds to me being stuck inside AcquireNextFrame(). If you look up to the hardware queue, you can see it cleanly rendering at 60fps, even while I'm stuck in AcquireNextFrame(). At least this is my interpretation (I have no idea what I'm doing).

答:
Doing a blocking wait before next call of AcquireNextFrame you are missing the actual frames. Desktop Duplication API logic suggests that you attempt to acquire next frame immediately if you expect a decent frame rate. Your sleeping call effectively relinquishes the available remainder of execution timeout without hard promise that you get a new slice in scheduled interval of time.

You have to poll at maximal frame rate. Do not sleep (even with zero sleep time) and request next frame immediately. You will have the option to drop the frames that come too early. Desktop Duplication API is designed in a way that getting extra frames might be not too expensive of you identify them early and stop their processing.

If you still prefer to sleep between the frames, you might want to read the accuracy remark:

To increase the accuracy of the sleep interval, call the timeGetDevCaps function to determine the supported minimum timer resolution and the timeBeginPeriod function to set the timer resolution to its minimum. Use caution when calling timeBeginPeriod, as frequent calls can significantly affect the system clock, system power usage, and the scheduler. If you call timeBeginPeriod, call it one time early in the application and be sure to call the timeEndPeriod function at the very end of the application.

Body:
I'm trying to use Windows Desktop Duplication API to capture the screen and save the raw output to a video. I'm using AcquireNextFrame with a very high timeout value (999ms). This way I should get every new frame from windows as soon as it at has one, which naturally should be at 60fps anyway. I end up getting sequences where everything looks good (frame 6-11), and then sequences where things look bad (frame 12-14). If I check AccumulatedFrames

lFrameInfo.AccumulatedFrames

the value is often 2 or higher. From my understanding, this means windows is saying "hey hold up, I don't have a frame for you yet", because calls to AcquireNextFrame take so long. But once windows does finally give me a frame, it is saying "hey you were actually too slow and ended up missing a frame". If i could somehow get these frames I think I would be getting 60hz.

This can be further clarified with logging:

I0608 10:40:16.964375  4196 window_capturer_dd.cc:438] 206 - Frame 6 start acquire
I0608 10:40:16.973867  4196 window_capturer_dd.cc:451] 216 - Frame 6 acquired
I0608 10:40:16.981364  4196 window_capturer_dd.cc:438] 223 - Frame 7 start acquire
I0608 10:40:16.990864  4196 window_capturer_dd.cc:451] 233 - Frame 7 acquired
I0608 10:40:16.998364  4196 window_capturer_dd.cc:438] 240 - Frame 8 start acquire
I0608 10:40:17.007876  4196 window_capturer_dd.cc:451] 250 - Frame 8 acquired
I0608 10:40:17.015393  4196 window_capturer_dd.cc:438] 257 - Frame 9 start acquire
I0608 10:40:17.023905  4196 window_capturer_dd.cc:451] 266 - Frame 9 acquired
I0608 10:40:17.032411  4196 window_capturer_dd.cc:438] 274 - Frame 10 start acquire
I0608 10:40:17.039912  4196 window_capturer_dd.cc:451] 282 - Frame 10 acquired
I0608 10:40:17.048925  4196 window_capturer_dd.cc:438] 291 - Frame 11 start acquire
I0608 10:40:17.058428  4196 window_capturer_dd.cc:451] 300 - Frame 11 acquired
I0608 10:40:17.065943  4196 window_capturer_dd.cc:438] 308 - Frame 12 start acquire
I0608 10:40:17.096945  4196 window_capturer_dd.cc:451] 336 - Frame 12 acquired
I0608 10:40:17.098947  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 12
I0608 10:40:17.101444  4196 window_capturer_dd.cc:438] 343 - Frame 13 start acquire
I0608 10:40:17.128958  4196 window_capturer_dd.cc:451] 368 - Frame 13 acquired
I0608 10:40:17.130957  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 13
I0608 10:40:17.135459  4196 window_capturer_dd.cc:438] 377 - Frame 14 start acquire
I0608 10:40:17.160959  4196 window_capturer_dd.cc:451] 399 - Frame 14 acquired
I0608 10:40:17.162958  4196 window_capturer_dd.cc:464] 1 FRAMES MISSED on frame: 14

Frame 6-11 look good, the acquires are roughly 17ms apart. Frame 12 should be acquired at (300+17=317ms). Frame 12 starts waiting at 308, but doesn't get anything until 336ms. Windows didn't have anything for me until the frame after (300+17+17~=336ms). Okay sure maybe windows just missed a frame, but when I finally get it, I can check AccumulatedFrames and its value was 2 (meaning I missed a frame because I waited too long before calling AcquireNextFrame). In my understanding, it only makes sense for AccumulatedFrames to be larger than 1 if AcquireNextFrame returns immediately.

Furthermore, I can use PresentMon while my capture software is running. The logs show MsBetweenDisplayChange for every frame, which is fairly steady at 16.666ms (with a couple outliers, but much less than my capture software is seeing).

These people (1, 2) seem to have been able to get 60fps, so I'm wondering what I am doing incorrectly.

My code is based on this:

int main() {
    int FPS = 60;
    int video_length_sec = 5;

    int total_frames = FPS * video_length_sec;
    for (int i = 0; i < total_frames; i++) {
        if(!CaptureSingleFrame()){
            i--;
        }
    }
}

ComPtr<ID3D11Device> lDevice;
ComPtr<ID3D11DeviceContext> lImmediateContext;
ComPtr<IDXGIOutputDuplication> lDeskDupl;
ComPtr<ID3D11Texture2D> lAcquiredDesktopImage;
ComPtr<ID3D11Texture2D> lGDIImage;
ComPtr<ID3D11Texture2D> lDestImage;
DXGI_OUTPUT_DESC lOutputDesc;
DXGI_OUTDUPL_DESC lOutputDuplDesc;
D3D11_TEXTURE2D_DESC desc;

// Driver types supported
D3D_DRIVER_TYPE gDriverTypes[] = {
    D3D_DRIVER_TYPE_HARDWARE
};
UINT gNumDriverTypes = ARRAYSIZE(gDriverTypes);

// Feature levels supported
D3D_FEATURE_LEVEL gFeatureLevels[] = {
    D3D_FEATURE_LEVEL_11_0,
    D3D_FEATURE_LEVEL_10_1,
    D3D_FEATURE_LEVEL_10_0,
    D3D_FEATURE_LEVEL_9_1
};
UINT gNumFeatureLevels = ARRAYSIZE(gFeatureLevels);

bool Init() {
    int lresult(-1);

    D3D_FEATURE_LEVEL lFeatureLevel;

    HRESULT hr(E_FAIL);

    // Create device
    for (UINT DriverTypeIndex = 0; DriverTypeIndex < gNumDriverTypes; ++DriverTypeIndex)
    {
        hr = D3D11CreateDevice(
            nullptr,
            gDriverTypes[DriverTypeIndex],
            nullptr,
            0,
            gFeatureLevels,
            gNumFeatureLevels,
            D3D11_SDK_VERSION,
            &lDevice,
            &lFeatureLevel,
            &lImmediateContext);

        if (SUCCEEDED(hr))
        {
            // Device creation success, no need to loop anymore
            break;
        }

        lDevice.Reset();

        lImmediateContext.Reset();
    }

    if (FAILED(hr))
        return false;

    if (lDevice == nullptr)
        return false;

    // Get DXGI device
    ComPtr<IDXGIDevice> lDxgiDevice;
    hr = lDevice.As(&lDxgiDevice);

    if (FAILED(hr))
        return false;

    // Get DXGI adapter
    ComPtr<IDXGIAdapter> lDxgiAdapter;
    hr = lDxgiDevice->GetParent(
        __uuidof(IDXGIAdapter), &lDxgiAdapter);

    if (FAILED(hr))
        return false;

    lDxgiDevice.Reset();

    UINT Output = 0;

    // Get output
    ComPtr<IDXGIOutput> lDxgiOutput;
    hr = lDxgiAdapter->EnumOutputs(
        Output,
        &lDxgiOutput);

    if (FAILED(hr))
        return false;

    lDxgiAdapter.Reset();

    hr = lDxgiOutput->GetDesc(
        &lOutputDesc);

    if (FAILED(hr))
        return false;

    // QI for Output 1
    ComPtr<IDXGIOutput1> lDxgiOutput1;
    hr = lDxgiOutput.As(&lDxgiOutput1);

    if (FAILED(hr))
        return false;

    lDxgiOutput.Reset();

    // Create desktop duplication
    hr = lDxgiOutput1->DuplicateOutput(
        lDevice.Get(), //TODO what im i doing here
        &lDeskDupl);

    if (FAILED(hr))
        return false;

    lDxgiOutput1.Reset();

    // Create GUI drawing texture
    lDeskDupl->GetDesc(&lOutputDuplDesc);
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    desc.ArraySize = 1;
    desc.BindFlags = D3D11_BIND_FLAG::D3D11_BIND_RENDER_TARGET;
    desc.MiscFlags = D3D11_RESOURCE_MISC_GDI_COMPATIBLE;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = 0;
    desc.Usage = D3D11_USAGE_DEFAULT;

    hr = lDevice->CreateTexture2D(&desc, NULL, &lGDIImage);

    if (FAILED(hr))
        return false;

    if (lGDIImage == nullptr)
        return false;

    // Create CPU access texture
    desc.Width = lOutputDuplDesc.ModeDesc.Width;
    desc.Height = lOutputDuplDesc.ModeDesc.Height;
    desc.Format = lOutputDuplDesc.ModeDesc.Format;
    std::cout << desc.Width << "x" << desc.Height << "\n\n\n";
    desc.ArraySize = 1;
    desc.BindFlags = 0;
    desc.MiscFlags = 0;
    desc.SampleDesc.Count = 1;
    desc.SampleDesc.Quality = 0;
    desc.MipLevels = 1;
    desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ | D3D11_CPU_ACCESS_WRITE;
    desc.Usage = D3D11_USAGE_STAGING;

    return true;
}

void WriteFrameToCaptureFile(ID3D11Texture2D* texture) {

    D3D11_MAPPED_SUBRESOURCE* pRes = new D3D11_MAPPED_SUBRESOURCE;
    UINT subresource = D3D11CalcSubresource(0, 0, 0);

    lImmediateContext->Map(texture, subresource, D3D11_MAP_READ_WRITE, 0, pRes);

    void* d = pRes->pData;
    char* data = reinterpret_cast<char*>(d);

    // writes data to file
    WriteFrameToCaptureFile(data, 0);
}

bool CaptureSingleFrame()
{
    HRESULT hr(E_FAIL);
    ComPtr<IDXGIResource> lDesktopResource = nullptr;
    DXGI_OUTDUPL_FRAME_INFO lFrameInfo;
    ID3D11Texture2D* currTexture;

    hr = lDeskDupl->AcquireNextFrame(
        999,
        &lFrameInfo,
        &lDesktopResource);

    if (FAILED(hr)) {
        LOG(INFO) << "Failed to acquire new frame";
        return false;
    }

    if (lFrameInfo.LastPresentTime.HighPart == 0) {
        // not interested in just mouse updates, which can happen much faster than 60fps if you really shake the mouse
        hr = lDeskDupl->ReleaseFrame();
        return false;
    }

    int accum_frames = lFrameInfo.AccumulatedFrames;
    if (accum_frames > 1 && current_frame != 1) {
        // TOO MANY OF THESE is the problem
        // especially after having to wait >17ms in AcquireNextFrame()
    }

    // QI for ID3D11Texture2D
    hr = lDesktopResource.As(&lAcquiredDesktopImage);

    // Copy image into a newly created CPU access texture
    hr = lDevice->CreateTexture2D(&desc, NULL, &currTexture);
    if (FAILED(hr))
        return false;
    if (currTexture == nullptr)
        return false;

    lImmediateContext->CopyResource(currTexture, lAcquiredDesktopImage.Get());

    writer_thread->Schedule(
        FROM_HERE, [this, currTexture]() {
        WriteFrameToCaptureFile(currTexture);
    });
    pending_write_counts_++;

    hr = lDeskDupl->ReleaseFrame();

    return true;
}

**EDIT - According to my measurements, you must call AcquireNextFrame() before the frame will actually appear by about ~10ms, or windows will fail to acquire it and get you the next one. Every time my recording program takes more than 7 ms to wrap around (after acquiring frame i until calling AcquireNextFrame() on i+1), frame i+1 is missed.

***EDIT - Heres a screenshot of GPU View showing what I'm talking about. The first 6 frames process in no time, then the 7th frame takes 119ms. The long rectangle beside "capture_to_argb.exe" corresponds to me being stuck inside AcquireNextFrame(). If you look up to the hardware queue, you can see it cleanly rendering at 60fps, even while I'm stuck in AcquireNextFrame(). At least this is my interpretation (I have no idea what I'm doing).


问:
Kibana is not starting
I have setup kibana and trying to run but getting below exception :

```<code>[fatal] Error: listen EADDRNOTAVAIL
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1141:19)
    at listen (net.js:1184:10)
    at net.js:1282:9
    at dns.js:85:18
    at process._tickDomainCallback (node.js:381:11)
FATAL { [Error: listen EADDRNOTAVAIL]
  cause:
   { [Error: listen EADDRNOTAVAIL]
     code: 'EADDRNOTAVAIL',
     errno: 'EADDRNOTAVAIL',
     syscall: 'listen' },
  isOperational: true,
  code: 'EADDRNOTAVAIL',
  errno: 'EADDRNOTAVAIL',
  syscall: 'listen' }
</code>```

I am very new in kibana. I dont understand why I am getting this error.

答: This is a problem related to the IP address you are binding to, Kibana can't bind to the IP address you provided within kibana.yml configuration, try to set your host as 127.0.0.1.</p>

Title: Kibana is not starting

Body:
I have setup kibana and trying to run but getting below exception :

[fatal] Error: listen EADDRNOTAVAIL
    at exports._errnoException (util.js:746:11)
    at Server._listen2 (net.js:1141:19)
    at listen (net.js:1184:10)
    at net.js:1282:9
    at dns.js:85:18
    at process._tickDomainCallback (node.js:381:11)
FATAL { [Error: listen EADDRNOTAVAIL]
  cause:
   { [Error: listen EADDRNOTAVAIL]
     code: 'EADDRNOTAVAIL',
     errno: 'EADDRNOTAVAIL',
     syscall: 'listen' },
  isOperational: true,
  code: 'EADDRNOTAVAIL',
  errno: 'EADDRNOTAVAIL',
  syscall: 'listen' }

I am very new in kibana. I dont understand why I am getting this error.


问:
How do I store the location of an image in a database?
I have a list of colors, with textures that I want to show to particular users, so I need to load the image of the colors that a particular user has, the color's information is contained in a ObjecDTO and one of the properties is its image path. My question is how should I store the image path in the database, are there any special rules, for example since the database and the image file are on the same server should I store a complete file URL, or a relative url, what characters should I escape etcetera, or are there better approaches than mine?

I've searched the web but mostly point to storing BLOBs in the database, which I've found  to be a bad practice.

Any guidance is really appreciated.

regards Tristian.

答:
I would really suggest to store relative paths and put the remaining as a config. That way, you can migrate more easily. For the datatype, I suggest something along the line of varchar(255) and ensure that restriction in your code.

And don’t forget to set it as UTF-8 if it’s a user field

ContentLicense: CC BY-SA 2.5


问:
Split implementation across multiple files/modules and keep everything as private as possible
Consider the following code in my library:

```<code>pub struct Foo;
impl Foo {
    fn helper(&self) { /* .. */ }
}

pub fn do_something(foo: &Foo) {
    foo.helper();
}
</code>```

The users of my library should be able to use Foo and do_something(), but shall never call helper(). Everything works fine with the code above. But now imagine the code gets huge and I want to separate those definitions into their own files/modules -- they are then pulled back into the root-namespace with pub use. See here:

```<code>mod foo {  // module contents in `src/foo.rs`
    pub struct Foo;
    impl Foo {
        fn helper(&self) { /* .. */ }
    }
}

mod do_something {  // module contents in `src/do_something.rs`
    use super::Foo;
    pub fn do_something(foo: &Foo) {
        foo.helper();
    }
}

pub use foo::Foo;
pub use do_something::do_something;
</code>```

Now the compiler complains that helper() is private. Indeed it is, but I still want do_something() be able to use it. But I don't want my users to use it. How can I do that?

My attempted solution boils down to "How to access private items of sibling modules?". So answering that question would help me. But providing an alternative solution/a workaround would also be great!

答:
As of Rust 1.18, you can use the pub(crate) syntax to expose something throughout your entire crate but not outside of it:

```<code>mod foo {  // module contents in `src/foo.rs`
    pub struct Foo;
    impl Foo {
        pub(crate) fn helper(&self) { /* .. */ }
    }
}
</code>```

All the possibilities, as suggested by the compiler, include:

pub(crate): visible only on the current crate

pub(super): visible only in the current module's parent

pub(in path::to::module): visible only on the specified path

Body:
Consider the following code in my library:

pub struct Foo;
impl Foo {
    fn helper(&self) { /* .. */ }
}

pub fn do_something(foo: &Foo) {
    foo.helper();
}

The users of my library should be able to use Foo and do_something(), but shall never call helper(). Everything works fine with the code above. But now imagine the code gets huge and I want to separate those definitions into their own files/modules -- they are then pulled back into the root-namespace with pub use. See here:

mod foo {  // module contents in `src/foo.rs`
    pub struct Foo;
    impl Foo {
        fn helper(&self) { /* .. */ }
    }
}

mod do_something {  // module contents in `src/do_something.rs`
    use super::Foo;
    pub fn do_something(foo: &Foo) {
        foo.helper();
    }
}

pub use foo::Foo;
pub use do_something::do_something;

Now the compiler complains that helper() is private. Indeed it is, but I still want do_something() be able to use it. But I don't want my users to use it. How can I do that?

My attempted solution boils down to "How to access private items of sibling modules?". So answering that question would help me. But providing an alternative solution/a workaround would also be great!

Body:
As of Rust 1.18, you can use the pub(crate) syntax to expose something throughout your entire crate but not outside of it:

mod foo {  // module contents in `src/foo.rs`
    pub struct Foo;
    impl Foo {
        pub(crate) fn helper(&self) { /* .. */ }
    }
}

All the possibilities, as suggested by the compiler, include:

pub(crate): visible only on the current crate

pub(super): visible only in the current module's parent

pub(in path::to::module): visible only on the specified path


问:
What data can be obtained when someone accesses my site?
I'm creating a function that logs data from the machine that accessed my website. I already know that it is possible in PHP to get the IP and the browser string ($ _ SERVER ['HTTP_USER_AGENT']). And from the IP, I identify the user's city / state / country.
What I need to know is what other data can be obtained in PHP (or another language) when someone accesses a page from my website.</p>

答:
So far I have already discovered other information that can be obtained from the machine that accessed the website. It's the complete URL. What helps a lot, because if you are trying to break into the server with MySQL injection or PHP injection, we have how to know exactly the method they are using and provide protection.

$url_completa = (isset($_SERVER['HTTPS']) ? "https" : "http") . "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";


问:
Dealing with Large Bitmaps (tiling a small bitmap to create wallpaper)
I'm having memory problems and think it might have to do with creating large bitmaps.

The task at hand is to get a fairly small tile image and create a larger tiled image and set this as the phone wallpaper. The way I'm doing this is:

1) Create a view that is 2 * screen width, 1 * screen height

2) Set the view background to a BitmapDrawable with the tile mode set to repeat

3) Create a bitmap with the views dimensions

4) draw the view to the bitmap by: view.draw(new Canvas(bitmap))

5) set wallpper: getApplicationContext().setWallpaper(bitmap)

This works fine on my phone (HTC Magic) and other phones that I have tried. But I am getting bug reports relating to this issue. I tried to recreate the problem by doubling the required dimensions and the problem seems to be happening in the 4th step when the view is being drawn to the bitmap:

ERROR/dalvikvm-heap(124): Heap Massage needed (7372800-byte external allocation too big)

I'm not sure how to go about solving this. Please help!
Thanks

答:
Unfortunately, I don't think you can do much... We are on a mobile phone here ; Android limis the process memory to 16MB.

Here are a couple of tips and tricks I can give you (because I have the sames issues in my application)

Are you sure you need 32 bits pixels? that's three 8bit color channels plus a 8bit alpha channel. You can use RGB_565 for a visually acceptable result.

Recycle the image that you don't need when you create your bitmap (and that you won't need to draw your bitmap)

null any other object that you don't need

Run System.gc() to force a garbage collection just before you create the Bitmap

Hope this helps!


问:
Splitting Ionic card in half. I want to show students on the right and the teachers on the left
This is what I currently have: https://gyazo.com/7b0c0d53beef6846545bece011332cd5 .  You can see that I have a lot of pictures next to each other, but I want to have 2 halves in the ionic card. On the topleft the groupname , bottom left the teachers and on the right side the studens in the group. I want it like this: https://gyazo.com/d5e71aa9cfe6de9f121ce236f951a6d7 .

HTML

```<code>    <ion-header>
  <ion-navbar color ="primary">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>{{ appName }}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <ion-item>
          <h2>{{ group.name }}</h2>

              <div class="pic" *ngFor="let student of group.students">
                <img [src]="student.avatar" />
              </div>
              <h3>{{group.students.length}}  Leerlingen</h3>

              <div class="pic" *ngFor="let teacher of group.teachers">
                <img [src]="teacher.avatar" />
              </div>
              <h3>{{group.teachers.length}} leerkrachten</h3>

          </ion-item>

      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>

</ion-content>
</code>```

CSS

```<code>.pic{
  display: inline-block;
  height: 40px;
  width: 40px;
}
</code>```

答:
Try this new modification if it fits  </p>

```<code><ion-card >
      <ion-item>
        <ion-row>
          <ion-col col-6>
       <ion-row> <h2>{{ group.name }}</h2></ion-row>
          <ion-row>
            <div class="pic" *ngFor="let student of group.students">
              <img [src]="student.avatar" />
            </div>
          </ion-row>
          <ion-row>
            <h3>{{group.students.length}}  Leerlingen</h3>
           </ion-row>
          </ion-col>

          <ion-col col-6>
           <ion-row>
            <div class="pic" *ngFor="let teacher of group.teachers">
              <img [src]="teacher.avatar" />
            </div>
            </ion-row>
            <ion-row>
            <h3>{{group.teachers.length}} leerkrachten</h3>
            </ion-row>
          </ion-col>
        </ion-row>

         </ion-item>
        </ion-card>
</code>```

Body:
This is what I currently have: https://gyazo.com/7b0c0d53beef6846545bece011332cd5 .  You can see that I have a lot of pictures next to each other, but I want to have 2 halves in the ionic card. On the topleft the groupname , bottom left the teachers and on the right side the studens in the group. I want it like this: https://gyazo.com/d5e71aa9cfe6de9f121ce236f951a6d7 .

HTML

    <ion-header>
  <ion-navbar color ="primary">
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>{{ appName }}</ion-title>
  </ion-navbar>
</ion-header>

<ion-content>
<ion-grid>
  <ion-row>
    <ion-col *ngFor="let group of groupData">
      <ion-card >
        <ion-item>

{{ group.name }}

{{group.students.length}}  Leerlingen

{{group.teachers.length}} leerkrachten

          </ion-item>

      </ion-card>
    </ion-col>
  </ion-row>
</ion-grid>

</ion-content>

CSS

.pic{
  display: inline-block;
  height: 40px;
  width: 40px;
}

Body:
Try this new modification if it fits

<ion-card >
      <ion-item>
        <ion-row>
          <ion-col col-6>
       <ion-row> <h2>{{ group.name }}</h2></ion-row>
          <ion-row>
            <div class="pic" *ngFor="let student of group.students">
              <img [src]="student.avatar" />
            </div>
          </ion-row>
          <ion-row>
            <h3>{{group.students.length}}  Leerlingen</h3>
           </ion-row>
          </ion-col>

          <ion-col col-6>
           <ion-row>
            <div class="pic" *ngFor="let teacher of group.teachers">
              <img [src]="teacher.avatar" />
            </div>
            </ion-row>
            <ion-row>
            <h3>{{group.teachers.length}} leerkrachten</h3>
            </ion-row>
          </ion-col>
        </ion-row>

         </ion-item>
        </ion-card>


问:
Join that returns all left table records when the right table is connected through a linking table
I am having some trouble trying to figure out how to write a SQL statement that will return the same amount of records found in the left table. The only way to get data from the right table is to use a 3rd table.

For instance, I have three tables, Sites, Addresses, and Affiliations. Many affiliations can be active for a site (Contact, Mailing Address, Owner, and Official), but there may not be a person or address associated with the affiliation. IE. A site may have a Contact person but no Official designated, or a site may not yet have a Mailing Address assigned.
The Sites (left table) and Affiliations are linked by a common ID.
Sites.ID = Affiliations.Site_ID

The Affiliations and Addresses (right table) are linked by a common Address Record ID
Affiliations.Address_RID = Addresses.RID

The query I have is

```<code>SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
    AFFILIATIONS B,
    ADDRESSES C
WHERE A.ID = B.SITE_ID
    AND B.ADDRESS_RID = C.RID
    AND B.AFFILIATION_TYPE = 'MAILING ADDRESS'
ORDER BY A.ID
</code>```

The results I get if I query the sites table alone is 1580 site records. Running the above query for mailing addresses I get 1386 records.  I need to return all 1580 records with nulls for records where mailing addresses are absent.
I'm doing something wrong, but I am not seeing it.

Comments?

Thanks

答:
The "old" Oracle syntax for outer joins is like this:-

```<code>SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
    AFFILIATIONS B,
    ADDRESSES C
WHERE A.ID = B.SITE_ID (+)
    AND B.ADDRESS_RID = C.RID (+)
    AND B.AFFILIATION_TYPE (+) = 'MAILING ADDRESS'
ORDER BY A.ID
</code>```

But you really should be using the ANSI syntax - it is much easier to see what is a join condition and what is a filter:-

```<code>SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A
LEFT JOIN AFFILIATIONS B ON A.ID = B.SITE_ID AND B.AFFILIATION_TYPE = 'MAILING ADDRESS'
LEFT JOIN ADDRESSES C ON B.ADDRESS_RID = C.RID
ORDER BY A.ID
</code>```

Note that the condition on the Affiliation type needs to go in the join clause. if you include it in the where clause then you won't return any rows that don't have a 'MAILING ADDRESS' affiliation type.

Body:
I am having some trouble trying to figure out how to write a SQL statement that will return the same amount of records found in the left table. The only way to get data from the right table is to use a 3rd table.

For instance, I have three tables, Sites, Addresses, and Affiliations. Many affiliations can be active for a site (Contact, Mailing Address, Owner, and Official), but there may not be a person or address associated with the affiliation. IE. A site may have a Contact person but no Official designated, or a site may not yet have a Mailing Address assigned.
The Sites (left table) and Affiliations are linked by a common ID.
Sites.ID = Affiliations.Site_ID

The Affiliations and Addresses (right table) are linked by a common Address Record ID
Affiliations.Address_RID = Addresses.RID

The query I have is

SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
    AFFILIATIONS B,
    ADDRESSES C
WHERE A.ID = B.SITE_ID
    AND B.ADDRESS_RID = C.RID
    AND B.AFFILIATION_TYPE = 'MAILING ADDRESS'
ORDER BY A.ID

The results I get if I query the sites table alone is 1580 site records. Running the above query for mailing addresses I get 1386 records.  I need to return all 1580 records with nulls for records where mailing addresses are absent.
I'm doing something wrong, but I am not seeing it.

Comments?

Thanks

Body:
The "old" Oracle syntax for outer joins is like this:-

SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A,
    AFFILIATIONS B,
    ADDRESSES C
WHERE A.ID = B.SITE_ID (+)
    AND B.ADDRESS_RID = C.RID (+)
    AND B.AFFILIATION_TYPE (+) = 'MAILING ADDRESS'
ORDER BY A.ID

But you really should be using the ANSI syntax - it is much easier to see what is a join condition and what is a filter:-

SELECT A.ID,
    A.NAME,
    C.ADDR_1,
    C.CITY_NAME,
    C.STATE_CODE,
    C.POSTAL_CODE
FROM SITES A
LEFT JOIN AFFILIATIONS B ON A.ID = B.SITE_ID AND B.AFFILIATION_TYPE = 'MAILING ADDRESS'
LEFT JOIN ADDRESSES C ON B.ADDRESS_RID = C.RID
ORDER BY A.ID

Note that the condition on the Affiliation type needs to go in the join clause. if you include it in the where clause then you won't return any rows that don't have a 'MAILING ADDRESS' affiliation type.


问:
android.view.View not valid because waiting for a View type
I try to use the sephiroth74/android-target-tooltip library for my project but an argument is not valid...

This is what I do (in a fragment) :

```<code>Button btn = (Button) view.findViewById(R.id.btn);

        Tooltip.make(getContext(),
                new Tooltip.Builder(101)
                        .anchor(btn, Gravity.BOTTOM)
                        .closePolicy(new Tooltip.ClosePolicy()
                                .insidePolicy(true, false)
                                .outsidePolicy(true, false), 3000)
                        .activateDelay(800)
                        .showDelay(300)
                        .text("test")
                        .maxWidth(500)
                        .withArrow(true)
                        .withOverlay(true)
                        .floatingAnimation(Tooltip.AnimationBuilder.DEFAULT)
                        .build()
        ).show();
</code>```

The problem is in this line :

```<code>anchor(btn, Gravity.BOTTOM)
</code>```

It seem btn is not a good argument :

Cannot resolv method 'anchor(android.wiget.Button, int)'

If I try to change by :

```<code>anchor(view.findViewById(R.id.btn), Gravity.BOTTOM)
</code>```

I have :

Cannot resolv method 'anchor(android.view.View, int)'

What can I do ? This function is waiting for a View type but how can I give a View type with my Button ?

答:
I think I understand your issue. The issue is with the Gravity, which is being imported from a wrong class i.e. in your case you must have

```<code>import android.view.Gravity;
</code>```

in your import section whereas it should be

```<code>import it.sephiroth.android.library.tooltip.Tooltip;
</code>```

So, basically just replace the import line and your builder should look like this

```<code>new Tooltip.Builder(101)
    .anchor(btn, Tooltip.Gravity.BOTTOM)
....
....
</code>```

Body:
I try to use the sephiroth74/android-target-tooltip library for my project but an argument is not valid...

This is what I do (in a fragment) :

Button btn = (Button) view.findViewById(R.id.btn);

        Tooltip.make(getContext(),
                new Tooltip.Builder(101)
                        .anchor(btn, Gravity.BOTTOM)
                        .closePolicy(new Tooltip.ClosePolicy()
                                .insidePolicy(true, false)
                                .outsidePolicy(true, false), 3000)
                        .activateDelay(800)
                        .showDelay(300)
                        .text("test")
                        .maxWidth(500)
                        .withArrow(true)
                        .withOverlay(true)
                        .floatingAnimation(Tooltip.AnimationBuilder.DEFAULT)
                        .build()
        ).show();

The problem is in this line :

anchor(btn, Gravity.BOTTOM)

It seem btn is not a good argument :

Cannot resolv method 'anchor(android.wiget.Button, int)'

If I try to change by :

anchor(view.findViewById(R.id.btn), Gravity.BOTTOM)

I have :

Cannot resolv method 'anchor(android.view.View, int)'

What can I do ? This function is waiting for a View type but how can I give a View type with my Button ?

Body:
I think I understand your issue. The issue is with the Gravity, which is being imported from a wrong class i.e. in your case you must have

import android.view.Gravity;

in your import section whereas it should be

import it.sephiroth.android.library.tooltip.Tooltip;

So, basically just replace the import line and your builder should look like this

new Tooltip.Builder(101)
    .anchor(btn, Tooltip.Gravity.BOTTOM)
....
....


问:
Constructing printable representation of an object similar to __repr__ in Python
I'm fairly new to C++ mostly have used Python in the past and am looking for a way to easily construct a printable representation of an object - similar in vein to Python's repr. Here are some snippets from my code (it's a bank of course).

```<code>    class Account   {
    private:
        int pin;
        string firstName;
        string lastName;
        char minit;
        int acc_num;
        float balance;
        float limit;
    public:
        float getBalance(void);
        string getName(void);
        void setPin(int);
        void makeDeposit(float);
        void makeWithdrawal(float);
        Account(float initialDeposit, string fname, string lname, char MI = ' ', float x = 0);
    };
Account::Account(float initialDeposit, string fname, string lname, char MI, float x)  {
    cout << "Your account is being created" << endl;
    firstName = fname;
    lastName = lname;
    minit = MI;
    balance = initialDeposit;
    limit = x;
    pin = rand()%8999+1000;
}
</code>```

Account object constructed. I want to have a Bank object which is essentially an array of account objects.

```<code>    class BankSystem    {
    private:
        vector<Account> listOfAccounts;
        int Client_ID;
    public:
        BankSystem(int id);
        void addAccount(Account acc);
        Account getAccount(int j);
    };
BankSystem::BankSystem(int id)  {
    Client_ID = id;
    listOfAccounts.reserve(10);
}
</code>```

I would like to give the Bank class showAccounts method function which displays to the user all the account objects that they have access to. I'd like to make this printable so I can display it in cout. In Python I'd simply just use the __repr__ to "stringify" the account objects e.g.

```<code>def __repr__(self):
    return 'Account(x=%s, y=%s)' % (self.x, self.y)
</code>```

Wondering how I'd go about doing the same in C++. Thanks!

答:
The idiomatic way to go about this is to overload the operator<< function for output streams with your class, for example

```<code>#include <iostream>

using std::cout;
using std::endl;

class Something {
public:

    // make the output function a friend so it can access its private
    // data members
    friend std::ostream& operator<<(std::ostream&, const Something&);

private:
    int a{1};
    int b{2};
};

std::ostream& operator<<(std::ostream& os, const Something& something) {
    os << "Something(a=" << something.a << ", b=" << something.b << ")";
    return os;
}

int main() {
    auto something = Something{};
    cout << something << endl;
}
</code>```

Body:
I'm fairly new to C++ mostly have used Python in the past and am looking for a way to easily construct a printable representation of an object - similar in vein to Python's repr. Here are some snippets from my code (it's a bank of course).

    class Account   {
    private:
        int pin;
        string firstName;
        string lastName;
        char minit;
        int acc_num;
        float balance;
        float limit;
    public:
        float getBalance(void);
        string getName(void);
        void setPin(int);
        void makeDeposit(float);
        void makeWithdrawal(float);
        Account(float initialDeposit, string fname, string lname, char MI = ' ', float x = 0);
    };
Account::Account(float initialDeposit, string fname, string lname, char MI, float x)  {
    cout << "Your account is being created" << endl;
    firstName = fname;
    lastName = lname;
    minit = MI;
    balance = initialDeposit;
    limit = x;
    pin = rand()%8999+1000;
}

Account object constructed. I want to have a Bank object which is essentially an array of account objects.

    class BankSystem    {
    private:
        vector<Account> listOfAccounts;
        int Client_ID;
    public:
        BankSystem(int id);
        void addAccount(Account acc);
        Account getAccount(int j);
    };
BankSystem::BankSystem(int id)  {
    Client_ID = id;
    listOfAccounts.reserve(10);
}

I would like to give the Bank class showAccounts method function which displays to the user all the account objects that they have access to. I'd like to make this printable so I can display it in cout. In Python I'd simply just use the __repr__ to "stringify" the account objects e.g.

def __repr__(self):
    return 'Account(x=%s, y=%s)' % (self.x, self.y)

Wondering how I'd go about doing the same in C++. Thanks!

Body:
The idiomatic way to go about this is to overload the operator<< function for output streams with your class, for example

#include <iostream>

using std::cout;
using std::endl;

class Something {
public:

    // make the output function a friend so it can access its private
    // data members
    friend std::ostream& operator<<(std::ostream&, const Something&);

private:
    int a{1};
    int b{2};
};

std::ostream& operator<<(std::ostream& os, const Something& something) {
    os << "Something(a=" << something.a << ", b=" << something.b << ")";
    return os;
}

int main() {
    auto something = Something{};
    cout << something << endl;
}


问:
Angular 2 HTTP property retryWhen doesn't exist on type Observable<any>
I am trying to retry my requests so that I can get a refresh token before sending the user to log in again however I am getting an error when I try to use retryWhen on the request and I'm not sure why.

http.service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class HttpService {

  constructor(
    private http: Http
  ) { }

  public get(url: string, headers?: Headers): Observable<any> {
    return this.http.get(url, this.getHeaders(headers))
      .map(this.extractData)
      .retryWhen((error: any) => { ... }) // [ts] Property 'retryWhen' does not exist on type 'Observable<any>'.
      .catch(this.handleError);
  }
}
</code>```

答:
After using it for a couple days the original solution posted by Omri caused some issues where the property couldn't be found occasionally. (It worked in some builds and not others). I ended up finding a better solution that works more consistently and doesn't require an additional import.

Instead of importing Observable from rxjs/Observable import it from rxjs/Rx.

This DOES NOT work:

```<code>import { Observable } from 'rxjs/Observable';
</code>```

This DOES work:

```<code>import { Observable } from 'rxjs/Rx';
</code>```

Body:
I am trying to retry my requests so that I can get a refresh token before sending the user to log in again however I am getting an error when I try to use retryWhen on the request and I'm not sure why.

http.service.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class HttpService {

  constructor(
    private http: Http
  ) { }

  public get(url: string, headers?: Headers): Observable<any> {
    return this.http.get(url, this.getHeaders(headers))
      .map(this.extractData)
      .retryWhen((error: any) => { ... }) // [ts] Property 'retryWhen' does not exist on type 'Observable<any>'.
      .catch(this.handleError);
  }
}

Body:
After using it for a couple days the original solution posted by Omri caused some issues where the property couldn't be found occasionally. (It worked in some builds and not others). I ended up finding a better solution that works more consistently and doesn't require an additional import.

Instead of importing Observable from rxjs/Observable import it from rxjs/Rx.

This DOES NOT work:

import { Observable } from 'rxjs/Observable';

This DOES work:

import { Observable } from 'rxjs/Rx';


问:
How to extract a float from a string
I have a string: string = "2017.5 is halfway through the year". Is there a way to extract this "2017.5" from the string? I tried using string.isdigit(), but that only worked for non-floats.

答:
just a dirty implementation without regex and with the single digit/float per sentence:</p>

```<code>s = "new 2017.5 is halfway through the year1"

def process(all,new):

    def is_float_try(str):
        try:
            float(str)
            return True
        except ValueError:
            return False

    return new if new.isdigit() or is_float_try(new) else all

print reduce(process,s.split(),'')
# 2017.5
</code>```

Title: How to extract a float from a string

Body:
just a dirty implementation without regex and with the single digit/float per sentence:

s = "new 2017.5 is halfway through the year1"

def process(all,new):

    def is_float_try(str):
        try:
            float(str)
            return True
        except ValueError:
            return False

    return new if new.isdigit() or is_float_try(new) else all

print reduce(process,s.split(),'')
# 2017.5


问:
matplotlib error - no module named tkinter
I tried to use the matplotlib package via Pycharm IDE on windows 10.
when I run this code:

```<code>from matplotlib import pyplot
</code>```

I get the following error:

```<code>ImportError: No module named 'tkinter'
</code>```

I know that in python 2.x it was called Tkinter, but that is not the problem - I just installed a brand new python 3.5.1.

EDIT: in addition, I also tried to import 'tkinter' and 'Tkinter' - neither of these worked (both returned the error message I mentioned).

答: For windows users, re-run the installer. Select Modify. Check the box for tcl/tk and IDLE. The description for this says "Installs tkinter"</p>

ContentLicense: CC BY-SA 4.0

Body:
I tried to use the matplotlib package via Pycharm IDE on windows 10.
when I run this code:

from matplotlib import pyplot

I get the following error:

ImportError: No module named 'tkinter'

I know that in python 2.x it was called Tkinter, but that is not the problem - I just installed a brand new python 3.5.1.

EDIT: in addition, I also tried to import 'tkinter' and 'Tkinter' - neither of these worked (both returned the error message I mentioned).


问:
Error While Creating Schema from XSD file and Validating it
This is my Xml file

```<code><Test>
 <Detail>
  <name id="123" age="1">Abc</name>
  <lastname>cd</lastname>
 </Detail>
</Test>
</code>```

And this is my Corresponding XSD file Which Can be generated using http://xmlgrid.net/xml2xsd.html

```<code><xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
          <!-- XML Schema Generated from XML Document on Thu Jun 08 2017 22:08:05 GMT+0530 (India Standard Time) -->
          <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->
       <xs:element name="Test">
              <xs:complexType>
                     <xs:sequence>
                            <xs:element name="Detail">
                                   <xs:complexType>
                                          <xs:sequence>
                                                 <xs:element name="name" type="xs:string">
                                                        <xs:complexType>
                                                               <xs:attribute name="id" type="xs:int"></xs:attribute>
                                                               <xs:attribute name="age" type="xs:int"></xs:attribute>
                                                           </xs:complexType>
                                                    </xs:element>
                                                 <xs:element name="lastname" type="xs:string"></xs:element>
                                             </xs:sequence>
                                      </xs:complexType>
                               </xs:element>
                        </xs:sequence>
                 </xs:complexType>
          </xs:element>
   </xs:schema>
</code>```

When i tried to create a Schema in SQL Server

```<code>CREATE XML SCHEMA COLLECTION TestSchema
AS'<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">
          <!-- XML Schema Generated from XML Document on Thu Jun 08 2017 22:08:05 GMT+0530 (India Standard Time) -->
          <!-- with XmlGrid.net Free Online Service http://xmlgrid.net -->
       <xs:element name="Test">
              <xs:complexType>
                     <xs:sequence>
                            <xs:element name="Detail">
                                   <xs:complexType>
                                          <xs:sequence>
                                                 <xs:element name="name" type="xs:string">
                                                        <xs:complexType>
                                                               <xs:attribute name="id" type="xs:int"></xs:attribute>
                                                               <xs:attribute name="age" type="xs:int"></xs:attribute>
                                                           </xs:complexType>
                                                    </xs:element>
                                                 <xs:element name="lastname" type="xs:string"></xs:element>
                                             </xs:sequence>
                                      </xs:complexType>
                               </xs:element>
                        </xs:sequence>
                 </xs:complexType>
          </xs:element>
   </xs:schema>'
</code>```

I get the error as

```<code>Msg 2305, Level 16, State 1, Line 1
Element or attribute type specified more than once. Location: '/*:schema[1]/*:element[1]/*:
complexType[1]/*:sequence[1]/*:element[1]/*:
complexType[1]/*:sequence[1]/*:element[1]/*:
complexType[1]'.
</code>```

When i removed the type="xs:string" in <xs:element name="name" type="xs:string"> I can create my schema successfully without the error.

But while validating my Schema i got the error as

```<code>declare @x XML(TestSchema)

begin try
select @x='<?xml version="1.0" encoding="utf-8"?>
<Test>
<Detail>
<name id="123" age="1">Abc</name>
<lastname>cd</lastname>
</Detail>
</Test>'
end try
begin catch
print Error_Message()
end catch
</code>```

Can Any body help me to solve this ?

Thanks in advance,Jayendran

答:
In XSD, you can use xs:complexType and xs:simpleContent in order to allow both attributes and content on the same element:

```<code><xs:element name="name">
    <xs:complexType>
        <xs:simpleContent>
            <xs:extension base="xs:string">
                <xs:attribute name="id" type="xs:int"></xs:attribute>
                <xs:attribute name="age" type="xs:int"></xs:attribute>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
</xs:element>
</code>```

Body:
This is my Xml file

<Test>
 <Detail>
  <name id="123" age="1">Abc</name>
  <lastname>cd</lastname>
 </Detail>
</Test>

And this is my Corresponding XSD file Which Can be generated using http://xmlgrid.net/xml2xsd.html

<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">

       <xs:element name="Test">
              <xs:complexType>
                     <xs:sequence>
                            <xs:element name="Detail">
                                   <xs:complexType>
                                          <xs:sequence>
                                                 <xs:element name="name" type="xs:string">
                                                        <xs:complexType>
                                                               <xs:attribute name="id" type="xs:int"></xs:attribute>
                                                               <xs:attribute name="age" type="xs:int"></xs:attribute>
                                                           </xs:complexType>
                                                    </xs:element>
                                                 <xs:element name="lastname" type="xs:string"></xs:element>
                                             </xs:sequence>
                                      </xs:complexType>
                               </xs:element>
                        </xs:sequence>
                 </xs:complexType>
          </xs:element>
   </xs:schema>

When i tried to create a Schema in SQL Server

CREATE XML SCHEMA COLLECTION TestSchema
AS'<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified" attributeFormDefault="unqualified">

       <xs:element name="Test">
              <xs:complexType>
                     <xs:sequence>
                            <xs:element name="Detail">
                                   <xs:complexType>
                                          <xs:sequence>
                                                 <xs:element name="name" type="xs:string">
                                                        <xs:complexType>
                                                               <xs:attribute name="id" type="xs:int"></xs:attribute>
                                                               <xs:attribute name="age" type="xs:int"></xs:attribute>
                                                           </xs:complexType>
                                                    </xs:element>
                                                 <xs:element name="lastname" type="xs:string"></xs:element>
                                             </xs:sequence>
                                      </xs:complexType>
                               </xs:element>
                        </xs:sequence>
                 </xs:complexType>
          </xs:element>
   </xs:schema>'

I get the error as

Msg 2305, Level 16, State 1, Line 1
Element or attribute type specified more than once. Location: '/*:schema[1]/*:element[1]/*:
complexType[1]/*:sequence[1]/*:element[1]/*:
complexType[1]/*:sequence[1]/*:element[1]/*:
complexType[1]'.

When i removed the type="xs:string" in <xs:element name="name" type="xs:string"> I can create my schema successfully without the error.

But while validating my Schema i got the error as

declare @x XML(TestSchema)

begin try
select @x='<?xml version="1.0" encoding="utf-8"?>
<Test>
<Detail>
<name id="123" age="1">Abc</name>
<lastname>cd</lastname>
</Detail>
</Test>'
end try
begin catch
print Error_Message()
end catch

Can Any body help me to solve this ?

Thanks in advance,Jayendran

Body:
In XSD, you can use xs:complexType and xs:simpleContent in order to allow both attributes and content on the same element:

<xs:element name="name">
    <xs:complexType>
        <xs:simpleContent>
            <xs:extension base="xs:string">
                <xs:attribute name="id" type="xs:int"></xs:attribute>
                <xs:attribute name="age" type="xs:int"></xs:attribute>
            </xs:extension>
        </xs:simpleContent>
    </xs:complexType>
</xs:element>


答:
Pushing more data to Kafka should trigger Spark to output something. The current behavior is totally because of the internal implementation.

When you push some data, StreamingQuery will generate a batch to run. When this batch finishes, it will remember the max event time in this batch. Then in the next batch,
because you are using append mode, StreamingQuery will use the max event time and watermark to evict old values from StateStore and output it. Therefore you need to make sure generating at least two batches in order to see output.

Title: Empty output for Watermarked Aggregation Query in Append Mode

Body:
I use Spark 2.2.0-rc1.

I've got a Kafka topic which I'm querying a running watermarked aggregation, with a 1 minute watermark, giving out to console with append output mode.

import org.apache.spark.sql.types._
val schema = StructType(StructField("time", TimestampType) :: Nil)
val q = spark.
  readStream.
  format("kafka").
  option("kafka.bootstrap.servers", "localhost:9092").
  option("startingOffsets", "earliest").
  option("subscribe", "topic").
  load.
  select(from_json(col("value").cast("string"), schema).as("value"))
  select("value.*").
  withWatermark("time", "1 minute").
  groupBy("time").
  count.
  writeStream.
  outputMode("append").
  format("console").
  start

I am pushing following data in Kafka topic:

{"time":"2017-06-07 10:01:00.000"}
{"time":"2017-06-07 10:02:00.000"}
{"time":"2017-06-07 10:03:00.000"}
{"time":"2017-06-07 10:04:00.000"}
{"time":"2017-06-07 10:05:00.000"}

And I am getting following output:

scala> -------------------------------------------
Batch: 0
-------------------------------------------
+----+-----+
|time|count|
+----+-----+
+----+-----+

-------------------------------------------
Batch: 1
-------------------------------------------
+----+-----+
|time|count|
+----+-----+
+----+-----+

-------------------------------------------
Batch: 2
-------------------------------------------
+----+-----+
|time|count|
+----+-----+
+----+-----+

-------------------------------------------
Batch: 3
-------------------------------------------
+----+-----+
|time|count|
+----+-----+
+----+-----+

-------------------------------------------
Batch: 4
-------------------------------------------
+----+-----+
|time|count|
+----+-----+
+----+-----+

Is this expected behaviour?


问:
Javascript script doesn't load in HTML
```<code><!DOCTYPE html>
<html>
  <head>
    <title>Breakout</title>
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>

    <canvas width="900" height="450" class="canvas"></canvas>

    <script src="scripts/base.js"></script>
  </body>
</html>
</code>```

This is the index file

```<code>*{
  margin: 0;
  padding: 0;
}

.canvas{
  background-color: #b7b7b7;
}
</code>```

This is the CSS file

```<code>var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');

context.beginPath();

context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();

context.endPath();
</code>```

And the javascript file.
I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.

答: That's because in your var canvas, you're calling document.getElementByClassName which will return an "array-like" object. So, I'd suggest you to use IDs instead of selecting using a class.

Title: Javascript script doesn't load in HTML

Body:
<!DOCTYPE html>

    <title>Breakout</title>
    <link rel="stylesheet" href="css/style.css">

    <canvas width="900" height="450" class="canvas"></canvas>

This is the index file

*{
  margin: 0;
  padding: 0;
}

.canvas{
  background-color: #b7b7b7;
}

This is the CSS file

var canvas = document.getElementsByClassName('canvas');
var context = canvas.getContext('2d');

context.beginPath();

context.drawRect(20,30,50,40);
context.fillStyle("#0022ff");
context.fill();

context.endPath();

And the javascript file.
I am trying to create a breakout game and I am following a tutorial from udemy. Unfortunately, it seems there is something wrong with this code, but I don't know what. I verified the code one thousand times and I haven't found anything.


问:
Python won't let me use variable inside function
I don't understand why it won't let me use display_w or display_h inside of the function. I can't have it inside the function because I don't want it to reset when I use it again. How can I allow it to use those variables?</p>

```<code>import pygame

pygame.init()

display_w = 800
display_h = 600

white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)

def run():

    print("Input your message: ")
    msg = input()

    print("Enter font size: ")
    font_size = int(input())

    display = pygame.display.set_mode((display_w, display_h))
    pygame.display.set_caption("TextPos")

    text_x = 0
    text_y = 0

    def message_to_screen(msg, color, font_size, x, y):

        font = pygame.font.SysFont(None, font_size)
        screen_text = font.render(msg, True, color)
        display.blit(screen_text, [x, y])
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    running = False
                    pygame.quit()
                    run()
                if event.key == pygame.K_q:

                    print("Enter display width: ")
                    display_w = int(input())

                    print("Enter display height: ")
                    display_h = int(input())
                    running = False

            message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
            m_x, m_y = pygame.mouse.get_pos()
            text_x = m_x
            text_y = m_y

            display.fill(white)
            message_to_screen("X: %s" % m_x, black, 30, 10, 10)
            message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
            message_to_screen(msg, black, font_size, text_x, text_y)
            message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
            message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)

            pygame.display.update()
run()
</code>```

答:
A strange way of accessing the variable. Let's say your module name is xyz. Then:</p>

```<code>import xyz

def func():
    xyz.display_w = 80
</code>```

Body:
I don't understand why it won't let me use display_w or display_h inside of the function. I can't have it inside the function because I don't want it to reset when I use it again. How can I allow it to use those variables?

import pygame

pygame.init()

display_w = 800
display_h = 600

white = (255, 255, 255)
black = (0, 0, 0)
grey = (100, 100, 100)

def run():

    print("Input your message: ")
    msg = input()

    print("Enter font size: ")
    font_size = int(input())

    display = pygame.display.set_mode((display_w, display_h))
    pygame.display.set_caption("TextPos")

    text_x = 0
    text_y = 0

    def message_to_screen(msg, color, font_size, x, y):

        font = pygame.font.SysFont(None, font_size)
        screen_text = font.render(msg, True, color)
        display.blit(screen_text, [x, y])
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_r:
                    running = False
                    pygame.quit()
                    run()
                if event.key == pygame.K_q:

                    print("Enter display width: ")
                    display_w = int(input())

                    print("Enter display height: ")
                    display_h = int(input())
                    running = False

            message_to_screen(msg, (255, 255, 255), 50, text_x, text_y)
            m_x, m_y = pygame.mouse.get_pos()
            text_x = m_x
            text_y = m_y

            display.fill(white)
            message_to_screen("X: %s" % m_x, black, 30, 10, 10)
            message_to_screen("Y: %s" % m_y, black, 30, 10, 30)
            message_to_screen(msg, black, font_size, text_x, text_y)
            message_to_screen("Press Q to Change Screen Size", grey, 30, display_w - 310, 0)
            message_to_screen("Press R to Restart", grey, 30, display_w - 180, 30)

            pygame.display.update()
run()

Body:
A strange way of accessing the variable. Let's say your module name is xyz. Then:

import xyz

def func():
    xyz.display_w = 80


问:
Error: Bootstrap's JavaScript requires jQuery on laravel 5.4
hello guys after mixing laravel template i have some problem with the jquery with Error: Bootstrap's JavaScript requires jQuery

and after searcing im still confused whats happen can you help me

here is my code :

```<code><script src="{{{ URL::asset('js/ace-extra.min.js')}}}"></script>
<script src="{{{ URL::asset('js/bootstrap.min.js')}}}"></script>
  <script src="{{{ URL::asset('js/ace-elements.min.js')}}}"></script>
  <script src="{{{ URL::asset('js/ace.min.js')}}}"></script>
</code>```

`

and error on firefox :

here

答: You have not included jQuery into your HTML. Download that, and include it before bootstrap.</p>

Body:
hello guys after mixing laravel template i have some problem with the jquery with Error: Bootstrap's JavaScript requires jQuery

and after searcing im still confused whats happen can you help me

here is my code :

`

and error on firefox :

here


问:
How do I format a number with commas?
```<code>int a = 10000000;
a.ToString();
</code>```

How do I make the output?

10,000,000

答:
A simpler String.Format option:</p>

```<code>int a = 10000000;
String.Format("{0:n0}", a); //10,000,000
</code>```

OwnerDisplayName: ssl

LastEditorDisplayName: bendewey

Title: How do I format a number with commas?

Body:
int a = 10000000;
a.ToString();

How do I make the output?

10,000,000

Body:
A simpler String.Format option:

int a = 10000000;
String.Format("{0:n0}", a); //10,000,000


问:
Start/Stop mule flow programmatically
I keep one of my flow say 'flow A' in "stopped" as a initial state. Then in another flow say 'flow B', using groovy script or MEL expression; I am starting the same 'flow A'. At the end of the 'flow A', I am programmatically stopping the flow.

Now, If I again start the 'flow A' through 'flow B' it fails saying 'flow A' is already started; can not be restarted.

Any solution for this.

I want to start my flow any time I want, keeping initial state as stopped & again at the end stopping the flow using script.

Here is the code:

```<code><flow name="FlowB">
    <poll doc:name="Poll">
        <logger level="INFO" doc:name="Logger"/>
    </poll>
    <logger level="INFO" doc:name="Logger" message="triggered"/>
    <scripting:component doc:name="Groovy">
        <scripting:script engine="Groovy"><![CDATA[muleContext.registry.lookupFlowConstruct('FlowB').start()]]></scripting:script>
    </scripting:component>
    <logger level="INFO" doc:name="Logger"/>
    <expression-component doc:name="Expression"><![CDATA[app.registry.FlowA.stop();]]></expression-component>
</flow>
<flow name="FlowA" initialState="stopped">
    <sqs:receive-messages config-ref="Amazon_SQS__Configuration" doc:name="Amazon SQS (Streaming)"/>
    <logger level="INFO" doc:name="Logger"/>
</flow>
</code>```

I am using poller to start the flow A. So, if I again run the flow B to start the flow A; Its throwing an exception.

答:
either stopping flowA did not work (for whatever reason) or you tried to start flowA immediately after you stopped it. AFAIK starting/stopping takes place asynchronously, which means flowA might be in started state even if stop() method already returned.

here is a working example exposing /stop and /start http-endpoints.

```<code><mule xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
    <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>

    <flow name="flowA">
        <logger message="foobar" level="INFO" doc:name="Logger"/>
    </flow>

    <flow name="flowB_start">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/start" doc:name="HTTP"/>
        <expression-transformer expression="#[groovy:muleContext.registry.get('flowA').start()]" doc:name="Expression"/>
    </flow>

    <flow name="flowB_stop">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/stop" doc:name="HTTP"/>
        <expression-transformer expression="#[groovy:muleContext.registry.get('flowA').stop()]" doc:name="Expression"/>
    </flow>
</mule>
</code>```

i can start/stop flowA as often as i want.

Title: Start/Stop mule flow programmatically

Body:
I keep one of my flow say 'flow A' in "stopped" as a initial state. Then in another flow say 'flow B', using groovy script or MEL expression; I am starting the same 'flow A'. At the end of the 'flow A', I am programmatically stopping the flow.

Now, If I again start the 'flow A' through 'flow B' it fails saying 'flow A' is already started; can not be restarted.

Any solution for this.

I want to start my flow any time I want, keeping initial state as stopped & again at the end stopping the flow using script.

Here is the code:

<flow name="FlowB">
    <poll doc:name="Poll">
        <logger level="INFO" doc:name="Logger"/>
    </poll>
    <logger level="INFO" doc:name="Logger" message="triggered"/>

    </scripting:component>
    <logger level="INFO" doc:name="Logger"/>
    <expression-component doc:name="Expression"><![CDATA[app.registry.FlowA.stop();]]></expression-component>
</flow>
<flow name="FlowA" initialState="stopped">
    <sqs:receive-messages config-ref="Amazon_SQS__Configuration" doc:name="Amazon SQS (Streaming)"/>
    <logger level="INFO" doc:name="Logger"/>
</flow>

I am using poller to start the flow A. So, if I again run the flow B to start the flow A; Its throwing an exception.

Body:
either stopping flowA did not work (for whatever reason) or you tried to start flowA immediately after you stopped it. AFAIK starting/stopping takes place asynchronously, which means flowA might be in started state even if stop() method already returned.

here is a working example exposing /stop and /start http-endpoints.

<mule xmlns:scripting="http://www.mulesoft.org/schema/mule/scripting" xmlns:tracking="http://www.mulesoft.org/schema/mule/ee/tracking" xmlns:http="http://www.mulesoft.org/schema/mule/http" xmlns="http://www.mulesoft.org/schema/mule/core" xmlns:doc="http://www.mulesoft.org/schema/mule/documentation"
    xmlns:spring="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd
http://www.mulesoft.org/schema/mule/http http://www.mulesoft.org/schema/mule/http/current/mule-http.xsd
http://www.mulesoft.org/schema/mule/ee/tracking http://www.mulesoft.org/schema/mule/ee/tracking/current/mule-tracking-ee.xsd
http://www.mulesoft.org/schema/mule/scripting http://www.mulesoft.org/schema/mule/scripting/current/mule-scripting.xsd">
    <http:listener-config name="HTTP_Listener_Configuration" host="0.0.0.0" port="8081" doc:name="HTTP Listener Configuration"/>

    <flow name="flowA">
        <logger message="foobar" level="INFO" doc:name="Logger"/>
    </flow>

    <flow name="flowB_start">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/start" doc:name="HTTP"/>
        <expression-transformer expression="#[groovy:muleContext.registry.get('flowA').start()]" doc:name="Expression"/>
    </flow>

    <flow name="flowB_stop">
        <http:listener config-ref="HTTP_Listener_Configuration" path="/stop" doc:name="HTTP"/>
        <expression-transformer expression="#[groovy:muleContext.registry.get('flowA').stop()]" doc:name="Expression"/>
    </flow>
</mule>

i can start/stop flowA as often as i want.


问:
How to view uploaded pictures in jade
I was wondering how to view an uploaded picture in jade here are some of my code sample's below

Uploading The Image

```<code> app.post('/add', function (req, res, next) {
   var person = new Person({
     image: './public/images/' + req.files.person.image.name;
   });

   var tmp_path = req.files.person.image.path;
   var target_path = './public/images/' + req.files.person.image.name;

   fs.rename(tmp_path, target_path, function (err) {
    if (err) {
      return next(new Error(err));
    }

    fs.unlink(tmp_path, function (err) {
      if (err) {
        console.log(err);
      }

      person.save(function (err) {
        if (err) {
          return next(new Error(err.message));
        }

        res.redirect('/view/' + person._id);
      });
    });
  });
});
</code>```

Person View Page

```<code>app.get('/view/:id', function (req, res, next) {
  Person.findById(req.params.id, function (err, person) {
    if (err) {
      return next(new Error(err));
    }

    if (!person) {
      return next(new Error('Invalid reference to person information'));
    }

    fs.readFile(person.image, 'binary', function (err, file) {
      if (err) {
        return next(new Error(err));
      } else {
        res.render(path + 'view', {
          title: title,
          person: person,
          file: file
        });
      }
    });
  });
});
</code>```

And in my view.jade I use to display the picture

```<code>img(src='#{file}')
</code>```

But its not being displayed,SOMEONE PLEASE HELP ME !!

答:
This code Worked for me to display the image With Jade.

```<code> .image-block
      h2
      img(src="/image.jpg" alt="image not found")
</code>```

or

```<code>img(src="/#{pathTOImage}" alt="image not found")
</code>```

And in pug you have to write the code like this:

```<code>img(src="/" + pathTOImage)
</code>```

Title: How to view uploaded pictures in jade

Body:
I was wondering how to view an uploaded picture in jade here are some of my code sample's below

Uploading The Image

 app.post('/add', function (req, res, next) {
   var person = new Person({
     image: './public/images/' + req.files.person.image.name;
   });

   var tmp_path = req.files.person.image.path;
   var target_path = './public/images/' + req.files.person.image.name;

   fs.rename(tmp_path, target_path, function (err) {
    if (err) {
      return next(new Error(err));
    }

    fs.unlink(tmp_path, function (err) {
      if (err) {
        console.log(err);
      }

      person.save(function (err) {
        if (err) {
          return next(new Error(err.message));
        }

        res.redirect('/view/' + person._id);
      });
    });
  });
});

Person View Page

app.get('/view/:id', function (req, res, next) {
  Person.findById(req.params.id, function (err, person) {
    if (err) {
      return next(new Error(err));
    }

    if (!person) {
      return next(new Error('Invalid reference to person information'));
    }

    fs.readFile(person.image, 'binary', function (err, file) {
      if (err) {
        return next(new Error(err));
      } else {
        res.render(path + 'view', {
          title: title,
          person: person,
          file: file
        });
      }
    });
  });
});

And in my view.jade I use to display the picture

img(src='#{file}')

But its not being displayed,SOMEONE PLEASE HELP ME !!

Body:
This code Worked for me to display the image With Jade.

 .image-block
      h2
      img(src="/image.jpg" alt="image not found")

or

img(src="/#{pathTOImage}" alt="image not found")

And in pug you have to write the code like this:

img(src="/" + pathTOImage)


答:
Bootstrap JS works with some jQuery elements.

You need to import jQuery before importing Bootstrap JS.

```<code><script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- Then import bootstrap js -->
</code>```

Title: Error: Bootstrap's JavaScript requires jQuery on laravel 5.4

Body:
Bootstrap JS works with some jQuery elements.

You need to import jQuery before importing Bootstrap JS.

<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<!-- Then import bootstrap js -->


问:
Fill area between two horizontal lines matlab
I want to fill the area between d1 and d3, it makes it all, but the plot lines dissapiar after area command.</p>

```<code>fGhz=[1;2;3;4;5;6;7;8;9;10];

d1 = ones(10,1)*(600e-6);
d2 = ones(10,1)*(2000e-6);
d3 = ones(10,1)*(300e-6);

plot(fGhz, lambdan_d10,'-ok',fGhz, d1, 'b',fGhz, d3, 'g',fGhz, d2, 'r','LineWidth',2)

%area([fGhz(1) fGhz(10)],[d1(1) d1(1)],d3(1), 'EdgeColor', 'none', 'FaceColor', [.7 .7 .7])    % plot a line between (x1,y1) and (x2,y2), then fill down to a baseline (6)
%ylim([0 7e-3])
</code>```

答:
It hard to deals with Your code without lambdan_d10 description. Nevertheless, I think it is not crucial for this question. I assume it as sine.
Use rectangle function to fill this area:

```<code>% Your code
fGhz=[1;2;3;4;5;6;7;8;9;10];
lambdan_d10=sin(fGhz).*10^-2.5;
d1 = ones(10,1)*(600e-6);
d2 = ones(10,1)*(2000e-6);
d3 = ones(10,1)*(300e-6);
plot(fGhz, lambdan_d10)
plot(fGhz, lambdan_d10,'-ok',fGhz, d1, 'b',fGhz, d3, 'g',fGhz, d2, 'r','LineWidth',2)
% Fill area
XLIM=xlim();
rectangle('Position',[XLIM(1),d3(1),diff(XLIM),d1(1)-d3(1)],'FaceColor','y','EdgeColor','none')
</code>```

In addition I would advice you to have some template for such reporting figures. My example:

```<code>%% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%% Parameters
fGhz = [1;2;3;4;5;6;7;8;9;10];
d1   = 600e-6;
d2   = 2000e-6;
d3   = 300e-6;
%% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%% Calculations
lambdan_d10 = sin(fGhz).*10^-2.5;
%% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%% Plot results
fig1 = figure();
hold all
% plot main information
plot(fGhz, lambdan_d10,'-ok','LineWidth',2);
% get plot parameters
XLIM = xlim();
% plot helpers
plot(XLIM,[d1 d1], '-b','LineWidth',2)
plot(XLIM,[d2 d2], '-r','LineWidth',2)
plot(XLIM,[d3 d3], '-g','LineWidth',2)
rectangle('Position',[XLIM(1),d3(1),diff(XLIM),d1(1)-d3(1)],'FaceColor','y','EdgeColor','none')
% annotation
xlabel('Hz')
ylabel('eggs')
title('lambda-spam')
</code>```

Body:
I want to fill the area between d1 and d3, it makes it all, but the plot lines dissapiar after area command.

fGhz=[1;2;3;4;5;6;7;8;9;10];

d1 = ones(10,1)*(600e-6);
d2 = ones(10,1)*(2000e-6);
d3 = ones(10,1)*(300e-6);

plot(fGhz, lambdan_d10,'-ok',fGhz, d1, 'b',fGhz, d3, 'g',fGhz, d2, 'r','LineWidth',2)

%area([fGhz(1) fGhz(10)],[d1(1) d1(1)],d3(1), 'EdgeColor', 'none', 'FaceColor', [.7 .7 .7])    % plot a line between (x1,y1) and (x2,y2), then fill down to a baseline (6)
%ylim([0 7e-3])

Body:
It hard to deals with Your code without lambdan_d10 description. Nevertheless, I think it is not crucial for this question. I assume it as sine.
Use rectangle function to fill this area:

% Your code
fGhz=[1;2;3;4;5;6;7;8;9;10];
lambdan_d10=sin(fGhz).*10^-2.5;
d1 = ones(10,1)*(600e-6);
d2 = ones(10,1)*(2000e-6);
d3 = ones(10,1)*(300e-6);
plot(fGhz, lambdan_d10)
plot(fGhz, lambdan_d10,'-ok',fGhz, d1, 'b',fGhz, d3, 'g',fGhz, d2, 'r','LineWidth',2)
% Fill area
XLIM=xlim();
rectangle('Position',[XLIM(1),d3(1),diff(XLIM),d1(1)-d3(1)],'FaceColor','y','EdgeColor','none')

In addition I would advice you to have some template for such reporting figures. My example:

%% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%% Parameters
fGhz = [1;2;3;4;5;6;7;8;9;10];
d1   = 600e-6;
d2   = 2000e-6;
d3   = 300e-6;
%% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%% Calculations
lambdan_d10 = sin(fGhz).*10^-2.5;
%% >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
%% Plot results
fig1 = figure();
hold all
% plot main information
plot(fGhz, lambdan_d10,'-ok','LineWidth',2);
% get plot parameters
XLIM = xlim();
% plot helpers
plot(XLIM,[d1 d1], '-b','LineWidth',2)
plot(XLIM,[d2 d2], '-r','LineWidth',2)
plot(XLIM,[d3 d3], '-g','LineWidth',2)
rectangle('Position',[XLIM(1),d3(1),diff(XLIM),d1(1)-d3(1)],'FaceColor','y','EdgeColor','none')
% annotation
xlabel('Hz')
ylabel('eggs')
title('lambda-spam')