问:
Make a div as heigh as needed
In my example below when the content in the top right div is too high, the content of the bottom div flows over the content of the top div.

I would like the top div to push the bottom div down so that content in both divs stays visible in the situation below.

How could I solve this?

.left {
  background-color: grey;
  min-height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
  height: 150px;

}

.bottom {
  background-color: lightgreen;
  height: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper">
  <div class="left">
    left
  </div>
  <div class="right">
    <div class="top">
      top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>

    </div>
    <div class="bottom">
      bottom right
    </div>

  </div>

  <div></code>```

Edit

What I didn't mention before is that the bottom div should be on the bottom by default. This means that if there is enough space the bottom line of the bottom div should align with the bottom line of the left div

答:
You can do this with a flex row layout for the outer elements and column layout for the right side. Setting .top and .bottom to flex-grow: 1 will cause them to grow to match the parent height if there is not enough content for them to stretch to the parent height

.left {
  background-color: grey;
  min-height: 200px;
}
.top {
  background-color: lightblue;
}
.bottom {
  background-color: lightgreen;
}
/* added these */
.flex {
  display: flex;
}
.col {
  flex-direction: column;
}
.top,.bottom {
  flex-grow: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrapper flex">
  <div class="left">
    left
  </div>
  <div class="right flex col">
    <div class="top">
      top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>
    </div>
    <div class="bottom">
      bottom right
    </div>
  </div>
<div></code>```

Title: Make a div as heigh as needed

Body:
In my example below when the content in the top right div is too high, the content of the bottom div flows over the content of the top div.

I would like the top div to push the bottom div down so that content in both divs stays visible in the situation below.

How could I solve this?

.left {
  background-color: grey;
  min-height: 200px;
  float: left;
}

.right {
  height: auto;
  float: left;
}

.top {
  background-color: lightblue;
  height: 150px;

}

.bottom {
  background-color: lightgreen;
  height: 50px;
}

    left

      top right
 top right
 top right
 top right
 top right
 top right
top right
top right
top right

      bottom right

Edit

What I didn't mention before is that the bottom div should be on the bottom by default. This means that if there is enough space the bottom line of the bottom div should align with the bottom line of the left div

Body:
You can do this with a flex row layout for the outer elements and column layout for the right side. Setting .top and .bottom to flex-grow: 1 will cause them to grow to match the parent height if there is not enough content for them to stretch to the parent height

.left {
  background-color: grey;
  min-height: 200px;
}
.top {
  background-color: lightblue;
}
.bottom {
  background-color: lightgreen;
}
/* added these */
.flex {
  display: flex;
}
.col {
  flex-direction: column;
}
.top,.bottom {
  flex-grow: 1;
}

<div class="wrapper flex">
  <div class="left">
    left
  </div>
  <div class="right flex col">
    <div class="top">
      top right<br/> top right<br/> top right<br/> top right<br/> top right<br/> top right<br/>top right<br/>top right<br/>top right<br/>
    </div>
    <div class="bottom">
      bottom right
    </div>
  </div>
<div>


来源: stackexchange

问:
I need help converting my driver user interface code
I have a custom driver I have written.

Here is the source code to communicate to the driver in C:

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

/*********************************************************
* Main Function Entry
*
*********************************************************/
int _cdecl main(void)
{
HANDLE hFile;
DWORD dwReturn;

hFile = CreateFile("\\\\.\\Example", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

if(hFile)
{
WriteFile(hFile, "Hello from user mode!", sizeof("Hello from user mode!"), &dwReturn, NULL);
CloseHandle(hFile);
}

return 0;
}
</code>```

I want to be able to do this in .NET preferaly in VB.NET.

Does anyone know how to do the conversion?

答: You may find using the SerialPort class in the .net framework is easier.  Check out the response to this question.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a custom driver I have written.

Here is the source code to communicate to the driver in C:

#include <windows.h>
#include <stdio.h>

/*********************************************************
* Main Function Entry
*
*********************************************************/
int _cdecl main(void)
{
HANDLE hFile;
DWORD dwReturn;

hFile = CreateFile("\\\\.\\Example", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);

if(hFile)
{
WriteFile(hFile, "Hello from user mode!", sizeof("Hello from user mode!"), &dwReturn, NULL);
CloseHandle(hFile);
}

return 0;
}

I want to be able to do this in .NET preferaly in VB.NET.

Does anyone know how to do the conversion?


问:
How to increase left position dynamically using jquery?
Here is the HTML,

```<code><ul>
  <li>List One</li>
  <li>List Two</li>
  <li>List Thre</li>
  <li>List Four</li>
  .......................
</ul>
</code>```

Can I set left value dynamically and increment by 20% on each item?
For example-

```<code><ul>
  <li style="left:20%;">List One</li>
  <li style="left:40%;">List Two</li>
  <li style="left:60%;">List Thre</li>
  <li style="left:80%;">List Four</li>
  .......................
</ul>
</code>```

Thanks for your help.

答:
Use the index available in each() callback to increment the value:

$( "li" ).each(function(i) {
    var percent = 20 * (i+1) +'%';
    $( this ).css( "left", "+=" + percent );
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li {position:absolute; top:0}</code>```

List One

List Two

List Thre

List Four

```

ContentLicense: CC BY-SA 3.0

Body:
Here is the HTML,

List One

List Two

List Thre

List Four

  .......................

Can I set left value dynamically and increment by 20% on each item?
For example-

List One

List Two

List Thre

List Four

  .......................

Thanks for your help.

Body:
Use the index available in each() callback to increment the value:

$( "li" ).each(function(i) {
    var percent = 20 * (i+1) +'%';
    $( this ).css( "left", "+=" + percent );
});

li {position:absolute; top:0}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<ul>
  <li>List One</li>
  <li>List Two</li>
  <li>List Thre</li>
  <li>List Four</li>

</ul>


问:
How does CanActivate work in Angular2?
TL;DR
How does CanActivate work?

Long version
It is the first time that I see the implementation of a client-side access control.

In all the authentication systems that I used so far (e.g. PHP or other server side programming language), there's always been a function that checks if the user is already logged in, if such function returns true the server can deliver the page, otherwise the user get redirected to a login page.

In this case the client can't access the server code, it can only makes requests and wait until the server composes the page, then render it.

Instead, Angular works differently. It is a client-side framework which uses JavaScript, and its code is visible by everyone. The private page isn't securely placed inside the server, the only server task is to deliver the SPA, but it can't accept further requests.

Despite it, the framework implements features as CanActivate, and it works well.
So I was wondering about what forbids me to inject some JavaScript code and access a private page, even if I don't have the right, or more generally how this system works. On the Internet I didn't find enough information and I don't have enough skills to understand the source code. Can you help me to clarify my ideas?

I could just ask the question in the title, but I preferred to tell you everything I know, so if there's something wrong you can correct me. Thank you

答:
CanActivate does not Guard against stupid and/or insecure programming

TL;DR Even in SPAs sensitive data is protected by servers and is returned only if correct authentication token is passed along with the request. Wrappers or decorators like CanActivate, only make it convenient to manage the views, which without real data are just empty shells!

Long Version

Your question is not CanActivate specific but about concept of client side authentication IMO. You are correct in assuming that if any sensitive data has been pushed to SPA that should not be without proper authentication, then it can be accessed, with or without client authentication. However that is not the point of client side authentication.

Way CanActivate decorator or any other JavaScript/Mobile Token authentication system works is, it makes a authentication request to server, and server returns the authentication token.

Now SPA in its subsequent requests is expected to pass along that auth-token back to the server, and it is in these requests that server sends back real data if the authentication token is valid.

The SPA now takes this data and compiles it into a view for user. So, while SPA is conceptually a application all in the browser, it should (and does in sane cases) depend on sensitive data from the server which is authentication protected.

For folks coming from more traditional session based authentication systems this concept should not be very different. In case of sessions, authentication cookies are sent with sub-sequent requests, in case of SAPs Tokens are sent back. When it comes to authentication, that's the only difference.

As for the data returned, for SPAs, servers typically only return data and for classic server side application, servers compiles view + data and returns it.

Hope that makes sense and helps!

Title: How does CanActivate work in Angular2?


问:
How to Merge fields after query, i know CONCAT, but not this way

I know the way to merge field in

MySQL: CONCAT( )

Oracle: CONCAT( ), ||

SQL Server: `+

but...
I wanna merge AFTER query, is it possible?

答:
Here you go:

MySQL using group_concat:

```<code>select a.name,
    a.opcode,
    group_concat(month order by b.pk separator ', ') as months
from tablea a
join tableb b on a.opcode = b.opcode
group by a.name, a.opcode;
</code>```

Oracle using listagg:

```<code>select a.name,
    a.opcode,
    listagg(month,', ') within group (order by b.pk) as months
from tablea a
join tableb b on a.opcode = b.opcode
group by a.name, a.opcode;
</code>```

SQL Server using for xml path and stuff:

```<code>select a.*,
    stuff((
        select ', ' + month from tableb b
        where a.opcode = b.opcode
        order by pk
        for xml path(''), type
        ).value('(./text())[1]', 'varchar(max)')
    , 1, 2, '') as months
from tablea a;
</code>```

Body:
Here you go:

MySQL using group_concat:

select a.name,
    a.opcode,
    group_concat(month order by b.pk separator ', ') as months
from tablea a
join tableb b on a.opcode = b.opcode
group by a.name, a.opcode;

Oracle using listagg:

select a.name,
    a.opcode,
    listagg(month,', ') within group (order by b.pk) as months
from tablea a
join tableb b on a.opcode = b.opcode
group by a.name, a.opcode;

SQL Server using for xml path and stuff:

select a.*,
    stuff((
        select ', ' + month from tableb b
        where a.opcode = b.opcode
        order by pk
        for xml path(''), type
        ).value('(./text())[1]', 'varchar(max)')
    , 1, 2, '') as months
from tablea a;


问:
Windows batch: sleep
How do I get a Windows batch script to wait a few seconds?

sleep and wait don't seem to work (unrecognized command).

答:
Personally I use a Perl one-liner:

```<code>perl -e "sleep 10;"
</code>```

for a 10-second wait. Chances are you'll already have Perl installed on a development machine as part of your git installation; if not you will have to install it, for example, from ActiveState or Strawberry, but it's one of those things I install anyway.

Alternatively, you can install a sleep command from GnuWin32.

Title: Windows batch: sleep

Body:
Personally I use a Perl one-liner:

perl -e "sleep 10;"

for a 10-second wait. Chances are you'll already have Perl installed on a development machine as part of your git installation; if not you will have to install it, for example, from ActiveState or Strawberry, but it's one of those things I install anyway.

Alternatively, you can install a sleep command from GnuWin32.


问:
CopyFile API function not working after using GetOpenFileName to get the file path
I am using GetOpenFileName() to get the file path, and then CopyFile() to copy the file to the same directory with a different file name.

By using GetLastError(), I am getting an error code:

0x2 - The system cannot find the file specified.

But when I used MessageBox() to see the file names, it showed the correct file names.

In addition to this, I have also tried to StrTrim() the file name, but still it did not work.

I am using Borland C++Builder 6.0.

CODE

```<code>OPENFILENAME ofn;
char szFile[260];
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner =  Form1->Handle;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "All\0*.*\0Text\0*.txt\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = 0;
GetOpenFileName(&ofn);

LPSTR FileName;
FileName = ofn.lpstrFile;
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, strcat(FileName, ".newfile"), "New File Name", MB_OK);
CopyFile(FileName, strcat(FileName,".newfile"), false);
</code>```

EDITED CODE

I have tried using two variables, but it is still not working. Can anyone suggest a correction?

```<code>LPSTR FileName;
LPSTR NewFileName;
FileName = ofn.lpstrFile;
NewFileName = FileName;
strcat(NewFileName, ".newfile");
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, NewFileName, "New File Name", MB_OK);
CopyFile(FileName, NewFileName, false);
</code>```

WORKING CODE

The below code works, but I had to add a Text Box / Edit Control. Is there way to do it without adding any extra control?

```<code>LPSTR FileName;
AnsiString NewFileName;
FileName = ofn.lpstrFile;
Edit1->Text = FileName;
NewFileName = Edit1->Text + ".bak";
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, NewFileName.c_str(), "New File Name", MB_OK);
</code>```

答:
You are using a single buffer for both arguments of CopyFile(), and you are appending the new extension to that buffer, so of course CopyFile() is not going to find the file to copy.

You need to use two separate buffers for the two arguments of CopyFile(), eg:

```<code>TCHAR szSrcFile[MAX_PATH];
TCHAR szDstFile[MAX_PATH+12];

OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Form1->Handle;
ofn.lpstrFile = szSrcFile;
ofn.lpstrFile[0] = TEXT('\0');
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = TEXT("All\0*.*\0Text\0*.txt\0");
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

if (GetOpenFileName(&ofn))
{
    lstrcpy(szDstFile, szSrcFile);
    lstrcat(szDstFile, TEXT(".newfile"));
    MessageBox(Form1->Handle, szSrcFile, TEXT("File Name"), MB_OK);
    MessageBox(Form1->Handle, szDstFile, TEXT("New File Name"), MB_OK);
    CopyFile(szSrcFile, szDstFile, FALSE);
 }
</code>```

That being said, since you are using Borland's VCL framework, you should use the TOpenDialog component instead of GetOpenFileName() directly, and then you can use String variables for easy concatenation:

```<code>// these properties can also be set at design-time instead...
OpenDialog1->Filter = "All|*.*|Text|*.txt";
OpenDialog1->FilterIndex = 1;
OpenDialog1->Options = TOpenOptions() << ofPathMustExist << ofFileMustExist;

if (OpenDialog1->Execute())
{
    String SrcFile = OpenDialog1->FileName;
    String DstFile = SrcFile + ".newfile";
    CopyFileA(SrcFile.c_str(), DstFile.c_str(), FALSE);
}
</code>```

Body:
I am using GetOpenFileName() to get the file path, and then CopyFile() to copy the file to the same directory with a different file name.

By using GetLastError(), I am getting an error code:

0x2 - The system cannot find the file specified.

But when I used MessageBox() to see the file names, it showed the correct file names.

In addition to this, I have also tried to StrTrim() the file name, but still it did not work.

I am using Borland C++Builder 6.0.

CODE

OPENFILENAME ofn;
char szFile[260];
ZeroMemory(&ofn, sizeof(ofn));
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner =  Form1->Handle;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "All\0*.*\0Text\0*.txt\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = 0;
GetOpenFileName(&ofn);

LPSTR FileName;
FileName = ofn.lpstrFile;
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, strcat(FileName, ".newfile"), "New File Name", MB_OK);
CopyFile(FileName, strcat(FileName,".newfile"), false);

EDITED CODE

I have tried using two variables, but it is still not working. Can anyone suggest a correction?

LPSTR FileName;
LPSTR NewFileName;
FileName = ofn.lpstrFile;
NewFileName = FileName;
strcat(NewFileName, ".newfile");
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, NewFileName, "New File Name", MB_OK);
CopyFile(FileName, NewFileName, false);

WORKING CODE

The below code works, but I had to add a Text Box / Edit Control. Is there way to do it without adding any extra control?

LPSTR FileName;
AnsiString NewFileName;
FileName = ofn.lpstrFile;
Edit1->Text = FileName;
NewFileName = Edit1->Text + ".bak";
MessageBox (Form1->Handle, FileName, "File Name", MB_OK);
MessageBox (Form1->Handle, NewFileName.c_str(), "New File Name", MB_OK);

Body:
You are using a single buffer for both arguments of CopyFile(), and you are appending the new extension to that buffer, so of course CopyFile() is not going to find the file to copy.

You need to use two separate buffers for the two arguments of CopyFile(), eg:

TCHAR szSrcFile[MAX_PATH];
TCHAR szDstFile[MAX_PATH+12];

OPENFILENAME ofn;
ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = Form1->Handle;
ofn.lpstrFile = szSrcFile;
ofn.lpstrFile[0] = TEXT('\0');
ofn.nMaxFile = MAX_PATH;
ofn.lpstrFilter = TEXT("All\0*.*\0Text\0*.txt\0");
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;

if (GetOpenFileName(&ofn))
{
    lstrcpy(szDstFile, szSrcFile);
    lstrcat(szDstFile, TEXT(".newfile"));
    MessageBox(Form1->Handle, szSrcFile, TEXT("File Name"), MB_OK);
    MessageBox(Form1->Handle, szDstFile, TEXT("New File Name"), MB_OK);
    CopyFile(szSrcFile, szDstFile, FALSE);
 }

That being said, since you are using Borland's VCL framework, you should use the TOpenDialog component instead of GetOpenFileName() directly, and then you can use String variables for easy concatenation:

// these properties can also be set at design-time instead...
OpenDialog1->Filter = "All|*.*|Text|*.txt";
OpenDialog1->FilterIndex = 1;
OpenDialog1->Options = TOpenOptions() << ofPathMustExist << ofFileMustExist;

if (OpenDialog1->Execute())
{
    String SrcFile = OpenDialog1->FileName;
    String DstFile = SrcFile + ".newfile";
    CopyFileA(SrcFile.c_str(), DstFile.c_str(), FALSE);
}


问:
PhantomJS - WaitFor Method will not execute function. Programm is stuck
I got some trouble using the waitFor-Method within PhantomJS.

This is what I want to do:

Load multiple webpages by generated urls

Use jQuery to parse some links from that pages

Store each parsed link in the same array (In this example I'll just log them)

I'm Using the waitFor() -Method, so I can wait until a page has been evaluated. As I understand, this method will make the programm prevent to continue, until the function which I pass as a parameter has returned anything.

My Problem:
Actually the programm will not continue to run after it executes the waitFor-Method. It's just stuck. There is no error whatsoever. The function I passed as a parameter will not be executed...at least there is no logging in the console.

When I remove the waitFor-Methot it will execute the code properly, however I cannot execute the handleSeriesPageListPage()-Method multiple times. I'm really not too much into js and callbacks or asynchronous method handling. I guess I did some heavy mistakes and some javascript expert will be able to help me quickly :).

```<code>"use strict";
var page = require('webpage').create();
page.onConsoleMessage = function (msg) {
    console.log(msg);
};
var seriesPageBaseUrl = "https://www.example.com?pageid=";
var simpleBaseUrl = "https://www.example.com/";
var seriesPageIds = [0xx, 1xx];
var allSeriesUrls = [];

function handleSeriesPageListPage(url) {
    console.log("Open url: " + url);
    page.open(url, function (status) {
        console.log("status: " + status);
        if (status === "success") {
            waitFor(
                function () {
                    return page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
                        console.log("Included JS");
                        return page.evaluate(function () {
                            console.log("evaluate result...");
                            $('.list_item').each(function () {
                                var seriesLink = jQuery(this).find("a").first().attr("href");
                                var seriesUrl = simpleBaseUrl + seriesLink;
                                console.log(seriesUrl);
                                return true;
                            });
                        });
                    });
                }
            );
        } else {
            phantom.exit(1);
        }
    });
}

function nextSeriesListPage() {
    var seriesPageId = seriesPageIds.shift();
    if (typeof seriesPageId === "undefined") {
        console.log(allSeriesUrls);
        phantom.exit(0);
    }
    var targetURL = seriesPageBaseUrl + seriesPageId;
    handleSeriesPageListPage(targetURL);
}

nextSeriesListPage();
</code>```

答:
The waitFor() function you employed is not a suitable method for handling asynchronuous tasks, and you actually misunderstood what it does:

```<code>waitFor(testFx, onReady, timeOutMillis)
</code>```

takes three parameters (the third one is optional). The first parameter is a test function. It is executed repeatedly, but each time synchronuously, until its return value is true. Then, the function given as the second parameter is executed. If during the period given with the third parameter (or 3 seconds as a default) no true value is returned, the function quits with a log message of 'waitFor()' timeout.

You only provided a single paramter; a function that finishes without a return value (page.includeJs(), basically). Accordingly, waitFor() should quit after 3 seconds with the timeout message.

What you really wanted to achieve was

wait for the page being loaded

then inject the jQuery script, and wait for that,

then reevaluate, and wait for that,

then extract information

These are four asynchronuous tasks. The basic approach prescribed by PhantomJS is to proceed to the respective next step inside the previous callback function, resulting in four nested callbacks.

As this is not a nice pattern (It is commonmly called callback hell), the Promise pattern has been introduced as a Javascript feature (or included in several libraries).

To find out how to re-formulate callback APIs as Promises, take a look at
How do I convert an existing callback API to promises?

Body:
I got some trouble using the waitFor-Method within PhantomJS.

This is what I want to do:

Load multiple webpages by generated urls

Use jQuery to parse some links from that pages

Store each parsed link in the same array (In this example I'll just log them)

I'm Using the waitFor() -Method, so I can wait until a page has been evaluated. As I understand, this method will make the programm prevent to continue, until the function which I pass as a parameter has returned anything.

My Problem:
Actually the programm will not continue to run after it executes the waitFor-Method. It's just stuck. There is no error whatsoever. The function I passed as a parameter will not be executed...at least there is no logging in the console.

When I remove the waitFor-Methot it will execute the code properly, however I cannot execute the handleSeriesPageListPage()-Method multiple times. I'm really not too much into js and callbacks or asynchronous method handling. I guess I did some heavy mistakes and some javascript expert will be able to help me quickly :).

"use strict";
var page = require('webpage').create();
page.onConsoleMessage = function (msg) {
    console.log(msg);
};
var seriesPageBaseUrl = "https://www.example.com?pageid=";
var simpleBaseUrl = "https://www.example.com/";
var seriesPageIds = [0xx, 1xx];
var allSeriesUrls = [];

function handleSeriesPageListPage(url) {
    console.log("Open url: " + url);
    page.open(url, function (status) {
        console.log("status: " + status);
        if (status === "success") {
            waitFor(
                function () {
                    return page.includeJs("https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function () {
                        console.log("Included JS");
                        return page.evaluate(function () {
                            console.log("evaluate result...");
                            $('.list_item').each(function () {
                                var seriesLink = jQuery(this).find("a").first().attr("href");
                                var seriesUrl = simpleBaseUrl + seriesLink;
                                console.log(seriesUrl);
                                return true;
                            });
                        });
                    });
                }
            );
        } else {
            phantom.exit(1);
        }
    });
}

function nextSeriesListPage() {
    var seriesPageId = seriesPageIds.shift();
    if (typeof seriesPageId === "undefined") {
        console.log(allSeriesUrls);
        phantom.exit(0);
    }
    var targetURL = seriesPageBaseUrl + seriesPageId;
    handleSeriesPageListPage(targetURL);
}

nextSeriesListPage();

Body:
The waitFor() function you employed is not a suitable method for handling asynchronuous tasks, and you actually misunderstood what it does:

waitFor(testFx, onReady, timeOutMillis)

takes three parameters (the third one is optional). The first parameter is a test function. It is executed repeatedly, but each time synchronuously, until its return value is true. Then, the function given as the second parameter is executed. If during the period given with the third parameter (or 3 seconds as a default) no true value is returned, the function quits with a log message of 'waitFor()' timeout.

You only provided a single paramter; a function that finishes without a return value (page.includeJs(), basically). Accordingly, waitFor() should quit after 3 seconds with the timeout message.

What you really wanted to achieve was

wait for the page being loaded

then inject the jQuery script, and wait for that,

then reevaluate, and wait for that,

then extract information

These are four asynchronuous tasks. The basic approach prescribed by PhantomJS is to proceed to the respective next step inside the previous callback function, resulting in four nested callbacks.

As this is not a nice pattern (It is commonmly called callback hell), the Promise pattern has been introduced as a Javascript feature (or included in several libraries).

To find out how to re-formulate callback APIs as Promises, take a look at
How do I convert an existing callback API to promises?


问:
Cookies in browser console is different than cookies fetch from Laravel
I get two different values from the console and from the Laravel side.

This is how I get from the Laravel side

```<code>public function getCookies() {

    $cookies = \Cookie::get();

    dd($cookies);

}
</code>```

EDIT 1:

It seems the cookies will be automatically decrypted when get function is called.
Is there any way I could get the original value of the cookies without getting decrypted?

EDIT 2

Resolved this by including the cookies name in except array in EncryptCookies middleware. If you are interested in more of this discussion, can refer

https://github.com/laravel/framework/issues/6679

https://github.com/laravel/framework/pull/9150

答:
Laravel will automatically encrypt and decrypt all cookies.

All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client.

  Source: https://laravel.com/docs/5.4/requests#cookies

You can exclude a cookie from the automatic encryption by adding it to the $except array in the EncryptCookies middleware.

Body:
I get two different values from the console and from the Laravel side.

This is how I get from the Laravel side

public function getCookies() {

    $cookies = \Cookie::get();

    dd($cookies);

}

EDIT 1:

It seems the cookies will be automatically decrypted when get function is called.
Is there any way I could get the original value of the cookies without getting decrypted?

EDIT 2

Resolved this by including the cookies name in except array in EncryptCookies middleware. If you are interested in more of this discussion, can refer

https://github.com/laravel/framework/issues/6679

https://github.com/laravel/framework/pull/9150


问:
How to fetch data from db and write to csv more quickly?
I need to fetch data from DB and write it to a corresponding column in CSV file.
The following code do it very slow(iteratevly, one by one)

```<code>async def fetch_and_write():
  conn = await asyncpg.connect('...')
  with open('/Users/mac/Desktop/input.csv','r') as csvinput:
     with open('/Users/mac/Desktop/output.csv', 'w') as csvoutput:
        reader = csv.reader(csvinput)
        writer = csv.writer(csvoutput, lineterminator='\n')

        all = []
        row = next(reader)
        row.append('new_column_name')
        all.append(row)

        for row in reader:
            query = "SELECT .. FROM .. WHERE id = '%s';"
            query = query % row[14]
            try:
                result = await conn.fetch(query)
            except BaseException:
                print("Oops!That was no valid number.")
                continue

            row.append(result[0][0])
            all.append(row)

        writer.writerows(all)
</code>```

How can I read id from CSV in chunks and use "in" clause to improve performance?

答:
You can use postgres' Copy command to do the trick.
e.g. your query should be

Copy (Select * From foo) To '/tmp/test.csv' With CSV DELIMITER ',';

Body:
I need to fetch data from DB and write it to a corresponding column in CSV file.
The following code do it very slow(iteratevly, one by one)

async def fetch_and_write():
  conn = await asyncpg.connect('...')
  with open('/Users/mac/Desktop/input.csv','r') as csvinput:
     with open('/Users/mac/Desktop/output.csv', 'w') as csvoutput:
        reader = csv.reader(csvinput)
        writer = csv.writer(csvoutput, lineterminator='\n')

        all = []
        row = next(reader)
        row.append('new_column_name')
        all.append(row)

        for row in reader:
            query = "SELECT .. FROM .. WHERE id = '%s';"
            query = query % row[14]
            try:
                result = await conn.fetch(query)
            except BaseException:
                print("Oops!That was no valid number.")
                continue

            row.append(result[0][0])
            all.append(row)

        writer.writerows(all)

How can I read id from CSV in chunks and use "in" clause to improve performance?


问:
Spring JPA updating ManyToMany relations/link_table with very large child datasets
We have objects that could potentially have a ManyToMany relationship with hundreds or thousands of addresses and are looking for a way to efficiently model this in our database using Spring JPA. Right now, we have something like this:

DB Tables:

coupon:

    couponId

    ...

address:

    addressId

    address

    city

    ...

coupon_address:

    businessId

    addressId

Entities:

Coupon.java

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long couponId;

...

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name="coupon_address", joinColumns = {
    @JoinColumn(name="couponId") }, inverseJoinColumns={
    @JoinColumn(name="addressId") })
private Collection<Address> addresses;
</code>```

Address.java

```<code>@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long addressId;
...
</code>```

We have a stored procedure that will return the nearest addresses, which works fine.

Questions:

When we update details of a Coupon, we don't want to have to populate the Coupon object with all addresses prior to saving to database. If we don't do this though, the address relations are removed from the link table. Is there a way to save the Coupon without affecting the link table?

Is there a way to populate entries in the link table without having save the associated Coupon with the entire set of Addresses?

When we query for nearest Addresses, we only want the resultant addresses to be populated in the Coupon object for the client. Since we are using LAZY fetching the Coupons, we can probably avoid calling Coupon.getAddresses and populate the subset of Addresses manually.

I don't know how to handle issue #1 and not sure if #2 is sufficient. Most of the time, we won't have to worry about having a ton of addresses for each Coupon, but the potential does exist.

Thank You.

答:
That's because you're not updating a coupon. Updating a coupon would consist in doing

```<code>Coupon c = em.find(Coupon.class, id);
c.setXxx(...);
</code>```

Just do that to update your coupon, instead of merging a new coupon without any address.

No, with your current design, that's not possible. The only way you can modify the content of the join table is by modifying the content of the addresses collection. But you could choose to map the join table as an entity instead of using a ManyToMany. Or you could use native queries.

That can't happen. addresses is the collection of addresses of a coupon. Not the addresses found by some query used to load a coupon. If you want a subset of the addresses of a coupon, then execute a query selecting addresses. Not a query selecting coupons.

Body:
We have objects that could potentially have a ManyToMany relationship with hundreds or thousands of addresses and are looking for a way to efficiently model this in our database using Spring JPA. Right now, we have something like this:

DB Tables:

coupon:

    couponId

    ...

address:

    addressId

    address

    city

    ...

coupon_address:

    businessId

    addressId

Entities:

Coupon.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long couponId;

...

@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name="coupon_address", joinColumns = {
    @JoinColumn(name="couponId") }, inverseJoinColumns={
    @JoinColumn(name="addressId") })
private Collection<Address> addresses;

Address.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long addressId;
...

We have a stored procedure that will return the nearest addresses, which works fine.

Questions:

When we update details of a Coupon, we don't want to have to populate the Coupon object with all addresses prior to saving to database. If we don't do this though, the address relations are removed from the link table. Is there a way to save the Coupon without affecting the link table?

Is there a way to populate entries in the link table without having save the associated Coupon with the entire set of Addresses?

When we query for nearest Addresses, we only want the resultant addresses to be populated in the Coupon object for the client. Since we are using LAZY fetching the Coupons, we can probably avoid calling Coupon.getAddresses and populate the subset of Addresses manually.

I don't know how to handle issue #1 and not sure if #2 is sufficient. Most of the time, we won't have to worry about having a ton of addresses for each Coupon, but the potential does exist.

Thank You.

Body:
That's because you're not updating a coupon. Updating a coupon would consist in doing

Coupon c = em.find(Coupon.class, id);
c.setXxx(...);

Just do that to update your coupon, instead of merging a new coupon without any address.

No, with your current design, that's not possible. The only way you can modify the content of the join table is by modifying the content of the addresses collection. But you could choose to map the join table as an entity instead of using a ManyToMany. Or you could use native queries.

That can't happen. addresses is the collection of addresses of a coupon. Not the addresses found by some query used to load a coupon. If you want a subset of the addresses of a coupon, then execute a query selecting addresses. Not a query selecting coupons.


问:
Java Consider defining a bean of type in your configuration exception when add mongoDB support
I have a very simple Java Springboot project connect to the database. Still, I want a mongoDB connection and I could use mongoDB as well.

I read lots of document and I can't make it work. And my commits code is:

https://github.com/GuoJing/spb/commit/20c04ce38d43bb0ba229d0d3577fdccbd571062e

If adding @AutoWired annotation, application will not start. I think this should be same as official document.

in src/main/java/controller/UserController.java

```<code>@Autowired
private UserPropsRepository userPropsRepository;
</code>```

Here is my project, could anybody help me?

https://github.com/GuoJing/spb

My Exception is:

```<code>***************************
APPLICATION FAILED TO START
***************************

Description:

Field userPropsRepository in controller.UserController required a bean of type 'repository.UserPropsRepository' that could not be found.

Action:

Consider defining a bean of type 'repository.UserPropsRepository' in your configuration.
</code>```

答:
Problem solved.

Change my project structure, move root Package and Model and Dao ... to com.example.model ...

Move Application.java to root so it will scan components automatically

Related to this same problem and solution.

'Field required a bean of type that could not be found.' error spring restful API using mongodb

Body:
I have a very simple Java Springboot project connect to the database. Still, I want a mongoDB connection and I could use mongoDB as well.

I read lots of document and I can't make it work. And my commits code is:

https://github.com/GuoJing/spb/commit/20c04ce38d43bb0ba229d0d3577fdccbd571062e

If adding @AutoWired annotation, application will not start. I think this should be same as official document.

in src/main/java/controller/UserController.java

@Autowired
private UserPropsRepository userPropsRepository;

Here is my project, could anybody help me?

https://github.com/GuoJing/spb

My Exception is:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field userPropsRepository in controller.UserController required a bean of type 'repository.UserPropsRepository' that could not be found.

Action:

Consider defining a bean of type 'repository.UserPropsRepository' in your configuration.


问:
Error running trigger at specific time using GAS
I get the error message (below) when I run the code. My intention is to create a trigger at exact time 2017-04-03 20:10

```<code>ScriptApp.newTrigger('myfunction').timeBased().atDate(2017,04,03).atHour(20).nearMinute(10).create();
</code>```

Log

```<code>[17-04-02 20:16:53:455 IST] TriggerBuilder.timeBased() [0 seconds]
[17-04-02 20:16:53:456 IST] ClockTriggerBuilder.atDate([2017, 4, 3]) [0 seconds]
[17-04-02 20:16:53:456 IST] ClockTriggerBuilder.atHour([20]) [0 seconds]
[17-04-02 20:16:53:461 IST] Execution failed: Error: Already chosen a specific date time with at() or atDate(). (line 109, file "Code") [11.583 seconds total runtime]
</code>```

答:
You can create a new date object with a specific date and time then use new trigger().At(date), not to be confused with atDate(), function to create trigger at that date and time.

```<code>var dt = new Date(2017,03,03,20,10)
//Month index starts from 0 i.e. Jan =0,Feb=1... So on
 ScriptApp.newTrigger('myFunction').timeBased().at(dt).create()
</code>```

Hope that helps!

Body:
I get the error message (below) when I run the code. My intention is to create a trigger at exact time 2017-04-03 20:10

ScriptApp.newTrigger('myfunction').timeBased().atDate(2017,04,03).atHour(20).nearMinute(10).create();

Log

[17-04-02 20:16:53:455 IST] TriggerBuilder.timeBased() [0 seconds]
[17-04-02 20:16:53:456 IST] ClockTriggerBuilder.atDate([2017, 4, 3]) [0 seconds]
[17-04-02 20:16:53:456 IST] ClockTriggerBuilder.atHour([20]) [0 seconds]
[17-04-02 20:16:53:461 IST] Execution failed: Error: Already chosen a specific date time with at() or atDate(). (line 109, file "Code") [11.583 seconds total runtime]

Body:
You can create a new date object with a specific date and time then use new trigger().At(date), not to be confused with atDate(), function to create trigger at that date and time.

var dt = new Date(2017,03,03,20,10)
//Month index starts from 0 i.e. Jan =0,Feb=1... So on
 ScriptApp.newTrigger('myFunction').timeBased().at(dt).create()

Hope that helps!


问:
Determining how many messages are on the Azure Service Bus Queue
I know there is a way to determine the number of messages (or approximate number) in the Azure Queue (Store Account); however is there a way to query for the number of pending messages on an Azure Service Bus queue?

答:
I ran into this same problem trying to get the count from the dead letter queue. It looks like the deadletterqueue doesn't allow you to get a count directly, you get it from the MessageCountDetails of the normal Queue.</p>

```<code>string connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.Connstr"].ToString();
NamespaceManager nsmgr = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString(connectionString);
return nsmgr.GetQueue(QueueName).MessageCountDetails.DeadLetterMessageCount;
</code>```

Body:
I ran into this same problem trying to get the count from the dead letter queue. It looks like the deadletterqueue doesn't allow you to get a count directly, you get it from the MessageCountDetails of the normal Queue.

string connectionString = ConfigurationManager.AppSettings["Microsoft.ServiceBus.Connstr"].ToString();
NamespaceManager nsmgr = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString(connectionString);
return nsmgr.GetQueue(QueueName).MessageCountDetails.DeadLetterMessageCount;


问:
Define the size of a global array from the command line
I am doing an assignment where I need to use pthreads or semaphores to synchronize some processes which access some shared resource.  Since all of our examples in class use a global variable as the shared resource I planned on doing the same thing, but I wanted to base the value of the shared resource on a command line argument.  I know how to use command line arguments within my main method, but how do I define the size of a global array (the shared resource) based on a command line argument?

Update:

Wallyk's answer seems like it will work, but I'm still fuzzy on some of the finer details.  See the example and comments...

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

void print_array(void);

int *array;
int count;

int main(int argc, char **argv){
    int count = atoi(argv[1]);
    array = malloc(count *sizeof(array[0]));
    int i;
    for(i = 0; i < count; i++){ /*is there anyway I can get the size of my array without using an additional variable like count?*/
        array[i] = i;
    }
    print_array();
    return 0;
}

void print_array(){
    int i;
    for(i = 0; i < count; i++){
        printf("current count is %d\n", array[i]);
    }
}
</code>```

答:
You can't do a static dynamic declaration like:

```<code>int globalarray[n];
</code>```

Where n is a variable set at runtime.  This doesn't work because the array is initialized before the program begins running.

A good alternative is to use a pointer to dynamic memory:

```<code>int *globalarray;

int main (int argc, char **argv)
{
...
   int elements = atoi (argv [j]);  // parse out the program argument array size
   globalarray = malloc (elements * sizeof (globalarray[0]));
}
</code>```

Body:
I am doing an assignment where I need to use pthreads or semaphores to synchronize some processes which access some shared resource.  Since all of our examples in class use a global variable as the shared resource I planned on doing the same thing, but I wanted to base the value of the shared resource on a command line argument.  I know how to use command line arguments within my main method, but how do I define the size of a global array (the shared resource) based on a command line argument?

Update:

Wallyk's answer seems like it will work, but I'm still fuzzy on some of the finer details.  See the example and comments...

#include <stdio.h>

void print_array(void);

int *array;
int count;

int main(int argc, char **argv){
    int count = atoi(argv[1]);
    array = malloc(count *sizeof(array[0]));
    int i;
    for(i = 0; i < count; i++){ /*is there anyway I can get the size of my array without using an additional variable like count?*/
        array[i] = i;
    }
    print_array();
    return 0;
}

void print_array(){
    int i;
    for(i = 0; i < count; i++){
        printf("current count is %d\n", array[i]);
    }
}

Body:
You can't do a static dynamic declaration like:

int globalarray[n];

Where n is a variable set at runtime.  This doesn't work because the array is initialized before the program begins running.

A good alternative is to use a pointer to dynamic memory:

int *globalarray;

int main (int argc, char **argv)
{
...
   int elements = atoi (argv [j]);  // parse out the program argument array size
   globalarray = malloc (elements * sizeof (globalarray[0]));
}


问:
Getting a Value from a dropdown populated from an SQL database
I have populated a drop down from my MySQL Database successfully. I am now wanting to be able to extracte the value from this dropdown. When ever I extract the value from the dropdown it is only the position value of the value in the list.

Here is the working drop down below:

```<code><?php

include_once("connection.php");

 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }

 ?>

 <!DOCTYPE html>
 <html>
      <head>
           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           </script>
      </head>
      <body>
           <br /><br />
           <div class="container">
                <form action="dropdown_selection.php" method="post">
                     <select name="name" id="name">
                          <option value="">Show All Patients</option>
                           <?php echo fill_name($connect); ?>
                     </select>
                     <input type="submit" name="submit" value="Submit" />

                </form>
           </div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

      </body>
 </html>
</code>```

And here is the page it then refers to:

```<code><?php
$patient_name = $_POST['name'];
echo $patient_name

?>
</code>```

The output is either 1,2,3,4, but I am wanting it to output what is is selected in the dropdown.

Thnks for your help

答: The output is number is correct as you set option value to be ID, not NAME -> <option value="'.$row["id"].'"> therefore you get IDs

Body:
I have populated a drop down from my MySQL Database successfully. I am now wanting to be able to extracte the value from this dropdown. When ever I extract the value from the dropdown it is only the position value of the value in the list.

Here is the working drop down below:

<?php

include_once("connection.php");

 function fill_name($connect)
 {
      $output = '';
      $sql = "SELECT name, id FROM notes";
      $result = mysqli_query($connect, $sql);
      while($row = mysqli_fetch_array($result))
      {
           $output .= '<option value="'.$row["id"].'">'.$row["name"].'</option>';
      }
      return $output;
 }

 ?>

 <!DOCTYPE html>

           <title>Patient Notes View</title>
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
           </script>

                <form action="dropdown_selection.php" method="post">
                     <select name="name" id="name">
                          <option value="">Show All Patients</option>
                           <?php echo fill_name($connect); ?>
                     </select>
                     <input type="submit" name="submit" value="Submit" />

                </form>

And here is the page it then refers to:

<?php
$patient_name = $_POST['name'];
echo $patient_name

?>

The output is either 1,2,3,4, but I am wanting it to output what is is selected in the dropdown.

Thnks for your help


问:
How to retrieve primary key related value in asp.net mvc
I was researched every where that primary keys , candidate keys and foreign keys. I learnt each and every keys on asp.net MVC 5 entity framework.

Then I generated my code using MVC automatic generated option on Visual studio and I was surrounded with Migrations with editing some features..But, here is the thing...

I was created another model called Auction, in order to bid an item. After that, I was initialized a product ID  and other details in my Auction model. Even after that, I was try to assign user ID "using Microsoft.AspNet.Identity;"
and its worked. The thing is I want to make a relationship between Automatic generated User's Model called "IdentityModels" and "AccountViewModels". But its not worked.

```<code>// Here is my Auction model class' segment that I took on my Auction model

[Key]
 [Required]
 public long Id { get; internal set; }
........
//other codes are avoided
......
[Required]
public string SellerUserID { get; set; }
</code>```

Here is my AuctionController

```<code> public ActionResult ViewMyBids()
        {
            var db = new AuctionsDataContext();
            var pKey = User.Identity.GetUserId();

            // I want to pass the primary key in to the auction model and get the results to a list
            var result = db.Auctions.Find().SellerUserID(pKey);
            ViewBag.mes = result.SellerUserID;

            return ViewMyBids();

        }
</code>```

Even I don't know how to get the primary key's value
Let's say as an example:
there is
Employee and Department....
Employee has an ID,
Employee has EmpName,
Department has a DepartmentName,

Department wants to know a particular employee's name...
DO that so,

Department table needs a foreign key  which is related to employee ID,
within that employeeID ,it can directly assign to employee's Name which is stored in Employee table...

So, as like that I want to assign automatic generated user ID and using that ID I need to retrieve all the data that ID has....

How to do this, I know to use of foreign keys or composition keys .. But in my research I am unable to find any solution for this.

So help me to solve this..Thanks.......
pls...

答:
```<code>public ActionResult ViewMyBids()
{
    var db = new AuctionsDataContext();
    var pKey = User.Identity.GetUserId();

    // I want to pass the primary key in to the auction model and get the results to a list
    var result = db.Auctions
        .Where(p => p.SellerUserID == pKey)
        .ToList();

    // The result is a List<Auction> so the below code won't work unless you retrieve only one item
    // ViewBag.mes = result.SellerUserID;

    return ViewMyBids();
}
</code>```

Body:
I was researched every where that primary keys , candidate keys and foreign keys. I learnt each and every keys on asp.net MVC 5 entity framework.

Then I generated my code using MVC automatic generated option on Visual studio and I was surrounded with Migrations with editing some features..But, here is the thing...

I was created another model called Auction, in order to bid an item. After that, I was initialized a product ID  and other details in my Auction model. Even after that, I was try to assign user ID "using Microsoft.AspNet.Identity;"
and its worked. The thing is I want to make a relationship between Automatic generated User's Model called "IdentityModels" and "AccountViewModels". But its not worked.

// Here is my Auction model class' segment that I took on my Auction model

[Key]
 [Required]
 public long Id { get; internal set; }
........
//other codes are avoided
......
[Required]
public string SellerUserID { get; set; }

Here is my AuctionController

 public ActionResult ViewMyBids()
        {
            var db = new AuctionsDataContext();
            var pKey = User.Identity.GetUserId();

            // I want to pass the primary key in to the auction model and get the results to a list
            var result = db.Auctions.Find().SellerUserID(pKey);
            ViewBag.mes = result.SellerUserID;

            return ViewMyBids();

        }

Even I don't know how to get the primary key's value
Let's say as an example:
there is
Employee and Department....
Employee has an ID,
Employee has EmpName,
Department has a DepartmentName,

Department wants to know a particular employee's name...
DO that so,

Department table needs a foreign key  which is related to employee ID,
within that employeeID ,it can directly assign to employee's Name which is stored in Employee table...

So, as like that I want to assign automatic generated user ID and using that ID I need to retrieve all the data that ID has....

How to do this, I know to use of foreign keys or composition keys .. But in my research I am unable to find any solution for this.

So help me to solve this..Thanks.......
pls...


问:
python beautifulsoup attribute exist returns None
when trying to select elements that have the attribute "data-server" it returns none
here is the code</p>

```<code>>>> psoup.select_one(".server > .serverslist")
<div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ=">cloudy</div>
>>> psoup.select_one(".server > .serverslist[data-server]")
>>>
</code>```

答:
BeautifulSoup's CSS selectors are fairly limited. Attribute selectiors ([...]) can only be combined with a tag selector, not with other selectors (like the class selector you used):

```<code>>>> from bs4 import BeautifulSoup
>>> psoup = BeautifulSoup(
...     '<div class="server"><div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ=">cloudy</div></div>',
...     'lxml')
>>> psoup.select_one("div[data-server]")
<div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ=">cloudy</div>
>>> psoup.select_one("[data-server]")
<div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ=">cloudy</div>
>>> psoup.select_one(".serverslist[data-server]") is None
True
</code>```

You'll have to find a different way of expressing your selector, one that doesn't look for attributes and classes at the same time.

Body:
when trying to select elements that have the attribute "data-server" it returns none
here is the code

>>> psoup.select_one(".server > .serverslist")

cloudy

>>> psoup.select_one(".server > .serverslist[data-server]")
>>>

Body:
BeautifulSoup's CSS selectors are fairly limited. Attribute selectiors ([...]) can only be combined with a tag selector, not with other selectors (like the class selector you used):

>>> from bs4 import BeautifulSoup
>>> psoup = BeautifulSoup(
...     '<div class="server"><div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ=">cloudy</div></div>',
...     'lxml')
>>> psoup.select_one("div[data-server]")
<div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ=">cloudy</div>
>>> psoup.select_one("[data-server]")
<div class="serverslist " data-server="aHR0cDovL3d3dy5jbG91ZHkuZWMvZW1iZWQucGhwP2lkPWExYWU0NjkwZmZmYjQ=">cloudy</div>
>>> psoup.select_one(".serverslist[data-server]") is None
True

You'll have to find a different way of expressing your selector, one that doesn't look for attributes and classes at the same time.


问:
Get current logged in user in controller action in MVC 3
I am working on a MVC 3 intranet application ( windows authentication ). I want the username of current logged in user in my controller action. I have tried lot of variation but cannot get the username . I tried using Environment.Username it worked well in debug mode but when deployed it provided the pool name rather than the username.

Controller action.

```<code>  public ActionResult Index()
        {
            LoggedUser usr = new LoggedUser();
            var aa = usr.User;
        }
</code>```

LoggedUser

```<code>public class LoggedUser : Controller
    {
        public LoggedUser()
        {

        }
    }
</code>```

I was following this post  but was not able to make it work Getting the logged in username in ASP.NET MVC3 intranet application

Any help??

答:
if you want to use a controller level variable that needs the username, you can override OnActionExecuting event where you can access the authenticated user id.  You may have to check for null for the user.identity just to be cautious.</p>

```<code>    Obj myObj;
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        myObj = new Obj(User.Identity.Name);
        base.OnActionExecuting(filterContext);
    }
</code>```

Body:
I am working on a MVC 3 intranet application ( windows authentication ). I want the username of current logged in user in my controller action. I have tried lot of variation but cannot get the username . I tried using Environment.Username it worked well in debug mode but when deployed it provided the pool name rather than the username.

Controller action.

  public ActionResult Index()
        {
            LoggedUser usr = new LoggedUser();
            var aa = usr.User;
        }

LoggedUser

public class LoggedUser : Controller
    {
        public LoggedUser()
        {

        }
    }

I was following this post  but was not able to make it work Getting the logged in username in ASP.NET MVC3 intranet application

Any help??

Body:
if you want to use a controller level variable that needs the username, you can override OnActionExecuting event where you can access the authenticated user id.  You may have to check for null for the user.identity just to be cautious.

    Obj myObj;
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        myObj = new Obj(User.Identity.Name);
        base.OnActionExecuting(filterContext);
    }


问:
Hour and Minutes with javascript
I have made this with js:

```<code>// time

var date = new Date();

var currentTime = date.getHours() + ':' + date.getMinutes();

document.getElementById('timex').value = currentTime;
</code>```

This script inserts the hour and minutes in a input.

There is a problem, at 16:06 the time becomes  16:6. And this causes a problem with the html input. The same thing happens at 1am. Become 1:34 and not 01:34.

答:
Try this, simple and works like a charm:</p>

```<code>var date = new Date();

var currentTime = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);

document.getElementById('timex').value = currentTime;
</code>```

Title: Hour and Minutes with javascript

Body:
I have made this with js:

// time

var date = new Date();

var currentTime = date.getHours() + ':' + date.getMinutes();

document.getElementById('timex').value = currentTime;

This script inserts the hour and minutes in a input.

There is a problem, at 16:06 the time becomes  16:6. And this causes a problem with the html input. The same thing happens at 1am. Become 1:34 and not 01:34.

Body:
Try this, simple and works like a charm:

var date = new Date();

var currentTime = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);

document.getElementById('timex').value = currentTime;


答:
A global pointer to a malloc'd array is one possible solution.
So you malloc the array of needed size depending on your command line argument and make the pointer to the array visible to all your pthreads.</p>

Title: Define the size of a global array from the command line


问:
Parse Apache Common Log Format request urls containing Space
I am trying to parse the Apache common log format logs using the following regular expression in Python

```<code>APACHE_ACCESS_LOG_PATTERN = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+)\s*(\S*)" (\d{3}) (\S+)'
</code>```

My typical logs are in the format of

```<code>uplherc.upl.com - - [01/Aug/1995:00:00:04 -0400] "GET /images/ksclogo-medium.gif HTTP/1.0" 401 0
</code>```

but many of my URL's contain spaces, how do I parse them ex:

```<code>uplherc.upl.com - - [01/Aug/1995:00:00:04 -0400] "GET /images/ksclogo-medium large  .gif HTTP/1.0" 401 0
</code>```

Currently I am parsing using this code

```<code>match = re.search(APACHE_ACCESS_LOG_PATTERN, logline)
if match is None:
    print>>output_file, logline
    return
size_field = match.group(9)
if size_field == '-':
    size = long(0)
else:
    size = long(match.group(9))
return (Access(
    ipAddress     = match.group(1),
    clientIdentd = match.group(2),
    userId       = match.group(3),
    dateTime     = parse_apache_time(match.group(4)),
    method        = match.group(5),
    endpoint      = match.group(6),
    protocol      = match.group(7),
    responseCode = int(match.group(8)),
    contentSize  = size
), 1)
</code>```

Thank you

答:
So, if Apache doesn't encode spaces automatically, try to modify your regex this way:

APACHE_ACCESS_LOG_PATTERN = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (.+?) (\S+)" (\d{3}) (\S+)'

Body:
I am trying to parse the Apache common log format logs using the following regular expression in Python

APACHE_ACCESS_LOG_PATTERN = '^(\S+) (\S+) (\S+) \[([\w:/]+\s[+\-]\d{4})\] "(\S+) (\S+)\s*(\S*)" (\d{3}) (\S+)'

My typical logs are in the format of

uplherc.upl.com - - [01/Aug/1995:00:00:04 -0400] "GET /images/ksclogo-medium.gif HTTP/1.0" 401 0

but many of my URL's contain spaces, how do I parse them ex:

uplherc.upl.com - - [01/Aug/1995:00:00:04 -0400] "GET /images/ksclogo-medium large  .gif HTTP/1.0" 401 0

Currently I am parsing using this code

match = re.search(APACHE_ACCESS_LOG_PATTERN, logline)
if match is None:
    print>>output_file, logline
    return
size_field = match.group(9)
if size_field == '-':
    size = long(0)
else:
    size = long(match.group(9))
return (Access(
    ipAddress     = match.group(1),
    clientIdentd = match.group(2),
    userId       = match.group(3),
    dateTime     = parse_apache_time(match.group(4)),
    method        = match.group(5),
    endpoint      = match.group(6),
    protocol      = match.group(7),
    responseCode = int(match.group(8)),
    contentSize  = size
), 1)

Thank you


答:
As per my suggestion in comment, You can fetch "n" number of records in one query. Below is the modified version of code provided by you.

Not Tested

```<code>async def fetch_and_write():
    n = 500  # fetch #rows at once
    conn = await asyncpg.connect('...')
    with open('/Users/mac/Desktop/input.csv','r') as csvinput:
        with open('/Users/mac/Desktop/output.csv', 'w') as csvoutput:
        reader = csv.reader(csvinput)
        writer = csv.writer(csvoutput, lineterminator='\n')

        all = []
        ids_list = []
        row = next(reader)
        row.append('new_column_name')
        all.append(row)

        for row in reader:

            ids_list.append(row[14])
            if len(ids_list) >= n:

                in_p=', '.join(map(lambda x: '%s', args))

                query = "SELECT .. FROM .. WHERE id in '%s';"
                query = query % in_p
                try:
                    result = await conn.fetch(query)
                except BaseException:
                    print("Oops!That was no valid number.")
                    continue
                ids_list = []

                row.append(result[0][0])
                writer.writerows(all)
                all = []

        if len(ids_list)>0:
            in_p=', '.join(map(lambda x: '%s', args))

            query = "SELECT .. FROM .. WHERE id in '%s';"
            query = query % in_p
            try:
                result = await conn.fetch(query)
            except BaseException:
                print("Oops!That was no valid number.")
                continue

            row.append(result[0][0])
            writer.writerows(all)
</code>```

Title: How to fetch data from db and write to csv more quickly?

Body:
I need to fetch data from DB and write it to a corresponding column in CSV file.
The following code do it very slow(iteratevly, one by one)

async def fetch_and_write():
  conn = await asyncpg.connect('...')
  with open('/Users/mac/Desktop/input.csv','r') as csvinput:
     with open('/Users/mac/Desktop/output.csv', 'w') as csvoutput:
        reader = csv.reader(csvinput)
        writer = csv.writer(csvoutput, lineterminator='\n')

        all = []
        row = next(reader)
        row.append('new_column_name')
        all.append(row)

        for row in reader:
            query = "SELECT .. FROM .. WHERE id = '%s';"
            query = query % row[14]
            try:
                result = await conn.fetch(query)
            except BaseException:
                print("Oops!That was no valid number.")
                continue

            row.append(result[0][0])
            all.append(row)

        writer.writerows(all)

How can I read id from CSV in chunks and use "in" clause to improve performance?

Body:
As per my suggestion in comment, You can fetch "n" number of records in one query. Below is the modified version of code provided by you.

Not Tested

async def fetch_and_write():
    n = 500  # fetch #rows at once
    conn = await asyncpg.connect('...')
    with open('/Users/mac/Desktop/input.csv','r') as csvinput:
        with open('/Users/mac/Desktop/output.csv', 'w') as csvoutput:
        reader = csv.reader(csvinput)
        writer = csv.writer(csvoutput, lineterminator='\n')

        all = []
        ids_list = []
        row = next(reader)
        row.append('new_column_name')
        all.append(row)

        for row in reader:

            ids_list.append(row[14])
            if len(ids_list) >= n:

                in_p=', '.join(map(lambda x: '%s', args))

                query = "SELECT .. FROM .. WHERE id in '%s';"
                query = query % in_p
                try:
                    result = await conn.fetch(query)
                except BaseException:
                    print("Oops!That was no valid number.")
                    continue
                ids_list = []

                row.append(result[0][0])
                writer.writerows(all)
                all = []

        if len(ids_list)>0:
            in_p=', '.join(map(lambda x: '%s', args))

            query = "SELECT .. FROM .. WHERE id in '%s';"
            query = query % in_p
            try:
                result = await conn.fetch(query)
            except BaseException:
                print("Oops!That was no valid number.")
                continue

            row.append(result[0][0])
            writer.writerows(all)


问:
Directly piping readable stream in writable stream
What is the difference between:

```<code>const stream = createReadStream(source).pipe(createWriteStream(destination));

stream.on("error", (error) => {
   stream.destroy();
   stream.removeListener("close");
   reject(error);
});
stream.on("close", () => {
  // do something
});
</code>```

vs:

```<code>const writable = createWriteStream(destination);
const readable = createReadStream(source);
readable.on("error", onError);
writable.on("error", onError);
function onError(error) {
  readable.destroy();
  writable.destroy();
  writable.removeListener("close", onClose);
  reject(error);
}
</code>```

And why should we manually destroy the stream if some error happen? Node won't automatically do that?

Thanks.

答:
Well for one thing your second example doesn't perform any piping or transfer of data at all. The only other significant difference between the two is that in the first example you're not attaching an 'error' event listener to the read stream which means that if an error occurs while reading the data you won't catch the error. You shouldn't need to remove the "close" listener or destroy the stream. It looks like you're trying to copy a file to a new location and have the function return a Promise. In which case it won't matter if the 'close' event did fire because a Promise can only be resolved/rejected once. So if the 'error' event does fire then your Promise will be rejected and it can never become resolved so there is no reason to remove the 'close' listener. Additionally node will automatically mark the stream as destroyed after it emits an error. This should be all you need:

```<code>const fs = require('fs')

function copy (source, target) {
  return new Promise((resolve, reject) => {
    const rs = fs.createReadStream(source)
    const ws = fs.createWriteStream(target)
    rs.on('error', reject)
    ws.on('error', reject)
    rs.pipe(ws).on('close', resolve)
  })
}
</code>```

Then you can use it as such:

```<code>copy('/foo/bar.json', '/baz/qux.json')
  .then(() => console.log('copy done'))
</code>```

Body:
What is the difference between:

const stream = createReadStream(source).pipe(createWriteStream(destination));

stream.on("error", (error) => {
   stream.destroy();
   stream.removeListener("close");
   reject(error);
});
stream.on("close", () => {
  // do something
});

vs:

const writable = createWriteStream(destination);
const readable = createReadStream(source);
readable.on("error", onError);
writable.on("error", onError);
function onError(error) {
  readable.destroy();
  writable.destroy();
  writable.removeListener("close", onClose);
  reject(error);
}

And why should we manually destroy the stream if some error happen? Node won't automatically do that?

Thanks.

Body:
Well for one thing your second example doesn't perform any piping or transfer of data at all. The only other significant difference between the two is that in the first example you're not attaching an 'error' event listener to the read stream which means that if an error occurs while reading the data you won't catch the error. You shouldn't need to remove the "close" listener or destroy the stream. It looks like you're trying to copy a file to a new location and have the function return a Promise. In which case it won't matter if the 'close' event did fire because a Promise can only be resolved/rejected once. So if the 'error' event does fire then your Promise will be rejected and it can never become resolved so there is no reason to remove the 'close' listener. Additionally node will automatically mark the stream as destroyed after it emits an error. This should be all you need:

const fs = require('fs')

function copy (source, target) {
  return new Promise((resolve, reject) => {
    const rs = fs.createReadStream(source)
    const ws = fs.createWriteStream(target)
    rs.on('error', reject)
    ws.on('error', reject)
    rs.pipe(ws).on('close', resolve)
  })
}

Then you can use it as such:

copy('/foo/bar.json', '/baz/qux.json')
  .then(() => console.log('copy done'))


问:
How to access the instance variable initialized with some value inside a method of superclass in subclass Java
Base Class

```<code>public class Base
{
    public X obj;
    public void setValue()
    {
        obj = new A();
    }

}
</code>```

Util class

```<code>public class Util extends Base
{
    public X obj;

    public Util(X obj)
    {
        this.obj = obj;
    }

    public void function1()
    {
        obj.m1();  //obj is null
    }

    public void function2()
    {
        obj.m2();  //obj is null
    }

}
</code>```

Test Class

```<code>class Test extends Base
{
    // obj inherited from superclass is null.
    Util utilObj = new Util(obj)

    public void testMethod()
    {
         utilObj.function1();
         utilObj.function2();

    }

}
</code>```

How can i pass the  initialized value in constructor of  util class while creating its object inside Test class so that i can use the method of util class .It is giving Null pointer exception. I dont want to expose the call of setValue() method inside each Test class and can not declare it as static. i.e  public static X obj;in Base class .

Is there any way to access the initialized value of non-static variable initialized inside any method of superclass directly inside its subclass like static variable. Please help to solve this problem.

答:
Try use super();
You should be able to find more info at
http://docs.oracle.com/javase/tutorial/java/IandI/super.html</p>

Body:
Base Class

public class Base
{
    public X obj;
    public void setValue()
    {
        obj = new A();
    }

}

Util class

public class Util extends Base
{
    public X obj;

    public Util(X obj)
    {
        this.obj = obj;
    }

    public void function1()
    {
        obj.m1();  //obj is null
    }

    public void function2()
    {
        obj.m2();  //obj is null
    }

}

Test Class

class Test extends Base
{
    // obj inherited from superclass is null.
    Util utilObj = new Util(obj)

    public void testMethod()
    {
         utilObj.function1();
         utilObj.function2();

    }

}

How can i pass the  initialized value in constructor of  util class while creating its object inside Test class so that i can use the method of util class .It is giving Null pointer exception. I dont want to expose the call of setValue() method inside each Test class and can not declare it as static. i.e  public static X obj;in Base class .

Is there any way to access the initialized value of non-static variable initialized inside any method of superclass directly inside its subclass like static variable. Please help to solve this problem.


问:
Print text if int value is greater than 0
I have a razor mergefield called: @NumberChildren. If NumberChildren has a value greater than 0, then I need to print out a text.

Table 1 below is working fine, and I only see this table if there is a number which is greater than 0.

Table 2 should print out the text, if @NumberChildren is greater than 0. But the text in table 2 always print out no matter if @NumberChildren >= 0 =< 0

Can anybody see why is this happening ?

```<code><!-- Table 1: Print out how many children -->
@if (NumberChildren > 0)
{
<tr>
    <th width="300">
        <p class="text-left small-text-left"><strong>Number of children:</strong></p>
    </th>
</tr>
<tr>
    <th width="300">
        <p class="text-left small-text-left">
            @NumberChildren
        </p>
    </th>
</tr>
}

<!-- Table 2: Print out text if there is children-->
@if (NumberChildren > 0)
{
    <tr>
        <th>
            <span>
                Payment are incuded for children under 10 years.
            </span>
        </th>
    </tr>
}
</code>```

答:
There is no table in html code provided in here, you might have a single table but you are generating only tr - table-rows in c# code. Did you mean if there is a problem with tr generating ? because I think you have all this code wrapped in a
 tag and as the result
 tag is always generated. If the situation is different please share some more info here.

Body:
I have a razor mergefield called: @NumberChildren. If NumberChildren has a value greater than 0, then I need to print out a text.

Table 1 below is working fine, and I only see this table if there is a number which is greater than 0.

Table 2 should print out the text, if @NumberChildren is greater than 0. But the text in table 2 always print out no matter if @NumberChildren >= 0 =< 0

Can anybody see why is this happening ?

@if (NumberChildren > 0)
{

Number of children:

            @NumberChildren

}

@if (NumberChildren > 0)
{

                Payment are incuded for children under 10 years.

}

Body: There is no table in html code provided in here, you might have a single table but you are generating only tr - table-rows in c# code. Did you mean if there is a problem with tr generating ? because I think you have all this code wrapped in a <table> tag and as the result <table> tag is always generated. If the situation is different please share some more info here.


Title: Hour and Minutes with javascript

Body: d.toISOString().substring(11).slice(0,5)


问:
c++ function calling function not working
I have 3 functions:

First function takes an int a and prints the that number of dots.

The second function takes an int b and prints that number of stars.

The third function takes a and b and calls the dots function and stars function. When I call it in main, it returns 0 without any output.

Each of the functions work fine on their own - why doesn't the third one work then?

EDIT: Tried initializing i=0, code still compiles with the same result. Again, both functions dots() and stars() work fine when called on their own.

```<code>void dots(int a){
    for(int i; i<a; i++){
        cout << ".";
    }
}
void stars(int a){
    for(int i; i<a; i++){
        cout << "*";
    }
}

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}
</code>```

答:
Instantiate your iterative i values to 0. So, the for loops becomes:

```<code>for(int i = 0; i < limit; i++)
</code>```

Also, maybe you're program is closing too quickly before you can see the results if you're not executing it from your terminal/console.

```<code> int main() {

     /* your function invoked */

     int i = 0;
     cin >> i++; // This is a not so neat way to pause your program. Do something with your value so that you don't get unused variable warning.
     return 0;
 }
</code>```

Body:
I have 3 functions:

First function takes an int a and prints the that number of dots.

The second function takes an int b and prints that number of stars.

The third function takes a and b and calls the dots function and stars function. When I call it in main, it returns 0 without any output.

Each of the functions work fine on their own - why doesn't the third one work then?

EDIT: Tried initializing i=0, code still compiles with the same result. Again, both functions dots() and stars() work fine when called on their own.

void dots(int a){
    for(int i; i<a; i++){
        cout << ".";
    }
}
void stars(int a){
    for(int i; i<a; i++){
        cout << "*";
    }
}

//(not working):
void dotsstars(int a, int b){
    dots(a);
    stars(b);
}

int main(){
    dotsstars(5, 6);

    return 0;
}

Body:
Instantiate your iterative i values to 0. So, the for loops becomes:

for(int i = 0; i < limit; i++)

Also, maybe you're program is closing too quickly before you can see the results if you're not executing it from your terminal/console.

 int main() {

     /* your function invoked */

     int i = 0;
     cin >> i++; // This is a not so neat way to pause your program. Do something with your value so that you don't get unused variable warning.
     return 0;
 }


问:
Type mismatch when trying to destructure type in Elm?
I have a type:

```<code>type MenuItem msg
    = MenuItem
        { attributes : List (Attribute msg)
        , children : List (Html msg)
        }
</code>```

that's part of a NavBar. Then I have a function renderItems that renders a list of MenuItems:

```<code>renderItems : List (MenuItem msg) -> Html msg
renderItems items =
    ul [ class "nav-list" ] (List.map renderItem items)
</code>```

renderItems, as you can see,  calls renderItem, which looks like this:

```<code>renderItem : MenuItem msg -> Html msg
renderItem { attributes, children } =
    li [ class "nav-item" ]
        [ a ([ class "nav-link" ] ++ attributes)
            children
        ]
</code>```

But I get a compiler error here:

```<code>This record is causing problems in this pattern match.

14| renderItem { attributes, children } =
               ^^^^^^^^^^^^^^^^^^^^^^^^
The pattern matches things of type:

    MenuItem msg

But the values it will actually be trying to match are:

    { c | attributes : a, children : b }

Detected errors in 1 module.
</code>```

Can anyone interpret this for me? I don't understand the mismatch. attributes and children seem to match up pretty well.

答:
```<code>type MenuItem msg
    = MenuItem
        { attributes : List (Attribute msg)
        , children : List (Html msg)
        }
</code>```

is distinct from

```<code>type alias MenuItem msg
    = { attributes : List (Attribute msg)
      , children : List (Html msg)
      }
</code>```

The latter can be pattern matched the way you did:

```<code>renderItem { attributes, children } =
</code>```

but the former, since it is wrapped in a data constructor will also need to be unwrapped:

```<code>renderItem (MenuItem { attributes, children }) =
</code>```

Body:
I have a type:

type MenuItem msg
    = MenuItem
        { attributes : List (Attribute msg)
        , children : List (Html msg)
        }

that's part of a NavBar. Then I have a function renderItems that renders a list of MenuItems:

renderItems : List (MenuItem msg) -> Html msg
renderItems items =
    ul [ class "nav-list" ] (List.map renderItem items)

renderItems, as you can see,  calls renderItem, which looks like this:

renderItem : MenuItem msg -> Html msg
renderItem { attributes, children } =
    li [ class "nav-item" ]
        [ a ([ class "nav-link" ] ++ attributes)
            children
        ]

But I get a compiler error here:

This record is causing problems in this pattern match.

14| renderItem { attributes, children } =
               ^^^^^^^^^^^^^^^^^^^^^^^^
The pattern matches things of type:

    MenuItem msg

But the values it will actually be trying to match are:

    { c | attributes : a, children : b }

Detected errors in 1 module.

Can anyone interpret this for me? I don't understand the mismatch. attributes and children seem to match up pretty well.

Body:
type MenuItem msg
    = MenuItem
        { attributes : List (Attribute msg)
        , children : List (Html msg)
        }

is distinct from

type alias MenuItem msg
    = { attributes : List (Attribute msg)
      , children : List (Html msg)
      }

The latter can be pattern matched the way you did:

renderItem { attributes, children } =

but the former, since it is wrapped in a data constructor will also need to be unwrapped:

renderItem (MenuItem { attributes, children }) =


问:
Edge swipe and application exit Android wear 2.0
I am writing the application for Android wear and I need to achieve the behavior similar to Google maps app on Android wear when closing the application.

Usually, the "Swipe-To-Dismiss" gesture (swipe from left to right) closes the application (activity), but could you imagine the situation where you have a picture or map and you need to pan in the application. The pan from left to right always close the app.

There should be a solution described by Google on https://developer.android.com/training/wearables/ui/exit.html#swipe-to-dismiss.

If you want the user to go down the back stack, you can wrap the view in a SwipeDismissFrameLayout object, which supports edge swipe. Edge
  swipe is enabled when the view or its children returns true from a
  canScrollHorizontally() call. Edge swipe enables the user to dismiss
  the view by swiping from the leftmost side of the screen (currently
  set to 10% of the screen width) and not just anywhere in the view.

This is implemented in Google maps app for Android wear. Application is closed just in case you start swiping very close to the left edge. It is called "Edge swipe".

The problem is that canScrollHorizontally() must return true and I am not able to set this view property correctly - it is always false. https://developer.android.com/reference/android/support/wearable/view/SwipeDismissFrameLayout.html

Layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.SwipeDismissFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/swipe_dismiss_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:isScrollContainer="true"
    android:nestedScrollingEnabled="true"
    tools:context="jhettler.wearmaps.MainActivity"
    tools:deviceIds="wear">

    <RelativeLayout
        android:id="@+id/map_area"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fadeScrollbars="false"
        android:isScrollContainer="true"
        android:nestedScrollingEnabled="true">

    </RelativeLayout>

</android.support.wearable.view.SwipeDismissFrameLayout>```

I would like not to implement deprecated classes like DismissOverlayView and use power button to exit the application.

Any ideas or examples how to do it?

Thank you!

答:
Try disabling swipe-to-dismiss with this code:

```<code><resources>
  <style name="AppTheme" parent="@android:style/Theme.DeviceDefault">
    <item name="android:windowSwipeToDismiss">false</item>
  </style>
</resources>
</code>```

Disabling swipe-to-dismiss generally is not recommended because the user expects to dismiss any screen with a swipe. In an exceptional case, you can set windowSwipeToDismiss to false and the user would press the power button to exit your app.

This can be found in the Behavior Changes document for Android Wear 2.0. Things like reintroduction of Swipe-to-Dismiss, power button returns to the Watch Face and other changes for Android Wear 2.0 were discussed here.

Hope this helps.

Body:
I am writing the application for Android wear and I need to achieve the behavior similar to Google maps app on Android wear when closing the application.

Usually, the "Swipe-To-Dismiss" gesture (swipe from left to right) closes the application (activity), but could you imagine the situation where you have a picture or map and you need to pan in the application. The pan from left to right always close the app.

There should be a solution described by Google on https://developer.android.com/training/wearables/ui/exit.html#swipe-to-dismiss.

If you want the user to go down the back stack, you can wrap the view in a SwipeDismissFrameLayout object, which supports edge swipe. Edge
  swipe is enabled when the view or its children returns true from a
  canScrollHorizontally() call. Edge swipe enables the user to dismiss
  the view by swiping from the leftmost side of the screen (currently
  set to 10% of the screen width) and not just anywhere in the view.

This is implemented in Google maps app for Android wear. Application is closed just in case you start swiping very close to the left edge. It is called "Edge swipe".

The problem is that canScrollHorizontally() must return true and I am not able to set this view property correctly - it is always false. https://developer.android.com/reference/android/support/wearable/view/SwipeDismissFrameLayout.html

Layout file.

<?xml version="1.0" encoding="utf-8"?>
<android.support.wearable.view.SwipeDismissFrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/swipe_dismiss_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:isScrollContainer="true"
    android:nestedScrollingEnabled="true"
    tools:context="jhettler.wearmaps.MainActivity"
    tools:deviceIds="wear">

    <RelativeLayout
        android:id="@+id/map_area"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fadeScrollbars="false"
        android:isScrollContainer="true"
        android:nestedScrollingEnabled="true">

    </RelativeLayout>

</android.support.wearable.view.SwipeDismissFrameLayout>

I would like not to implement deprecated classes like DismissOverlayView and use power button to exit the application.

Any ideas or examples how to do it?

Thank you!

Body:
Try disabling swipe-to-dismiss with this code:

<resources>
  <style name="AppTheme" parent="@android:style/Theme.DeviceDefault">
    <item name="android:windowSwipeToDismiss">false</item>
  </style>
</resources>

Disabling swipe-to-dismiss generally is not recommended because the user expects to dismiss any screen with a swipe. In an exceptional case, you can set windowSwipeToDismiss to false and the user would press the power button to exit your app.

This can be found in the Behavior Changes document for Android Wear 2.0. Things like reintroduction of Swipe-to-Dismiss, power button returns to the Watch Face and other changes for Android Wear 2.0 were discussed here.

Hope this helps.


问:
Win32 equivalent of opendir
Would anyone know what the Win32 equivalent of opendir is (or if it even exists) ?
Obviously I could use FindFirstFile(Ex) with FindNextFile, but appending * to the path seems like such a hackish way to do it.</p>

答: FindFirstFile and FindNextFile are the appropriate Win32 APIs. Assuming you're writing C++ code, as a portable alternative you could consider using directory_iterator from the Boost Filesystem library (which is implemented on Windows using FindFirstFile and FindNextFile).

OwnerDisplayName: Frans-Willem

Title: Win32 equivalent of opendir

OwnerDisplayName: ChrisN


问:
Retrieving and parsing a MIME email from a database
Task given: An email is stored, byte for byte, in one or more chunks (of fixed length) in a database. This mail is to be retrieved from that database and it's contents shall be displayed to the user.

I have no problem wrapping the legacy database in an ActiveRecord model, concatenating the stored chunks and so on. What I don't really know is where to start on the MIME parsing part. I thought about something like perhaps having a dedicated EMail class which I can initialize with the data stored within the database and that class would allow me to see what MIME parts the mail consist of and allowed me to display, e.g., the text/* parts of it.

Now it seems that ActionMailer is able to parse incoming mails, but the doucmentation on receiving mails seems to be rather, erm, "sparse" and it just mentions receiving mails from STDIN.

How can I parse and display a MIME mail (or parts of it) in Rails, given that I can provide it's contents as a single string, variable, query result or soemthing like that?

答: "has_attachment*s*?" (plural) is the correct name for the method


问:
how do you make an arraylist of different enums?
I have tried looking for the answer for quite a bit of time , so can anyone help me ?

Thank you in advance.

@MehdiB. I have no clue of where to start.

@Bohemian so I am building this game which needs certain requirements to unlock certain items. and I would like to store these requirements in an array which has different

something like this :
ArrayList requirements = new ArrayList();

requirements.add(Weapon.AK47);
requirements.add(House.Mansion);

答: Use Arraylist with Object type elements and cast to whatever enums you wanna use when you use them </p>


问:
Why I am getting quicksort.exe has stopped working and error 255 <0xff> while running my code of quicksort algorithm?I am using Code Blocks
I am running this code on Code Blocks and getting error as quicksort.exe has stopped working. The main function works fine. What is the reason? How can I solve this issue?

The code is as following:

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

void quicksort(int *,int,int);
int part(int *,int,int);

int main()
{
    int i,n, a[100];
    printf("Enter the length of array\n");
    scanf("%d",&n);
    printf("Enter array elements\n");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    quicksort(a,0,n-1);
    printf("\nSorted array:\n");

    for(i=0;i<n;i++)
        printf("%d\n",a[i]);

    return 0;
}

void quicksort(int *a,int lb,int ub)
{
    int p;

    if(lb>ub)
        return;

    p= part(a,lb,ub);
    quicksort(a,lb,p-1);
    quicksort(a,p+1,ub);
    return;
 }

int part(int *x, int l, int u)
{

    int piv,i,t,t2,pos=l;
    piv=x[u];

    for(i=l;i<=u;i++)
    {
        if(x[i]<=piv)
        {
            t=x[i];
            x[i]=x[pos];
            x[pos]=t;
            pos++;
        }

    }
    t2=x[pos];
    x[pos]=x[u];
    x[u]=t2;
    return pos;
}
</code>```

While all other sorting algorithms are working fine. I am getting problem in mergesort and quick sort.

Is the problem with recursion or pointers?

答:
You can modify your code by this(There are two codes closest to your idea, I add annotate):

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

void quicksort(int *,int,int);
int part(int *,int,int);

int main()
{
    int i,n, a[100];
    printf("Enter the length of array\n");
    scanf("%d",&n);
    printf("Enter array elements\n");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    quicksort(a,0,n-1);
    printf("\nSorted array:\n");

    for(i=0;i<n;i++)
        printf("%d\n",a[i]);

    return 0;
}

void quicksort(int *a,int lb,int ub)
{
    int p;

    if(lb>ub)
        return;

    p= part(a,lb,ub);
    quicksort(a,lb,p-1);
    quicksort(a,p+1,ub);
    return;
}

int part(int *x, int l, int u)
{

    int piv,i,t,pos=l-1;  //not pos = l
    piv=x[u];

    for(i=l;i<=u;i++) // You can write:for(i = l; i < u; i++)
    {
        if(x[i]<=piv)
        {
            pos++;    //pos should add 1 before swap
            t=x[i];
            x[i]=x[pos];
            x[pos]=t;
        }

    }
    //If you write for(i = l; i < u; i++), use the following three lines of code
    //t2=x[pos+1];
    //x[pos+1]=x[u];
    //x[u]=t2;
    return pos;
}
</code>```

I think the reason your code crashes is if you use pos = l and write pos++ after swap , x[pos] might occurs out of bounds.But even if you modify it, there are other errors.Maybe you shoule draw a picture to understand quick sort and learn more details.

Body:
I am running this code on Code Blocks and getting error as quicksort.exe has stopped working. The main function works fine. What is the reason? How can I solve this issue?

The code is as following:

#include <stdio.h>
#include <stdlib.h>

void quicksort(int *,int,int);
int part(int *,int,int);

int main()
{
    int i,n, a[100];
    printf("Enter the length of array\n");
    scanf("%d",&n);
    printf("Enter array elements\n");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    quicksort(a,0,n-1);
    printf("\nSorted array:\n");

    for(i=0;i<n;i++)
        printf("%d\n",a[i]);

    return 0;
}

void quicksort(int *a,int lb,int ub)
{
    int p;

    if(lb>ub)
        return;

    p= part(a,lb,ub);
    quicksort(a,lb,p-1);
    quicksort(a,p+1,ub);
    return;
 }

int part(int *x, int l, int u)
{

    int piv,i,t,t2,pos=l;
    piv=x[u];

    for(i=l;i<=u;i++)
    {
        if(x[i]<=piv)
        {
            t=x[i];
            x[i]=x[pos];
            x[pos]=t;
            pos++;
        }

    }
    t2=x[pos];
    x[pos]=x[u];
    x[u]=t2;
    return pos;
}

While all other sorting algorithms are working fine. I am getting problem in mergesort and quick sort.

Is the problem with recursion or pointers?

Body:
You can modify your code by this(There are two codes closest to your idea, I add annotate):

#include <stdio.h>
#include <stdlib.h>

void quicksort(int *,int,int);
int part(int *,int,int);

int main()
{
    int i,n, a[100];
    printf("Enter the length of array\n");
    scanf("%d",&n);
    printf("Enter array elements\n");

    for(i=0;i<n;i++)
        scanf("%d",&a[i]);

    quicksort(a,0,n-1);
    printf("\nSorted array:\n");

    for(i=0;i<n;i++)
        printf("%d\n",a[i]);

    return 0;
}

void quicksort(int *a,int lb,int ub)
{
    int p;

    if(lb>ub)
        return;

    p= part(a,lb,ub);
    quicksort(a,lb,p-1);
    quicksort(a,p+1,ub);
    return;
}

int part(int *x, int l, int u)
{

    int piv,i,t,pos=l-1;  //not pos = l
    piv=x[u];

    for(i=l;i<=u;i++) // You can write:for(i = l; i < u; i++)
    {
        if(x[i]<=piv)
        {
            pos++;    //pos should add 1 before swap
            t=x[i];
            x[i]=x[pos];
            x[pos]=t;
        }

    }
    //If you write for(i = l; i < u; i++), use the following three lines of code
    //t2=x[pos+1];
    //x[pos+1]=x[u];
    //x[u]=t2;
    return pos;
}

I think the reason your code crashes is if you use pos = l and write pos++ after swap , x[pos] might occurs out of bounds.But even if you modify it, there are other errors.Maybe you shoule draw a picture to understand quick sort and learn more details.