问:
How to get the last changed table if they have the same table name and different table_PK
I want to take the last changed record for multiple TableName and display it only one time.
For some TableName I have multiple Table_Pk, for exp:

```<code>SELECT COUNT(Table_PK), TableName
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
GROUP BY TableName
HAVING COUNT(Table_PK) > 1
</code>```

result looks like:

```<code>Table_PK   TableName
   9       L0L001T03
   2       L0L001T05
   ....
</code>```

and I want to take Table_Pk, TableName once ordered by LastChanged.

Here is the code which I've tried but I get all records

```<code>SELECT  Distinct(Table_PK), TableName, LastChanged
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
ORDER BY LastChanged
</code>```

result is:

```<code>Table_Pk                            TableName            LastChanged
91A5249DB797FF4BB44579AC7D3C0949    L0L003T41             2019-05-29
7070D39FAF65674DA8537B93FFDE2371    L0L003T41             2019-05-28
......
</code>```

I should have 1153 rows but I have 2220

答:
If you only want the most recent record per table name, then you can use window function partitioning on the table name:

```<code>SELECT Table_PK, TableName, LastChanged
FROM (SELECT tt.Table_PK, tt.TableName, tt.LastChanged,
             ROW_NUMBER() OVER (PARTITION BY tt.TableName ORDER BY tt.LastChanged DESC) as seqnum
      FROM TBL_TECTABLES tt INNER JOIN
           sys.tables t
           ON 'TBL_Tec' + tt.Table_PK = t.name collate SQL_Latin1_General_CP1_CI_AS
      WHERE LEN(t.name) = 39
     ) t
WHERE seqnum = 1
ORDER BY LastChanged ;
</code>```

I added table aliases, but had to guess where the columns come from.  You may need to adjust the table aliases.

Body:
I want to take the last changed record for multiple TableName and display it only one time.
For some TableName I have multiple Table_Pk, for exp:

SELECT COUNT(Table_PK), TableName
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
GROUP BY TableName
HAVING COUNT(Table_PK) > 1

result looks like:

Table_PK   TableName
   9       L0L001T03
   2       L0L001T05
   ....

and I want to take Table_Pk, TableName once ordered by LastChanged.

Here is the code which I've tried but I get all records

SELECT  Distinct(Table_PK), TableName, LastChanged
FROM TBL_TECTABLES INNER JOIN
     sys.tables
     ON 'TBL_Tec' + Table_PK = name collate SQL_Latin1_General_CP1_CI_AS
WHERE LEN(name) = 39
ORDER BY LastChanged

result is:

Table_Pk                            TableName            LastChanged
91A5249DB797FF4BB44579AC7D3C0949    L0L003T41             2019-05-29
7070D39FAF65674DA8537B93FFDE2371    L0L003T41             2019-05-28
......

I should have 1153 rows but I have 2220

Body:
If you only want the most recent record per table name, then you can use window function partitioning on the table name:

SELECT Table_PK, TableName, LastChanged
FROM (SELECT tt.Table_PK, tt.TableName, tt.LastChanged,
             ROW_NUMBER() OVER (PARTITION BY tt.TableName ORDER BY tt.LastChanged DESC) as seqnum
      FROM TBL_TECTABLES tt INNER JOIN
           sys.tables t
           ON 'TBL_Tec' + tt.Table_PK = t.name collate SQL_Latin1_General_CP1_CI_AS
      WHERE LEN(t.name) = 39
     ) t
WHERE seqnum = 1
ORDER BY LastChanged ;

I added table aliases, but had to guess where the columns come from.  You may need to adjust the table aliases.


来源: stackexchange

问:
How to update the value of a key field in a dictionary in Python?
I have a dictionary as given below:

```<code>test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}
</code>```

I have written below program to retrieve keys from the dictionary:

```<code>test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():
    print(keys)
</code>```

I want to update the keys field value when we got a digit value in keys field. Example in the above dictionary

```<code>keys: 100
value: 271
</code>```

When we got keys value is an integer then I want to updates keys value like this xx_100:271

I would like to solve the problem in the simplest way possible using python.

答:
Instead of looping just keys, you need to loop both key and value to test which value is of type int. Below code does that:

```<code>test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for key,value in test.items():
    if (type(value)) == int:
        test['xx_'+str(key)]=test.pop(key)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a dictionary as given below:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

I have written below program to retrieve keys from the dictionary:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for keys in test.keys():
    print(keys)

I want to update the keys field value when we got a digit value in keys field. Example in the above dictionary

keys: 100
value: 271

When we got keys value is an integer then I want to updates keys value like this xx_100:271

I would like to solve the problem in the simplest way possible using python.

Body:
Instead of looping just keys, you need to loop both key and value to test which value is of type int. Below code does that:

test = {"100":271,"updated_at":{"date":"2017-10-14T12:15:52.172Z"},"created_at":{"date":"2017-10-14T12:15:52.172Z"}}

for key,value in test.items():
    if (type(value)) == int:
        test['xx_'+str(key)]=test.pop(key)


问:
However, while plaintext passwords are later assigned to password, this variable is never cleared from memory
defines password, which is
designated to contain user passwords. However, while plaintext passwords are later assigned to password, this
variable is never cleared from memory.

```<code>var password = ConfigurationManager.AppSettings["xyz"].ToString();
</code>```

what can i do to remove Heap Inspection for this ?

答:
You have two options to manually remove the string content from memory:

Option 1: Manual Garbage Collection

There is nothing special about the memory consumed by the string object holding the password. To remove the object from memory using manual garbage collection, remove all references to the password variable, then call System.GC.Collect().

Option 2: Use System.Security.SecureString

SecureString has a Dispose method that will release the memory consumed by the string when you are done with it. I haven't tried this myself, but you should be able to do something like this:

```<code>// Create a SecureString
SecureString password = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["xyz"].ToString())
{
    password.AppendChar(c);
}

// Use password
this.SomeMethod(password);

// Remove password
password.Dispose();
</code>```

Body:
defines password, which is
designated to contain user passwords. However, while plaintext passwords are later assigned to password, this
variable is never cleared from memory.

var password = ConfigurationManager.AppSettings["xyz"].ToString();

what can i do to remove Heap Inspection for this ?

Body:
You have two options to manually remove the string content from memory:

Option 1: Manual Garbage Collection

There is nothing special about the memory consumed by the string object holding the password. To remove the object from memory using manual garbage collection, remove all references to the password variable, then call System.GC.Collect().

Option 2: Use System.Security.SecureString

SecureString has a Dispose method that will release the memory consumed by the string when you are done with it. I haven't tried this myself, but you should be able to do something like this:

// Create a SecureString
SecureString password = new SecureString();
foreach (char c in ConfigurationManager.AppSettings["xyz"].ToString())
{
    password.AppendChar(c);
}

// Use password
this.SomeMethod(password);

// Remove password
password.Dispose();


问:
Unable to search character with string input from fgets
I'm writing a program to find the location of a certain character in a string using strchr. When using fgets to input the string from the user, the program does not execute properly.

However when using gets everything works fine.

Code that works using gets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    gets(input);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the letter %c was found at character %d\n", let, ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}
</code>```

Output:

```
what is the string that you would like to check?
what is the character that you would like to find?
in string "why is the world when wondering"...
the letter w was found at character 1
the letter w was found at character 12
the letter w was found at character 18
the letter w was found at character 23
```

Code that does not work usgin fgets():

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

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    fgets(input, 16, stdin);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the character is found at %d \n", ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}
</code>```

Output:

```
what is the string that you would like to check?
what is the character that you would like to find?
in string "abcdefghijklmno"...
```

答:
In the first code snippet the call

```<code>gets (input);
</code>```

does not restrict the number of characters the user can input. Take into account that the function gets is not supported by the C Standard and is unsafe.

In the second code snippet you declared the variable input as

```<code>char input[50];
</code>```

So it is more natural to call fgets the following way

```<code>fgets (input,sizeof( input ),stdin );
</code>```

instead of

```<code>fgets (input,16,stdin);
</code>```

The standard function getchar reads any character including white spaces.

So instead it it is much better to use

```<code>scanf( " %c", &let );
</code>```

Otherwise getchar can read any character (including for example the new line character) leaved in the input buffer. While the call of scanf will skip any white space character.

Body:
I'm writing a program to find the location of a certain character in a string using strchr. When using fgets to input the string from the user, the program does not execute properly.

However when using gets everything works fine.

Code that works using gets():

#include <stdio.h>
#include <string.h>

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    gets(input);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the letter %c was found at character %d\n", let, ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}

Output:

what is the string that you would like to check?
what is the character that you would like to find?
in string "why is the world when wondering"...
the letter w was found at character 1
the letter w was found at character 12
the letter w was found at character 18
the letter w was found at character 23

Code that does not work usgin fgets():

#include <stdio.h>
#include <string.h>

int main() {
    char let;
    char input[50];
    char *ptr;
    printf("what is the string that you would like to check?\n");
    fgets(input, 16, stdin);
    printf("what is the character that you would like to find?\n");
    let = getchar();
    printf("in string \"%s\"...\n", input);
    ptr = strchr(input, let);
    while (ptr != NULL) {
        printf("the character is found at %d \n", ptr - input + 1);
        ptr = strchr(ptr + 1, let);
    }
    return 0;
}

Output:

what is the string that you would like to check?
what is the character that you would like to find?
in string "abcdefghijklmno"...

Body:
In the first code snippet the call

gets (input);

does not restrict the number of characters the user can input. Take into account that the function gets is not supported by the C Standard and is unsafe.

In the second code snippet you declared the variable input as

char input[50];

So it is more natural to call fgets the following way

fgets (input,sizeof( input ),stdin );

instead of

fgets (input,16,stdin);

The standard function getchar reads any character including white spaces.

So instead it it is much better to use

scanf( " %c", &let );

Otherwise getchar can read any character (including for example the new line character) leaved in the input buffer. While the call of scanf will skip any white space character.


Title: Converting array of lists to array of dictionary

Body:
I have data as follows

{"array": [[1288.1639933233453], [1255.1777295971826],
[1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}

I want to convert above data as follows

[{"value": 1288.1639933233453},
{"value": 1255.1777295971826},
{"value": 1250.1075681742996},
{"value": 1283.9962801780075},
{"value": 1297.4411412000093}]

Body:
d = {"array": [[1288.1639933233453], [1255.1777295971826],
               [1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}
d = [{"value": i[0]} for i in d["array"]]
print(d)

output:

[{'value': 1288.1639933233453}, {'value': 1255.1777295971826}, {'value': 1250.1075681742996}, {'value': 1283.9962801780075}, {'value': 1297.4411412000093}]


问:
I have an error with WebDriver.dll in visual studio Chrome version must be between 70 and 73. CHROME WEB DRIVER
I have updated my chrome without thinking to much about it as I am fairly new with selenium however this has caused the following error in visual studio.

```<code>An unhandled exception of type 'System.InvalidOperationException' occurred in WebDriver.dll. Additional information: session not created: Chrome version must be between 70 and 73.
</code>```

I have tried to update the libraries but all my libraries are up to date.
Here are dose libraries and the version.

```<code>Selenium.Support 3.141.0
Selenium.Chrome.WebDriver 74.0.0
Selenium.WebDriver 3.141.0
NunitTestAdapter 2.1.1
</code>```

What can I do to fix this error without downgrading chrome. Thank you very much.

UPDATE Thanks to Dazed I found In packages.config

```<code><package id="Selenium.WebDriver.ChromeDriver" version="73.0.3683.68" targetFramework="net461" />
</code>```

And I replaced the version with my version.

```<code>  <package id="Selenium.WebDriver.ChromeDriver" version="74.0.3729.6" targetFramework="net461" />
</code>```

Also my csproj has the following lines.

```<code>    <Error Condition="!Exists('..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets'))" />
  </Target>
  <Import Project="..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets" Condition="Exists('..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets')" />
</code>```

When I replace the 73.0.3683.68 with 74.0.3729.6 I get the following error
Severity    Code    Description Project File    Line    Category    Suppression State

```<code>Error       This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Selenium.WebDriver.ChromeDriver.74.0.3729.6\build\Selenium.WebDriver.ChromeDriver.targets.    AutoFillForm    C:\Users\Junior\Desktop\columbia project\erp_columbia\erp_columbia\AutoFillForm\AutoFillForm\AutoFillForm.csproj    106
</code>```

Despite the fact the the files exists in my packages folder as you can see on this image.

答:
I was facing the same issue.
To solve the issue i did following steps:

Go to manage nuGet packages..

then go to browse tab and search the package with keyword: "Selenium.Chrome.WebDriver"
(For other browser, install corresponding package)

and then install it. (Note: if it is already installed then remove the package before installing it.)

update your chrome driver from here: http://chromedriver.chromium.org/downloads
and save it to your local machine and give the path of it into your code

For reference, you can visit my github page Google Login by selenium

Try to run my code by replacing your email id and password.

Body:
I have updated my chrome without thinking to much about it as I am fairly new with selenium however this has caused the following error in visual studio.

An unhandled exception of type 'System.InvalidOperationException' occurred in WebDriver.dll. Additional information: session not created: Chrome version must be between 70 and 73.

I have tried to update the libraries but all my libraries are up to date.
Here are dose libraries and the version.

Selenium.Support 3.141.0
Selenium.Chrome.WebDriver 74.0.0
Selenium.WebDriver 3.141.0
NunitTestAdapter 2.1.1

What can I do to fix this error without downgrading chrome. Thank you very much.

UPDATE Thanks to Dazed I found In packages.config

<package id="Selenium.WebDriver.ChromeDriver" version="73.0.3683.68" targetFramework="net461" />

And I replaced the version with my version.

  <package id="Selenium.WebDriver.ChromeDriver" version="74.0.3729.6" targetFramework="net461" />

Also my csproj has the following lines.

    <Error Condition="!Exists('..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets'))" />
  </Target>
  <Import Project="..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets" Condition="Exists('..\packages\Selenium.WebDriver.ChromeDriver.73.0.3683.68\build\Selenium.WebDriver.ChromeDriver.targets')" />

When I replace the 73.0.3683.68 with 74.0.3729.6 I get the following error
Severity    Code    Description Project File    Line    Category    Suppression State

Error       This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is ..\packages\Selenium.WebDriver.ChromeDriver.74.0.3729.6\build\Selenium.WebDriver.ChromeDriver.targets.    AutoFillForm    C:\Users\Junior\Desktop\columbia project\erp_columbia\erp_columbia\AutoFillForm\AutoFillForm\AutoFillForm.csproj    106

Despite the fact the the files exists in my packages folder as you can see on this image.


Body:
x = {"array": [[1288.1639933233453], [1255.1777295971826],
[1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}
y = [{'value' : i[0]} for i in x['array']]
print(y)


问:
CSS class can be applied manually, but JavaScript doesn't do it (Really weird problem)
I have a navbar at the top of my page, and I am able to apply the hover effect onto all my items on the bar except the one with the icon on it.

When I type the code into the terminal the CSS effect does come in but the hover effect doesn't work. Also, using any CSS pseudo selectors didn't help at all.

        Home (current)

        About

 class="nav-item dropdown">

            Portfolio

          Professional
          Personal

        Contact

```

```var par=document.querySelectorAll(".nav-link");
var partext=document.querySelectorAll(".nav-link span");

for (var j=0;j<par.length;j++){
    par[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    par[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    partext[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });
    partext[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });
```

<pre class="lang-py prettyprint-override"><code>.navlinktext{

text-decoration-color: white;
  color: white;
  font-size: 1.5rem;

}

.hoverlendin{

  background-color: lightcoral;

}
</code>```

Home, About and Portfolio items change background and text color as expected, however Contact item only changes background, the text remmains the same. What I am doing wrong?

答:
querySelectorAll count was getting mismatched due to the two spans under .nav-link in first element.

Please find the correct version of code below.

var par=document.querySelectorAll(".nav-link");
var partext=document.querySelectorAll(".nav-link span");

for (var j=0;j<par.length;j++){
    par[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    par[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    partext[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });
    partext[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });
   }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.navlinktext {
  text-decoration-color: white;
  color: white;
  font-size: 1.5rem;
}

.hoverlendin {
  background-color: lightcoral;
}</code>```

        Home
(current)

        About

            Portfolio

          Professional
          Personal

        Contact

```

Body:
I have a navbar at the top of my page, and I am able to apply the hover effect onto all my items on the bar except the one with the icon on it.

When I type the code into the terminal the CSS effect does come in but the hover effect doesn't work. Also, using any CSS pseudo selectors didn't help at all.

        Home (current)

        About

 class="nav-item dropdown">

            Portfolio

          Professional
          Personal

        Contact

var par=document.querySelectorAll(".nav-link");
var partext=document.querySelectorAll(".nav-link span");

for (var j=0;j<par.length;j++){
    par[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    par[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    partext[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });
    partext[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });

.navlinktext{

text-decoration-color: white;
  color: white;
  font-size: 1.5rem;

}

.hoverlendin{

  background-color: lightcoral;

}

Home, About and Portfolio items change background and text color as expected, however Contact item only changes background, the text remmains the same. What I am doing wrong?

Body:
querySelectorAll count was getting mismatched due to the two spans under .nav-link in first element.

Please find the correct version of code below.

var par=document.querySelectorAll(".nav-link");
var partext=document.querySelectorAll(".nav-link span");

for (var j=0;j<par.length;j++){
    par[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    par[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("hoverlendin");
    });
    partext[j].addEventListener("mouseenter",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });
    partext[j].addEventListener("mouseleave",function () {
        // this.style.backgroundColor= "red";

        this.classList.toggle("navlinktext");
    });
   }

.navlinktext {
  text-decoration-color: white;
  color: white;
  font-size: 1.5rem;
}

.hoverlendin {
  background-color: lightcoral;
}

<div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="C:\Users\Anon\Desktop\CVWebsite\cv.html"><span class="linkSpan">Home <p class="sr-only" style="display:inline-block;margin:0;">(current)</p></span> </a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="C:\Users\Anon\Desktop\CVWebsite\cvAbout.html"><span class="linkSpan">About</span></a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
            <span class="linkSpan">Portfolio</span>
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Professional</a>
          <a class="dropdown-item" href="#">Personal</a>
          <!-- <div class="dropdown-divider"></div> -->
          <!-- <a class="dropdown-item" href="#">Something else here</a> -->
         </div>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="C:\Users\Anon\Desktop\CVWebsite\cvContact.html"><span class="linkSpan"><i class="far fa-paper-plane" style="margin-right: 0.5rem;"></i>Contact</span></a>
      </li>
    </ul>
    </div>


问:
Backend not showing
I’m trying to install a copy of my live wordpress site (crafty-stuff.com) on my local system running win10 & wamp.

Have downloaded wp-content (through filezilla) and have a copy of the live database (phpmyadmin) with switched out urls(notepad++).

So the site is working OK – all content seems to be showing up at http://localhost/crafty-stuff for me, with just the nav and site banner needing a fix, but when I try to login into the backend “http://localhost/crafty-stuff/wp-login.php” I just get to my home page with a wordpress bar/taskbar on top, but with no way/link on it to get to the add posts and pages management backend area.

If I clear the database (drop all tables) and remove wp-config.php I can get to the backend OK after a fresh(to blank WordPress) install procedure.

So thinking my copy of the database is somehow wrong, for if I then drop the blank database tables and import the hosted site’s .sql (with altered urls) I again lose the backend.

Navigating to http://localhost/crafty-stuff/wp-admin/ manually when logged in, gives “Sorry, you are not allowed to access this page.” if that is the url for the backend.

Any help?

答:
Got it working – had to separate all tables in the hosted db into single import files(one for each table), do a clean blank WordPress install, and drop then import each of the tables separately until I got a problem login into the backend.

Something in wp_usermeta was the problem, so did an install of the hosted site’s full db, dropped the wp_usermeta and imported another version from a clean blank WordPress.

Not yet capable of going through the wp_usermeta to see if I can work out the problem fully.

Thanks for the help guys anyway :)

Title: Backend not showing


问:
How to download pdf just after creating it in java
i'm using java and I create a pdf file from database.
And now i want to make it download for the user automatically.
When user hit that servlet page.
here is my some code...</p>

```<code>            /* Define the SQL query */
            ResultSet rs=st.executeQuery("select Id,Name from student");
            Document my_pdf_report = new Document();
            my_pdf_report.open();
            //we have four columns in our table
            PdfPTable my_report_table = new PdfPTable(2);
            //create a cell object
            PdfPCell table_cell;
            while (rs.next()) {
                            String id = rs.getString("Id");
                            table_cell=new PdfPCell(new Phrase(id));
                            my_report_table.addCell(table_cell);
                            String name=rs.getString("Name");
                            table_cell=new PdfPCell(new Phrase(name));
                            }
            /* Attach report table to PDF */
            my_pdf_report.add(my_report_table);
            Document pdf =new Document();
            pdf=my_pdf_report;
            my_pdf_report.close();
            /* Close all DB related objects */
            rs.close();
            st.close();
            connected.close();
</code>```

答:
Here is the sample code you need to put in your servlet method to make the file downloadable. </p>

```<code>   resp.setContentType("text/plain");
            resp.setHeader("Content-disposition", "attachment; filename=sample.txt"); //use your file name to be displayed when downloaded

            try(InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt"); // location of file
              OutputStream out = resp.getOutputStream()) {

                byte[] buffer = new byte[ARBITARY_SIZE];

                int numBytesRead;
                while ((numBytesRead = in.read(buffer)) > 0) {
                    out.write(buffer, 0, numBytesRead);
                }
            }
</code>```

Body:
i'm using java and I create a pdf file from database.
And now i want to make it download for the user automatically.
When user hit that servlet page.
here is my some code...

            /* Define the SQL query */
            ResultSet rs=st.executeQuery("select Id,Name from student");
            Document my_pdf_report = new Document();
            my_pdf_report.open();
            //we have four columns in our table
            PdfPTable my_report_table = new PdfPTable(2);
            //create a cell object
            PdfPCell table_cell;
            while (rs.next()) {
                            String id = rs.getString("Id");
                            table_cell=new PdfPCell(new Phrase(id));
                            my_report_table.addCell(table_cell);
                            String name=rs.getString("Name");
                            table_cell=new PdfPCell(new Phrase(name));
                            }
            /* Attach report table to PDF */
            my_pdf_report.add(my_report_table);
            Document pdf =new Document();
            pdf=my_pdf_report;
            my_pdf_report.close();
            /* Close all DB related objects */
            rs.close();
            st.close();
            connected.close();

Body:
Here is the sample code you need to put in your servlet method to make the file downloadable.

   resp.setContentType("text/plain");
            resp.setHeader("Content-disposition", "attachment; filename=sample.txt"); //use your file name to be displayed when downloaded

            try(InputStream in = req.getServletContext().getResourceAsStream("/WEB-INF/sample.txt"); // location of file
              OutputStream out = resp.getOutputStream()) {

                byte[] buffer = new byte[ARBITARY_SIZE];

                int numBytesRead;
                while ((numBytesRead = in.read(buffer)) > 0) {
                    out.write(buffer, 0, numBytesRead);
                }
            }


问:
How to set sleep into the flow in Mulesoft without losing the message payload
I'd like insert script to delay processing flow in Mulesoft. I have tried to insert script in groovy but I lost the messagge payload, so when I have to get message payload recived null pointer.
How can I to do not lose the message payload?

Thanks

答:
In Mule 4 you should use the Runtime "wait" function. Any other alternative will block all your threads.
https://docs.mulesoft.com/mule-runtime/4.1/dw-runtime-functions-wait</p>

ContentLicense: CC BY-SA 3.0


Body:
d1 = {"array": [[1288.1639933233453], [1255.1777295971826], [1250.1075681742996], [1283.9962801780075], [1297.4411412000093]]}
vals = d1["array"]
l = []
for val in vals:
    l.append({"value": val[0]})
print(l)

[{'value': 1288.1639933233453},
 {'value': 1255.1777295971826},
 {'value': 1250.1075681742996},
 {'value': 1283.9962801780075},
 {'value': 1297.4411412000093}]


问:
Change an image when item checked in the list. Android Honeycomb
I am using array adapter with list view. When I click on an item from the list, I can change the background drawable, but I also want to change an image(from the adapter layout) of the checked item. How can I change this image?
Thanks.</p>

答:
Does that image comes from the data that is displayed? (For instance, your data has some field with a drawable?)

If so, you can change that drawable and call adapter.notifyDataSetChanged().

(I'm assuming you are confortable with android API... if you are not I can give you a  more detailed approach)

UPDATE

I've never done this but try to do something similar to this:

oldDrawable.mutate().setBackgroundDrawable(newDrawable);

Also, reading this should help you further:

http://developer.android.com/resources/articles/drawable-mutations.html


问:
How to deal with timezone to compute lag
I'm trying to compute the lag in miliseconds between my client (from France) and my server (from Germany).

Client side (Angular Typescript) :

```<code>this.http.getDate().subscribe(response => {
               if (response.type === HttpEventType.Sent) {

           const dateSent = new Date();
            const dateOffset = dateSent.getTimezoneOffset();
            const timeSent = dateSent.getTime() + dateOffset;
            console.log(timeSent);

    } else if (response instanceof HttpResponse) {

          const dateReceived = new Date(response.body.dateReceived);
          const timeReceived = dateReceived.getTime();
          console.log(timeReceived);
        }
      });
</code>```

Server side (Java) :

```<code>return new Date();
</code>```

timeSent = 1559221214039 and timeReceived = 1559221212914

Why the difference between them is -1125 miliseconds ? With the developer tool of firefox, the network says, it tooks 200ms.

Could someone tell me what I'm doing wrong ?

Thanks for helping

答:
Javascript date getTimezoneOffset() method returns the time-zone offset
  in minutes for the current locale. The time-zone offset is the minutes
  in difference, the Greenwich Mean Time (GMT) is relative to your local
  time.

For example, if your time zone is GMT+10, -600 will be returned.
  Daylight savings time prevents this value from being a constant.

https://www.tutorialspoint.com/javascript/date_gettimezoneoffset.htm

you are multiplying by 60*1000

Body:
I'm trying to compute the lag in miliseconds between my client (from France) and my server (from Germany).

Client side (Angular Typescript) :

this.http.getDate().subscribe(response => {
               if (response.type === HttpEventType.Sent) {

           const dateSent = new Date();
            const dateOffset = dateSent.getTimezoneOffset();
            const timeSent = dateSent.getTime() + dateOffset;
            console.log(timeSent);

    } else if (response instanceof HttpResponse) {

          const dateReceived = new Date(response.body.dateReceived);
          const timeReceived = dateReceived.getTime();
          console.log(timeReceived);
        }
      });

Server side (Java) :

return new Date();

timeSent = 1559221214039 and timeReceived = 1559221212914

Why the difference between them is -1125 miliseconds ? With the developer tool of firefox, the network says, it tooks 200ms.

Could someone tell me what I'm doing wrong ?

Thanks for helping


问:
Workflow for creating new Maven project in Eclipse and bringing it to Github
I want to create a new Maven project in Eclipse and push it to a new repository on github. I am a bit stuck on the right order of steps to achieve this.

To use a Maven archetype, I cannot use a directory with files in it. So I cannot create a Maven project in a git local repository. So using the archetype should probably come first.

I also need to create a repository in my github account. If I do this through the github desktop app, this already creates a local repository for me.

Now I have an Eclipse project and a local repository, up to now unrelated. How should I "relate" them?

I found a lot of information about cloning from github, but my github repository does not have a Maven project yet, so I cannot import in Eclipse. If I use command line instead and an empty directory, I cannot apply Maven archetypes any more because the directory is not empty.

I am confused. Can somebody de-confuse me?

答:
Finally, I did the following:

I created a new Maven project with an archetype in the directory for github local repositories.

I used the github app to create repository with the same name in the same directory.

Then I published this repository to github.

Now I imported the project from the github local repository to eclipse.

The workflow is generally the one suggested by @lealceldeiro, but without using the command line git.


问:
How to Execute a command through electron app
I am trying to execute a command on the click of an element in the electron app.

The code is:

```<code>function displayadbinfo(command) {
    const childProcess = require('child_process');
    alert(childProcess.execSync(command).toString());
}
</code>```

This code pops up an alert when I click on the app which is launched with npm start. However, after building the executable file, the command returns an empty response.

答:
child_process.execSync returns a buffer or a string rather than a stream, which could be causing an empty response. It waits for the child process to exit and tries to return all the buffered data at once. I suggest you to use child_process.spawn.

The difference is that child_process.spawn returns a ChildProcess object and stdout and stderr are accessible using streams rather than synchronously returned as a buffer. So, you'd be able to see the output correctly.

I am not sure if electron-builder or electron-packager might be causing issues.

You can find an article discussing the differences between spawn () and exec () here on hacksparrow.com

Body:
I am trying to execute a command on the click of an element in the electron app.

The code is:

function displayadbinfo(command) {
    const childProcess = require('child_process');
    alert(childProcess.execSync(command).toString());
}

This code pops up an alert when I click on the app which is launched with npm start. However, after building the executable file, the command returns an empty response.


问:
IIS express: Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to
In Visual studio, Solution->Web.Project->Properties->Web, I have changed my Project Url from     http://localhost:51123/ to http://localhost:51123/NewProjectName and I keep getting this error:

"Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to ...." on every module added.

Adding a remove tag works but then it should have been a problem even before i changed the url. Any suggestions?

答:
I tried all of the above methods and nothing worked for me. I was keep on getting the error something like

```<code>Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'QueryStringModule'
</code>```

At last I changed my server from

IIS Express to Local IIS in the project property build as given below.

and it worked for me.

Body:
I tried all of the above methods and nothing worked for me. I was keep on getting the error something like

Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'QueryStringModule'

At last I changed my server from

IIS Express to Local IIS in the project property build as given below.

and it worked for me.


问:
Two visible CATiledLayers causing problems!
This issue has been encountered by someone else, but I've not seen any solutions - see ( http://openradar.appspot.com/6941930 ).

I have a UIScrollView whose content view's layer contains two CATiledLayers. One tiled layer draws content quite fast (but long enough to make drawInRect: too slow!), the other draws them slowly.

The quicker CATiledLayer doesn't Zoom has has default LOD settings, with a large tile size.

The slower CATiledLayer is zoomable.

Using just one of the CATiledLayers behaves as expected.

The problem is adding both layers to the visible screen causes one or the other to behave slowly. Annoyingly, it seems to make the content that draws normally fast, much slower.

I've not seen a way yet to reliably know when one CATiledLayer has completed its draw.

I think the solution would be to queue the Tiled Layers, so draw the slower tiled layer when the quicker one has finished. But the documentation on CATiledLayer is pretty bad.

I've tried to use a NSTimer, and set it for a 3 second wait before drawing the 2nd Tiled Layer. This however does not seem to solve the problem! I'm lost!

答: CATiledLayer seems to favor any tiles near the center of the screen. Perhaps one of your layer's is closer to an edge?</p>

ContentLicense: CC BY-SA 2.5


问:
xml XPath count
I'm working on an xml and xslt project and I have a problem; the question asked is count the number of open ports having a given number this is the path used

```<code>liste_hotes --)
    hote --)
        liste_ports --)
            port num_port="80" --)
                Etat etat="open"
</code>```

```<code>count(liste_hotes/hote/liste_ports/port[@num_port='80']/Etat[@etat='open'])
</code>```

答: XML is case-sensitive: count(expression) is not the same as Count(expression), and there is no Count() function.

Title: xml XPath count

Body:
I'm working on an xml and xslt project and I have a problem; the question asked is count the number of open ports having a given number this is the path used

liste_hotes --)
    hote --)
        liste_ports --)
            port num_port="80" --)
                Etat etat="open"

count(liste_hotes/hote/liste_ports/port[@num_port='80']/Etat[@etat='open'])


问:
Given a Gtk Notebook, how does one drag and drop a page to a new window?
Just like the title says, I have a Gtk Notebook and wish to DND a notebook page onto a new window. Does anyone have an example?</p>

答:
Here is a full fledged example how to create a window upon dropping a page outside the current window, including how to DND between notebooks, and how to destroy the sub window after all pages are removed.</p>

```<code>#!/usr/bin/env python

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class GUI:
    def __init__(self):

        self.window = Gtk.Window()
        self.window.set_size_request(400, 400)
        notebook = Gtk.Notebook()
        self.window.add(notebook)
        notebook.connect('create-window', self.notebook_create_window)
        notebook.set_group_name('0') # very important for DND
        for i in range (4):
            label = Gtk.Label('label in page number ' + str(i))
            tab_label = Gtk.Label('page ' + str(i))
            notebook.append_page(label, tab_label)
            notebook.set_tab_detachable(label, True)
        self.window.show_all()
        self.window.connect('destroy', Gtk.main_quit)

    def notebook_create_window (self, notebook, widget, x, y):
        # handler for dropping outside of current window
        window = Gtk.Window()
        new_notebook = Gtk.Notebook()
        window.add(new_notebook)
        new_notebook.set_group_name('0') # very important for DND
        new_notebook.connect('page-removed', self.notebook_page_removed, window)
        window.connect('destroy', self.sub_window_destroyed, new_notebook, notebook)
        window.set_transient_for(self.window)
        window.set_destroy_with_parent(True)
        window.set_size_request(400, 400)
        window.move(x, y)
        window.show_all()
        return new_notebook

    def notebook_page_removed (self, notebook, child, page, window):
        #destroy the sub window after the notebook is empty
        if notebook.get_n_pages() == 0:
            window.destroy()

    def sub_window_destroyed (self, window, cur_notebook, dest_notebook):
        # if the sub window gets destroyed, push pages back to the main window
        # detach the notebook pages in reverse sequence to avoid index errors
        for page_num in reversed(range(cur_notebook.get_n_pages())):
            widget = cur_notebook.get_nth_page(page_num)
            tab_label = cur_notebook.get_tab_label(widget)
            cur_notebook.detach_tab(widget)
            dest_notebook.append_page(widget, tab_label)
            dest_notebook.set_tab_detachable(widget, True)

app = GUI()
Gtk.main()
</code>```

Body:
Here is a full fledged example how to create a window upon dropping a page outside the current window, including how to DND between notebooks, and how to destroy the sub window after all pages are removed.

#!/usr/bin/env python

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class GUI:
    def __init__(self):

        self.window = Gtk.Window()
        self.window.set_size_request(400, 400)
        notebook = Gtk.Notebook()
        self.window.add(notebook)
        notebook.connect('create-window', self.notebook_create_window)
        notebook.set_group_name('0') # very important for DND
        for i in range (4):
            label = Gtk.Label('label in page number ' + str(i))
            tab_label = Gtk.Label('page ' + str(i))
            notebook.append_page(label, tab_label)
            notebook.set_tab_detachable(label, True)
        self.window.show_all()
        self.window.connect('destroy', Gtk.main_quit)

    def notebook_create_window (self, notebook, widget, x, y):
        # handler for dropping outside of current window
        window = Gtk.Window()
        new_notebook = Gtk.Notebook()
        window.add(new_notebook)
        new_notebook.set_group_name('0') # very important for DND
        new_notebook.connect('page-removed', self.notebook_page_removed, window)
        window.connect('destroy', self.sub_window_destroyed, new_notebook, notebook)
        window.set_transient_for(self.window)
        window.set_destroy_with_parent(True)
        window.set_size_request(400, 400)
        window.move(x, y)
        window.show_all()
        return new_notebook

    def notebook_page_removed (self, notebook, child, page, window):
        #destroy the sub window after the notebook is empty
        if notebook.get_n_pages() == 0:
            window.destroy()

    def sub_window_destroyed (self, window, cur_notebook, dest_notebook):
        # if the sub window gets destroyed, push pages back to the main window
        # detach the notebook pages in reverse sequence to avoid index errors
        for page_num in reversed(range(cur_notebook.get_n_pages())):
            widget = cur_notebook.get_nth_page(page_num)
            tab_label = cur_notebook.get_tab_label(widget)
            cur_notebook.detach_tab(widget)
            dest_notebook.append_page(widget, tab_label)
            dest_notebook.set_tab_detachable(widget, True)

app = GUI()
Gtk.main()


问:
ORA-01002: fetch out of sequence in oracle

ORA-01002: fetch out of sequence in oracle when using sys_refcursor.

I am expecting list of employees in the cursor. In my real scenario I need to check the count of employees and if count greater than zero I should use the same  select statement. Instead of executing same select statement multiple times I tried the below code snippet. But I am getting Fetch out of sequence error in the output cursor.

My table:

```<code>create or replace procedure sp_temp_1  (
var_job in VARCHAR2,
cur_custid out sys_refcursor
)
AS

  /* Declare Ref Cursor */
  --cur_custid  SYS_REFCURSOR;

  /* Declare Type using Fields from the employees table. */
  TYPE t_custrec IS RECORD (
    firstname    temp_emp.firstname%TYPE,
    lastname     temp_emp.lastname%TYPE
  );

  /* Declare Record based off of Type */
  custrec   t_custrec;

BEGIN

  OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM temp_emp
     WHERE JOB = var_job; /* Data Analyst does not exist forcing Zero Rows returned */

  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;

  dbms_output.put_line('Num Rows: ' || cur_custid%rowcount);

  IF cur_custid%rowcount = 0
  THEN
  dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  END IF;

END;
</code>```

I am expecting list of employees , but the sys_refcursor is providing "fetch out of sequence error" in Oracle:

答:
I'm not sure why SQL Developer is giving that error; it seems to be unhappy trying to display the bound out cursor. There error is coming from that output window though, not your code.

If you run exactly the same test block manually as a script from a SQL worksheet, with a client variable to bind the out cursor to, you don't get an error:

```<code>var cur_custid refcursor;

DECLARE
  VAR_JOB VARCHAR2(200);
  CUR_CUSTID sys_refcursor;
BEGIN
  VAR_JOB := 'teach';

  SP_TEMP_1(
    VAR_JOB => VAR_JOB,
    CUR_CUSTID => CUR_CUSTID
  );
  /* Legacy output:
DBMS_OUTPUT.PUT_LINE('CUR_CUSTID = ' || CUR_CUSTID);
*/
  :CUR_CUSTID := CUR_CUSTID; --<-- Cursor
--rollback;
END;
/

Num Rows: 3

PL/SQL procedure successfully completed.

print cur_custid
</code>```

But you don't get any output either. The print shows the cursor result, but it's empty.

The problem really is that you have consumed the cursor within your procedure; after this:

```<code>  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;
</code>```

you have, clearly, encountered cur_custid%notfound, which means there are no rows left in the cursor. There is no rewind facility, automatic or manual; so when the caller gets control of that out variable back, the cursor is still empty. Or if you prefer to think of it this way, the cursor pointer is still pointing past the end of the data - there are no rows left to consume. (Again, why the procedure execution wizard errors at that point is unclear.)

Your premise:

I need to check the count of employees and if count greater than zero I should use the same select statement. Instead of executing same select statement multiple times I tried

... is flawed. You can do what you're doing, but as you've consumed the cursor you have to re-open it, which still duplicates the statement:

```<code>  IF cur_custid%rowcount = 0
  THEN
  dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  ELSE
  dbms_output.put_line('Non-zero Rows Condition Met.  Re-opening Cursor.');
    OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM temp_emp
     WHERE JOB = var_job; /* Data Analyst does not exist forcing Zero Rows returned */
  END IF;
</code>```

In that case you really only need to do a single fetch in your loop, and exit immediately; or indeed don't loop at all, just do a single simple fetch. You only care about zero/non-zero, not the actual non-zero count.

db<>fiddle with your original code, a new version with the second cursor opening, and a second new version with a single fetch. And slightly modified calling blocks to output the results via dbms_output.

It might be simpler to do just do an initial count, and decide which cursor to open.

It's odd that the two possible cursors have a different number of columns, incidentally. Presumably whatever is calling this is supposed to loop through the cursor, and if it sees a zero in the ID columns it knows there is no data? It would be much cleaner to just make that note whether it processed any rows. Then your procedure doesn't need any of this logic, it can just open the single meaningful cursor - if you really need a procedure to do that at all. (Your real scenario might be doing much more work than your example implies; in which case the count approach would still probably be more appropriate.)

Body:
ORA-01002: fetch out of sequence in oracle when using sys_refcursor.

I am expecting list of employees in the cursor. In my real scenario I need to check the count of employees and if count greater than zero I should use the same  select statement. Instead of executing same select statement multiple times I tried the below code snippet. But I am getting Fetch out of sequence error in the output cursor.

My table:

create or replace procedure sp_temp_1  (
var_job in VARCHAR2,
cur_custid out sys_refcursor
)
AS

  /* Declare Ref Cursor */
  --cur_custid  SYS_REFCURSOR;

  /* Declare Type using Fields from the employees table. */
  TYPE t_custrec IS RECORD (
    firstname    temp_emp.firstname%TYPE,
    lastname     temp_emp.lastname%TYPE
  );

  /* Declare Record based off of Type */
  custrec   t_custrec;

BEGIN

  OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM temp_emp
     WHERE JOB = var_job; /* Data Analyst does not exist forcing Zero Rows returned */

  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;

  dbms_output.put_line('Num Rows: ' || cur_custid%rowcount);

  IF cur_custid%rowcount = 0
  THEN
  dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  END IF;

END;

I am expecting list of employees , but the sys_refcursor is providing "fetch out of sequence error" in Oracle:

Body:
I'm not sure why SQL Developer is giving that error; it seems to be unhappy trying to display the bound out cursor. There error is coming from that output window though, not your code.

If you run exactly the same test block manually as a script from a SQL worksheet, with a client variable to bind the out cursor to, you don't get an error:

var cur_custid refcursor;

DECLARE
  VAR_JOB VARCHAR2(200);
  CUR_CUSTID sys_refcursor;
BEGIN
  VAR_JOB := 'teach';

  SP_TEMP_1(
    VAR_JOB => VAR_JOB,
    CUR_CUSTID => CUR_CUSTID
  );
  /* Legacy output:
DBMS_OUTPUT.PUT_LINE('CUR_CUSTID = ' || CUR_CUSTID);
*/
  :CUR_CUSTID := CUR_CUSTID; --<-- Cursor
--rollback;
END;
/

Num Rows: 3

PL/SQL procedure successfully completed.

print cur_custid

But you don't get any output either. The print shows the cursor result, but it's empty.

The problem really is that you have consumed the cursor within your procedure; after this:

  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;

you have, clearly, encountered cur_custid%notfound, which means there are no rows left in the cursor. There is no rewind facility, automatic or manual; so when the caller gets control of that out variable back, the cursor is still empty. Or if you prefer to think of it this way, the cursor pointer is still pointing past the end of the data - there are no rows left to consume. (Again, why the procedure execution wizard errors at that point is unclear.)

Your premise:

I need to check the count of employees and if count greater than zero I should use the same select statement. Instead of executing same select statement multiple times I tried

... is flawed. You can do what you're doing, but as you've consumed the cursor you have to re-open it, which still duplicates the statement:

  IF cur_custid%rowcount = 0
  THEN
  dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  ELSE
  dbms_output.put_line('Non-zero Rows Condition Met.  Re-opening Cursor.');
    OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM temp_emp
     WHERE JOB = var_job; /* Data Analyst does not exist forcing Zero Rows returned */
  END IF;

In that case you really only need to do a single fetch in your loop, and exit immediately; or indeed don't loop at all, just do a single simple fetch. You only care about zero/non-zero, not the actual non-zero count.

db<>fiddle with your original code, a new version with the second cursor opening, and a second new version with a single fetch. And slightly modified calling blocks to output the results via dbms_output.

It might be simpler to do just do an initial count, and decide which cursor to open.

It's odd that the two possible cursors have a different number of columns, incidentally. Presumably whatever is calling this is supposed to loop through the cursor, and if it sees a zero in the ID columns it knows there is no data? It would be much cleaner to just make that note whether it processed any rows. Then your procedure doesn't need any of this logic, it can just open the single meaningful cursor - if you really need a procedure to do that at all. (Your real scenario might be doing much more work than your example implies; in which case the count approach would still probably be more appropriate.)


问:
Spring Security 2.0 Facebook Connect
I´m trying to implement Facebook login to our Spring Framework 2.5 based application which has usual login/password authentication already.

I got to this part of code in my controller where i have user´s Facebook data in userFb object:

```<code>String code = request.getParameter("code");
String accessToken = fbStuffKeeper.retrieveAccessToken(code);
facebookClient = new DefaultFacebookClient(accessToken);
User userFb = facebookClient.fetchObject("me", User.class);
</code>```

I can check if user is already in DB and if not I am able to store him in a DB and store his FB_uid and other necessary credentials.
Problem is that I want to login this user after some condition if he is already authorized to system.
My current authentication manager decides by this rule:

```<code><authentication-provider>
    <jdbc-user-service data-source-ref="dataSource"
                       users-by-username-query="select username, password, confirmed, 1 AS enabled FROM person WHERE confirmed=1 and username=?"
                       authorities-by-username-query="select username, authority from person where username=?"/>
    <password-encoder hash="md5"/>
</authentication-provider>
</code>```

So my question is: How do I login user found in DB who tries to connect using Facebook? Another authentication provider? Is there any way to do his login using some similar code as is mine mentioned one?

Thank you very much.

***EDIT:
Thank you very much. It looks it might help. I have now one user in DB which I want to login. I made this code in the controller:

```<code>User userFb = facebookClient.fetchObject("me", User.class);
Person person = personDao.getPersonByFbUid(userFb.getId());
GrantedAuthority[] grantedAuthorities = new GrantedAuthorityImpl[1];
grantedAuthorities[0] = new GrantedAuthorityImpl(person.getAuthority());
Authentication a = new FacebookAuthenticationToken(grantedAuthorities, person);
a.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(a);
</code>```

I also created FacebookAuthenticationToken:

```<code>public class FacebookAuthenticationToken extends AbstractAuthenticationToken {
private Person person;
   public FacebookAuthenticationToken(GrantedAuthority[] authorities, Person person) {
    super(authorities);
    this.person = person;
}
public Object getCredentials() {
    return person;
}
public Object getPrincipal() {
    this.person;
} /* +  Person getter and setter */
</code>```

And all works fine now. Thank you once more for your help.

答:
One possible way is following. Although it may not be perfect, but it works well.

Create a FacebookAuthenticationToken class, that extends AbstractAuthenticationToken and holds your facebook user object (assuming it to be FacebookUser).

After your code you mentioned above, append the following code right after it into the same controller:

```<code>String code = request.getParameter("code");
String accessToken = fbStuffKeeper.retrieveAccessToken(code);
facebookClient = new DefaultFacebookClient(accessToken);
User userFb = facebookClient.fetchObject("me", User.class);

// Find FacebookUser with current FB_uid, create new if found none, load its information in an instance of FacebookUser

Authentication a = new FacebookAuthenticationToken(fbUserObject);
a.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(a);

// your authentication is complete, redirect to some other page
</code>```

Title: Spring Security 2.0 Facebook Connect

Body:
I´m trying to implement Facebook login to our Spring Framework 2.5 based application which has usual login/password authentication already.

I got to this part of code in my controller where i have user´s Facebook data in userFb object:

String code = request.getParameter("code");
String accessToken = fbStuffKeeper.retrieveAccessToken(code);
facebookClient = new DefaultFacebookClient(accessToken);
User userFb = facebookClient.fetchObject("me", User.class);

I can check if user is already in DB and if not I am able to store him in a DB and store his FB_uid and other necessary credentials.
Problem is that I want to login this user after some condition if he is already authorized to system.
My current authentication manager decides by this rule:

<authentication-provider>
    <jdbc-user-service data-source-ref="dataSource"
                       users-by-username-query="select username, password, confirmed, 1 AS enabled FROM person WHERE confirmed=1 and username=?"
                       authorities-by-username-query="select username, authority from person where username=?"/>
    <password-encoder hash="md5"/>
</authentication-provider>

So my question is: How do I login user found in DB who tries to connect using Facebook? Another authentication provider? Is there any way to do his login using some similar code as is mine mentioned one?

Thank you very much.

***EDIT:
Thank you very much. It looks it might help. I have now one user in DB which I want to login. I made this code in the controller:

User userFb = facebookClient.fetchObject("me", User.class);
Person person = personDao.getPersonByFbUid(userFb.getId());
GrantedAuthority[] grantedAuthorities = new GrantedAuthorityImpl[1];
grantedAuthorities[0] = new GrantedAuthorityImpl(person.getAuthority());
Authentication a = new FacebookAuthenticationToken(grantedAuthorities, person);
a.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(a);

I also created FacebookAuthenticationToken:

public class FacebookAuthenticationToken extends AbstractAuthenticationToken {
private Person person;
   public FacebookAuthenticationToken(GrantedAuthority[] authorities, Person person) {
    super(authorities);
    this.person = person;
}
public Object getCredentials() {
    return person;
}
public Object getPrincipal() {
    this.person;
} /* +  Person getter and setter */

And all works fine now. Thank you once more for your help.

Body:
One possible way is following. Although it may not be perfect, but it works well.

Create a FacebookAuthenticationToken class, that extends AbstractAuthenticationToken and holds your facebook user object (assuming it to be FacebookUser).

After your code you mentioned above, append the following code right after it into the same controller:

String code = request.getParameter("code");
String accessToken = fbStuffKeeper.retrieveAccessToken(code);
facebookClient = new DefaultFacebookClient(accessToken);
User userFb = facebookClient.fetchObject("me", User.class);

// Find FacebookUser with current FB_uid, create new if found none, load its information in an instance of FacebookUser

Authentication a = new FacebookAuthenticationToken(fbUserObject);
a.setAuthenticated(true);
SecurityContextHolder.getContext().setAuthentication(a);

// your authentication is complete, redirect to some other page


问:
In a Keras Sequential model, Conv2D seems to require the kernel be narrower than the previous layer is thick. Why?
I'm creating a Sequential model in Keras that takes a colour image and convolves it through multiple Conv2D layers of approximately the same size and shape as the top layer (minus the edges sliced off by the convolutions, basically).

My understanding is as follows:

kernel_size indicates the patch size for each convolution's input
filters indicates the layer depth for each convolution's output.

I then do some other stuff after the convolutions, which isn't relevant here.

However, when I tried to compile my model prior to testing it on a little data, I discovered that Tensorflow complains when I try to make kernel_size for a given layer greater than filters for the previous layer. It doesn't actually say that; instead it says

Negative dimension size caused by subtracting 3 from 1 for 'conv2d_2/convolution' (op: 'Conv2D') with input shapes [?,1,1022,1022], [3,3,1022,1]

which isn't exactly informative. However, I noticed that the numbers it puts in correspond to

Negative dimension size caused by subtracting <this layer's kernel_size> from <previous layer's filters> ....

and setting filters to be higher stopped the error.

My question is: why should this be? I thought filters specified depth, and kernel_size specified width. There shouldn't be any need to fit a convolution patch into the thickness of the previous layer. Moreover, this problem does not occur on the first layer, whose channel depth (which I understand to be effectively equivalent to filters) is 3.

Is this a bug, or am I misinterpreting these parameters' meaning, or something else?

Code snippet:

```<code>__model = Sequential()

# feature layers
__model.add(Conv2D(input_shape=(3, iX, iY), data_format="channels_first", kernel_size=kernelfilters[0][0],
                   filters=kernelfilters[0][1], activation=ACTIVATION))

for kernelfilter in kernelfilters:
    __model.add(Conv2D(kernel_size=kernelfilter[0], filters=kernelfilter[1], activation=ACTIVATION))
</code>```

The last line is the one that breaks.

Each kernelfilter in the kernelfilters array is a pair of numbers specifying a kernel_size and a filters value, in that order. iX and iY are the initial image dimensions. ACTIVATION is a constant, currently set to "relu" but I might change it later!

答:
Your premise is wrong, this is not the case in general. This only happens if you fiddle with the image_data_format keras parameter (in ~/.keras/keras.kson) or with the data_format parameter for each layer.

Changing this parameter in an in consistent way (in some layers only) would completely screw up how the data is interpreted, as it changes the position of the channels dimension, which could be interpreter as one of the spatial dimensions. for the TF backend (meaning the input_shape in the top layer should be a tuple of the form (width, height, channels)).

Body:
I'm creating a Sequential model in Keras that takes a colour image and convolves it through multiple Conv2D layers of approximately the same size and shape as the top layer (minus the edges sliced off by the convolutions, basically).

My understanding is as follows:

kernel_size indicates the patch size for each convolution's input
filters indicates the layer depth for each convolution's output.

I then do some other stuff after the convolutions, which isn't relevant here.

However, when I tried to compile my model prior to testing it on a little data, I discovered that Tensorflow complains when I try to make kernel_size for a given layer greater than filters for the previous layer. It doesn't actually say that; instead it says

Negative dimension size caused by subtracting 3 from 1 for 'conv2d_2/convolution' (op: 'Conv2D') with input shapes [?,1,1022,1022], [3,3,1022,1]

which isn't exactly informative. However, I noticed that the numbers it puts in correspond to

Negative dimension size caused by subtracting <this layer's kernel_size> from <previous layer's filters> ....

and setting filters to be higher stopped the error.

My question is: why should this be? I thought filters specified depth, and kernel_size specified width. There shouldn't be any need to fit a convolution patch into the thickness of the previous layer. Moreover, this problem does not occur on the first layer, whose channel depth (which I understand to be effectively equivalent to filters) is 3.

Is this a bug, or am I misinterpreting these parameters' meaning, or something else?

Code snippet:

__model = Sequential()

# feature layers
__model.add(Conv2D(input_shape=(3, iX, iY), data_format="channels_first", kernel_size=kernelfilters[0][0],
                   filters=kernelfilters[0][1], activation=ACTIVATION))

for kernelfilter in kernelfilters:
    __model.add(Conv2D(kernel_size=kernelfilter[0], filters=kernelfilter[1], activation=ACTIVATION))

The last line is the one that breaks.

Each kernelfilter in the kernelfilters array is a pair of numbers specifying a kernel_size and a filters value, in that order. iX and iY are the initial image dimensions. ACTIVATION is a constant, currently set to "relu" but I might change it later!


问:
Set Limit on ListView multiple section mode
I have an ArrayList of Strings defined called names defined and I add to my ListView object as follows:

I create an Array Adapter and set multiple choice mode in both the Array Adapter and ListView object. This works great, I can scroll and pick multiple objects. But the problem is I want to force the user into being able to pick only 4 items from the ListView. How can I set a restriction?

```<code>adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,names);
nameList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
nameList.setAdapter(adapter);
</code>```

答:
Yes, I had an idea and found a good solution.

I solved the issue "after scroll listview user can also again select more than 3 checkboxes". set static int count = 0;

```<code>if (isChecked) {
    count++;
} else if (!isChecked) {
    count--;
}

if (count >= 4) {
    buttonView.setChecked(false);
    count--;
} else {
    int getPosition = (Integer) buttonView.getTag();
    contact.get(getPosition).setSelected(buttonView.isChecked());
}
</code>```

And Most imprtant is that add count=0 in else and viewHolder.chkContact.setTag(position) after else;

```<code>if(convertView == null){

}
else
{
    viewHolder = (ViewHolder) convertView.getTag();
    count=0;
}
viewHolder.chkContact.setTag(position);
</code>```

Body:
I have an ArrayList of Strings defined called names defined and I add to my ListView object as follows:

I create an Array Adapter and set multiple choice mode in both the Array Adapter and ListView object. This works great, I can scroll and pick multiple objects. But the problem is I want to force the user into being able to pick only 4 items from the ListView. How can I set a restriction?

adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,names);
nameList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
nameList.setAdapter(adapter);

Body:
Yes, I had an idea and found a good solution.

I solved the issue "after scroll listview user can also again select more than 3 checkboxes". set static int count = 0;

if (isChecked) {
    count++;
} else if (!isChecked) {
    count--;
}

if (count >= 4) {
    buttonView.setChecked(false);
    count--;
} else {
    int getPosition = (Integer) buttonView.getTag();
    contact.get(getPosition).setSelected(buttonView.isChecked());
}

And Most imprtant is that add count=0 in else and viewHolder.chkContact.setTag(position) after else;

if(convertView == null){

}
else
{
    viewHolder = (ViewHolder) convertView.getTag();
    count=0;
}
viewHolder.chkContact.setTag(position);


问:
How to display a SQL stored procedure in VB?
I am using SSMS 2008 and VB.  I'm a novice VB developer.  I am trying to display results of a simple stored proc on my ASPX page.  But I get the error below.  Here is my code behind for the ASPX page:

```<code>>           MsgBox(GlobalFunctions.GlobalF.GetDevSQLServerStoredProcedure())
</code>```

And my code from GlobalF namespace:

```<code>Public Shared Function GetDevSQLServerStoredProcedure()
    Dim conn As SQLConnection
    Dim DSPageData As New System.Data.DataSet

    conn = New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString"))
    Dim cmd As New SQLCommand

    cmd.CommandType = CommandType.StoredProcedure
    cmd.Connection = conn
    cmd.CommandText = "AllTableCount"

    Dim da = New SQLDataAdapter(cmd)
    da.Fill(DSPageData)
    Return DSPageData
End Function
</code>```

And my error:

Argument 'Prompt' cannot be converted
  to type 'String'

[ArgumentException: Argument 'Prompt'
  cannot be converted to type 'String'.]
  Microsoft.VisualBasic.Interaction.MsgBox(Object
  Prompt, MsgBoxStyle Buttons, Object
  Title) +320

  ASP.website_complaints_complainttrendinglist3_aspx.Main()
  in
  e:\inetpub\amdmetrics-d.web.abbott.com\wwwroot\Website\Complaints\ComplaintTrendingList3.aspx:113
  ASP.website_complaints_complainttrendinglist3_aspx.Page_Load(Object
  Sender, EventArgs E) in
  e:\inetpub\amdmetrics-d.web.abbott.com\wwwroot\Website\Complaints\ComplaintTrendingList3.aspx:60
  System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
  +14    System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e) +35

  System.Web.UI.Control.OnLoad(EventArgs
  e) +99

  System.Web.UI.Control.LoadRecursive()
  +50    System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint) +627

This stored procedure just returns number of records in my database.  But I want to perform other stored procedures which return a table.  How do I implement this without errors?

Finally my new SQL SP:

```<code>CREATE proc [dbo].PrintTestMsg AS BEGIN
PRINT 'HELLO'
PRINT 'WORLD'
PRINT 'PAGE3'
PRINT 'PAGE4'
END

SELECT * FROM SELECT (EXEC PrintTestMsg)
</code>```

I get syntax error in SSMS with above select.

What about the code below?  Could I get a dataset now?

```<code>private string DatasetToString(DataSet ds)
{

StringBuilder sb = new StringBuilder();
DataTable dt = ds.Tables(0);

foreach (DataRow dr in dt.Rows) {
sb.Append(“;”);
sb.Append(dt.Rows(1).ToString());
}

return sb.ToString();

}
</code>```

答:
Don't worry about converting the Dataset to a string.  Your real problem here is that you can't use the normal MsbBox() function in asp.net at all.  Really.  If you try, it will display the message on a hidden private desktop on the web server.  It will not pop up the message on the user's machine.  Not only that, but it will block until clicked on, and since it's on a hidden desktop this can never happen.  The result is that your user's page will never load.

What you want to do instead is bind the result of GetDevSQLServerStoredProcedure() method to a GridView, DataGrid, or Repeater control.  There are other problems in your code as well, so I'll do a quick clean-up for each part to show you what it should look like:

```<code>''#Always list the type returned at the end of the method name
Public Shared Function GetDevSQLServerStoredProcedure() As DataSet
    Dim DSPageData As New System.Data.DataSet

    ''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
    ''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
    Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
          cmd As New SQLCommand("PrintTestMsg", conn), _
          da As New SQLDataAdapter(cmd)

        cmd.CommandType = CommandType.StoredProcedure

        da.Fill(DSPageData)
    End Using

    Return DSPageData
End Function
</code>```

Now, your stored procedure.  This doesn't return anything, so I added code to also return the printed data to your page:

```<code>CREATE proc [dbo].PrintTestMsg AS BEGIN
    PRINT 'HELLO'
    PRINT 'WORLD'
    PRINT 'PAGE3'
    PRINT 'PAGE4'

    SELECT 'HELLO' AS Msg
    UNION
    SELECT 'WORLD'
    UNION
    SELECT 'PAGE3'
    UNION
    SELECT 'PAGE4'
END
</code>```

You need to add this to your aspx markup:

```<code><asp:GridView ID="PrintMessageGrid" runat="server" AutoGenerateColumns="True" />
</code>```

And, finally, replace your MsgBox() function call with this code:

```<code>PrintMessageGrid.DataSource = GetDevSQLServerStoredProcedure()
PrintMessageGrid.DataBind()
</code>```

Note that this is just enough to get things working in a basic sense, so that you can continue to explore ASP.Net.  Some of the techniques I just posted I would never use in a production web site.  Examples include AutoGenerateColumns in the GridView and even datasets (datareader is almost always a better option).  This is just the bare minimum change to your original code so you can start piecing things together and learn better techniques as you get more practice.

Body:
I am using SSMS 2008 and VB.  I'm a novice VB developer.  I am trying to display results of a simple stored proc on my ASPX page.  But I get the error below.  Here is my code behind for the ASPX page:

>           MsgBox(GlobalFunctions.GlobalF.GetDevSQLServerStoredProcedure())

And my code from GlobalF namespace:

Public Shared Function GetDevSQLServerStoredProcedure()
    Dim conn As SQLConnection
    Dim DSPageData As New System.Data.DataSet

    conn = New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString"))
    Dim cmd As New SQLCommand

    cmd.CommandType = CommandType.StoredProcedure
    cmd.Connection = conn
    cmd.CommandText = "AllTableCount"

    Dim da = New SQLDataAdapter(cmd)
    da.Fill(DSPageData)
    Return DSPageData
End Function

And my error:

Argument 'Prompt' cannot be converted
  to type 'String'

[ArgumentException: Argument 'Prompt'
  cannot be converted to type 'String'.]
  Microsoft.VisualBasic.Interaction.MsgBox(Object
  Prompt, MsgBoxStyle Buttons, Object
  Title) +320

  ASP.website_complaints_complainttrendinglist3_aspx.Main()
  in
  e:\inetpub\amdmetrics-d.web.abbott.com\wwwroot\Website\Complaints\ComplaintTrendingList3.aspx:113
  ASP.website_complaints_complainttrendinglist3_aspx.Page_Load(Object
  Sender, EventArgs E) in
  e:\inetpub\amdmetrics-d.web.abbott.com\wwwroot\Website\Complaints\ComplaintTrendingList3.aspx:60
  System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr
  fp, Object o, Object t, EventArgs e)
  +14    System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object
  sender, EventArgs e) +35

  System.Web.UI.Control.OnLoad(EventArgs
  e) +99

  System.Web.UI.Control.LoadRecursive()
  +50    System.Web.UI.Page.ProcessRequestMain(Boolean
  includeStagesBeforeAsyncPoint, Boolean
  includeStagesAfterAsyncPoint) +627

This stored procedure just returns number of records in my database.  But I want to perform other stored procedures which return a table.  How do I implement this without errors?

Finally my new SQL SP:

CREATE proc [dbo].PrintTestMsg AS BEGIN
PRINT 'HELLO'
PRINT 'WORLD'
PRINT 'PAGE3'
PRINT 'PAGE4'
END

SELECT * FROM SELECT (EXEC PrintTestMsg)

I get syntax error in SSMS with above select.

What about the code below?  Could I get a dataset now?

private string DatasetToString(DataSet ds)
{

StringBuilder sb = new StringBuilder();
DataTable dt = ds.Tables(0);

foreach (DataRow dr in dt.Rows) {
sb.Append(“;”);
sb.Append(dt.Rows(1).ToString());
}

return sb.ToString();

}

Body:
Don't worry about converting the Dataset to a string.  Your real problem here is that you can't use the normal MsbBox() function in asp.net at all.  Really.  If you try, it will display the message on a hidden private desktop on the web server.  It will not pop up the message on the user's machine.  Not only that, but it will block until clicked on, and since it's on a hidden desktop this can never happen.  The result is that your user's page will never load.

What you want to do instead is bind the result of GetDevSQLServerStoredProcedure() method to a GridView, DataGrid, or Repeater control.  There are other problems in your code as well, so I'll do a quick clean-up for each part to show you what it should look like:

''#Always list the type returned at the end of the method name
Public Shared Function GetDevSQLServerStoredProcedure() As DataSet
    Dim DSPageData As New System.Data.DataSet

    ''# A Using block will ensure the .Dispose() method is called for these variables, even if an exception is thrown
    ''# This is IMPORTANT - not disposing your connections properly can result in an unrespsonsive database
    Using conn As New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString")), _
          cmd As New SQLCommand("PrintTestMsg", conn), _
          da As New SQLDataAdapter(cmd)

        cmd.CommandType = CommandType.StoredProcedure

        da.Fill(DSPageData)
    End Using

    Return DSPageData
End Function

Now, your stored procedure.  This doesn't return anything, so I added code to also return the printed data to your page:

CREATE proc [dbo].PrintTestMsg AS BEGIN
    PRINT 'HELLO'
    PRINT 'WORLD'
    PRINT 'PAGE3'
    PRINT 'PAGE4'

    SELECT 'HELLO' AS Msg
    UNION
    SELECT 'WORLD'
    UNION
    SELECT 'PAGE3'
    UNION
    SELECT 'PAGE4'
END

You need to add this to your aspx markup:

<asp:GridView ID="PrintMessageGrid" runat="server" AutoGenerateColumns="True" />

And, finally, replace your MsgBox() function call with this code:

PrintMessageGrid.DataSource = GetDevSQLServerStoredProcedure()
PrintMessageGrid.DataBind()

Note that this is just enough to get things working in a basic sense, so that you can continue to explore ASP.Net.  Some of the techniques I just posted I would never use in a production web site.  Examples include AutoGenerateColumns in the GridView and even datasets (datareader is almost always a better option).  This is just the bare minimum change to your original code so you can start piecing things together and learn better techniques as you get more practice.


问:
Database change notifications in asp.net core using signalr and sqldependency
If I made any changes in SQL table row then UI should automatically refresh the new changes without F5 or reloading the browser.

I have already tried this in asp.net mvc and its working good but I'm unable to do in asp.net mvc core..

答:
You are looking for a sql backplane solution which as of now and this github isssue, is not supported under core.

Read that issue for more details. But they are recommending the use of a Redis backplane which is support as in the documentation.


问:
Run make file in subdirectory using shell script
I need to run make file_name command in a subdirectory using shell
script and then cd .. out of that subdirectory and run the remaining commands in the main directory.

答:
You can run make from the parent directory without switching to the subdirectory first:

make -C subdir file_name
```


问:
Delphi - Implicit typecast operator not working for method parameters
I'm writing a kind of array wrapper, using a record as container, and including some "class-like" functions to it.
I also want the possibility to assign an array to it, as with a normal array, so I have implemented a Implicit class operator:

```<code>type
  TArrayWrapper = record
    class operator Implicit(AArray: array of TObject): TArrayWrapper; overload;
    Items: TArray<TObject>;

    procedure Add(AItem: TObject);
    ...
  end;
</code>```

So I can do things like:

```<code>procedure DoSomething;
var
  myArray: TArrayWrapper;
begin
  myArray := [Obj1, Obj2, Obj3];
  ...
end;
</code>```

The problem appears when I try to pass an array of Integer to a method that has as parameter a TArrayWrapper:

```<code>procedure DoSomethingElse(AArrayWrapper: TArrayWrapper);
begin
    ...
end;

procedure DoSomething;
var
  myArray: TArrayWrapper;
begin
  myArray := [Obj1, Obj2, Obj3];
  DoSomethingElse(myArray);   <--- Works!!!!

  DoSomethingElse([Obj1, Obj2, Obj3]); <--- Error E2001: Ordinal type required -> It is considering it like a set, not as an array
end;
</code>```

What could be happening?

Thank you in advance.

答:
The compiler has not implemented the string like operations on a dynamic array for class operators, when the record/class is used as a parameter.

There is not a QP report for this, as far as I can see. Now there is, see below.

A similar example is found in the comments here: Dynamic Arrays in Delphi XE7

A workaround:

```<code>DoSomethingElse(TArray<TObject>.Create(Obj1, Obj2, Obj3));
</code>```

Or as @Stefan suggests, in order to avoid unnecessary allocations. Add a constructor to the record:

```<code>type
  TArrayWrapper = record
    class operator Implicit(AArray: array of TObject): TArrayWrapper;
    constructor Init( const AArray: array of TObject);
  end;

DoSomethingElse(TArrayWrapper.Init([obj1,obj2,obj3]));
</code>```

Reported as: RSP-24610 Class operators do not accept dynamic arrays passed with brackets

Body:
I'm writing a kind of array wrapper, using a record as container, and including some "class-like" functions to it.
I also want the possibility to assign an array to it, as with a normal array, so I have implemented a Implicit class operator:

type
  TArrayWrapper = record
    class operator Implicit(AArray: array of TObject): TArrayWrapper; overload;
    Items: TArray<TObject>;

    procedure Add(AItem: TObject);
    ...
  end;

So I can do things like:

procedure DoSomething;
var
  myArray: TArrayWrapper;
begin
  myArray := [Obj1, Obj2, Obj3];
  ...
end;

The problem appears when I try to pass an array of Integer to a method that has as parameter a TArrayWrapper:

procedure DoSomethingElse(AArrayWrapper: TArrayWrapper);
begin
    ...
end;

procedure DoSomething;
var
  myArray: TArrayWrapper;
begin
  myArray := [Obj1, Obj2, Obj3];
  DoSomethingElse(myArray);   <--- Works!!!!

  DoSomethingElse([Obj1, Obj2, Obj3]); <--- Error E2001: Ordinal type required -> It is considering it like a set, not as an array
end;

What could be happening?

Thank you in advance.

Body:
The compiler has not implemented the string like operations on a dynamic array for class operators, when the record/class is used as a parameter.

There is not a QP report for this, as far as I can see. Now there is, see below.

A similar example is found in the comments here: Dynamic Arrays in Delphi XE7

A workaround:

DoSomethingElse(TArray<TObject>.Create(Obj1, Obj2, Obj3));

Or as @Stefan suggests, in order to avoid unnecessary allocations. Add a constructor to the record:

type
  TArrayWrapper = record
    class operator Implicit(AArray: array of TObject): TArrayWrapper;
    constructor Init( const AArray: array of TObject);
  end;

DoSomethingElse(TArrayWrapper.Init([obj1,obj2,obj3]));

Reported as: RSP-24610 Class operators do not accept dynamic arrays passed with brackets


问:
Is it possible to seed data from Configuration file, into a table that has been changed due to plural and single spelling difference
I am currently setting up the seeding data from the configuration file, but come across the plural and single name change of a table. (Category/Categories).

The seed method works fine for all other tables except for Categories, which I assume is to do with the difference of property name (Category) and Actual table name it creates (Categories)

Database Context:

```<code>        public DbSet<Category> Categories { get; set; }

        public ApplicationDbContext(): base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Database.SetInitializer<ApplicationDbContext>(null);
            base.OnModelCreating(modelBuilder);
        }

</code>```

Configuration:

```<code> var test = new Category { CategoryName = "test" }; --- This cant find CategoryName despite the property being in the model.

            context.Categories.Add(test);

            context.SaveChanges();

</code>```

It seems like a simple misunderstanding between model and table but I cant figure out how to map, is this possible without having to change table name?

Edit:
This is the Category Model:

```<code>
namespace WebApplication1.Models
{
    public class Category
    {
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }

        public virtual ICollection<Item> Items{ get; set; }

    }
}
</code>```

答: Answered by Gert Arnold. The Category I was trying to get was a different namespace.</p>

Body:
I am currently setting up the seeding data from the configuration file, but come across the plural and single name change of a table. (Category/Categories).

The seed method works fine for all other tables except for Categories, which I assume is to do with the difference of property name (Category) and Actual table name it creates (Categories)

Database Context:

        public DbSet<Category> Categories { get; set; }

        public ApplicationDbContext(): base("DefaultConnection", throwIfV1Schema: false)
        {
        }

        public static ApplicationDbContext Create()
        {
            return new ApplicationDbContext();
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            //Database.SetInitializer<ApplicationDbContext>(null);
            base.OnModelCreating(modelBuilder);
        }

Configuration:

 var test = new Category { CategoryName = "test" }; --- This cant find CategoryName despite the property being in the model.

            context.Categories.Add(test);

            context.SaveChanges();

It seems like a simple misunderstanding between model and table but I cant figure out how to map, is this possible without having to change table name?

Edit:
This is the Category Model:

namespace WebApplication1.Models
{
    public class Category
    {
        public int CategoryID { get; set; }
        public string CategoryName { get; set; }

        public virtual ICollection<Item> Items{ get; set; }

    }
}


问:
How to reflect and load all classes that implements specific interface
I'm trying to load & create all classes that implements specific

interface in java using reflection?

Say i have :

```<code>package Test;

interface foo {}
class one implements foo {
}
class two implements foo {
}
</code>```

how it can be done?

can u assist?

答:
You can look in a specific package and iterate in all classes (I just copy and past the code, follow the link). Then, you test if it uses a specific interface.

public static void main(String[] args) throws Exception{
   List<Class> classes = getClasses(ClassWithMain.class.getClassLoader(), "fr/jamailun/test");
   for(Class c : classes){
      for(Class i : c.getInterfaces()) {
         if(i.isAssignableFrom(FooInterface.class)) {
            System.out.println("The class " + c + "implements interface "+FooInterface);
            //your code then
         }
      }
   }
}

public static List<Class> getClasses(ClassLoader cl, String pack) throws Exception {
   String dottedPackage = pack.replaceAll("[/]", ".");
   List<Class> classes = new ArrayList<>();
   URL uPackage = cl.getResource(pack);
   DataInputStream dis = new DataInputStream((InputStream) uPackage.getContent());
   String line;
   while ((line = dis.readLine()) != null) {
      if(line.endsWith(".class")) {
          classes.add(Class.forName(dottedPackage+"."+line.substring(0,line.lastIndexOf('.'))));
      }
   }
   return classes;
}
```

Notice that "ClassWithMain" is here the class that contains this main method : could be anywhere just change the name.

Body:
I'm trying to load & create all classes that implements specific

interface in java using reflection?

Say i have :

package Test;

interface foo {}
class one implements foo {
}
class two implements foo {
}

how it can be done?

can u assist?

Body:
You can look in a specific package and iterate in all classes (I just copy and past the code, follow the link). Then, you test if it uses a specific interface.

public static void main(String[] args) throws Exception{
   List<Class> classes = getClasses(ClassWithMain.class.getClassLoader(), "fr/jamailun/test");
   for(Class c : classes){
      for(Class i : c.getInterfaces()) {
         if(i.isAssignableFrom(FooInterface.class)) {
            System.out.println("The class " + c + "implements interface "+FooInterface);
            //your code then
         }
      }
   }
}

public static List<Class> getClasses(ClassLoader cl, String pack) throws Exception {
   String dottedPackage = pack.replaceAll("[/]", ".");
   List<Class> classes = new ArrayList<>();
   URL uPackage = cl.getResource(pack);
   DataInputStream dis = new DataInputStream((InputStream) uPackage.getContent());
   String line;
   while ((line = dis.readLine()) != null) {
      if(line.endsWith(".class")) {
          classes.add(Class.forName(dottedPackage+"."+line.substring(0,line.lastIndexOf('.'))));
      }
   }
   return classes;
}

Notice that "ClassWithMain" is here the class that contains this main method : could be anywhere just change the name.


问:
Set php version in CentOS 6
I just successfully upgraded my server php version from 5.3 to 5.6

When I run:

```<code>php -v
</code>```

I get:

```<code>PHP 5.6.40 (cli)
</code>```

But when I create a file write

```<code>echo phpInfo();
</code>```

The php version showing is 5.3.3

How do I set the php version on phpinfo() to show 5.6

Thanks,

答:
Try this..

```<code>rm /usr/bin/php
ln -s /usr/bin/php56 /usr/bin/php
service httpd restart
</code>```

And then run

```<code>php -v
</code>```

Title: Set php version in CentOS 6

Body:
I just successfully upgraded my server php version from 5.3 to 5.6

When I run:

php -v

I get:

PHP 5.6.40 (cli)

But when I create a file write

echo phpInfo();

The php version showing is 5.3.3

How do I set the php version on phpinfo() to show 5.6

Thanks,

Body:
Try this..

rm /usr/bin/php
ln -s /usr/bin/php56 /usr/bin/php
service httpd restart

And then run

php -v


问:
jQuery ul event target - can i find the li that actually is event target?
```<code>$("#slider ul").hover(function(){
  //do something
});
</code>```

Is there a way to find out which child (li) was actually hovered on to make this function work?

This is a long function that when originally written as $("#slider ul li") etc, worked, but only when completely leaving the slider ul area. I need it to work when moving from one li directly to neighboring li, etc.

答:
Another alternative

Try this:

```<code>$("#slider ul").delegate("li", "mouseover", function(e){
    var el = e.target;
   //do something
});
</code>```

Working example:  http://jsfiddle.net/hpJJz/

Body:
$("#slider ul").hover(function(){
  //do something
});

Is there a way to find out which child (li) was actually hovered on to make this function work?

This is a long function that when originally written as $("#slider ul li") etc, worked, but only when completely leaving the slider ul area. I need it to work when moving from one li directly to neighboring li, etc.

Body:
Another alternative

Try this:

$("#slider ul").delegate("li", "mouseover", function(e){
    var el = e.target;
   //do something
});

Working example:  http://jsfiddle.net/hpJJz/