问:
Use Linq to search through table for items from a custom class
My code below works but I'm trying to find out how to optimize this and/or make it faster by changing it to one line because currently it performs a query on the database table once per loop and this seems to take forever

The custom class and sql table both have the same exact names as you can see. The queryList is a list of the custom class.

```<code>foreach (var item in queryList)
{
    var query = context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days).ToList();

    if (query.Count() > 0)
    {
         context.DataTable.RemoveRange(query);
    }
}
</code>```

答:
You can test the members of queryList inside the Where:

```<code>var query = context.DataTable.Where(i => i.Symbol == symbol && queryList.Any(item => i.ValueName == item.ValueName && i.Days == item.Days)).ToList();
</code>```

Body:
My code below works but I'm trying to find out how to optimize this and/or make it faster by changing it to one line because currently it performs a query on the database table once per loop and this seems to take forever

The custom class and sql table both have the same exact names as you can see. The queryList is a list of the custom class.

foreach (var item in queryList)
{
    var query = context.DataTable.Where(i => i.ValueName == item.ValueName && i.Symbol == symbol && i.Days == item.Days).ToList();

    if (query.Count() > 0)
    {
         context.DataTable.RemoveRange(query);
    }
}

Body:
You can test the members of queryList inside the Where:

var query = context.DataTable.Where(i => i.Symbol == symbol && queryList.Any(item => i.ValueName == item.ValueName && i.Days == item.Days)).ToList();


来源: stackexchange

问:
SQL Server: Compute group size and group number in a single query
Is there a way to compute group size and group number in a single query instead of using subqueries, in SQL Server 2017 (Developers Edition). I thought this can be done with OVER(PARTITION BY)  and ROW_NUMBER or RANK or NTILES somehow. A runtime efficiency is also important.

Here is a quick example that I produced with two subqueries. It groups records based on ID and date (ignoring time) and adds two fields with parameters for the groups:

```<code>CREATE TABLE #t(ID INT, DtTm SMALLDATETIME)
INSERT INTO #t SELECT 1, '2017-01-07 06:00:00';
INSERT INTO #t SELECT 1, '2017-01-07 07:00:00';
INSERT INTO #t SELECT 1, '2017-01-07 08:00:00';
INSERT INTO #t SELECT 1, '2017-01-13 09:00:00';
INSERT INTO #t SELECT 1, '2017-01-13 10:00:00';
INSERT INTO #t SELECT 2, '2017-01-14 11:00:00';
INSERT INTO #t SELECT 2, '2017-01-14 12:00:00';

WITH a AS (
    SELECT ID, Dt=CAST(DtTm AS DATE), GrpSize=COUNT(*)
    FROM #t GROUP BY ID, CAST(DtTm AS DATE)),
c AS (
    SELECT *, GrpNum=ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Dt)
    FROM a)
SELECT #t.*, c.GrpSize, c.GrpNum
    FROM #t JOIN c
    ON #t.ID=c.ID AND c.Dt=CAST(#t.DtTm AS DATE)
</code>```

The output has two extra columns: one with a group number per each ID, another has the size of the group per each ID.

```<code>ID  DtTm                GrpSize GrpNum
1   2017-01-07 06:00:00 3       1
1   2017-01-07 07:00:00 3       1
1   2017-01-07 08:00:00 3       1
1   2017-01-13 09:00:00 2       2
1   2017-01-13 10:00:00 2       2
2   2017-01-14 11:00:00 2       1
2   2017-01-14 12:00:00 2       1
</code>```

答:
You seem to want dense_rank():

```<code>select t.*,
       count(*) over (partition by id, cast(dtm as date)) as grpsize,
       dense_rank() over (partition by id order by cast(dtm as date)) as grpid
from #t t;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to compute group size and group number in a single query instead of using subqueries, in SQL Server 2017 (Developers Edition). I thought this can be done with OVER(PARTITION BY)  and ROW_NUMBER or RANK or NTILES somehow. A runtime efficiency is also important.

Here is a quick example that I produced with two subqueries. It groups records based on ID and date (ignoring time) and adds two fields with parameters for the groups:

CREATE TABLE #t(ID INT, DtTm SMALLDATETIME)
INSERT INTO #t SELECT 1, '2017-01-07 06:00:00';
INSERT INTO #t SELECT 1, '2017-01-07 07:00:00';
INSERT INTO #t SELECT 1, '2017-01-07 08:00:00';
INSERT INTO #t SELECT 1, '2017-01-13 09:00:00';
INSERT INTO #t SELECT 1, '2017-01-13 10:00:00';
INSERT INTO #t SELECT 2, '2017-01-14 11:00:00';
INSERT INTO #t SELECT 2, '2017-01-14 12:00:00';

WITH a AS (
    SELECT ID, Dt=CAST(DtTm AS DATE), GrpSize=COUNT(*)
    FROM #t GROUP BY ID, CAST(DtTm AS DATE)),
c AS (
    SELECT *, GrpNum=ROW_NUMBER() OVER(PARTITION BY ID ORDER BY Dt)
    FROM a)
SELECT #t.*, c.GrpSize, c.GrpNum
    FROM #t JOIN c
    ON #t.ID=c.ID AND c.Dt=CAST(#t.DtTm AS DATE)

The output has two extra columns: one with a group number per each ID, another has the size of the group per each ID.

ID  DtTm                GrpSize GrpNum
1   2017-01-07 06:00:00 3       1
1   2017-01-07 07:00:00 3       1
1   2017-01-07 08:00:00 3       1
1   2017-01-13 09:00:00 2       2
1   2017-01-13 10:00:00 2       2
2   2017-01-14 11:00:00 2       1
2   2017-01-14 12:00:00 2       1

Body:
You seem to want dense_rank():

select t.*,
       count(*) over (partition by id, cast(dtm as date)) as grpsize,
       dense_rank() over (partition by id order by cast(dtm as date)) as grpid
from #t t;


问:
Get file's signed URL from amazon s3 using Filesystem Laravel 5.2
I'm looking for a good solution to get the signed url from amazon s3.

I have a version working with it, but not using laravel:

private function getUrl ()
{
        $distribution = $_SERVER["AWS_CDN_URL"];

        $cf = Amazon::getCFClient();

        $url = $cf->getSignedUrl(array(
            'url'     => $distribution . self::AWS_PATH.rawurlencode($this->fileName),
            'expires' => time() + (session_cache_expire() * 60)));

        return $url;
}
```

I don't know if this is the best way to do with laravel, considering it has a entire file system to work...

But if don't have another way, how do I get the client? Debugging I've found an instance of it inside the Filesystem object, but it is protected...

答:
For Laravel 5.5 and up,
you can now use temporary URLs/s3 presigned URL.

```<code>use \Storage;

// Make sure you have s3 as your disk driver
$url = Storage::disk('s3')->temporaryUrl(
   'file1.jpg', Carbon::now()->addMinutes(5)
);
</code>```

This only works for s3 storage driver AFAIK.

https://laravel.com/docs/5.5/filesystem#retrieving-files

Body:
I'm looking for a good solution to get the signed url from amazon s3.

I have a version working with it, but not using laravel:

private function getUrl ()
{
        $distribution = $_SERVER["AWS_CDN_URL"];

        $cf = Amazon::getCFClient();

        $url = $cf->getSignedUrl(array(
            'url'     => $distribution . self::AWS_PATH.rawurlencode($this->fileName),
            'expires' => time() + (session_cache_expire() * 60)));

        return $url;
}

I don't know if this is the best way to do with laravel, considering it has a entire file system to work...

But if don't have another way, how do I get the client? Debugging I've found an instance of it inside the Filesystem object, but it is protected...

Body:
For Laravel 5.5 and up,
you can now use temporary URLs/s3 presigned URL.

use \Storage;

// Make sure you have s3 as your disk driver
$url = Storage::disk('s3')->temporaryUrl(
   'file1.jpg', Carbon::now()->addMinutes(5)
);

This only works for s3 storage driver AFAIK.

https://laravel.com/docs/5.5/filesystem#retrieving-files


问:
HEAD~ vs HEAD^ vs HEAD@{} also known as tilde vs caret vs at sign
HEAD is a pointer at the current branch. I have seen a variety of notations for ancestors of HEAD including

HEAD~2

HEAD^2

HEAD@{2}

HEAD~~

HEAD^^

What does each of the above mean, exactly? Where is the documentation for this?

答:
git reference suffixes (^N, ~N, @{...})

ref~ is shorthand for ref~1 and means the commit's first parent. ref~2 means the commit's first parent's first parent. ref~3 means the commit's first parent's first parent's first parent. And so on.

ref^ is shorthand for ref^1 and means the commit's first parent. But where the two differ is that ref^2 means the commit's second parent (remember, commits can have two parents when they are a merge).

The ^ and ~ operators can be combined.

Here's a diagram showing how to reference various commits using HEAD as the starting point.

src


问:
How to bypass getIntent() and getStringExtra() when running MainActivity for the first time
I am having an issue where the following code is causing my app to crash.

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
final String years = intent.getStringExtra(MenuActivity.yearsMessage);
final String rate = intent.getStringExtra(MenuActivity.rateMessage);
</code>```

If it is the first time opening my app, the blank values that come from the getStringExtra() commands cause the app to crash when they are called later in the code.

```<code>double rate = Double.parseDouble(rateString);
double years = Double.parseDouble(yearsString);
double outFloat = inFloat * Math.pow((1f + rate), years);
return df2.format(outFloat);
</code>```

Does anyone know a way that I can declare the default values for the getStringExtra method when it is the first time opening the App?

答:
Try checking for null values on the variables years and rate, as CommonsWare said and it might also be a good idea to put the parses inside a try catch, just in case that the parse fails</p>

```<code>if (years != null && rate != null) {
    try {
        double rate = Double.parseDouble(rateString);
        double years = Double.parseDouble(yearsString);
        double outFloat = inFloat * Math.pow((1f + rate), years);
        return df2.format(outFloat);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}
</code>```

Body:
I am having an issue where the following code is causing my app to crash.

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
final String years = intent.getStringExtra(MenuActivity.yearsMessage);
final String rate = intent.getStringExtra(MenuActivity.rateMessage);

If it is the first time opening my app, the blank values that come from the getStringExtra() commands cause the app to crash when they are called later in the code.

double rate = Double.parseDouble(rateString);
double years = Double.parseDouble(yearsString);
double outFloat = inFloat * Math.pow((1f + rate), years);
return df2.format(outFloat);

Does anyone know a way that I can declare the default values for the getStringExtra method when it is the first time opening the App?

Body:
Try checking for null values on the variables years and rate, as CommonsWare said and it might also be a good idea to put the parses inside a try catch, just in case that the parse fails

if (years != null && rate != null) {
    try {
        double rate = Double.parseDouble(rateString);
        double years = Double.parseDouble(yearsString);
        double outFloat = inFloat * Math.pow((1f + rate), years);
        return df2.format(outFloat);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}


问:
Setting ivy conflict managers
I am trying to set conflict managers in Ivy, but I can't find a concrete example of how to set them. For example, to set the "strict" manager, what would this look like?</p>

```<code><conflict-managers>
  ???
</conflict-managers>
</code>```

答:
The Ivy reference documentation strictly follows the XML tag structure of the ivy.xml and ivy-settings.xml files. You are expected to extract the information required directly from the document structure.

Decoding from the Ivy docs:
The conflict-managers tag is for declaring what conflict managers a project may use and configuring them if they accept configuration, not for setting the conflict manager to use.

```<code><conflict-managers>
    <latest-cm name="mylatest-conflict-manager" latest="my-latest-strategy"/>
    <compatible-cm name="my-latest-compatible-conflict-manager" latest="my-latest-strategy"/>

</conflict-managers>
</code>```

The settings tag has an attribute for choosing the default conflict manager:

```<code><settings defaultConflictManager="strict"/>
</code>```

Or in an ivy.xml:

```<code><dependencies>
    <dependency.../>
    <conflict manager="strict">
</dependencies>
</code>```

Note that most of the conflict managers are more liberal in their interpretation of your intentions than you would expect. Two examples:
* Branches are considered irrelevant, if a dependency is available on two branches the "latest" family of resolvers will pick the latest available from either.
* Both the "latest-time" and "latest-revision" resolvers ignore version constraints except to set boundaries on the matching space. e.g. if a depends on b-1.0 and c-1.0 but c-1.0 depends on b-5.0 then you will get b-5.0 despite it not meeting the constraint requested.
I assume your need is result of discovering one of these design flaws.

Title: Setting ivy conflict managers

Body:
I am trying to set conflict managers in Ivy, but I can't find a concrete example of how to set them. For example, to set the "strict" manager, what would this look like?

<conflict-managers>
  ???
</conflict-managers>

Body:
The Ivy reference documentation strictly follows the XML tag structure of the ivy.xml and ivy-settings.xml files. You are expected to extract the information required directly from the document structure.

Decoding from the Ivy docs:
The conflict-managers tag is for declaring what conflict managers a project may use and configuring them if they accept configuration, not for setting the conflict manager to use.

<conflict-managers>
    <latest-cm name="mylatest-conflict-manager" latest="my-latest-strategy"/>
    <compatible-cm name="my-latest-compatible-conflict-manager" latest="my-latest-strategy"/>

</conflict-managers>

The settings tag has an attribute for choosing the default conflict manager:

<settings defaultConflictManager="strict"/>

Or in an ivy.xml:

<dependencies>
    <dependency.../>
    <conflict manager="strict">
</dependencies>

Note that most of the conflict managers are more liberal in their interpretation of your intentions than you would expect. Two examples:
* Branches are considered irrelevant, if a dependency is available on two branches the "latest" family of resolvers will pick the latest available from either.
* Both the "latest-time" and "latest-revision" resolvers ignore version constraints except to set boundaries on the matching space. e.g. if a depends on b-1.0 and c-1.0 but c-1.0 depends on b-5.0 then you will get b-5.0 despite it not meeting the constraint requested.
I assume your need is result of discovering one of these design flaws.


问:
How to Step into NServiceBus 2.0 with Debugger and also Navigate in it with Resharper?
We've just newly decided to use NServiceBus on our project and we're experiencing some problems. Rather than "ask for a fish" every time we hit an issue, we'd prefer to "teach ourselves to fish". This means setting things up so we can step into the NServiceBus source code and understand NServiceBus more deeply.

We need some help figuring out how to pull this off. It is unclear how to get Visual Studio to successfully build NServiceBus upon each compile, since NServiceBus comes with its own Nant build process that uses ILMerge to create consolidated assemblies and so forth.

We have already tried building NServiceBus with the Nant script and then referencing those dlls and pdb's. However, that does not let us step everywhere, and it also does not let VS.NET and Resharper navigate via "Find Usages" and other features.

So what we would really like to create is a VS.NET Solution that builds our in-house software and NServiceBus, and allows us to seamlessly Step and Navigate between them.

Is this possible? What would we need to do to pull this off?

答:
Not quite the exact answer you were looking for, but you can check out the post i made on debugging into NServiceBus which involves the following steps:

Downloading the source code.

Building the source code using the
"build.bat"

Then referencing the
dlls and pdb files in your
solutions, so that you can step into
the NServiceBus source code.

I've successfully change the logging behaviour to always to a Message.ToString() in our code so that the Log4Net logs were a bit clearer.

Check it out here:

http://www.craftyfella.com/2010/12/debugging-into-nservicebus-so-you-can.html

Hope it helps.

Dave

ContentLicense: CC BY-SA 2.5


问:
How to make tabbed labels responsive?
I have a tabbed feature on my site, and it is responsive, except for the labels.  I am not sure what to add to my style sheet to get the labels to wrap properly. Right now, when I reduced the size of the div, the labels spill out.

Here is a fiddle of what I have, everything I have tried so far has not worked, any insight would be greatly appreciated.

Thank you!

```<code><https://jsfiddle.net/v9eu9gsL/>
</code>```

答:
```<code>.ui-tabs .ui-tabs-nav li {
  white-space: normal;
}
</code>```

https://jsfiddle.net/w0x7ju9y/

Title: How to make tabbed labels responsive?

Body:
I have a tabbed feature on my site, and it is responsive, except for the labels.  I am not sure what to add to my style sheet to get the labels to wrap properly. Right now, when I reduced the size of the div, the labels spill out.

Here is a fiddle of what I have, everything I have tried so far has not worked, any insight would be greatly appreciated.

Thank you!

<https://jsfiddle.net/v9eu9gsL/>

Body:
.ui-tabs .ui-tabs-nav li {
  white-space: normal;
}

https://jsfiddle.net/w0x7ju9y/


问:
Git Bash: remote: command not found
I want to split off a folder inside my existing github repository into it's own repository so I tried following the instructions here: https://help.github.com/articles/splitting-a-subfolder-out-into-a-new-repository/

I've never installed git on my machine before so I downloaded the latest installer and went through the options. I choose the option 'Use Git from windows command prompt'. Once it's installed there are some commands that do not work.

Git Bash:

Git CMD:

I've tried setting the PATH variable as well manually but that doesn't fix it, I still get the same 'command not found'.

Is this a bug with the latest git? Or did I somehow mess up the install?

I'm on windows 10 machine.

答:
git is the program remote and -v are arguments for it

First you will want to clone a repository that you want for example

git clone https://github.com/justinmeister/Mario-Level-1 mario_game

this will create a folder called mario_game with the git remote setup.

cd mario_game

git remote -v

Now you will see the remote as https://github.com/justinmeister/Mario-Level-1

Title: Git Bash: remote: command not found


问:
Allow token based API access to some endpoints on Azure App Service
I have a NodeJS app running on Azure's app service. It's used by real humans, and uses Active Directory Authentication:

At the moment, requests that are not authenticated are redirected to the Active Directly login page. It's working great.

But, I now have the requirement that another application, as opposed to a human, be able to access certain API endpoints - presumably via some kind of token authentication.

I think options for doing this are:

Use built-in Azure stuff. There's an example here of how to have a client Azure app authenticate to another, but I don't think that'll work for me as my client app is NOT an Azure app. So, I need anything - eg a curl request - to be able to authenticate to my app. Am I right here? Does azure have anything built in for "non-azure app to authenticate with Azure app"?

I could select the "Allow Anonymous requests (no action)" option in the screenshot above, and then handle it all myself: implement an api_tokens table, and for every request, check for an API token if it's a client_api/* endpoint, check for an Active Directory authenticated user for any other endpoint, and manually redirect them to a login page myself if they're not authenticated.

Ideally, I could say: if the request is to client_api/* then allow unauthenticated requests, and and I'll check the request includes a valid token, but for all other requests, do as you do now - use Active Directory auth and re-direct unauthenticated requests to the login page, automatically.

So my questions are:
- Am I right that auzure has nothing to make option 1) work for me?
- Is there a way to do option 3)?
- If not, I guess that leaves option 2) - or is there a better way I'm not thinking of?

答:
We have done something similar with your 1) option, good news is that your client (which calls the API) does not have to be hosted within Azure.

We had a custom CRM plugin which needed to invoke calls to an Azure AD protected API APP, the process is rather lengthy, but it works (we set it up a long while ago, so I think the following steps are about right):

Create your own API hosted within Azure and make sure it is registered in Azure AD as an app (within Azure AD -> App registrations in the portal)

Then create a NEW application within Azure AD, call it (say) "Client AD Application", and setup the basic properties and keys, etc.

Effectively, from now, your client APIs will act as the "Client AD Application".

You then need to grant access to your APIs from the "Client AD Application" by assigning delegate permissions to your protected API (again, just do this in the UI within Azure AD). You do this by assigning "elegate Permissions" TO the new "Client AD Application" app (which was not intuitive to me)

once you have the 2 apps setup, and permissions assigned, you then need to invoke the OAUTH API endpoint to get a token, then use that token in the subsequent calls to your API.

Most of this is documented here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

EDIT:--

As for an example, our call to the oauth endpoint looks like this:

Send POST request to:
https://login.windows.net/[tennant]/oauth2/token
with the headers:

client_id: (application ID for the new AD App)

client_secret: (secret for the new AD App)

resource: (what API endpoint are you trying to access - i.e. your protected API)

username: valid AD username

password: valid AD password

grant_type: password (always 'password')

This will give you a response like the below:

```<code>{
    "token_type": "Bearer",
    "scope": "user_impersonation",
    "expires_in": "3600",
    "ext_expires_in": "0",
    "expires_on": "XXX",
    "not_before": "XXX",
    "resource": "...the resource you asked for...",
    "access_token": "...",
    "refresh_token": "..."
}
</code>```

Hope that helps mate.

Body:
We have done something similar with your 1) option, good news is that your client (which calls the API) does not have to be hosted within Azure.

We had a custom CRM plugin which needed to invoke calls to an Azure AD protected API APP, the process is rather lengthy, but it works (we set it up a long while ago, so I think the following steps are about right):

Create your own API hosted within Azure and make sure it is registered in Azure AD as an app (within Azure AD -> App registrations in the portal)

Then create a NEW application within Azure AD, call it (say) "Client AD Application", and setup the basic properties and keys, etc.

Effectively, from now, your client APIs will act as the "Client AD Application".

You then need to grant access to your APIs from the "Client AD Application" by assigning delegate permissions to your protected API (again, just do this in the UI within Azure AD). You do this by assigning "elegate Permissions" TO the new "Client AD Application" app (which was not intuitive to me)

once you have the 2 apps setup, and permissions assigned, you then need to invoke the OAUTH API endpoint to get a token, then use that token in the subsequent calls to your API.

Most of this is documented here:
https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-protocols-oauth-code

EDIT:--

As for an example, our call to the oauth endpoint looks like this:

Send POST request to:
https://login.windows.net/[tennant]/oauth2/token
with the headers:

client_id: (application ID for the new AD App)

client_secret: (secret for the new AD App)

resource: (what API endpoint are you trying to access - i.e. your protected API)

username: valid AD username

password: valid AD password

grant_type: password (always 'password')

This will give you a response like the below:

{
    "token_type": "Bearer",
    "scope": "user_impersonation",
    "expires_in": "3600",
    "ext_expires_in": "0",
    "expires_on": "XXX",
    "not_before": "XXX",
    "resource": "...the resource you asked for...",
    "access_token": "...",
    "refresh_token": "..."
}

Hope that helps mate.


问:
IOATDMA is not being used by network drivers
I am testing crystal beach dma on x86_64 Intel xeon board. I want to test both e1000e and ixgbe drivers with crystal beach dma.

I have patched ioatdma driver(pci.c and hw.h files ) for crystal beach dma. Now I am facing issue that both drivers do not use this channels at all. The bytes_transferred and memcpy_count are always zero.

Following are the configurations –

Kernel I am using is 2.6.32.431

```<code>[root@hvtxrs82 dma]# pwd

/sys/class/dma

[root@hvtxrs82 dma]# ls

dma0chan0   dma12chan0  dma15chan0  dma3chan0  dma6chan0  dma9chan0

dma10chan0  dma13chan0  dma1chan0   dma4chan0  dma7chan0

dma11chan0  dma14chan0  dma2chan0   dma5chan0  dma8chan0
</code>```

I have inserted both e1000e and ixgbe drivers. And dmachannels show that.

```<code>[root@hvtxrs82 dma]# cat /sys/class/dma/dma0chan0/in_use
4
</code>```

lspci ouput -

```<code>80:04.0 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 0 (rev 04)

80:04.1 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 1 (rev 04)

80:04.2 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 2 (rev 04)

80:04.3 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 3 (rev 04)

80:04.4 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 4 (rev 04)

80:04.5 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 5 (rev 04)

80:04.6 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 6 (rev 04)

80:04.7 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 7 (rev 04)
</code>```

I have changed stack settings as sysctl net.ipv4.tcp_dma_copybreak=1

```<code>[root@hvtxrs82 dma]# cat /sys/class/dma/dma0chan0/bytes_transferred

0
</code>```

Same is for all channels. However ethtool shows traffic and packets received. So why is dma channels not getting used?

答:
Linux disabled net_dma's TCP receive copy offload in December 2013 because of a bug.

So it's probably a good thing that it's not working.

Body:
I am testing crystal beach dma on x86_64 Intel xeon board. I want to test both e1000e and ixgbe drivers with crystal beach dma.

I have patched ioatdma driver(pci.c and hw.h files ) for crystal beach dma. Now I am facing issue that both drivers do not use this channels at all. The bytes_transferred and memcpy_count are always zero.

Following are the configurations –

Kernel I am using is 2.6.32.431

[root@hvtxrs82 dma]# pwd

/sys/class/dma

[root@hvtxrs82 dma]# ls

dma0chan0   dma12chan0  dma15chan0  dma3chan0  dma6chan0  dma9chan0

dma10chan0  dma13chan0  dma1chan0   dma4chan0  dma7chan0

dma11chan0  dma14chan0  dma2chan0   dma5chan0  dma8chan0

I have inserted both e1000e and ixgbe drivers. And dmachannels show that.

[root@hvtxrs82 dma]# cat /sys/class/dma/dma0chan0/in_use
4

lspci ouput -

80:04.0 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 0 (rev 04)

80:04.1 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 1 (rev 04)

80:04.2 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 2 (rev 04)

80:04.3 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 3 (rev 04)

80:04.4 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 4 (rev 04)

80:04.5 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 5 (rev 04)

80:04.6 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 6 (rev 04)

80:04.7 System peripheral: Intel Corporation Ivytown Crystal Beach DMA Channel 7 (rev 04)

I have changed stack settings as sysctl net.ipv4.tcp_dma_copybreak=1

[root@hvtxrs82 dma]# cat /sys/class/dma/dma0chan0/bytes_transferred

0

Same is for all channels. However ethtool shows traffic and packets received. So why is dma channels not getting used?


问:
Clicking Tableview Cell Does Not Display Data
I'm having trouble with my didSelectRowAt function of my tableview. For some reason, although my segue identifier and destination view are correct, when I click the row, it does not load anything. Furthermore, Xcode informs me:

Cannot assign value of type 'Double?' to type 'String?'

but I cannot find an online resource that tells me how to resolve this. For reference, the data I would like to display is from a nested JSON feed.

JSON Struct

```<code>struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}
</code>```

Cell Select Function

```<code>func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetail", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? RankDetail {
        destination.playerRank = rank[(rankTable.indexPathForSelectedRow?.row)!]
    }
}
</code>```

Destination View Controller Code

```<code>import UIKit

class RankDetail: UIViewController {
    @IBOutlet var rankLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!

    var playerRank:PlayerStats?

    override func viewDidLoad() {
        super.viewDidLoad()
        rankLabel.text = "\(playerRank?.solo_competitive_rank)"
        scoreLabel.text = playerRank?.score
    }
</code>```

答:
Looks like the error occurs in the RankDetail class.
Here's a simple fix.

class RankDetail: UIViewController {
    @IBOutlet var rankLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!

    var playerRank:PlayerStats?

    override func viewDidLoad() {
        super.viewDidLoad()
        rankLabel.text = "\(playerRank?.solo_competitive_rank)"
        // scoreLabel.text if of type String?, so it can't store Double? directly
        // scoreLabel.text = playerRank?.score
        // converting to String? should fix it
        scoreLabel.text = "\(playerRank?.score)"
}
```

<p>EDIT:
Present <code>ViewController</code> using the following code. Saves you the trouble of having to worry about segues.</p>

<pre class="lang-swift prettyprint-override"><code>if let viewController = storyboard?.instantiateViewController(withIdentifier: "NewViewController") {
      present(viewController, animated: true, completion: nil)
</code>```

}

Body:
I'm having trouble with my didSelectRowAt function of my tableview. For some reason, although my segue identifier and destination view are correct, when I click the row, it does not load anything. Furthermore, Xcode informs me:

Cannot assign value of type 'Double?' to type 'String?'

but I cannot find an online resource that tells me how to resolve this. For reference, the data I would like to display is from a nested JSON feed.

JSON Struct

struct PlayerStatsParent:Decodable{
    let rankings: [PlayerStats]
}

struct PlayerStats:Decodable {
    let personaname: String?
    let score: Double?
    let solo_competitive_rank: Int?
    let avatar: String?
}

Cell Select Function

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    performSegue(withIdentifier: "showDetail", sender: self)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? RankDetail {
        destination.playerRank = rank[(rankTable.indexPathForSelectedRow?.row)!]
    }
}

Destination View Controller Code

import UIKit

class RankDetail: UIViewController {
    @IBOutlet var rankLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!

    var playerRank:PlayerStats?

    override func viewDidLoad() {
        super.viewDidLoad()
        rankLabel.text = "\(playerRank?.solo_competitive_rank)"
        scoreLabel.text = playerRank?.score
    }

Body:
Looks like the error occurs in the RankDetail class.
Here's a simple fix.

class RankDetail: UIViewController {
    @IBOutlet var rankLabel: UILabel!
    @IBOutlet var scoreLabel: UILabel!

    var playerRank:PlayerStats?

    override func viewDidLoad() {
        super.viewDidLoad()
        rankLabel.text = "\(playerRank?.solo_competitive_rank)"
        // scoreLabel.text if of type String?, so it can't store Double? directly
        // scoreLabel.text = playerRank?.score
        // converting to String? should fix it
        scoreLabel.text = "\(playerRank?.score)"
}

EDIT:
Present ViewController using the following code. Saves you the trouble of having to worry about segues.

if let viewController = storyboard?.instantiateViewController(withIdentifier: "NewViewController") {
      present(viewController, animated: true, completion: nil)

}


问:
Make Div Container Match the Size of an Image Before it Loads on Different-Sized Devices
Total noob CSS question here: I have an image with a natural resolution of 900x576 and a surrounding
 container

```<code><div class="img-container">
    <img src="some-image.png" />
</div>
</code>```

This image will be displayed on many different mobile devices, all of which have different resolutions. The image will grow or shrink depending on the device its displayed on, and it will be loaded from a server (which could take a moment or 2)

I want the img-container to  be dynamically resized to the dimensions of the image no matter what device its displayed on, so when the image finally loads, the div doesn't abruptly grow from a height of 0px (because there's nothing inside of it yet) to the height of the image

This might be such a simple task that I'm overlooking it - can this be done purely with CSS?

答:
If the images are always going to be the same aspect ratio you can set  </p>

```<code>.img-container {
    position: relative;
    padding-bottom: 80%; // ratio 5:4
}
.img-container img {
    position: absolute;
    top:0;
    left:0;
    bottom:0;
}
</code>```

Body:
Total noob CSS question here: I have an image with a natural resolution of 900x576 and a surrounding
 container

This image will be displayed on many different mobile devices, all of which have different resolutions. The image will grow or shrink depending on the device its displayed on, and it will be loaded from a server (which could take a moment or 2)

I want the img-container to  be dynamically resized to the dimensions of the image no matter what device its displayed on, so when the image finally loads, the div doesn't abruptly grow from a height of 0px (because there's nothing inside of it yet) to the height of the image

This might be such a simple task that I'm overlooking it - can this be done purely with CSS?

Body:
If the images are always going to be the same aspect ratio you can set

.img-container {
    position: relative;
    padding-bottom: 80%; // ratio 5:4
}
.img-container img {
    position: absolute;
    top:0;
    left:0;
    bottom:0;
}


问:
Optional deconstruction function parameter
How do you modify the function below to make the second parameter optional?

TypeScript:

```<code>function getName(name: string, {
    lastName
  }: {
    lastName: string
  }) {
  // ...
}

getName('John'); // error
</code>```

Update:

The solution I've found so far is to take out the deconstruction into the function body:

```<code>function getName(name: string, options: {
    lastName: string
  } = {} as any) {
    const { lastName } = options;
    // ...
}

getName('John'); // OK
</code>```

However, I still cannot find how to make it work in this context:

```<code>const getName = Bluebird.coroutine(function* co(name: string,
  {
    lastName
  }: {
    lastName: string
  }) {
    // ...
});

getName('John'); // error

/* -------- DECLARATIONS -------- */

declare namespace Bluebird {
    interface CoroutineOptions {
        yieldHandler(value: any): any;
    }
}

declare class Bluebird<R> {
    static coroutine<T, A1, A2>(
        generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
        options?: Bluebird.CoroutineOptions
    ): (a1: A1, a2: A2) => Bluebird<T>;
}
</code>```

Moving the deconstruction to the function body still gives an error:

```<code>const getName = Bluebird.coroutine(function* co(name: string, options: {
    lastName: string
  } = {} as any) {
    // ...
});

getName('John'); // error: Expected 2 arguments but got 1.
</code>```

答:
You will need to define the interface for the lastName property as optional when defining the options object. If no options is defined, the default object is an empty object {}.

```<code>function foo(required: string, options: { lastName?: string } = {}) {
    console.log(required);
    if (options.lastName) {
        console.log(options.lastName);
    }
}

foo('foo1')
foo('foo2', {})
foo('foo3', {lastName: 'bar'})
</code>```

Running the above, the console output is:

```<code>foo1
foo2
foo3
bar
</code>```

See TypeScript playground link to try it out yourself.

Body:
How do you modify the function below to make the second parameter optional?

TypeScript:

function getName(name: string, {
    lastName
  }: {
    lastName: string
  }) {
  // ...
}

getName('John'); // error

Update:

The solution I've found so far is to take out the deconstruction into the function body:

function getName(name: string, options: {
    lastName: string
  } = {} as any) {
    const { lastName } = options;
    // ...
}

getName('John'); // OK

However, I still cannot find how to make it work in this context:

const getName = Bluebird.coroutine(function* co(name: string,
  {
    lastName
  }: {
    lastName: string
  }) {
    // ...
});

getName('John'); // error

/* -------- DECLARATIONS -------- */

declare namespace Bluebird {
    interface CoroutineOptions {
        yieldHandler(value: any): any;
    }
}

declare class Bluebird<R> {
    static coroutine<T, A1, A2>(
        generatorFunction: (a1: A1, a2: A2) => IterableIterator<any>,
        options?: Bluebird.CoroutineOptions
    ): (a1: A1, a2: A2) => Bluebird<T>;
}

Moving the deconstruction to the function body still gives an error:

const getName = Bluebird.coroutine(function* co(name: string, options: {
    lastName: string
  } = {} as any) {
    // ...
});

getName('John'); // error: Expected 2 arguments but got 1.

Body:
You will need to define the interface for the lastName property as optional when defining the options object. If no options is defined, the default object is an empty object {}.

function foo(required: string, options: { lastName?: string } = {}) {
    console.log(required);
    if (options.lastName) {
        console.log(options.lastName);
    }
}

foo('foo1')
foo('foo2', {})
foo('foo3', {lastName: 'bar'})

Running the above, the console output is:

foo1
foo2
foo3
bar

See <a href="https://www.typescriptlang.org/play/index.html#src=function%20foo(required%3A%20string%2C%20options%3A%20%7B%20lastName%3F%3A%20string%20%7D%20%3D%20%7B%7D)%20%7B%0D%0A%20%20%20%20console.log(required)%3B%0D%0A%20%20%20%20if%20(options.lastName)%20%7B%0D%0A%20%20%20%20%20%20%20%20console.log(options.lastName)%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Afoo('foo1')%0D%0Afoo('foo2'%2C%20%7B%7D)%0D%0Afoo('foo3'%2C%20%7BlastName%3A%20'bar'%7D)" rel="nofollow noreferrer">TypeScript playground link to try it out yourself.


问:
ASP MVC ConfirmEmailAsync not working
I register a user, receive a token via email which looks like this:

Please confirm your account by clicking here

I click the link and I can see that the ConfirmEmail method in AccountController fires:

```<code>    [AllowAnonymous]
    public async Task<ActionResult> ConfirmEmail(string userId, string code)
    {
        if (userId == null || code == null)
        {
            return View("Error");
        }
        var result = await UserManager.ConfirmEmailAsync(userId, code);
        return View(result.Succeeded ? "ConfirmEmail" : "Error");
    }
</code>```

And that result.Succeeded is true.

Everything appears fine, but when trying to log in after completing this process I get taken to the page telling me my account is locked

Locked out.

This account has been locked out, please try again later.

What couldI be doing wrong? Do I need to manually change the lockout flag in the db? If so, what is the point of the ConfirmEmailAsync method?

答:
ConfirmEmailAsync just sets the EmailConfirmed on the user account record to true. From UserManager (edited for brevity):

```<code>public virtual async Task<IdentityResult> ConfirmEmailAsync(TUser user, string token)
{
    ...
    var store = GetEmailStore();
    ...
    await store.SetEmailConfirmedAsync(user, true, CancellationToken);
    return await UpdateUserAsync(user);
}
</code>```

Where GetEmailStore returns the IUserEmailStore (which is implemented by UserStore by default), which sets the flag:

```<code>public virtual Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
    ...
    user.EmailConfirmed = confirmed;
    return Task.CompletedTask;
}
</code>```

The error you're getting indicated that the LockoutEnabled flag on the user account is true. You can set this to false by calling the SetLockoutEnabledAsync method on the UserManager.

There is also a SupportsUserLockout flag on the UserManager which unlocks accounts by default on creation. In order to set this you will need to create your own UserManager and override this flag to false.

Title: ASP MVC ConfirmEmailAsync not working

Body:
I register a user, receive a token via email which looks like this:

Please confirm your account by clicking here

I click the link and I can see that the ConfirmEmail method in AccountController fires:

    [AllowAnonymous]
    public async Task<ActionResult> ConfirmEmail(string userId, string code)
    {
        if (userId == null || code == null)
        {
            return View("Error");
        }
        var result = await UserManager.ConfirmEmailAsync(userId, code);
        return View(result.Succeeded ? "ConfirmEmail" : "Error");
    }

And that result.Succeeded is true.

Everything appears fine, but when trying to log in after completing this process I get taken to the page telling me my account is locked

Locked out.

This account has been locked out, please try again later.

What couldI be doing wrong? Do I need to manually change the lockout flag in the db? If so, what is the point of the ConfirmEmailAsync method?

Body:
ConfirmEmailAsync just sets the EmailConfirmed on the user account record to true. From UserManager (edited for brevity):

public virtual async Task<IdentityResult> ConfirmEmailAsync(TUser user, string token)
{
    ...
    var store = GetEmailStore();
    ...
    await store.SetEmailConfirmedAsync(user, true, CancellationToken);
    return await UpdateUserAsync(user);
}

Where GetEmailStore returns the IUserEmailStore (which is implemented by UserStore by default), which sets the flag:

public virtual Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken = default(CancellationToken))
{
    ...
    user.EmailConfirmed = confirmed;
    return Task.CompletedTask;
}

The error you're getting indicated that the LockoutEnabled flag on the user account is true. You can set this to false by calling the SetLockoutEnabledAsync method on the UserManager.

There is also a SupportsUserLockout flag on the UserManager which unlocks accounts by default on creation. In order to set this you will need to create your own UserManager and override this flag to false.


问:
Dataframe with a Factor that has More Levels than Observations in R
Weird problem.

How can I have a dataframe that has more levels in a factor variable than there are observations?

```<code>> str(cash.SR)
'data.frame':   50 obs. of  2 variables:
 $ state     : Factor w/ 55 levels "Alabama","Alaska",..: 1 45 46 15 12 36 4 44 18 55 ...
 $ cash_avail: int  14909657 11401584 5900970 5760263 5612664 5466801 5435156 4850103 4415570 3459859 ...
</code>```

This is nothing complicated.  I have a df with 2 columns and 50 rows (one corresponding to each state).

Thanks.

答:
It's very easy to create factors with more levels than values:

```<code> tfac <- factor(1, levels=1:3)
 dput(tfac)
     #structure(1L, .Label = c("1", "2", "3"), class = "factor")
</code>```

If you subset from a factor variable with 55 levels and only get 50 hits there is no automatic shrinkage in the length of levels. You need to use drop.levels to return a factor object with fewer levels.

Body:
Weird problem.

How can I have a dataframe that has more levels in a factor variable than there are observations?

> str(cash.SR)
'data.frame':   50 obs. of  2 variables:
 $ state     : Factor w/ 55 levels "Alabama","Alaska",..: 1 45 46 15 12 36 4 44 18 55 ...
 $ cash_avail: int  14909657 11401584 5900970 5760263 5612664 5466801 5435156 4850103 4415570 3459859 ...

This is nothing complicated.  I have a df with 2 columns and 50 rows (one corresponding to each state).

Thanks.

Body:
It's very easy to create factors with more levels than values:

 tfac <- factor(1, levels=1:3)
 dput(tfac)
     #structure(1L, .Label = c("1", "2", "3"), class = "factor")

If you subset from a factor variable with 55 levels and only get 50 hits there is no automatic shrinkage in the length of levels. You need to use drop.levels to return a factor object with fewer levels.


问:
How to make Bootstrap popover appears once on page load
I want to make bootstrap popover should appears once on the page load over a button (just to use it as an instruction) and after clicking the button it should get destroyed.

I want to popover on the button and gets user's attention every time they visit my page and drag their attention to click on it if they are new visitors.

I have made following code, the popovers appears on the page load but it works just like normal popover afterwards it doesn't get destroyed when i click button.

HTML:

```<code><div class="container">
    <div class="row">
        <div class="col-sm-12">
            <h1>Hello World</h1>

            <p>Click on button to see Popover</p>

            <button type="button" id="example" class="btn btn-primary" rel="popover"
                data-content="Check this new option when you visit our website to catch the latest news!"
                data-original-title="This is new feature">pop
            </button>
        </div>
    </div>
</div>
</code>```

JS:

```<code>function destroyNew(){
    $('#example').popover('destroy');
}

$(window).load(function () {
    $("#example").popover('show');
});
</code>```

I have also modified the JS and tried in this way:

JS:

```<code>$("#example").on('click', function () {
        $('#example').popover('destroy');
    }
});

$(window).load(function () {
        $("#example").popover('show');
});
</code>```

The above code doesn't make the popover at all, not on the page load neither normally.

I want some experts to help me out, Thanks in advance.

答:
For Bootstrap 4, this is currently how to get rid of it:

```<code>$(function() {
    $("#element").popover('show');

    $("#element").on('click', function () {
        $("#element").popover('dispose');
    });
 });
</code>```

see documentation here

Body:
I want to make bootstrap popover should appears once on the page load over a button (just to use it as an instruction) and after clicking the button it should get destroyed.

I want to popover on the button and gets user's attention every time they visit my page and drag their attention to click on it if they are new visitors.

I have made following code, the popovers appears on the page load but it works just like normal popover afterwards it doesn't get destroyed when i click button.

HTML:

Hello World

Click on button to see Popover

            <button type="button" id="example" class="btn btn-primary" rel="popover"
                data-content="Check this new option when you visit our website to catch the latest news!"
                data-original-title="This is new feature">pop
            </button>

JS:

function destroyNew(){
    $('#example').popover('destroy');
}

$(window).load(function () {
    $("#example").popover('show');
});

I have also modified the JS and tried in this way:

JS:

$("#example").on('click', function () {
        $('#example').popover('destroy');
    }
});

$(window).load(function () {
        $("#example").popover('show');
});

The above code doesn't make the popover at all, not on the page load neither normally.

I want some experts to help me out, Thanks in advance.

Body:
For Bootstrap 4, this is currently how to get rid of it:

$(function() {
    $("#element").popover('show');

    $("#element").on('click', function () {
        $("#element").popover('dispose');
    });
 });

see documentation here


问:
Duplicate last value when I use implode()
I am facing a problem with php implode() function. It is strangely duplicating the last element if the array. Here is an example to explain better:

```<code>$arr = array('One', 'Two');

// Then...
$str = implode(' - ', $arr);

// Outputs: One - Two - Two
</code>```

No element has been added to or removed from the array. I tried array_unique but there are only unique elements.

Thanks in advance.

Edited

Here is a bit of my code:

```<code>(isset($this->_title)) OR $this->_title = $this->__guess_title();
// Here $this->_title = 'Welcome'

(is_array($this->_title)) OR $this->_title = array($this->_title);
// Now $this->_title = array('Welcome')

$this->_title = apply_filters('the_title', $this->_title);
// The filter added site name, so the title array is
// array('Welcome', 'SiteName')

// $this->_title_sep = ' - ';
$this->_title = implode($this->_title_sep, $this->_title);

return $this->_title;
// Outputs: Welcome - SiteName - SiteName
</code>```

Here is how I added the filter:

```<code>// $title is an array, so I add site_name to it and return it.
add_filter('the_title', function( $title ) {
    $title[] = option('site_name');
    return $title;
});
</code>```

Here is the array, and Here is after implode (screenshots).

答:
```<code><?php
$arr = array('One', 'Two');
$str = implode(' - ', $arr);
echo $str;
?>

//Output is -> One - Two

The code works perfect and it doesn't display "One - Two - Two". I have tested it also and there's no duplicate for the last element.
</code>```

Body:
I am facing a problem with php implode() function. It is strangely duplicating the last element if the array. Here is an example to explain better:

$arr = array('One', 'Two');

// Then...
$str = implode(' - ', $arr);

// Outputs: One - Two - Two

No element has been added to or removed from the array. I tried array_unique but there are only unique elements.

Thanks in advance.

Edited

Here is a bit of my code:

(isset($this->_title)) OR $this->_title = $this->__guess_title();
// Here $this->_title = 'Welcome'

(is_array($this->_title)) OR $this->_title = array($this->_title);
// Now $this->_title = array('Welcome')

$this->_title = apply_filters('the_title', $this->_title);
// The filter added site name, so the title array is
// array('Welcome', 'SiteName')

// $this->_title_sep = ' - ';
$this->_title = implode($this->_title_sep, $this->_title);

return $this->_title;
// Outputs: Welcome - SiteName - SiteName

Here is how I added the filter:

// $title is an array, so I add site_name to it and return it.
add_filter('the_title', function( $title ) {
    $title[] = option('site_name');
    return $title;
});

Here is the array, and Here is after implode (screenshots).


问:
Access nested Select query get the a row with a max value
I have two tables and need to create a query that lists all of the first table and a field from a second table where a second field in the second table is a maximum value.

```<code>Table1
MatID | MatCode | Name |
-----------------------
1     | A       | Ex1  |
2     | B       | Ex2  |
3     | C       | Ex3  |

Table 2
MatID | MatCode | OtherName | Count |
------------------------------------
1     | A       | Red       | 5     |
1     | A       | Blue      | 15    |
1     | A       | Green     | 2     |
2     | B       | Red       | 25    |
2     | B       | Blue      | 3     |
2     | B       | Green     | 1     |
3     | C       | Red       | 2     |
3     | C       | Blue      | 3     |
3     | C       | Green     | 11    |
</code>```

The Result would be

```<code>MatID | MatCode | Name | OtherName |
-----------------------------------
1     | A       | Ex1  | Blue
2     | B       | Ex2  | Red
3     | C       | Ex3  | Green
</code>```

Hope this is clear.

Thanks in Advance

答:
Try:  </p>

```<code>SELECT Z.MatID, Z.MatCode, Z.Name, C.OtherName
FROM
(SELECT A.MatID, A.MatCode, A.Name, MAX(Count) as Max_Count
FROM
Table1 A INNER JOIN table2 B
ON A.MatID = B.MatID AND A.MatCode = B.MatCode
GROUP BY A.MatID, A.MatCode, A.Name ) Z
INNER JOIN Table2 C
ON Z.MatID = C.MatID AND Z.MatCode = C.MatCode AND Z.Max_Count = C.Count;
</code>```

Body:
I have two tables and need to create a query that lists all of the first table and a field from a second table where a second field in the second table is a maximum value.

Table1
MatID | MatCode | Name |
-----------------------
1     | A       | Ex1  |
2     | B       | Ex2  |
3     | C       | Ex3  |

Table 2
MatID | MatCode | OtherName | Count |
------------------------------------
1     | A       | Red       | 5     |
1     | A       | Blue      | 15    |
1     | A       | Green     | 2     |
2     | B       | Red       | 25    |
2     | B       | Blue      | 3     |
2     | B       | Green     | 1     |
3     | C       | Red       | 2     |
3     | C       | Blue      | 3     |
3     | C       | Green     | 11    |

The Result would be

MatID | MatCode | Name | OtherName |
-----------------------------------
1     | A       | Ex1  | Blue
2     | B       | Ex2  | Red
3     | C       | Ex3  | Green

Hope this is clear.

Thanks in Advance

Body:
Try:

SELECT Z.MatID, Z.MatCode, Z.Name, C.OtherName
FROM
(SELECT A.MatID, A.MatCode, A.Name, MAX(Count) as Max_Count
FROM
Table1 A INNER JOIN table2 B
ON A.MatID = B.MatID AND A.MatCode = B.MatCode
GROUP BY A.MatID, A.MatCode, A.Name ) Z
INNER JOIN Table2 C
ON Z.MatID = C.MatID AND Z.MatCode = C.MatCode AND Z.Max_Count = C.Count;


问:
Java: StringIndexOutOfBoundsException
I'm getting StringIndexOutOfBoundsException:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 3, end 4, length 3
      at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3116)
      at java.base/java.lang.String.substring(String.java:1885)
      at ReadZILLA.main(Main.java:26)

from the following code:

```<code>import java.io.*;
import java.text.*;

class ReadZILLA {

public static void main(String[] args) throws IOException {
    int vowel = 0;
    int words = 0;
    int line = 10;
    int line_no = 11-line;
    int n = 1;
    String a = "a";
    String e = "e";
    String i = "i";
    String o = "o";
    String u = "u";
    String A = "A";
    String E = "E";
    String I = "I";
    String O = "O";
    String U = "U";
    String space = " ";
    BufferedReader in_text = new BufferedReader(new InputStreamReader(System.in));
    String text = in_text.readLine();

    while(line > 1){
        String char_def = text.substring(n-1,n);
        System.out.println(char_def);

        if (char_def == a || char_def == e || char_def == i || char_def == o || char_def == u || char_def == A || char_def == E || char_def == I|| char_def == O || char_def == U){
            vowel = vowel + 1;
        } else if (char_def == space){
            words = words +1;
        } else if (char_def == "\n"){
            System.out.println ("Numbers of vowels: " + vowel + "in line " + line_no);
            vowel = 0;
            line = line-1;

        }

        n = n +1;

    }

    int words_avg = words/10;
    System.out.println("Number of words: " + words);
    System.out.println("Average number of words: " + words_avg);

}
</code>```

The program is called ReadZILLA and it's supposed to output the numbers of vowels, words and average words in a line from the input.
E.G input: tHe DoG is BrOWN /n thE cat IS rED
output: vowels: 8, words: 8, average words per line: 4

答:
Let's try to understand the problem. In order to do that, first you need to understand what is StringIndexOutOfBoundsException.

StringIndexOutOfBoundsException: "Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string."

So, you are trying to reach some index that is higher than size of the chars in it or negative.

Also if you want to reach character n you should give index=n-1.

Your exception says that you are trying to access characters between 3 and 4 but length is 3.

Here:

```<code>Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 3, end 4, length 3
</code>```

So, you have to add if statement that checks if increased n once more or continue with next line.

Title: Java: StringIndexOutOfBoundsException

Body:
I'm getting StringIndexOutOfBoundsException:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 3, end 4, length 3
      at java.base/java.lang.String.checkBoundsBeginEnd(String.java:3116)
      at java.base/java.lang.String.substring(String.java:1885)
      at ReadZILLA.main(Main.java:26)

from the following code:

import java.io.*;
import java.text.*;

class ReadZILLA {

public static void main(String[] args) throws IOException {
    int vowel = 0;
    int words = 0;
    int line = 10;
    int line_no = 11-line;
    int n = 1;
    String a = "a";
    String e = "e";
    String i = "i";
    String o = "o";
    String u = "u";
    String A = "A";
    String E = "E";
    String I = "I";
    String O = "O";
    String U = "U";
    String space = " ";
    BufferedReader in_text = new BufferedReader(new InputStreamReader(System.in));
    String text = in_text.readLine();

    while(line > 1){
        String char_def = text.substring(n-1,n);
        System.out.println(char_def);

        if (char_def == a || char_def == e || char_def == i || char_def == o || char_def == u || char_def == A || char_def == E || char_def == I|| char_def == O || char_def == U){
            vowel = vowel + 1;
        } else if (char_def == space){
            words = words +1;
        } else if (char_def == "\n"){
            System.out.println ("Numbers of vowels: " + vowel + "in line " + line_no);
            vowel = 0;
            line = line-1;

        }

        n = n +1;

    }

    int words_avg = words/10;
    System.out.println("Number of words: " + words);
    System.out.println("Average number of words: " + words_avg);

}

The program is called ReadZILLA and it's supposed to output the numbers of vowels, words and average words in a line from the input.
E.G input: tHe DoG is BrOWN /n thE cat IS rED
output: vowels: 8, words: 8, average words per line: 4

Body:
Let's try to understand the problem. In order to do that, first you need to understand what is StringIndexOutOfBoundsException.

StringIndexOutOfBoundsException: "Thrown by String methods to indicate that an index is either negative or greater than the size of the string. For some methods such as the charAt method, this exception also is thrown when the index is equal to the size of the string."

So, you are trying to reach some index that is higher than size of the chars in it or negative.

Also if you want to reach character n you should give index=n-1.

Your exception says that you are trying to access characters between 3 and 4 but length is 3.

Here:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: begin 3, end 4, length 3

So, you have to add if statement that checks if increased n once more or continue with next line.


问:
Best way to upgrade an Angular 2.0.0-rc.4 application
I have recently started on a project that is on Angular 2.0.0-rc.4 For some reason it was not upgraded in time. I don't find enough help online.

What would be the best approach to upgrade this kind of project.
I was think of doing it in increments RC4 to RC5 (because there is some help on this), then 2 final and then 4.

Ultimate goal is to upgrade to latest Angular version.
Any links or docs would be highly appreciated.

答: Have you tried the upgrade tool? https://angular-update-guide.firebaseapp.com/</p>


问:
Cassandra cqlsh - connection refused
I've just started working with Cassandra (datastax), version 2.1.3 and cqlsh version 5.0.1.

Cassandra starts up fine and the cluster is operational instantly.

Cqlsh is not working (on any of the nodes) and emits the following error:

Connection error: ('Unable to connect to any servers', {'127.0.0.1': error(111,
  "Tried connecting to [('127.0.0.1', 9042)]. Last error: Connection refused")})

I have tried starting cqlsh up with the hosts own ip, other hosts ip, different ports yet the result remains the same - always connection refused.

答:
Look for native_transport_port in /etc/cassandra/cassandra.yaml
The default is 9842.

```<code>native_transport_port: 9842
</code>```

For connecting to localhost with cqlsh, this port worked for me.

cqlsh 127.0.0.1 9842

Title: Cassandra cqlsh - connection refused

Body:
Look for native_transport_port in /etc/cassandra/cassandra.yaml
The default is 9842.

native_transport_port: 9842

For connecting to localhost with cqlsh, this port worked for me.

cqlsh 127.0.0.1 9842


问:
Docusign eSign: CreateEnvelope requests timing out
We've been having issues sending certain Docusign envelopes lately, specifically those with large file sizes.

The errors we've been getting are:

```<code>Error calling CreateEnvelope: The operation has timed out
</code>```

And

```<code>The request was aborted: The request was canceled.
</code>```

No inner exception with any additional information in either case.

These errors only occur on our production server; on my local development machine everything works fine, so I can only assume that this is a connectivity issue; that there simply isn't enough time to send the supplied data over the available connection before something times out. What I would like to know is, what is the something that's timing out? Are these errors coming from my end, or Docusign's? If the former, is there any way to increase the timeout? I've got my HTTP execution timeout set to 300 seconds:

```<code><httpRuntime maxRequestLength="30000" requestValidationMode="4.0" executionTimeout="300" targetFramework="4.5" />
</code>```

... but that doesn't seem to affect anything, it always seems to time out at the default 1 minute 50 seconds.

Is there anything more I can do to prevent these requests from timing out?

Thanks,

Adam

答:
Our issue has been resolved. The timeouts were indeed being caused by something on our end; there is a "Timeout" property which can be set against the EnvelopesApi object before sending; it can also be passed into the constructor when declared. So our fix was as simple as:

```<code>EnvelopesApi envelopesApi = new EnvelopesApi();
envelopesApi.Configuration.Timeout = DocusignTimeout;
</code>```

The crux of our issue was that the Timeout property was not exposed in older versions of eSign. We had upgraded to 2.1.0 (the current version) earlier this week, but something must not have taken, as the metadata still showed our DocuSign.eSign.Client.Configuration class at version 15.4.0.0. Uninstalling the reinstalling eSign and RestSharp packages from NuGet gave us the correct version of this class, and enabled us to set our own timeout.

Hope this is helpful!

Body:
We've been having issues sending certain Docusign envelopes lately, specifically those with large file sizes.

The errors we've been getting are:

Error calling CreateEnvelope: The operation has timed out

And

The request was aborted: The request was canceled.

No inner exception with any additional information in either case.

These errors only occur on our production server; on my local development machine everything works fine, so I can only assume that this is a connectivity issue; that there simply isn't enough time to send the supplied data over the available connection before something times out. What I would like to know is, what is the something that's timing out? Are these errors coming from my end, or Docusign's? If the former, is there any way to increase the timeout? I've got my HTTP execution timeout set to 300 seconds:

<httpRuntime maxRequestLength="30000" requestValidationMode="4.0" executionTimeout="300" targetFramework="4.5" />

... but that doesn't seem to affect anything, it always seems to time out at the default 1 minute 50 seconds.

Is there anything more I can do to prevent these requests from timing out?

Thanks,

Adam

Body:
Our issue has been resolved. The timeouts were indeed being caused by something on our end; there is a "Timeout" property which can be set against the EnvelopesApi object before sending; it can also be passed into the constructor when declared. So our fix was as simple as:

EnvelopesApi envelopesApi = new EnvelopesApi();
envelopesApi.Configuration.Timeout = DocusignTimeout;

The crux of our issue was that the Timeout property was not exposed in older versions of eSign. We had upgraded to 2.1.0 (the current version) earlier this week, but something must not have taken, as the metadata still showed our DocuSign.eSign.Client.Configuration class at version 15.4.0.0. Uninstalling the reinstalling eSign and RestSharp packages from NuGet gave us the correct version of this class, and enabled us to set our own timeout.

Hope this is helpful!


问:
redeploying a .NET assembly that contains CLR stored procedures
I have written a CLR stored procedure that is in an assembly.

I have a build system that can auto-build and deploy .net application from our source control repository.

I want the two things to work together so I can redeploy the assembly that hosts the CLR stored proc.

However it looks like, unlike IIS, simply replacing the binaries doesn't work. It seems like you have to DROP ASSEMBLY on the database. In order to do that you need to drop all the objects that reference that assembly.

That seems reasonable in one way -- i.e., from a database integrity point of view-- and unreasonable in another -- the JIT approach that applies for runtime evaluation of dependencies for .NET in general.

So, is it possible to do something so I can replace the binary then give SQL server a kick and make it figure out that the new assembly satisfies all the requirements (i.e., has the right public namespaces, types, methods etc to satisfy the sprocs that are bound to it).

答:
I agree with what AlexS suggested except the last sentence.

First off, reflection will not truly work as the datatypes used in the CLR functions do not necessarily determine the SQL datatypes.  For example, you could have SqlString on the CLR side but use NVARCHAR(50) or NVARCHAR(MAX) instead of NVARCHAR(4000) on the SQL side.

However, it is still possible to automate this.  You should be using the source code repository to be storing the Stored Proc and Function definitions that point to the CLR code, just as you would any Stored Proc or Function.  So you could grab all of those definitions and run all of the CREATE PROCEDURE and CREATE FUNCTION statements as Step 4.

Also, Steps 1 and 2 can be a single SQL script.

Essentially, this entire process can be automated :).


问:
How would I get the value out of an ID a dynamically created div?
I'm trying to get the value (or find a better way) to get the value out of a div that I'm creating dynamically, my goal is to get the homeId and awayId out of the inputs so that I can use them in the ajax call below. Any help would be greatly appreciated. Is there a good/better way to use the variables from above in my click function below? </p>

```<code>getGames().done(function(results){
        $.each(results, function (i, gameData){
            $.each(gameData, function(key, game){

                var gamesHome = game.home_team_conference;
                var gamesAway = game.away_team_conference;

                if(gamesHome == "Big Ten" || gamesAway == "Big Ten"){

                    var gameId = game.id;
                    var homeTeam = game.home_team;
                    var awayTeam = game.away_team;
                    var pointTotal = game.total_points_bet;
                    var gameTime = game.game_time_hour;
                    var gameDate = game.game_time_date;
                    var homeId = game.home_team_id;
                    var awayId = game.away_team_id;
                    var network = game.broadcast_network;
                    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var hueTwo = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';

                $('.wrapper').append('\
                    <div id="'+ gameId +'" class="main-wrapper col-lg-6 col-md-6 col-sm-12">\
                    <div class="game-cards">\
                    <div class="chart-container">\
                    <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\
                    </div>\
                    <div class="right-info">\
                    <h4>' + awayTeam + '<br>' + " @ " + '<br>' + homeTeam +'</h4>\
                    <h5 id="time-channel">'+ gameDate +' @ ' + gameTime  + '<br>' + ' On ' + network +'</h5>\
                    <div class="total-points-live">\
                    <h5>Total Points Bet</h5>\
                    <h5 id="point-total">'+ pointTotal +'</h5>\
                    <p>'+ awayTeam +'</p>\
                    <input class="bet-input-away" data-away-id="'+ awayId +'" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\
                    <p>'+ homeTeam +'</p>\
                    <input class="bet-input-home" data-home-id="'+ homeId +'" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\
                    <p class="bet-button" gameid="'+ gameId +'">Click To Place Bet</p>\
                    </div>\
                    </div>\
                    </div>\
                    ');

                }

            });

        });
    });
    // This is the click function that sends the bet to the server.
    $('.wrapper').on('click', '.bet-button', function() {
        debugger;
        var self = $(this);
        var gameId = self.attr('gameid');
        var awayVal = $('#' + gameId + ' input[name=betAmountAway]').val();
        var homeVal = $('#' + gameId + ' input[name=betAmountHome]').val();
        var awayId = $('#' + gameId + '.bet-input-away').attr('data-away-id');
        var homeId = $('#' + gameId + '.bet-input-home').attr('data-home-id');

        // var awayId = $('.bet-input-away').attr();
        // var homeId = $('.bet-input-home').attr(homeId);

        // This is what sends the bet to the server.
        $.ajax({
              url: "https://--------.islandshore.net/dbdata/bet/new/1/"+ gameId +"/"+ homeId +"/"+ homeVal +"",
              type: "get",
              success: function(response) {
                $('#' + gameId + ' input[name=betAmountHome]').val(''); //This resets the value box
                $('#' + gameId + ' input[name=betAmountAway]').val(''); //This resets the value box
              },
              error: function(xhr) {
                console.log('xhr')
              }
        });

        console.log(awayId);
        console.log(homeId);
        console.log(gameId);
        console.log(homeVal);
        console.log(awayVal);
    });
</code>```

<p>So far what is working is the awayVal and the homeVal, but I can't seem to get the homeId or awayId to work. </p>

答:
You are missing spaces in 2 selectors. The difference of which means you are looking for a single element with that id and that class vs looking for the class somewhere inside the element with the id

```<code>var awayId = $('#' + gameId + ' .bet-input-away').attr('data-away-id');
var homeId = $('#' + gameId + ' .bet-input-home').attr('data-home-id');
                            // ^^ add spaces
</code>```

Instead of doing repetitive $('#' + gameId + ... store a reference once to the wrapper element and use find() for all the other elements

```<code>var $wrapper = $('#' + gameId);
// find() example
var awayId = $wrapper.find('.bet-input-away').attr('data-away-id');
</code>```

Body:
I'm trying to get the value (or find a better way) to get the value out of a div that I'm creating dynamically, my goal is to get the homeId and awayId out of the inputs so that I can use them in the ajax call below. Any help would be greatly appreciated. Is there a good/better way to use the variables from above in my click function below?

getGames().done(function(results){
        $.each(results, function (i, gameData){
            $.each(gameData, function(key, game){

                var gamesHome = game.home_team_conference;
                var gamesAway = game.away_team_conference;

                if(gamesHome == "Big Ten" || gamesAway == "Big Ten"){

                    var gameId = game.id;
                    var homeTeam = game.home_team;
                    var awayTeam = game.away_team;
                    var pointTotal = game.total_points_bet;
                    var gameTime = game.game_time_hour;
                    var gameDate = game.game_time_date;
                    var homeId = game.home_team_id;
                    var awayId = game.away_team_id;
                    var network = game.broadcast_network;
                    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
                    var hueTwo = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';

                $('.wrapper').append('\

\

\

\
                    <canvas id="'+ homeTeam +'" width="500" height="500"></canvas>\

\

\

' + awayTeam + '
' + " @ " + '
' + homeTeam +'
\

'+ gameDate +' @ ' + gameTime  + '
' + ' On ' + network +'
\

\

Total Points Bet
\

'+ pointTotal +'
\

'+ awayTeam +'
\
                    <input class="bet-input-away" data-away-id="'+ awayId +'" data-team-type="'+ awayTeam +'" type="number" pattern="[0-9]*" name="betAmountAway" placeholder="Wager Amount">\

'+ homeTeam +'
\
                    <input class="bet-input-home" data-home-id="'+ homeId +'" data-team-type="'+ homeTeam +'" type="number" pattern="[0-9]*" name="betAmountHome" placeholder="Wager Amount">\

Click To Place Bet
\

\

\

\
                    ');

                }

            });

        });
    });
    // This is the click function that sends the bet to the server.
    $('.wrapper').on('click', '.bet-button', function() {
        debugger;
        var self = $(this);
        var gameId = self.attr('gameid');
        var awayVal = $('#' + gameId + ' input[name=betAmountAway]').val();
        var homeVal = $('#' + gameId + ' input[name=betAmountHome]').val();
        var awayId = $('#' + gameId + '.bet-input-away').attr('data-away-id');
        var homeId = $('#' + gameId + '.bet-input-home').attr('data-home-id');

        // var awayId = $('.bet-input-away').attr();
        // var homeId = $('.bet-input-home').attr(homeId);

        // This is what sends the bet to the server.
        $.ajax({
              url: "https://--------.islandshore.net/dbdata/bet/new/1/"+ gameId +"/"+ homeId +"/"+ homeVal +"",
              type: "get",
              success: function(response) {
                $('#' + gameId + ' input[name=betAmountHome]').val(''); //This resets the value box
                $('#' + gameId + ' input[name=betAmountAway]').val(''); //This resets the value box
              },
              error: function(xhr) {
                console.log('xhr')
              }
        });

        console.log(awayId);
        console.log(homeId);
        console.log(gameId);
        console.log(homeVal);
        console.log(awayVal);
    });

So far what is working is the awayVal and the homeVal, but I can't seem to get the homeId or awayId to work.

Body:
You are missing spaces in 2 selectors. The difference of which means you are looking for a single element with that id and that class vs looking for the class somewhere inside the element with the id

var awayId = $('#' + gameId + ' .bet-input-away').attr('data-away-id');
var homeId = $('#' + gameId + ' .bet-input-home').attr('data-home-id');
                            // ^^ add spaces

Instead of doing repetitive $('#' + gameId + ... store a reference once to the wrapper element and use find() for all the other elements

var $wrapper = $('#' + gameId);
// find() example
var awayId = $wrapper.find('.bet-input-away').attr('data-away-id');


问:
Advice on Implementing a simple Delete button in Swing
So my issue that I have is implementing a functioning delete button for my GUI.
While I have just about everything working, I have been stumped with trying to implement this function. What it does is as i click the 'Add' button, it creates a row with text fields  and a check box. The 'Delete' works in the sense that it only deletes the most recent field create once I click on the checkbox to delete it. My intention is that the GUI works in a dynamic way to where I can click whatever check boxes and delete only those specific rows with the boxes checked.
I've researched methods of using an ItemListener but I'm still wrestling with that as I figure its the most proficient way to go. I've also done the storing the components in an array to iterate over. I feel I'm close with what I have now, any advice appreciated.

Below is the 'Add' button code to create new rows in my GUI. Then there is the 'Delete' button code which places the components in an array, but only deletes the most recent row created that has been checked.

```<code>add = new JButton("Add");
 add.addActionListener(e ->{
      rowPanel = new JPanel(new GridLayout(1,4,5,5));
     for(int i = 0; i < 4; i++ ){

         rowPanel.add(new JTextField(8));
     }
     for(int l=0; l < 1; l++){
         rowPanel.add(new JCheckBox(), BorderLayout.EAST);

     }

     infoPanel.add(rowPanel);
     infoPanel.revalidate();
     infoPanel.repaint();

 });

 delete = new JButton("Delete");
 delete.addActionListener(e -> {
     Component[] components = rowPanel.getComponents();
     for(Component c : components){
         if(c instanceof JCheckBox){
             if(((JCheckBox)c).isSelected()){
             infoPanel.remove(rowPanel);
            }
         }
     }

     infoPanel.revalidate();
     infoPanel.repaint();

 });
</code>```

答:
You can use a JTable as a container and add a custom row that is a checkbox and a textfield. This way you just have to get the checkbox's event and see what index in the JTable it is located and delete it.

This might be useful:
https://docs.oracle.com/javase/tutorial/uiswing/components/table.html#editrender

Body:
So my issue that I have is implementing a functioning delete button for my GUI.
While I have just about everything working, I have been stumped with trying to implement this function. What it does is as i click the 'Add' button, it creates a row with text fields  and a check box. The 'Delete' works in the sense that it only deletes the most recent field create once I click on the checkbox to delete it. My intention is that the GUI works in a dynamic way to where I can click whatever check boxes and delete only those specific rows with the boxes checked.
I've researched methods of using an ItemListener but I'm still wrestling with that as I figure its the most proficient way to go. I've also done the storing the components in an array to iterate over. I feel I'm close with what I have now, any advice appreciated.

Below is the 'Add' button code to create new rows in my GUI. Then there is the 'Delete' button code which places the components in an array, but only deletes the most recent row created that has been checked.

add = new JButton("Add");
 add.addActionListener(e ->{
      rowPanel = new JPanel(new GridLayout(1,4,5,5));
     for(int i = 0; i < 4; i++ ){

         rowPanel.add(new JTextField(8));
     }
     for(int l=0; l < 1; l++){
         rowPanel.add(new JCheckBox(), BorderLayout.EAST);

     }

     infoPanel.add(rowPanel);
     infoPanel.revalidate();
     infoPanel.repaint();

 });

 delete = new JButton("Delete");
 delete.addActionListener(e -> {
     Component[] components = rowPanel.getComponents();
     for(Component c : components){
         if(c instanceof JCheckBox){
             if(((JCheckBox)c).isSelected()){
             infoPanel.remove(rowPanel);
            }
         }
     }

     infoPanel.revalidate();
     infoPanel.repaint();

 });


问:
How to bypass getIntent() and getStringExtra() when running MainActivity for the first time
I am having an issue where the following code is causing my app to crash.

```<code>super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
final String years = intent.getStringExtra(MenuActivity.yearsMessage);
final String rate = intent.getStringExtra(MenuActivity.rateMessage);
</code>```

If it is the first time opening my app, the blank values that come from the getStringExtra() commands cause the app to crash when they are called later in the code.

```<code>double rate = Double.parseDouble(rateString);
double years = Double.parseDouble(yearsString);
double outFloat = inFloat * Math.pow((1f + rate), years);
return df2.format(outFloat);
</code>```

Does anyone know a way that I can declare the default values for the getStringExtra method when it is the first time opening the App?

答:
You can check when there is an extra available,  try this way:

```<code>if (intent.hasExtra("years") && intent.hasExtra("rate")){
  final String years = intent.getStringExtra("years");
  final String rate = intent.getStringExtra("rate");
}
</code>```

Intent - hasExtra

Don't forget that you have to send the data using key/value parameter in your intent, like this:

```<code>Intent intent = new Intent(this,YourActivity.class);
intent.putExtra("years", yearsMessage);
intent.putEtra("rate", ratesMessage);
startActivity(intent);
</code>```

Body:
I am having an issue where the following code is causing my app to crash.

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
final String years = intent.getStringExtra(MenuActivity.yearsMessage);
final String rate = intent.getStringExtra(MenuActivity.rateMessage);

If it is the first time opening my app, the blank values that come from the getStringExtra() commands cause the app to crash when they are called later in the code.

double rate = Double.parseDouble(rateString);
double years = Double.parseDouble(yearsString);
double outFloat = inFloat * Math.pow((1f + rate), years);
return df2.format(outFloat);

Does anyone know a way that I can declare the default values for the getStringExtra method when it is the first time opening the App?

Body:
You can check when there is an extra available,  try this way:

if (intent.hasExtra("years") && intent.hasExtra("rate")){
  final String years = intent.getStringExtra("years");
  final String rate = intent.getStringExtra("rate");
}

Intent - hasExtra

Don't forget that you have to send the data using key/value parameter in your intent, like this:

Intent intent = new Intent(this,YourActivity.class);
intent.putExtra("years", yearsMessage);
intent.putEtra("rate", ratesMessage);
startActivity(intent);


答: I thinkYour syntax for receiving the strings from the other activity is faulty. Replace the menuactivity.yearsmessage with a key that you assigned in the putExtra on the sending activity</p>

Title: How to bypass getIntent() and getStringExtra() when running MainActivity for the first time


问:
ASP-MVC: Object Instance Lost When Redirecting After Authorizing
I have an "Authorize" attribute on the Action that binds the form data.

If the user submits the form but is not authorized, the login prompt appears. Once logged in, the user is properly redirected, but the model is null.

How to handle this?

答: This is always a problem, and is going to require you to jump through many hoops to keep this state.  You can always double store the model in Session and ViewState, that way if the user comes from a place that has a null model you can look for it in the Session. </p>

OwnerDisplayName: zsharp

LastEditorDisplayName: Fabian Steeg

OwnerDisplayName: Nick Berardi


问:
C struct and malloc problem (C)
It's amazing how even the littlest program can cause so much trouble in C.

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

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}
</code>```

The compiler says:

```<code>main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token
</code>```

Can you please help?

答: Change (tree*) and (node*) to (struct tree*) and (struct node*). You can't just say tree because that's also a variable.

Title: C struct and malloc problem (C)

Body:
It's amazing how even the littlest program can cause so much trouble in C.

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

typedef struct node {
    int value;
    struct node *leftChild;
    struct node *rightChild;
} node;

typedef struct tree {
    int numNodes;
    struct node** nodes;
} tree;

tree *initTree() {
    tree* tree = (tree*) malloc(sizeof(tree));
    node *node = (node*) malloc(sizeof(node));
    tree->nodes[0] = node;
    return tree;
}

int main() {
    return 0;
}

The compiler says:

main.c: In function 'initTree':
main.c:17: error: expected expression before ')' token
main.c:18: error: expected expression before ')' token

Can you please help?


问:
Singleton Piece for Settings
I've been having a ton of fun using Apostrophe, and I recently ran into a question about the best way to set up some site-wide settings. Is there a way to create a singleton object of some sort, that would function like a piece but only have a single instance?

I'm asking because I'm looking for a way to store site-wide settings in an easily accessible and editable way. Things like global banner images, contact form links that would show up on every page (on the outerLayout), etc. I'd like to be able to leverage built in Apostrophe controls for things like this (like a singleton referencing the page for contact forms, and an image with a set ratio) without having to add a separate custom page to configure these things.

Thanks!

答:
You want to be using the global doc, which can be set up to have its own schema

http://apostrophecms.org/docs/tutorials/getting-started/settings.html

Title: Singleton Piece for Settings


问:
XPath for second element with given child value?
I have to find out the second Supplier with Chicago as the city.

I have the following table created.

```<code>CREATE TABLE Tb_Supplier(
XMLColumn XML)
GO

INSERT Tb_XPathQueryTable VALUES(
    '<SuppliersList>
      <Supplier name="Joe">
        <City>Paris</City>
        <Product name="Airplane"/>
        <Product name="Milk"/>
        <Product name="TV"/>
        <Product name="Orange"/>
     </Supplier>
      <Supplier name="Herman">
        <City>Chicago</City>
        <Product name="Orange"/>
     </Supplier>
     <Supplier name="Bernstein">
        <City>Madison</City>
        <Product name="Truck"/>
        <Product name="TV"/>
      </Supplier>
     <Supplier name="Hunter">
        <City>Wausau</City>
      </Supplier>
      <Supplier name="Mayer">
        <City>Madison</City>
      </Supplier>
      <Supplier name="Rosenfeld">
        <City>Chicago</City>
        <Product name="Computer"/>
        <Product name="Book"/>
        <Product name="Truck"/>
      </Supplier>
    </SuppliersList>');
</code>```

I have to find out the second supplier with Chicago as the city.

I have tried the following code and a few variations:

```<code>SELECT XMLColumn.query('/SuppliersList/Supplier/City[text()="Chicago"]/../Supplier[2]')
FROM Tb_Supplier
</code>```

When I use the above code without the /Supplier[2] it shows both of the suppliers with Chicago.

The output is supposed to have

```<code>  <Supplier name="Rosenfeld">
    <City>Chicago</City>
    <Product name="Computer"/>
    <Product name="Book"/>
    <Product name="Truck"/>
  </Supplier>
</code>```

答:
This XPath,

```<code>(/SuppliersList/Supplier[City="Chicago"])[2]
</code>```

will select the second Supplier with "Chicago" as the City, as requested.

Body:
I have to find out the second Supplier with Chicago as the city.

I have the following table created.

CREATE TABLE Tb_Supplier(
XMLColumn XML)
GO

INSERT Tb_XPathQueryTable VALUES(
    '<SuppliersList>
      <Supplier name="Joe">
        <City>Paris</City>
        <Product name="Airplane"/>
        <Product name="Milk"/>
        <Product name="TV"/>
        <Product name="Orange"/>
     </Supplier>
      <Supplier name="Herman">
        <City>Chicago</City>
        <Product name="Orange"/>
     </Supplier>
     <Supplier name="Bernstein">
        <City>Madison</City>
        <Product name="Truck"/>
        <Product name="TV"/>
      </Supplier>
     <Supplier name="Hunter">
        <City>Wausau</City>
      </Supplier>
      <Supplier name="Mayer">
        <City>Madison</City>
      </Supplier>
      <Supplier name="Rosenfeld">
        <City>Chicago</City>
        <Product name="Computer"/>
        <Product name="Book"/>
        <Product name="Truck"/>
      </Supplier>
    </SuppliersList>');

I have to find out the second supplier with Chicago as the city.

I have tried the following code and a few variations:

SELECT XMLColumn.query('/SuppliersList/Supplier/City[text()="Chicago"]/../Supplier[2]')
FROM Tb_Supplier

When I use the above code without the /Supplier[2] it shows both of the suppliers with Chicago.

The output is supposed to have

  <Supplier name="Rosenfeld">
    <City>Chicago</City>
    <Product name="Computer"/>
    <Product name="Book"/>
    <Product name="Truck"/>
  </Supplier>

Body:
This XPath,

(/SuppliersList/Supplier[City="Chicago"])[2]

will select the second Supplier with "Chicago" as the City, as requested.


问:
Is it possible to program iPhone in C++
I'm all for language diversity, but Objective C is insane. So I'm curious: is it possible to code iPhone apps with C++ while using the Cocoa API, etc?</p>

答:
You have to use Objective C to interface with the Cocoa API, so there is no choice. Of course, you can use as much C++ as you like behind the scenes (Objective C++ makes this easy).

It is an insane language indeed, but it's also... kind of fun to use once you're a bit used to it. :-)

OwnerDisplayName: nesteruk

Title: Is it possible to program iPhone in C++

LastEditorDisplayName: Ned Batchelder


问:
Is it possible to send additional HTTP headers to web services via New-WebServiceProxy
A web service I need to interact with (often manually for testing) requires an extra HTTP header on certain requests. Quick manual testing works quite great with PowerShell's New-WebServiceProxy but so far I haven't found an option to add another HTTP header to the request.

Is there something for that?

答:
I am surprised this hasn't come up:

```<code>$uri = 'http://...'

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Accept','Application/Json')
$headers.Add('X-My-Header','...')

$result = Invoke-WebRequest -Uri $uri -Headers $headers
</code>```

For completeness, a reference to the headers property:

https://msdn.microsoft.com/en-us/library/s4ys34ea(v=vs.110).aspx

Body:
I am surprised this hasn't come up:

$uri = 'http://...'

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Accept','Application/Json')
$headers.Add('X-My-Header','...')

$result = Invoke-WebRequest -Uri $uri -Headers $headers

For completeness, a reference to the headers property:

https://msdn.microsoft.com/en-us/library/s4ys34ea(v=vs.110).aspx


问:
Saving Tensorflow Graph and Variables while excluding Adam Optimizer Variables
I am saving a tensor flow graph and variables using :

```<code> builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
 builder.add_meta_graph_and_variables(sess, ["nn"])
 builder.save(as_text=False)
</code>```

I would like the smallest save file with which I can run classification with. Specifically I am looking to exclude Adam variables that were created during training from the save file.

When I iterate on the values returned by tf.all_variables() prior to saving, I get variables I expect like:

```<code>tf.Variable 'mymodel/fully_connected/weights:0' shape=(128, 100) dtype=float32_ref
</code>```

But also two Adam copies of the same:

```<code>tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam:0' shape=(128, 100) dtype=float32_ref

tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam_1:0' shape=(128, 100) dtype=float32_ref
</code>```

This triples the size of my checkpoint file and I am constrained by the target system. The save file will only be used for classification, not training, so I don't need Adam optimizer variables.

Any suggestions on how I can most easily not have these written to the save file?

Any other suggestions for reducing save file size while still being able to run classification are appreciated.

答:
I ended up getting things working using the following code.

I saved the graph, weights, biases, etc. like this:

```<code>  with tf.Session(graph=tf.Graph()) as sess:
    // Checkpoint of trained model that has Adam optimizer variables
    tf.saved_model.loader.load(sess, ["audio_nn"], FLAGS.checkpoint_dir)

    # Dump out checkpoint without Adam optimizer variables
    saver = tf.train.Saver(tf.model_variables())
    saver.save(sess, 'my-model')
</code>```

Fortunately tf.model_variables() returned only the variables needed for the model and not the Adam optimizer variables.

And restored for classification like this:

```<code> with tf.Session(graph=tf.Graph()) as sess:
    imported_meta = tf.train.import_meta_graph("my-model.meta")
    imported_meta.restore(sess, "my-model")

    features_tensor = sess.graph.get_tensor_by_name( params.INPUT_TENSOR_NAME)
    prediction_tensor = sess.graph.get_tensor_by_name( 'mymodel/prediction:0')

    ... prediction code ...
</code>```

The checkpoint file is now about one third the size as before.

Body:
I am saving a tensor flow graph and variables using :

 builder = tf.saved_model.builder.SavedModelBuilder(export_dir)
 builder.add_meta_graph_and_variables(sess, ["nn"])
 builder.save(as_text=False)

I would like the smallest save file with which I can run classification with. Specifically I am looking to exclude Adam variables that were created during training from the save file.

When I iterate on the values returned by tf.all_variables() prior to saving, I get variables I expect like:

tf.Variable 'mymodel/fully_connected/weights:0' shape=(128, 100) dtype=float32_ref

But also two Adam copies of the same:

tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam:0' shape=(128, 100) dtype=float32_ref

tf.Variable 'mymodel/train/mymodel/fully_connected/weights/Adam_1:0' shape=(128, 100) dtype=float32_ref

This triples the size of my checkpoint file and I am constrained by the target system. The save file will only be used for classification, not training, so I don't need Adam optimizer variables.

Any suggestions on how I can most easily not have these written to the save file?

Any other suggestions for reducing save file size while still being able to run classification are appreciated.

Body:
I ended up getting things working using the following code.

I saved the graph, weights, biases, etc. like this:

  with tf.Session(graph=tf.Graph()) as sess:
    // Checkpoint of trained model that has Adam optimizer variables
    tf.saved_model.loader.load(sess, ["audio_nn"], FLAGS.checkpoint_dir)

    # Dump out checkpoint without Adam optimizer variables
    saver = tf.train.Saver(tf.model_variables())
    saver.save(sess, 'my-model')

Fortunately tf.model_variables() returned only the variables needed for the model and not the Adam optimizer variables.

And restored for classification like this:

 with tf.Session(graph=tf.Graph()) as sess:
    imported_meta = tf.train.import_meta_graph("my-model.meta")
    imported_meta.restore(sess, "my-model")

    features_tensor = sess.graph.get_tensor_by_name( params.INPUT_TENSOR_NAME)
    prediction_tensor = sess.graph.get_tensor_by_name( 'mymodel/prediction:0')

    ... prediction code ...

The checkpoint file is now about one third the size as before.