问:
In unp2 book, why there is overflow in Posix shm example?
I don't quite understand the code below. Why is there an overflow and why is sem_trywait() used? Can't I just repeatedly check the semaphore by spinning while(sem_trywait(&ptr->nempty) == -1 && errno==EAGAIN);?

Thanks,
Jeff

server2.c:

```<code>#include        "cliserv2.h"
int main(int argc, char **argv)
{

        int             fd, index, lastnoverflow, temp;
        long    offset;
        struct shmstruct        *ptr;
        char* addr;
        if (argc != 2)
                err_quit("usage: server2 <name>");

                /* 4create shm, set its size, map it, close descriptor */
        shm_unlink(Px_ipc_name(argv[1]));               /* OK if this fails */
        addr =Px_ipc_name(argv[1]);
        fd = Shm_open(addr, O_RDWR | O_CREAT | O_EXCL, FILE_MODE);
        ptr = Mmap(NULL, sizeof(struct shmstruct), PROT_READ | PROT_WRITE,
                           MAP_SHARED, fd, 0);
        Ftruncate(fd, sizeof(struct shmstruct));
        Close(fd);

                /* 4initialize the array of offsets */
        for (index = 0; index < NMESG; index++)
                ptr->msgoff[index] = index * MESGSIZE;

                /* 4initialize the semaphores in shared memory */
        Sem_init(&ptr->mutex, 1, 1);
        Sem_init(&ptr->nempty, 1, NMESG);
        Sem_init(&ptr->nstored, 1, 0);
        Sem_init(&ptr->noverflowmutex, 1, 1);

                /* 4this program is the consumer */
        index = 0;
        lastnoverflow = 0;
        for ( ; ; ) {
                Sem_wait(&ptr->nstored);
                Sem_wait(&ptr->mutex);
                offset = ptr->msgoff[index];
                printf("index = %d: %s\n", index, &ptr->msgdata[offset]);
                if (++index >= NMESG)
                        index = 0;                              /* circular buffer */
                Sem_post(&ptr->mutex);
                Sem_post(&ptr->nempty);

                Sem_wait(&ptr->noverflowmutex);
                temp = ptr->noverflow;          /* don't printf while mutex held */
                Sem_post(&ptr->noverflowmutex);
                if (temp != lastnoverflow) {
                        printf("noverflow = %d\n", temp);
                        lastnoverflow = temp;
                }
        }

        exit(0);
}
</code>```

client2.c:

```<code>#include        "cliserv2.h"

int main(int argc, char **argv)
{

        int             fd, i, nloop, nusec;
        pid_t   pid;
        char    mesg[MESGSIZE];
        long    offset;
        struct shmstruct        *ptr;

        if (argc != 4)
                err_quit("usage: client2 <name> <#loops> <#usec>");
        nloop = atoi(argv[2]);
        nusec = atoi(argv[3]);

                /* 4open and map shared memory that server must create */
        fd = Shm_open(Px_ipc_name(argv[1]), O_RDWR, FILE_MODE);
        ptr = Mmap(NULL, sizeof(struct shmstruct), PROT_READ | PROT_WRITE,
                           MAP_SHARED, fd, 0);
        Close(fd);

        pid = getpid();
        for (i = 0; i < nloop; i++) {
                Sleep_us(nusec);
                snprintf(mesg, MESGSIZE, "pid %ld: message %d", (long) pid, i);
                if (sem_trywait(&ptr->nempty) == -1) {
                        if (errno == EAGAIN) {
                                Sem_wait(&ptr->noverflowmutex);
                                ptr->noverflow++;
                                Sem_post(&ptr->noverflowmutex);
                                continue;
                        } else
                                err_sys("sem_trywait error");
                }
                Sem_wait(&ptr->mutex);
                offset = ptr->msgoff[ptr->nput];
                if (++(ptr->nput) >= NMESG)
                        ptr->nput = 0;          /* circular buffer */
                Sem_post(&ptr->mutex);
                strcpy(&ptr->msgdata[offset], mesg);
                Sem_post(&ptr->nstored);
        }
        msync(ptr, sizeof(struct shmstruct), MS_SYNC);
        munmap(ptr, sizeof(struct shmstruct));
        exit(0);
}
</code>```

答:
In 13.6, the book explains the use of the overflow counter:

Overflow counter

The possibility exists that a client
  wants to send a message but all the
  message slots are taken. But if the
  client is actually a server of some
  type (perhaps an FTP server or an HTTP
  server), the client does not want to
  wait for the server to free up a slot.
  Therefore, we will write our clients
  so that they do not block but
  increment the noverflow counter when
  this happens. (...)

So, the reason is that the client should never block, even in case it can't send the message. Spinning, like you suggested, is no better than simply using sem_wait() directly, which was already covered earlier in the book. The author just demonstrated how to handle a different situation, where blocking is not wanted.

ContentLicense: CC BY-SA 2.5

Body:
I don't quite understand the code below. Why is there an overflow and why is sem_trywait() used? Can't I just repeatedly check the semaphore by spinning while(sem_trywait(&ptr->nempty) == -1 && errno==EAGAIN);?

Thanks,
Jeff

server2.c:

#include        "cliserv2.h"
int main(int argc, char **argv)
{

        int             fd, index, lastnoverflow, temp;
        long    offset;
        struct shmstruct        *ptr;
        char* addr;
        if (argc != 2)
                err_quit("usage: server2 <name>");

                /* 4create shm, set its size, map it, close descriptor */
        shm_unlink(Px_ipc_name(argv[1]));               /* OK if this fails */
        addr =Px_ipc_name(argv[1]);
        fd = Shm_open(addr, O_RDWR | O_CREAT | O_EXCL, FILE_MODE);
        ptr = Mmap(NULL, sizeof(struct shmstruct), PROT_READ | PROT_WRITE,
                           MAP_SHARED, fd, 0);
        Ftruncate(fd, sizeof(struct shmstruct));
        Close(fd);

                /* 4initialize the array of offsets */
        for (index = 0; index < NMESG; index++)
                ptr->msgoff[index] = index * MESGSIZE;

                /* 4initialize the semaphores in shared memory */
        Sem_init(&ptr->mutex, 1, 1);
        Sem_init(&ptr->nempty, 1, NMESG);
        Sem_init(&ptr->nstored, 1, 0);
        Sem_init(&ptr->noverflowmutex, 1, 1);

                /* 4this program is the consumer */
        index = 0;
        lastnoverflow = 0;
        for ( ; ; ) {
                Sem_wait(&ptr->nstored);
                Sem_wait(&ptr->mutex);
                offset = ptr->msgoff[index];
                printf("index = %d: %s\n", index, &ptr->msgdata[offset]);
                if (++index >= NMESG)
                        index = 0;                              /* circular buffer */
                Sem_post(&ptr->mutex);
                Sem_post(&ptr->nempty);

                Sem_wait(&ptr->noverflowmutex);
                temp = ptr->noverflow;          /* don't printf while mutex held */
                Sem_post(&ptr->noverflowmutex);
                if (temp != lastnoverflow) {
                        printf("noverflow = %d\n", temp);
                        lastnoverflow = temp;
                }
        }

        exit(0);
}

client2.c:

#include        "cliserv2.h"

int main(int argc, char **argv)
{

        int             fd, i, nloop, nusec;
        pid_t   pid;
        char    mesg[MESGSIZE];
        long    offset;
        struct shmstruct        *ptr;

        if (argc != 4)
                err_quit("usage: client2 <name> <#loops> <#usec>");
        nloop = atoi(argv[2]);
        nusec = atoi(argv[3]);

                /* 4open and map shared memory that server must create */
        fd = Shm_open(Px_ipc_name(argv[1]), O_RDWR, FILE_MODE);
        ptr = Mmap(NULL, sizeof(struct shmstruct), PROT_READ | PROT_WRITE,
                           MAP_SHARED, fd, 0);
        Close(fd);

        pid = getpid();
        for (i = 0; i < nloop; i++) {
                Sleep_us(nusec);
                snprintf(mesg, MESGSIZE, "pid %ld: message %d", (long) pid, i);
                if (sem_trywait(&ptr->nempty) == -1) {
                        if (errno == EAGAIN) {
                                Sem_wait(&ptr->noverflowmutex);
                                ptr->noverflow++;
                                Sem_post(&ptr->noverflowmutex);
                                continue;
                        } else
                                err_sys("sem_trywait error");
                }
                Sem_wait(&ptr->mutex);
                offset = ptr->msgoff[ptr->nput];
                if (++(ptr->nput) >= NMESG)
                        ptr->nput = 0;          /* circular buffer */
                Sem_post(&ptr->mutex);
                strcpy(&ptr->msgdata[offset], mesg);
                Sem_post(&ptr->nstored);
        }
        msync(ptr, sizeof(struct shmstruct), MS_SYNC);
        munmap(ptr, sizeof(struct shmstruct));
        exit(0);
}


来源: stackexchange

问:
How do I properly perform multiprocessing from PyQt?
I create a button and try to run multiprocessing when I click button ,

but the UI is become blocked . I hope process run in backgorund .

How can I fix it ?

```<code>from PySide2 import QtCore,QtGui,QtWidgets
import sys
import multiprocessing
from threading import Timer
class TTT(multiprocessing.Process):
    def __init__(self):
        super(TTT, self).__init__()
        self.daemon = True
    def run(self):
        while True:
            t = Timer(5, self.doSomething)
            t.start()
            t.join()

    def doSomething(self):
        try:
            print('123')
        except Exception as e:
            print(e)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        btn = QtWidgets.QPushButton('run process')
        btn.clicked.connect(self.create_process)
        self.setCentralWidget(btn)

    def create_process(self):
        QtWidgets.QMessageBox.information(self,'hhh','hhh')
        t = TTT()
        t.start()
        t.join()

if __name__=="__main__":
    app=QtWidgets.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())
</code>```

答: I have never used multiprocessing, but docs says that the join() method blocks the caller until it is finished. Putting the method in an infinite loop will block the caller(the UI) forever.</p>

ContentLicense: CC BY-SA 3.0

Body:
I create a button and try to run multiprocessing when I click button ,

but the UI is become blocked . I hope process run in backgorund .

How can I fix it ?

from PySide2 import QtCore,QtGui,QtWidgets
import sys
import multiprocessing
from threading import Timer
class TTT(multiprocessing.Process):
    def __init__(self):
        super(TTT, self).__init__()
        self.daemon = True
    def run(self):
        while True:
            t = Timer(5, self.doSomething)
            t.start()
            t.join()

    def doSomething(self):
        try:
            print('123')
        except Exception as e:
            print(e)

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        btn = QtWidgets.QPushButton('run process')
        btn.clicked.connect(self.create_process)
        self.setCentralWidget(btn)

    def create_process(self):
        QtWidgets.QMessageBox.information(self,'hhh','hhh')
        t = TTT()
        t.start()
        t.join()

if __name__=="__main__":
    app=QtWidgets.QApplication(sys.argv)
    ex = MainWindow()
    ex.show()
    sys.exit(app.exec_())


问:
Inno Setup, do not include duplicate files multiple times in the installer
I have a .NET solution with multiple projects. Each project has it's own output folder (project1 to projectN). All the projects has common files which are coped by msbuild to each folder. (And this is normal). The common files has exactly the same name, modification time and content. The common files are about 90% of the total size of each project.

I'd like to create an installer with Inno Setup / Inno Script Studio
Each project has it's own component. (Can be selected during the install)

My iss file look like:

```<code>Source: "{#BuildOutputDirectory}_project1\*"; Excludes: "*.pdb,*.xml"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: project1
Source: "{#BuildOutputDirectory}_project2\*"; Excludes: "*.pdb,*.xml"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: project2
...
Source: "{#BuildOutputDirectory}_projectN\*"; Excludes: "*.pdb,*.xml"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: projectN
</code>```

My problem is that the duplicate files are included in the installer multiple times. The Total size of the projects folder is 517MB, the size of the uniqe files is 78MB the installer size 98MB (compression lzma2 solid). The expected installer size should be about 21MB (I've compressed the unique files with 7-Zip and the result was this)

And the install creation time is quite long, because it compresses the duplicate files multiple times. But this is not really a problem.

What should I do to filter the duplicate files? (I have one idea, to generate the iss file with a simple application which already filters them, but it is only a workaround)

答:
I have one idea, to generate the iss file with a simple application which already filters them, but it is only a workaround

There's no better solution.

Just consider calling the application (or rather some simple [PowerShell?] script) from Inno Setup preprocessor (using Exec preprocessor function). This way the .iss will work on its own, without a need to run the application/script before compiling the installer.

Actually you can implement it in Inno Setup preprocessor completely, without a need for an external application/script. But coding this in preprocessor is not easy.

See Do not include duplicate files multiple times in the Inno Setup installer.

For other similar tasks, see:

Inno Setup - Recurse sub directories without creating those same sub directories

Generating Inno Setup file flags programmatically

Inno Setup: Dynamically add a component for all files in a folder and its subfolders

Body:
I have a .NET solution with multiple projects. Each project has it's own output folder (project1 to projectN). All the projects has common files which are coped by msbuild to each folder. (And this is normal). The common files has exactly the same name, modification time and content. The common files are about 90% of the total size of each project.

I'd like to create an installer with Inno Setup / Inno Script Studio
Each project has it's own component. (Can be selected during the install)

My iss file look like:

Source: "{#BuildOutputDirectory}_project1\*"; Excludes: "*.pdb,*.xml"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: project1
Source: "{#BuildOutputDirectory}_project2\*"; Excludes: "*.pdb,*.xml"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: project2
...
Source: "{#BuildOutputDirectory}_projectN\*"; Excludes: "*.pdb,*.xml"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs; Components: projectN

My problem is that the duplicate files are included in the installer multiple times. The Total size of the projects folder is 517MB, the size of the uniqe files is 78MB the installer size 98MB (compression lzma2 solid). The expected installer size should be about 21MB (I've compressed the unique files with 7-Zip and the result was this)

And the install creation time is quite long, because it compresses the duplicate files multiple times. But this is not really a problem.

What should I do to filter the duplicate files? (I have one idea, to generate the iss file with a simple application which already filters them, but it is only a workaround)

ContentLicense: CC BY-SA 4.0


问:
fatal: Could not read from remote repository. When I push my local repo to remote server
In my remote server I have a directory /var/www/html/Qiyun02-server, and in it I use:

```<code>git init --bare Qiyun02-server
</code>```

created a repo named Qiyun02-server.

and in my Qiyun02 project of my local Mac, I use

```<code>git remote add origin 103.15.22.21:/var/www/html/Qiyun02-server:Qiyun02-server
</code>```

added the remote origin.

Then :

```<code>git add -A
git commit -m 'my first commit for remote origin'
</code>```

Then I push to the remote server:

```<code>git push --set-upstream origin master
</code>```

But I get bellow errors:

```<code>MacBook-Pro:Qiyun02 ldl$ sudo git push --set-upstream origin master
Password:
root@103.15.22.21's password:
fatal: '/var/www/html/Qiyun02-server:Qiyun02-server' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

答:
Your not providing the correct URL path.

This is mistake :   git remote add origin 103.15.22.21:/var/www/html/Qiyun02-server:Qiyun02-server

Don't use url what you did above.

Follow the below way of adding url using HTTPS that's what your doing.

HTTP/S:

```<code>git remote add origin <url>
</code>```

example <url> : https://github.com/xxx/xxx/

SSH:

```<code>git remote add origin git@github.com:username/new_repo
</code>```

I suggest you follow this beginner tutorial, how to setup the git repo.

Body:
In my remote server I have a directory /var/www/html/Qiyun02-server, and in it I use:

git init --bare Qiyun02-server

created a repo named Qiyun02-server.

and in my Qiyun02 project of my local Mac, I use

git remote add origin 103.15.22.21:/var/www/html/Qiyun02-server:Qiyun02-server

added the remote origin.

Then :

git add -A
git commit -m 'my first commit for remote origin'

Then I push to the remote server:

git push --set-upstream origin master

But I get bellow errors:

MacBook-Pro:Qiyun02 ldl$ sudo git push --set-upstream origin master
Password:
root@103.15.22.21's password:
fatal: '/var/www/html/Qiyun02-server:Qiyun02-server' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Body:
Your not providing the correct URL path.

This is mistake :   git remote add origin 103.15.22.21:/var/www/html/Qiyun02-server:Qiyun02-server

Don't use url what you did above.

Follow the below way of adding url using HTTPS that's what your doing.

HTTP/S:

git remote add origin <url>

example <url> : https://github.com/xxx/xxx/

SSH:

git remote add origin git@github.com:username/new_repo

I suggest you follow this beginner tutorial, how to setup the git repo.


问:
Running into: Unexpectedly found nil while unwrapping an Optional value, when I try to make it optional, I get another error
I get this error when trying to make farmTile optional: Value of optional type Bool? not unwrapped; did you mean to use '!' or '?'?

It was working fine an hour ago.

```<code>var farmTile:SKSpriteNode!

func createFarmTile(){

    farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    farmTile?.size = CGSize(width: 185, height: 195)
    farmTile?.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile!)
    farmTile?.name = "farmTile"
    farmTile.zPosition = 1

   if farmTile?.contains(touchLocation){
       print("test")
   }
}
</code>```

答:
farmTile?.contains(touchLocation) returns an optional Bool. You should handle the optional properly. Do something like this...

```<code>var farmTile: SKSpriteNode? // optional

func createFarmTile(){

    guard let farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    else { /* do what you need to do if it is missing */ ; return }

    farmTile.size = CGSize(width: 185, height: 195)
    farmTile.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile)
    farmTile.name = "farmTile"
    farmTile.zPosition = 1
    self.farmTile = farmTile

    if farmTile.contains(touchLocation){
       print("test")
    }
}
</code>```

Body:
I get this error when trying to make farmTile optional: Value of optional type Bool? not unwrapped; did you mean to use '!' or '?'?

It was working fine an hour ago.

var farmTile:SKSpriteNode!

func createFarmTile(){

    farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    farmTile?.size = CGSize(width: 185, height: 195)
    farmTile?.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile!)
    farmTile?.name = "farmTile"
    farmTile.zPosition = 1

   if farmTile?.contains(touchLocation){
       print("test")
   }
}

Body:
farmTile?.contains(touchLocation) returns an optional Bool. You should handle the optional properly. Do something like this...

var farmTile: SKSpriteNode? // optional

func createFarmTile(){

    guard let farmTile = SKSpriteNode(imageNamed: "farmtile.png")
    else { /* do what you need to do if it is missing */ ; return }

    farmTile.size = CGSize(width: 185, height: 195)
    farmTile.position = CGPoint(x: -95, y: 150)
    self.addChild(farmTile)
    farmTile.name = "farmTile"
    farmTile.zPosition = 1
    self.farmTile = farmTile

    if farmTile.contains(touchLocation){
       print("test")
    }
}


问:
How to get specified rows from the returns of CimInstance type in PowerShell
I am trying to get specified rows from a CimInstance object and I thought to turn them to string, but did not find the answer how to do that.

```
PS C:\Users\laptop> Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightness

Active            : True
CurrentBrightness : 50
InstanceName      : DISPLAY\LEN40A1\4&342c5d56&0&UID67568640_0
Level             : {0, 1, 2, 3...}
Levels            : 101
PSComputerName    :
```

I need to get two rows, "CurrentBrightness : 50" and "Levels  : 101", from the results on screen, but the return is a [Microsoft.Management.Infrastructure.CimInstance]. I had tried to make them to be strings though.

答:
The "rows" you see are actually the properties of an object displayed in list form. You can select properties of any given object via the Select-Object cmdlet:

```<code>Get-CimInstance ... | Select-Object CurrentBrightness, Levels
</code>```

Body:
I am trying to get specified rows from a CimInstance object and I thought to turn them to string, but did not find the answer how to do that.

PS C:\Users\laptop> Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightness

Active            : True
CurrentBrightness : 50
InstanceName      : DISPLAY\LEN40A1\4&342c5d56&0&UID67568640_0
Level             : {0, 1, 2, 3...}
Levels            : 101
PSComputerName    :

I need to get two rows, "CurrentBrightness : 50" and "Levels  : 101", from the results on screen, but the return is a [Microsoft.Management.Infrastructure.CimInstance]. I had tried to make them to be strings though.

Body:
The "rows" you see are actually the properties of an object displayed in list form. You can select properties of any given object via the Select-Object cmdlet:

Get-CimInstance ... | Select-Object CurrentBrightness, Levels


问:
Oracle DB to_date with year - to_date(2017,'YYYY') unexpected return
While writing few queries I needed to return only those rows that have date column  set in this year (2017) , that's not my problem I know how to write this query in couple of diffrent ways, but I came across something strange and unexpected for me. Can anyone explain why Oracle db 11.2 is  behaving this way?

```<code>select sysdate from dual

returns:
2017/12/05 09:22:27

select to_date(2017,'YYYY'),trunc(sysdate,'YYYY') from dual
returns :
2017/12/01 00:00:00 2017/01/01 00:00:00

select to_date(2017,'YYYY'),trunc(sysdate,'YYYY') from dual
where trunc(sysdate,'YYYY') = to_date(2017,'YYYY')

no rows returned
</code>```

Why does to_date(2017,'YYYY') returns 2017/12/01, will it return 2017/01/01 next month? Why does it work that way? I would expect it to always return 2017/01/01 no matter the current month (if month part is indeed changing depending on sysdate).

答:
In Oracle, TO_DATE will assume that:

If you do not specify the year then it is the current year;

If you do not specify the month then it is the current month;

If you do not specify the day then it is the first day of the month;

If you do not specify the hours then it is the midnight hour (0);

If you do not specify the minutes then it is 0 minutes past the hour; and

If you do not specify the seconds then it is 0 seconds into the minute.

You are specifying only the year (2017) so it will be:

Zero minutes and seconds past midnight of the first day of the current month of the year you specify (2017).

If you want the first day of the year then specify the month (and preferably the rest of the date):

```<code>select to_date( '201701','YYYYMM'),
       trunc(sysdate,'YYYY')
from   dual
where  trunc(sysdate,'YYYY') = to_date( '201701','YYYYMM' )
</code>```

Or use a date literal:

```<code>select DATE '2017-01-01',
       trunc(sysdate,'YYYY')
from   dual
where  trunc(sysdate,'YYYY') = DATE '2017-01-01'
</code>```

Body:
While writing few queries I needed to return only those rows that have date column  set in this year (2017) , that's not my problem I know how to write this query in couple of diffrent ways, but I came across something strange and unexpected for me. Can anyone explain why Oracle db 11.2 is  behaving this way?

select sysdate from dual

returns:
2017/12/05 09:22:27

select to_date(2017,'YYYY'),trunc(sysdate,'YYYY') from dual
returns :
2017/12/01 00:00:00 2017/01/01 00:00:00

select to_date(2017,'YYYY'),trunc(sysdate,'YYYY') from dual
where trunc(sysdate,'YYYY') = to_date(2017,'YYYY')

no rows returned

Why does to_date(2017,'YYYY') returns 2017/12/01, will it return 2017/01/01 next month? Why does it work that way? I would expect it to always return 2017/01/01 no matter the current month (if month part is indeed changing depending on sysdate).

Body:
In Oracle, TO_DATE will assume that:

If you do not specify the year then it is the current year;

If you do not specify the month then it is the current month;

If you do not specify the day then it is the first day of the month;

If you do not specify the hours then it is the midnight hour (0);

If you do not specify the minutes then it is 0 minutes past the hour; and

If you do not specify the seconds then it is 0 seconds into the minute.

You are specifying only the year (2017) so it will be:

Zero minutes and seconds past midnight of the first day of the current month of the year you specify (2017).

If you want the first day of the year then specify the month (and preferably the rest of the date):

select to_date( '201701','YYYYMM'),
       trunc(sysdate,'YYYY')
from   dual
where  trunc(sysdate,'YYYY') = to_date( '201701','YYYYMM' )

Or use a date literal:

select DATE '2017-01-01',
       trunc(sysdate,'YYYY')
from   dual
where  trunc(sysdate,'YYYY') = DATE '2017-01-01'


问:
Add text to 'Ready Page' in Inno Setup
I added few custom pages to my Installer. These pages gather some data from user and disk, and I'd like to show this data to user before final installation step starts. Inno Setup has 'Ready to Install' page exactly for this purpose.

How can I add text to this page? By default it shows to me:

```<code>Destination location:
  C:\Program Files\MyProgram
</code>```

I'd like to append some text here. Is it possible?

答:
Alter the following code:

procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = wpReady then
  begin
    Wizardform.ReadyMemo.Lines.Add(''); { Empty string }
    Wizardform.ReadyMemo.Lines.Add('Setup HP-UX test created by Armand');
  end;
end;
```

Title: Add text to 'Ready Page' in Inno Setup

Body:
I added few custom pages to my Installer. These pages gather some data from user and disk, and I'd like to show this data to user before final installation step starts. Inno Setup has 'Ready to Install' page exactly for this purpose.

How can I add text to this page? By default it shows to me:

Destination location:
  C:\Program Files\MyProgram

I'd like to append some text here. Is it possible?


问:
How to handle one Stored Procedure output (ResultSet or Table) into another Stored Procedure as Table
one Stored Procedure is returning me a table and I want to hold that result into another Stored Procedure.
and I am facing SQL syntax error.

First Stored Procedure

```<code>DELIMITER $$
USE `dataBase`$$
DROP PROCEDURE IF EXISTS `testReturnTable`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `testReturnTable`()
BEGIN
    SELECT `user_id`, `email` FROM `users`;
END$$
DELIMITER ;
</code>```

and I am trying to call this Store Procedure into another and want to hold the data into a view or table

```<code>DELIMITER $$
USE `dataBase`$$
DROP PROCEDURE IF EXISTS `testReturnCall`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `testReturnCall`()
BEGIN
    DROP VIEW IF EXISTS `my_view`;
    CREATE OR REPLACE VIEW my_view AS (CALL testReturnTable());
    SELECT * FROM my_view;
END$$
DELIMITER ;
</code>```

and getting error

```<code>You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CALL testReturnTable());
</code>```

I can use function here as well, but I don't know how to handle result set,
please advice.

答: it is not possible to get table ouput from one stored procedure to another stored procedure. But we have alternate to do this which is Temp table </p>

Body:
one Stored Procedure is returning me a table and I want to hold that result into another Stored Procedure.
and I am facing SQL syntax error.

First Stored Procedure

DELIMITER $$
USE `dataBase`$$
DROP PROCEDURE IF EXISTS `testReturnTable`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `testReturnTable`()
BEGIN
    SELECT `user_id`, `email` FROM `users`;
END$$
DELIMITER ;

and I am trying to call this Store Procedure into another and want to hold the data into a view or table

DELIMITER $$
USE `dataBase`$$
DROP PROCEDURE IF EXISTS `testReturnCall`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `testReturnCall`()
BEGIN
    DROP VIEW IF EXISTS `my_view`;
    CREATE OR REPLACE VIEW my_view AS (CALL testReturnTable());
    SELECT * FROM my_view;
END$$
DELIMITER ;

and getting error

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CALL testReturnTable());

I can use function here as well, but I don't know how to handle result set,
please advice.


问:
Synchronise animation with top of a keyboard with accessory view
I have a UITextField which has an accessory view. I also have another view which resides at the bottom of the screen. I want this view to animate up as the keyboard shows, which I have done plenty of times by utilizing the UIKeyboardWillShowNotification. However, this time it is a little special since I want the bottom view to follow the top of the keyboard and not the top of the accessory view.

Obviously I have tried this solution:

```<code>[UIView animateWithDuration:keyboardAnimationDuration delay:0 options:keyboardAnimationCurve animations:^{
        viewBottomConstraint.constant = keyboardHeight - accessoryViewHeight;
        [self.overviewViewController.view layoutIfNeeded];
} completion:nil];
</code>```

(keyboardAnimationDuration, keyboardAnimationCurve and keyboardHeight all come from the userInfo dictionary of the keyboard notification)

This solution gives me the correct end position of the bottom view, but the animation is slightly off since the keyboard (including the accessory view) has to traverse a longer distance in the same duration (to the top of the accessory view instead of to the top of the keyboard).

I have considered calculating a relative animation duration for my bottom view like this:

```<code>keyboardToAccessoryRatio = (keyboardHeight - accessoryViewHeight) / keyboardHeight
relativeDuration = keyboardAnimationDuration * keyboardToAccessoryRatio
</code>```

And then have the animation start with a delay of keyboardAnimationDuration - relativeDuration. However, this would only work nicely if the keyboard was using the UIViewAnimationOptionCurveLinear curve, but it is, in fact, using UIViewAnimationCurveEaseInOut.

So any other suggestions?

PS. I cannot simply add my button view to the accessory view as they are actually in separate view controllers. The animation is done as a part of a custom transition within a UIViewControllerAnimatedTransitioning class.

答: In the end I gave up and added the accessory view as a regular view which I made follow the keyboard.</p>

Body:
I have a UITextField which has an accessory view. I also have another view which resides at the bottom of the screen. I want this view to animate up as the keyboard shows, which I have done plenty of times by utilizing the UIKeyboardWillShowNotification. However, this time it is a little special since I want the bottom view to follow the top of the keyboard and not the top of the accessory view.

Obviously I have tried this solution:

[UIView animateWithDuration:keyboardAnimationDuration delay:0 options:keyboardAnimationCurve animations:^{
        viewBottomConstraint.constant = keyboardHeight - accessoryViewHeight;
        [self.overviewViewController.view layoutIfNeeded];
} completion:nil];

(keyboardAnimationDuration, keyboardAnimationCurve and keyboardHeight all come from the userInfo dictionary of the keyboard notification)

This solution gives me the correct end position of the bottom view, but the animation is slightly off since the keyboard (including the accessory view) has to traverse a longer distance in the same duration (to the top of the accessory view instead of to the top of the keyboard).

I have considered calculating a relative animation duration for my bottom view like this:

keyboardToAccessoryRatio = (keyboardHeight - accessoryViewHeight) / keyboardHeight
relativeDuration = keyboardAnimationDuration * keyboardToAccessoryRatio

And then have the animation start with a delay of keyboardAnimationDuration - relativeDuration. However, this would only work nicely if the keyboard was using the UIViewAnimationOptionCurveLinear curve, but it is, in fact, using UIViewAnimationCurveEaseInOut.

So any other suggestions?

PS. I cannot simply add my button view to the accessory view as they are actually in separate view controllers. The animation is done as a part of a custom transition within a UIViewControllerAnimatedTransitioning class.


问:
Chinese charatcers are looking bolder in mozilla other than chrome & IE
The URL is http://ca.hoganlovells.com/zh/people. I have used Times New Roman for font family. They are looking perfect in Chrome & IE but in mozilla it's rendering heavier/bolder.

Appreciate your help.

答:
I think the problem with font family only. Try using below font family

```<code>font-family: sinkin_sans300_light, "Microsoft YaHei New", "Microsoft Yahei", 微软雅黑, 宋体, SimSun, STXihei, 华文细黑, sans-serif;
font-family: "MS Gothic",sans-serif;
font-family: "MS PGothic",sans-serif;
</code>```

Refer the url: http://www.kendraschaefer.com/2012/06/chinese-standard-web-fonts-the-ultimate-guide-to-css-font-family-declarations-for-web-design-in-simplified-chinese/

Body:
I think the problem with font family only. Try using below font family

font-family: sinkin_sans300_light, "Microsoft YaHei New", "Microsoft Yahei", 微软雅黑, 宋体, SimSun, STXihei, 华文细黑, sans-serif;
font-family: "MS Gothic",sans-serif;
font-family: "MS PGothic",sans-serif;

Refer the url: http://www.kendraschaefer.com/2012/06/chinese-standard-web-fonts-the-ultimate-guide-to-css-font-family-declarations-for-web-design-in-simplified-chinese/


问:
Finding special characters in XML with Preg_match in PHP
I have an xml which returns this format

<row site_id="999" sale_id="49612" payment_type="MOD_TICKET" pay_payment_info="TICKET=49600" />

I am able to retrieve the record into an array using
preg_match as follows

```<code><!-- $line = trim($line);
if(preg_match("/^<[^$]+\ \/>$/", $line))
{
    preg_match_all("/([^=<\s]+)=\"([^\"]+)\"/", $line, $m);
    $result = array();
    foreach($m as $n)
     -->
</code>```

However, this works but if the XML return something like

```<code><row site_id="999" sale_id="49612" payment_type="MOD_TICKET" pay_payment_info="~$TICKET=49600" />
</code>```

The search does not work, how do I add those two characters (~$) into the search

the

答:
You can use simplexml_load_string() to parse the XML

```<code><?php
$xml  = '<row site_id="999" sale_id="49612" payment_type="MOD_TICKET" pay_payment_info="TICKET=49600" />';

$obj = simplexml_load_string($xml);

echo "```";
foreach($obj->Attributes() as $key => $val){
    print_r($key);
    $val = (array) $val;
    print_r($val[0]);
}
```

Reference :
http://php.net/manual/en/function.simplexml-load-string.php

Body:
I have an xml which returns this format

<row site_id="999" sale_id="49612" payment_type="MOD_TICKET" pay_payment_info="TICKET=49600" />

I am able to retrieve the record into an array using
preg_match as follows

However, this works but if the XML return something like

<row site_id="999" sale_id="49612" payment_type="MOD_TICKET" pay_payment_info="~$TICKET=49600" />

The search does not work, how do I add those two characters (~$) into the search

the

Body:
You can use simplexml_load_string() to parse the XML

<?php
$xml  = '<row site_id="999" sale_id="49612" payment_type="MOD_TICKET" pay_payment_info="TICKET=49600" />';

$obj = simplexml_load_string($xml);

echo "<pre>";
foreach($obj->Attributes() as $key => $val){
    print_r($key);
    $val = (array) $val;
    print_r($val[0]);
}

Reference :
http://php.net/manual/en/function.simplexml-load-string.php


问:
How to imlement ReactiveUserDetailsService with MongoDB
There in Spring security 5 appear an interface as ReactiveUserDetailsService.

Now my question is how to implement UserDetailsService using:

 Spring-data-Mongo

 Spring Security (5)

That I have (users stored in memory)

```<code>@Bean
public MapReactiveUserDetailsService userDetailsService() {
    UserDetails user = User.withDefaultPasswordEncoder().username("test").password("password").roles("USER").build();
    UserDetails admin = User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER", "ADMIN").build();
    return new MapReactiveUserDetailsService(user, admin);
}
</code>```

What I want:

```<code>@Document(collection = "user")
public class User implements UserDetails {

    @Id
    private Long id;
    private LocalDate createdAt;
    private String username;
    private String password;
    private boolean accountNonLocker;
    private boolean enabled;
    @DBRef
    private List<GrantedAuthority> grantedAuthorities;
    //getters and setters
}

@Component
public class SecUserDetailsService implements ReactiveUserDetailsService {

}
</code>```

And I don't know how to implement it. not found any resources on web.

答:
Already found a solution:

 Implement UserDetails interface in UseAccount class and create Role class that implements GrantedAuthority interface:

Role

```<code>@Data
@Document
public class Role implements GrantedAuthority {
    @Id
    private String id;

    @Override
    public String getAuthority() {
        return id;
    }
}
</code>```

UseAcount

```<code>@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document
public class UserAccount implements UserDetails {

    @Id
    private String id;
    private String username;
    private String password;
    private String firstName;
    private String lastName;
    private String idnp;

    @Email
    private String email;

    @Builder.Default()
    private boolean active = true;

    @Builder.Default()
    @DBRef
    private List<Role> roles = new ArrayList<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return active;
    }

    @Override
    public boolean isAccountNonLocked() {
        return active;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return active;
    }

    @Override
    public boolean isEnabled() {
        return active;
    }

    @Override
    public String getName() {
        return firstName + " " + lastName;
    }
}
</code>```

Define Security configuration and in it create web filter.

```<code>@Configuration
@EnableWebFluxSecurity
public class SecurityConfiguration {

    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
        return http
            .csrf().disable()
            .authorizeExchange()
                .pathMatchers("/login", "/logout").permitAll()
                .pathMatchers("/i18n/**",
                    "/css/**",
                    "/fonts/**",
                    "/icons-reference/**",
                    "/img/**",
                    "/js/**",
                    "/vendor/**").permitAll()
            .anyExchange()
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .and()
            .logout()
                .logoutUrl("/logout")
                .and()
            .build();
    }

    //in case you want to encrypt password
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
</code>```

Create repository to extract your user from database.

And last step is to create UserDetailsService

```<code>@Component
public class SecUserDetailsService implements ReactiveUserDetailsService {

    @Autowired
    public ReactiveUserAccountRepository reactiveUserAccountRepository;

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        Mono<UserAccount> data = reactiveUserAccountRepository.findByUsername(username);
        return data.cast(UserDetails.class);
    }
}
</code>```

Body:
There in Spring security 5 appear an interface as ReactiveUserDetailsService.

Now my question is how to implement UserDetailsService using:

 Spring-data-Mongo

 Spring Security (5)

That I have (users stored in memory)

@Bean
public MapReactiveUserDetailsService userDetailsService() {
    UserDetails user = User.withDefaultPasswordEncoder().username("test").password("password").roles("USER").build();
    UserDetails admin = User.withDefaultPasswordEncoder().username("admin").password("admin").roles("USER", "ADMIN").build();
    return new MapReactiveUserDetailsService(user, admin);
}

What I want:

@Document(collection = "user")
public class User implements UserDetails {

    @Id
    private Long id;
    private LocalDate createdAt;
    private String username;
    private String password;
    private boolean accountNonLocker;
    private boolean enabled;
    @DBRef
    private List<GrantedAuthority> grantedAuthorities;
    //getters and setters
}

@Component
public class SecUserDetailsService implements ReactiveUserDetailsService {

}

And I don't know how to implement it. not found any resources on web.

Body:
Already found a solution:

 Implement UserDetails interface in UseAccount class and create Role class that implements GrantedAuthority interface:

Role

@Data
@Document
public class Role implements GrantedAuthority {
    @Id
    private String id;

    @Override
    public String getAuthority() {
        return id;
    }
}

UseAcount

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Document
public class UserAccount implements UserDetails {

    @Id
    private String id;
    private String username;
    private String password;
    private String firstName;
    private String lastName;
    private String idnp;

    @Email
    private String email;

    @Builder.Default()
    private boolean active = true;

    @Builder.Default()
    @DBRef
    private List<Role> roles = new ArrayList<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return roles;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return active;
    }

    @Override
    public boolean isAccountNonLocked() {
        return active;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return active;
    }

    @Override
    public boolean isEnabled() {
        return active;
    }

    @Override
    public String getName() {
        return firstName + " " + lastName;
    }
}

Define Security configuration and in it create web filter.

@Configuration
@EnableWebFluxSecurity
public class SecurityConfiguration {

    @Bean
    SecurityWebFilterChain springWebFilterChain(ServerHttpSecurity http) {
        return http
            .csrf().disable()
            .authorizeExchange()
                .pathMatchers("/login", "/logout").permitAll()
                .pathMatchers("/i18n/**",
                    "/css/**",
                    "/fonts/**",
                    "/icons-reference/**",
                    "/img/**",
                    "/js/**",
                    "/vendor/**").permitAll()
            .anyExchange()
                .authenticated()
                .and()
            .formLogin()
                .loginPage("/login")
                .and()
            .logout()
                .logoutUrl("/logout")
                .and()
            .build();
    }

    //in case you want to encrypt password
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}

Create repository to extract your user from database.

And last step is to create UserDetailsService

@Component
public class SecUserDetailsService implements ReactiveUserDetailsService {

    @Autowired
    public ReactiveUserAccountRepository reactiveUserAccountRepository;

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        Mono<UserAccount> data = reactiveUserAccountRepository.findByUsername(username);
        return data.cast(UserDetails.class);
    }
}


问:
Rails control Job execution
I have a job created with rails g job cleanUp.

Is where any option to check if Job is running? Something like this CleanUpJob.isRunning?

If where is no way to make it without additional gems, which will be the simplest? delayed_job?

Second thing to control Job is progress, any thoughts how to implement CleanUpJob.progress or progress_job should be my choice?

briefly:

I need to create a job with two methods (isRunning?, progress).
I don't really want additional tables if possible.

答:
You can use Class: Sidekiq::ScheduledSet for this purpose.

Documentation here
This Class is used in Sidekiq web interface.

Example:
 Save job id (jid) when set job. Then you can call it for queried instance

```<code>def is_running?
  require 'sidekiq/api'
  ss = Sidekiq::ScheduledSet.new
  jobs = ss.select {|ret| ret.jid == self.jid}
  jobs.any?
end
</code>```

Or, you can set DB flag inside Job with around_perform hook.

```<code> class SomeJob < ActiveJob::Base
      queue_as :some_job

      around_perform do |job, block|
        start_import_process_log job.arguments[0], job.arguments[1] || {}
        block.call
        finish_import_process_log
      end

 #   ...
    private

  def start_import_process_log import_process, options={}
    #some actions
  end

  def finish_import_process_log
  end

 end
</code>```

In this example associated log record is created.
Or you can use before_perform/ after_perform.

In my practice I'm using creting log records on long tasks.

When I need to find and kill job as example - I'm using Sidekiq::ScheduledSet.

Title: Rails control Job execution

Body:
You can use Class: Sidekiq::ScheduledSet for this purpose.

Documentation here
This Class is used in Sidekiq web interface.

Example:
 Save job id (jid) when set job. Then you can call it for queried instance

def is_running?
  require 'sidekiq/api'
  ss = Sidekiq::ScheduledSet.new
  jobs = ss.select {|ret| ret.jid == self.jid}
  jobs.any?
end

Or, you can set DB flag inside Job with around_perform hook.

 class SomeJob < ActiveJob::Base
      queue_as :some_job

      around_perform do |job, block|
        start_import_process_log job.arguments[0], job.arguments[1] || {}
        block.call
        finish_import_process_log
      end

 #   ...
    private

  def start_import_process_log import_process, options={}
    #some actions
  end

  def finish_import_process_log
  end

 end

In this example associated log record is created.
Or you can use before_perform/ after_perform.

In my practice I'm using creting log records on long tasks.

When I need to find and kill job as example - I'm using Sidekiq::ScheduledSet.


问:
How to find an element present in data-hook through selenium
I have the HTML code as:

```<code><a class="a-size-base a-link-normal review-title a-color-base a-text-bold" data-hook="review-title" href="/gp/customer-reviews/R252N8IFRXV8TW/ref=cm_cr_getr_d_rvw_ttl?ie=UTF8&ASIN=B071NZZHF9">Security concern</a>
</code>```

and i have to search the element by data-hook as the class name is common for other attributes also and href and link-text are dynamic as it is changing for the next element as there are multiple elements that i need to fetch.

Can i search it by data-hook. If yes could someone help me with it!

答:
You can also use the below code if multiple data-hook item you need.</p>

```<code>List<WebElement> list = driver.findElements(By.className("review-title"));

for(WebElement elem : list){
    System.out.println(elem.getAttribute("data-hook"));
}
</code>```

Body:
I have the HTML code as:

Security concern

and i have to search the element by data-hook as the class name is common for other attributes also and href and link-text are dynamic as it is changing for the next element as there are multiple elements that i need to fetch.

Can i search it by data-hook. If yes could someone help me with it!

Body:
You can also use the below code if multiple data-hook item you need.

List<WebElement> list = driver.findElements(By.className("review-title"));

for(WebElement elem : list){
    System.out.println(elem.getAttribute("data-hook"));
}


问:
Create a new color drawable
I am trying to convert a hex value to an int so I can create a new color drawable. I'm not sure if this is possible, but according to the documentation, it should. It plainly asks for

public ColorDrawable (int color)

Added in API level 1 Creates a new ColorDrawable with the specified
  color.

Parameters color    The color to draw.

So, my code isn't working because I'm getting an Invalid int: "FF6666" error. Any ideas?

```<code>int decode = Integer.decode("FF6666");
ColorDrawable colorDrawable = new ColorDrawable(decode);
</code>```

答:
By followingthe above advice,to be a summary of this question:

ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#ce9b2c"));`

ColorDrawable colorDrawable = new ColorDrawable(0xFFCE9B2C);
Note there is  8 hex digits, not 6 hex digit,which no work. Case all

ColorDrawable colorDrawable = new ColorDrawable(ContextCompat.getColor(mContext,R.color.default_color));

Selecting up to you!

Title: Create a new color drawable

Body:
I am trying to convert a hex value to an int so I can create a new color drawable. I'm not sure if this is possible, but according to the documentation, it should. It plainly asks for

public ColorDrawable (int color)

Added in API level 1 Creates a new ColorDrawable with the specified
  color.

Parameters color    The color to draw.

So, my code isn't working because I'm getting an Invalid int: "FF6666" error. Any ideas?

int decode = Integer.decode("FF6666");
ColorDrawable colorDrawable = new ColorDrawable(decode);


问:
How to make multiple PivotItems visible in Excel VBA
I have a Pivot table in sheet "Main". In PivotField "Report Filter" I have "Country Code" which contain 200 countries. I want to Make visible more than 1 countries from that filter using InputBox.

The problem is I need to choose minimum one country or ALL in filter manually and run this program. I can't get the correct data by doing this.
I need to deselect all the countries and then I need to run.

My Code

```<code>Sub Addcountries()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim pf As PivotField
Dim target As PivotTable

Set ws = Sheets("Main")
str1 = Application.InputBox("Enter the Country - comma separated")

If str1 = False Then
    MsgBox "Please Enter one Country", , "Filter Country"
    Exit Sub
Else
    If InStr(1, str1, ",") > 0 Then
        Data = Split(str1, ",")
        For i = LBound(Data) To UBound(Data)
            ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(Data(i)).Visible = True
        Next i
    Else
        ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(str1).Visible = True
    End If
End If

End Sub
</code>```

答:
You can loop through the PivotItems collection, and check each PivotItem.Name if it matches one of the selected countires inside Data array - you can accomplish that using the Match function.

Code

```<code>If str1 = False Then
    MsgBox "Please Enter one Country", , "Filter Country"
    Exit Sub
Else
    If InStr(1, str1, ",") > 0 Then ' more than 1 country >> create array
        Data = Split(str1, ",")
    Else ' single country
        Data = Array(str1) '<-- create array with 1 element (for Match to work)
    End If

    ' === You need a different loop, loop through all Pivot-Items, then look for a match with Data (array) ===
    Dim pi As PivotItem

    ' clear previous Filter
    ws.PivotTables("MainTable").PivotFields("Country Code").ClearAllFilters

    For Each pi In ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems
        ' check if current Pivot-Item equals one of the elements of the array (use Match function)
        If Not IsError(Application.Match(pi.Name, Data, 0)) Then ' Match successful
            pi.Visible = True
        Else
            pi.Visible = False
        End If
    Next pi
End If

' rest of your code
</code>```

Body:
I have a Pivot table in sheet "Main". In PivotField "Report Filter" I have "Country Code" which contain 200 countries. I want to Make visible more than 1 countries from that filter using InputBox.

The problem is I need to choose minimum one country or ALL in filter manually and run this program. I can't get the correct data by doing this.
I need to deselect all the countries and then I need to run.

My Code

Sub Addcountries()

Dim ws As Worksheet
Dim str1 As Variant
Dim Data As Variant
Dim pf As PivotField
Dim target As PivotTable

Set ws = Sheets("Main")
str1 = Application.InputBox("Enter the Country - comma separated")

If str1 = False Then
    MsgBox "Please Enter one Country", , "Filter Country"
    Exit Sub
Else
    If InStr(1, str1, ",") > 0 Then
        Data = Split(str1, ",")
        For i = LBound(Data) To UBound(Data)
            ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(Data(i)).Visible = True
        Next i
    Else
        ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems(str1).Visible = True
    End If
End If

End Sub

Body:
You can loop through the PivotItems collection, and check each PivotItem.Name if it matches one of the selected countires inside Data array - you can accomplish that using the Match function.

Code

If str1 = False Then
    MsgBox "Please Enter one Country", , "Filter Country"
    Exit Sub
Else
    If InStr(1, str1, ",") > 0 Then ' more than 1 country >> create array
        Data = Split(str1, ",")
    Else ' single country
        Data = Array(str1) '<-- create array with 1 element (for Match to work)
    End If

    ' === You need a different loop, loop through all Pivot-Items, then look for a match with Data (array) ===
    Dim pi As PivotItem

    ' clear previous Filter
    ws.PivotTables("MainTable").PivotFields("Country Code").ClearAllFilters

    For Each pi In ws.PivotTables("MainTable").PivotFields("Country Code").PivotItems
        ' check if current Pivot-Item equals one of the elements of the array (use Match function)
        If Not IsError(Application.Match(pi.Name, Data, 0)) Then ' Match successful
            pi.Visible = True
        Else
            pi.Visible = False
        End If
    Next pi
End If

' rest of your code


问:
Jmeter: How to handle web socket error
enter image description hereI have a query on Jmeter web socket sampler.
I have used sampler (https://bitbucket.org/pjtr/jmeter-websocket-samplers)

I am trying to Test a scenario when I send invalid request then I should handle the error or if there is any error thrown by server then I should verify.

but in Jmeter I am not receiving any server error, it shows green all the time irrespective of valid or invalid request for web socket sampler.
Please suggest how to handle this?

Best Regards,
Sunil
enter image description here

答:
Add a Response Assertion as a child of the WebSocker Sampler to check its status code, message, content, whatever.

If you need specific instructions kindly update your question with example "successful" and "error" responses, both Sampler result and Response data tabs.

See How to Use JMeter Assertions in Three Easy Steps article for more information on adding pass/fail criteria to your tests via JMeter Assertions.

Title: Jmeter: How to handle web socket error


问:
I have created an call back API to receive the JSON data but its not working
I have created a call back API to receive the JSON data after hitting my server. But somehow its not working as expected

This the response which i have to receive in my API

{"ERROR":0,"STATUS":1,"ORDERID":753093,"OPTRANSID":"2107938600"}

I have written the php file for this rcstatus.php

```<code>$url = 'http://softwarecompany.club/pks/recharge/b2b/rcstatus.php?status='.$_GET['status'].'&Orderid='.$_GET['Orderid'].'&Optransid='.$_GET['Optransid'];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
$data = curl_exec($ch);
echo $data;
$json = json_decode($url,true);
$json['STATUS'];
</code>```

Please help me to achieve this. I have never worked with JSON data before. So please help me to achieve it. Thanks in advance!!!

答:
Replace $url to $data in last when you get the response like this.</p>

```<code>$url = 'http://softwarecompany.club/pks/recharge/b2b/rcstatus.php?status='.$_GET['status'].'&Orderid='.$_GET['Orderid'].'&Optransid='.$_GET['Optransid'];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
$data = curl_exec($ch); // This is Your Response
$json = json_decode($data,true);
$json['STATUS'];
</code>```

Body:
I have created a call back API to receive the JSON data after hitting my server. But somehow its not working as expected

This the response which i have to receive in my API

{"ERROR":0,"STATUS":1,"ORDERID":753093,"OPTRANSID":"2107938600"}

I have written the php file for this rcstatus.php

$url = 'http://softwarecompany.club/pks/recharge/b2b/rcstatus.php?status='.$_GET['status'].'&Orderid='.$_GET['Orderid'].'&Optransid='.$_GET['Optransid'];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
$data = curl_exec($ch);
echo $data;
$json = json_decode($url,true);
$json['STATUS'];

Please help me to achieve this. I have never worked with JSON data before. So please help me to achieve it. Thanks in advance!!!

Body:
Replace $url to $data in last when you get the response like this.

$url = 'http://softwarecompany.club/pks/recharge/b2b/rcstatus.php?status='.$_GET['status'].'&Orderid='.$_GET['Orderid'].'&Optransid='.$_GET['Optransid'];

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
$data = curl_exec($ch); // This is Your Response
$json = json_decode($data,true);
$json['STATUS'];


问:
Generate all strings under length N in C
I tried coding this myself and horribly failed. This is basically what I want:

```<code>a
b
...
z
aa
ba
...
za
ab
bb
...
zz
aaa
baa
...
zzz
</code>```

In the end it should have generated every string that is shorter then N characters with charset a-z. So I'm not looking for permutations (of which 1001 implementations can be found on the internet), but for combinations with replacement (at least that's how it's called in Python). Order is not important, speed is.

答:
Looks like you want it in C, here is a way to do it:</p>

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

int inc(char *c){
    if(c[0]==0) return 0;
    if(c[0]=='z'){
        c[0]='a';
        return inc(c+sizeof(char));
    }
    c[0]++;
    return 1;
}

int main(void){
    int n = 3;
    int i,j;
    char *c = malloc((n+1)*sizeof(char));
    for(i=1;i<=n;i++){
        for(j=0;j<i;j++) c[j]='a';
        c[i]=0;
        do {
            printf("%s\n",c);
        } while(inc(c));
    }
    free(c);
}
</code>```

Body:
I tried coding this myself and horribly failed. This is basically what I want:

a
b
...
z
aa
ba
...
za
ab
bb
...
zz
aaa
baa
...
zzz

In the end it should have generated every string that is shorter then N characters with charset a-z. So I'm not looking for permutations (of which 1001 implementations can be found on the internet), but for combinations with replacement (at least that's how it's called in Python). Order is not important, speed is.

Body:
Looks like you want it in C, here is a way to do it:

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

int inc(char *c){
    if(c[0]==0) return 0;
    if(c[0]=='z'){
        c[0]='a';
        return inc(c+sizeof(char));
    }
    c[0]++;
    return 1;
}

int main(void){
    int n = 3;
    int i,j;
    char *c = malloc((n+1)*sizeof(char));
    for(i=1;i<=n;i++){
        for(j=0;j<i;j++) c[j]='a';
        c[i]=0;
        do {
            printf("%s\n",c);
        } while(inc(c));
    }
    free(c);
}


问:
create product category UL within XML package?
I have created an xml package for ASPDOTNETSTOREFRONT which runs a query. The file then creates an UL where it creates product links. However i need another UL to show up for the category and the product links to show into within that.

```<code><ul>Category 1</ul>
 <ul>
  <li>product 1</li>
 </ul>
</ul>
</code>```

Something like the above?

Here is my xml package:

```<code><?xml version="1.0" standalone="yes" ?>
<package version="2.1" displayname="Simple Product" debug="true" includeentityhelper="false">

    <!-- ###################################################################################################### -->
    <!-- Copyright AspDotNetStorefront.com, 1995-2011.  All Rights Reserved.                                    -->
    <!-- http://www.aspdotnetstorefront.com                                                                     -->
    <!-- For details on this license please visit  the product homepage at the URL above.                       -->
    <!-- THE ABOVE NOTICE MUST REMAIN INTACT.                                                                   -->
    <!--                                                                                -->
    <!-- ###################################################################################################### -->

    <query name="Products" rowElementName="Product">
        <sql>
            <![CDATA[
                WITH Categories (ParentCategoryID, CategoryID, Name, ComputedLevel, Sort) AS
                    (
                    SELECT c.ParentCategoryID, c.CategoryID, c.Name, 0 AS ComputedLevel, CAST('\'+c.Name AS NVARCHAR(255))
                    FROM Category AS c
                    WHERE ParentCategoryID = 0
                    AND Deleted=0
                    AND Published=1
                    UNION ALL
                    SELECT c.ParentCategoryID, c.CategoryID, c.Name, ComputedLevel + 1, CAST(s.Sort + '\'+c.Name AS NVARCHAR(255))
                    FROM Category AS c
                    INNER JOIN Categories AS s ON c.ParentCategoryID = s.CategoryID
                    WHERE Deleted=0
                    AND Published=1
                    )

                    SELECT ParentCategoryID, c.CategoryID, Sort, p.ProductID, p.Name, p.SEName
                    FROM Categories c (NOLOCK)
                    LEFT JOIN ProductCategory pc (NOLOCK) ON pc.CategoryID = c.CategoryID
                    JOIN Product p (NOLOCK) ON p.ProductID = pc.ProductID

                    ORDER BY 3,5
            ]]>
        </sql>

    </query>

    <PackageTransform>
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:aspdnsf="urn:aspdnsf" exclude-result-prefixes="aspdnsf">
            <xsl:output method="html" omit-xml-declaration="yes" />

            <xsl:param name="LocaleSetting" select="/root/Runtime/LocaleSetting" />
            <xsl:param name="WebConfigLocaleSetting" select="/root/Runtime/WebConfigLocaleSetting" />
            <xsl:param name="XmlPackageName" select="/root/System/XmlPackageName" />
            <xsl:param name="SecID">
                <xsl:choose>
                    <xsl:when test="count(/root/QueryString/sectionid) > 0">
                        <xsl:value-of select="/root/QueryString/sectionid" />
                    </xsl:when>
                    <xsl:otherwise>0</xsl:otherwise>
                </xsl:choose>
            </xsl:param>

            <xsl:param name="CategoryID">
                <xsl:choose>
                    <xsl:when test="/root/System/PageName = 'showmanufacturer.aspx' or /root/System/PageName = 'showsection.aspx' or /root/System/PageName = 'showdistributor.aspx' or /root/System/PageName = 'showvector.aspx' or /root/System/PageName = 'showgenre.aspx'">0</xsl:when>
                    <xsl:when test="/root/System/PageName = 'showcategory.aspx' and boolean(/root/QueryString/categoryid)">
                        <xsl:value-of select="/root/QueryString/categoryid"/>
                    </xsl:when>
                    <xsl:when test="(/root/System/PageName = 'showcategory.aspx' or /root/System/PageName = 'showproduct.aspx') and boolean(/root/Cookies/LastViewedEntityInstanceID) and /root/Cookies/LastViewedEntityName = 'Category'">
                        <xsl:value-of select="/root/Cookies/LastViewedEntityInstanceID"/>
                    </xsl:when>
                    <xsl:otherwise>0</xsl:otherwise>
                </xsl:choose>
            </xsl:param>

            <xsl:param name="AncestorID">
                <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
                    <xsl:value-of select="ancestor::*/EntityID"/>
                </xsl:for-each>
            </xsl:param>

            <xsl:param name="ParentID">
                <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
                    <xsl:value-of select="parent::*/EntityID"/>
                </xsl:for-each>
            </xsl:param>

            <xsl:param name="CatID">
                <xsl:choose>
                    <xsl:when test="count(/root/QueryString/categoryid) > 0">
                        <xsl:value-of select="/root/QueryString/categoryid" />
                    </xsl:when>
                    <xsl:otherwise>0</xsl:otherwise>
                </xsl:choose>
            </xsl:param>

            <xsl:template match="/">
                <xsl:element name="ul">
                    <xsl:attribute name="id">
                        <![CDATA[accordion3]]>
                    </xsl:attribute>
                    <xsl:apply-templates select="/root/Products/Product">
                        <xsl:with-param name="prefix" select="''"/>
                    </xsl:apply-templates>
                </xsl:element>
            </xsl:template>

            <xsl:template match="Product">
                <xsl:param name="prefix"></xsl:param>
                <xsl:param name="eName" select="aspdnsf:GetMLValue(Name)" />
                <li >
                    <!--<xsl:value-of select="$prefix" />-->
                    <xsl:if test="number(ParentEntityID) != 0">
                        <!--<span class="catMark">>></span> -->

                        <a href="{concat('p-',ProductID,'-',SEName,'.aspx')}">
                            <xsl:if test="EntityID = $CategoryID or descendant::Entity/EntityID = $CategoryID">
                                <xsl:attribute name="style">font-weight:bold</xsl:attribute>
                            </xsl:if>
                            <xsl:value-of select="$eName"/>
                        </a>

                    </xsl:if>
                    <xsl:if test="number(ParentEntityID) = 0">
                        <div class="menuText">
                            <xsl:value-of select="$eName"/>
                        </div>
                    </xsl:if>
                    <xsl:if test="count(child::Entity)>0">
                        <ul >
                            <xsl:apply-templates select="Product">
                                <xsl:with-param name="prefix" select="concat($prefix, '  ')"/>
                            </xsl:apply-templates>
                        </ul>
                    </xsl:if>
                </li>
            </xsl:template>

        </xsl:stylesheet>
    </PackageTransform>
</package>
</code>```

The UL is created here:

```<code><xsl:template match="/">
                <xsl:element name="ul">
                    <xsl:attribute name="id">
                        <![CDATA[accordion3]]>
                    </xsl:attribute>
                    <xsl:apply-templates select="/root/Products/Product">
                        <xsl:with-param name="prefix" select="''"/>
                    </xsl:apply-templates>
                </xsl:element>
            </xsl:template>
</code>```

And here is where the product link is created:

```<code>    <xsl:template match="Product">
        <xsl:param name="prefix"></xsl:param>
        <xsl:param name="eName" select="aspdnsf:GetMLValue(Name)" />
        <li >
            <!--<xsl:value-of select="$prefix" />-->
            <xsl:if test="number(ParentEntityID) != 0">
                <!--<span class="catMark">>></span> -->

                <a href="{concat('p-',ProductID,'-',SEName,'.aspx')}">
                    <xsl:if test="EntityID = $CategoryID or descendant::Entity/EntityID = $CategoryID">
                        <xsl:attribute name="style">font-weight:bold</xsl:attribute>
                    </xsl:if>
                    <xsl:value-of select="$eName"/>
                </a>

            </xsl:if>
            <xsl:if test="number(ParentEntityID) = 0">
                <div class="menuText">
                    <xsl:value-of select="$eName"/>
                </div>
            </xsl:if>
            <xsl:if test="count(child::Entity)>0">
                <ul >
                    <xsl:apply-templates select="Product">
                        <xsl:with-param name="prefix" select="concat($prefix, '  ')"/>
                    </xsl:apply-templates>
                </ul>
            </xsl:if>
        </li>
    </xsl:template>
</code>```

EDIT: ADDED XML extract:

```<code><Product>
  <ParentCategoryID>77</ParentCategoryID>
  <CategoryID>78</CategoryID>
  <Sort>\Box Product\Accessories\AA990F</Sort>
  <ProductID>299</ProductID>
  <Name>Air compressor</Name>
  <SEName>air-compressor</SEName>
</Product>
</code>```

答:
I am posting this answer because may someone face this problem in future..
Use this code to render products with categoies.

Example:

Category 1

```<code>.Product 1

.product 2
</code>```

Category 2

```<code>.Product 1
.Product 2

<?xml version="1.0" standalone="yes" ?>
<package version="2.1" displayname="Simple Product" debug="false"
includeentityhelper="false">
 <query name="Products" rowElementName="Product">
<sql>
  <![CDATA[
            WITH Categories (ParentCategoryID, CategoryID, Name,
         ComputedLevel, Sort) AS
                (
                SELECT c.ParentCategoryID, c.CategoryID, c.Name, 0 AS
                   ComputedLevel, CAST('\'+c.Name AS NVARCHAR(255))
                FROM Category AS c
                WHERE ParentCategoryID =@CatID
                AND Deleted=0
                AND Published=1
                UNION ALL
                SELECT c.ParentCategoryID, c.CategoryID, c.Name,
              ComputedLevel + 1, CAST(s.Sort + '\'+c.Name AS
               NVARCHAR(255))
                FROM Category AS c
                INNER JOIN Categories AS s ON c.ParentCategoryID =
              s.CategoryID
                WHERE Deleted=0
                AND Published=1
                )

                SELECT ParentCategoryID, c.CategoryID,C.Name as
                CategoryName, Sort, p.ProductID, p.Name, p.SEName
                FROM Categories c (NOLOCK)
                LEFT JOIN ProductCategory pc (NOLOCK) ON pc.CategoryID =
                c.CategoryID
                JOIN Product p (NOLOCK) ON p.ProductID = pc.ProductID

                ORDER BY 3,5
                  ]]>
                    </sql>
                 <queryparam paramname="@CatID"
                  paramtype="runtime"   requestparamname="CatID"

sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@SecID"          paramtype="runtime"   requestparamname="SecID"                                         sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@ManID"          paramtype="runtime"   requestparamname="ManID"                                         sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@DistID"         paramtype="runtime"   requestparamname="DistID"                                        sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@GenreID"        paramtype="runtime"   requestparamname="GenreID"                                       sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@VectorID"       paramtype="runtime"   requestparamname="VectorID"                                      sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@locale"         paramtype="runtime"   requestparamname="LocaleSetting"                                 sqlDataType="varchar" defvalue="en-US"  validationpattern="" />
    <queryparam paramname="@CustLevelID"    paramtype="runtime"   requestparamname="CustomerLevelID"                               sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@AffID"          paramtype="runtime"   requestparamname="AffiliateID"                                   sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@ProdTypeID"     paramtype="runtime"   requestparamname="ProductTypeFilterID"                           sqlDataType="int"     defvalue="1"      validationpattern="" />
    <queryparam paramname="@pgnum"          paramtype="request"   requestparamname="pagenum"                                       sqlDataType="int"     defvalue="1"      validationpattern="" />
    <queryparam paramname="@InvFilter"      paramtype="appconfig" requestparamname="HideProductsWithLessThanThisInventoryLevel"    sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@entityname"     paramtype="runtime"   requestparamname="EntityName"                                    sqlDataType="varchar" defvalue=""       validationpattern="" />
    <queryparam paramname="@StoreID"        paramtype="runtime"   requestparamname="StoreID"                                                           sqlDataType="int"       defvalue="1"      validationpattern="" />
    <queryparam paramname="@FilterProduct"  paramtype="runtime"   requestparamname="FilterProduct"                                                   sqlDataType="bit"     defvalue="0"      validationpattern="" />
  </query>

  <PackageTransform>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:aspdnsf="urn:aspdnsf" exclude-result-prefixes="aspdnsf">
      <xsl:output method="html" omit-xml-declaration="yes" />

      <xsl:param name="LocaleSetting" select="/root/Runtime/LocaleSetting" />
      <xsl:param name="WebConfigLocaleSetting" select="/root/Runtime/WebConfigLocaleSetting" />
      <xsl:param name="XmlPackageName" select="/root/System/XmlPackageName" />
      <xsl:param name="SecID">

        <xsl:variable name="ShowSubcatsInGrid" select="aspdnsf:AppConfig('ShowSubcatsInGrid')" />
        <xsl:variable name="EntityName" select="/root/Runtime/EntityName" />
        <xsl:variable name="EntityID" select="/root/Runtime/EntityID" />

        <xsl:variable name="CurrentEntity" select="/root/EntityHelpers/*[name()=$EntityName]/descendant::Entity[EntityID=$EntityID]" />

        <xsl:choose>
          <xsl:when test="count(/root/QueryString/sectionid) > 0">
            <xsl:value-of select="/root/QueryString/sectionid" />
          </xsl:when>
          <xsl:otherwise>0</xsl:otherwise>
        </xsl:choose>
      </xsl:param>

      <xsl:param name="CategoryID">
        <xsl:choose>
          <xsl:when test="/root/System/PageName = 'showmanufacturer.aspx' or /root/System/PageName = 'showsection.aspx' or /root/System/PageName = 'showdistributor.aspx' or /root/System/PageName = 'showvector.aspx' or /root/System/PageName = 'showgenre.aspx'">0</xsl:when>
          <xsl:when test="/root/System/PageName = 'showcategory.aspx' and boolean(/root/QueryString/categoryid)">
            <xsl:value-of select="/root/QueryString/categoryid"/>
          </xsl:when>
          <xsl:when test="(/root/System/PageName = 'showcategory.aspx' or /root/System/PageName = 'showproduct.aspx') and boolean(/root/Cookies/LastViewedEntityInstanceID) and /root/Cookies/LastViewedEntityName = 'Category'">
            <xsl:value-of select="/root/Cookies/LastViewedEntityInstanceID"/>
          </xsl:when>
          <xsl:otherwise>0</xsl:otherwise>
        </xsl:choose>
      </xsl:param>

      <xsl:param name="AncestorID">

        <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
          <xsl:value-of select="ancestor::*/EntityID"/>
        </xsl:for-each>
      </xsl:param>

      <xsl:param name="ParentID">
        <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
          <xsl:value-of select="parent::*/EntityID"/>
        </xsl:for-each>
      </xsl:param>

      <xsl:param name="CatID">

        <xsl:choose>
          <xsl:when test="count(/root/QueryString/categoryid) > 0">
            <xsl:value-of select="/root/QueryString/categoryid" />
          </xsl:when>
          <xsl:otherwise>0</xsl:otherwise>
        </xsl:choose>
      </xsl:param>

      <xsl:template match="/">
        <xsl:element name="ul">
          <xsl:attribute name="id">
            <![CDATA[accordion3]]>
          </xsl:attribute>
          <xsl:apply-templates select="/root/Products/Product">
            <xsl:with-param name="prefix" select="''"/>
          </xsl:apply-templates>
        </xsl:element>
      </xsl:template>

      <xsl:template match="Product">
        <xsl:param name="prefix"></xsl:param>
        <xsl:param name="eName" select="aspdnsf:GetMLValue(Name)" />
         <xsl:variable name="oldname" select="'old'" />
        <li >
          <!--<xsl:value-of select="$prefix" />-->

          <xsl:if test="number(ParentEntityID) != 0">
            <!--<span class="catMark">>></span> -->

            <!--<xsl:if test="$oldname != CategoryName">-->
          <xsl:if test ="not(preceding-sibling::Product[(CategoryName/text() = current()/CategoryName/text())])">
            <h1>
              <xsl:value-of select="CategoryName"/>
            </h1>
                 <!--<xsl:variable name="oldname" select="CategoryName" />-->
                <!--<xsl:copy>
                 <xsl:value-of name="oldname" select="CategoryName"/>
                </xsl:copy>-->

              </xsl:if>

            <a href="{concat('p-',ProductID,'-',SEName,'.aspx')}">
              <xsl:if test="EntityID = $CategoryID or descendant::Entity/EntityID = $CategoryID">
              <xsl:attribute name="style">font-weight:bold</xsl:attribute>
              </xsl:if>
              <xsl:value-of select="$eName"/>
            </a>

          </xsl:if>
          <xsl:if test="number(ParentEntityID) = 0">
            <div class="menuText">
              <xsl:value-of select="$eName"/>
            </div>
          </xsl:if>

          <xsl:if test="count(child::Product)>0">

            <ul >
              <xsl:apply-templates select="Product">
                <xsl:with-param name="prefix" select="concat($prefix, '  ')"/>
              </xsl:apply-templates>
            </ul>
          </xsl:if>
        </li>
      </xsl:template>

    </xsl:stylesheet>
  </PackageTransform>
</package>
</code>```

Body:
I have created an xml package for ASPDOTNETSTOREFRONT which runs a query. The file then creates an UL where it creates product links. However i need another UL to show up for the category and the product links to show into within that.

Category 1

product 1

Something like the above?

Here is my xml package:

<?xml version="1.0" standalone="yes" ?>
<package version="2.1" displayname="Simple Product" debug="true" includeentityhelper="false">

    <query name="Products" rowElementName="Product">
        <sql>
            <![CDATA[
                WITH Categories (ParentCategoryID, CategoryID, Name, ComputedLevel, Sort) AS
                    (
                    SELECT c.ParentCategoryID, c.CategoryID, c.Name, 0 AS ComputedLevel, CAST('\'+c.Name AS NVARCHAR(255))
                    FROM Category AS c
                    WHERE ParentCategoryID = 0
                    AND Deleted=0
                    AND Published=1
                    UNION ALL
                    SELECT c.ParentCategoryID, c.CategoryID, c.Name, ComputedLevel + 1, CAST(s.Sort + '\'+c.Name AS NVARCHAR(255))
                    FROM Category AS c
                    INNER JOIN Categories AS s ON c.ParentCategoryID = s.CategoryID
                    WHERE Deleted=0
                    AND Published=1
                    )

                    SELECT ParentCategoryID, c.CategoryID, Sort, p.ProductID, p.Name, p.SEName
                    FROM Categories c (NOLOCK)
                    LEFT JOIN ProductCategory pc (NOLOCK) ON pc.CategoryID = c.CategoryID
                    JOIN Product p (NOLOCK) ON p.ProductID = pc.ProductID

                    ORDER BY 3,5
            ]]>
        </sql>

    </query>

    <PackageTransform>
        <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:aspdnsf="urn:aspdnsf" exclude-result-prefixes="aspdnsf">
            <xsl:output method="html" omit-xml-declaration="yes" />

            <xsl:param name="LocaleSetting" select="/root/Runtime/LocaleSetting" />
            <xsl:param name="WebConfigLocaleSetting" select="/root/Runtime/WebConfigLocaleSetting" />
            <xsl:param name="XmlPackageName" select="/root/System/XmlPackageName" />
            <xsl:param name="SecID">
                <xsl:choose>
                    <xsl:when test="count(/root/QueryString/sectionid) > 0">
                        <xsl:value-of select="/root/QueryString/sectionid" />
                    </xsl:when>
                    <xsl:otherwise>0</xsl:otherwise>
                </xsl:choose>
            </xsl:param>

            <xsl:param name="CategoryID">
                <xsl:choose>
                    <xsl:when test="/root/System/PageName = 'showmanufacturer.aspx' or /root/System/PageName = 'showsection.aspx' or /root/System/PageName = 'showdistributor.aspx' or /root/System/PageName = 'showvector.aspx' or /root/System/PageName = 'showgenre.aspx'">0</xsl:when>
                    <xsl:when test="/root/System/PageName = 'showcategory.aspx' and boolean(/root/QueryString/categoryid)">
                        <xsl:value-of select="/root/QueryString/categoryid"/>
                    </xsl:when>
                    <xsl:when test="(/root/System/PageName = 'showcategory.aspx' or /root/System/PageName = 'showproduct.aspx') and boolean(/root/Cookies/LastViewedEntityInstanceID) and /root/Cookies/LastViewedEntityName = 'Category'">
                        <xsl:value-of select="/root/Cookies/LastViewedEntityInstanceID"/>
                    </xsl:when>
                    <xsl:otherwise>0</xsl:otherwise>
                </xsl:choose>
            </xsl:param>

            <xsl:param name="AncestorID">
                <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
                    <xsl:value-of select="ancestor::*/EntityID"/>
                </xsl:for-each>
            </xsl:param>

            <xsl:param name="ParentID">
                <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
                    <xsl:value-of select="parent::*/EntityID"/>
                </xsl:for-each>
            </xsl:param>

            <xsl:param name="CatID">
                <xsl:choose>
                    <xsl:when test="count(/root/QueryString/categoryid) > 0">
                        <xsl:value-of select="/root/QueryString/categoryid" />
                    </xsl:when>
                    <xsl:otherwise>0</xsl:otherwise>
                </xsl:choose>
            </xsl:param>

            <xsl:template match="/">
                <xsl:element name="ul">
                    <xsl:attribute name="id">
                        <![CDATA[accordion3]]>
                    </xsl:attribute>
                    <xsl:apply-templates select="/root/Products/Product">
                        <xsl:with-param name="prefix" select="''"/>
                    </xsl:apply-templates>
                </xsl:element>
            </xsl:template>

            <xsl:template match="Product">
                <xsl:param name="prefix"></xsl:param>
                <xsl:param name="eName" select="aspdnsf:GetMLValue(Name)" />

                    <xsl:if test="number(ParentEntityID) != 0">

                            <xsl:if test="EntityID = $CategoryID or descendant::Entity/EntityID = $CategoryID">
                                <xsl:attribute name="style">font-weight:bold</xsl:attribute>
                            </xsl:if>
                            <xsl:value-of select="$eName"/>

                    </xsl:if>
                    <xsl:if test="number(ParentEntityID) = 0">

                            <xsl:value-of select="$eName"/>

                    </xsl:if>
                    <xsl:if test="count(child::Entity)>0">

                            <xsl:apply-templates select="Product">
                                <xsl:with-param name="prefix" select="concat($prefix, '  ')"/>
                            </xsl:apply-templates>

                    </xsl:if>

            </xsl:template>

        </xsl:stylesheet>
    </PackageTransform>
</package>

The UL is created here:

<xsl:template match="/">
                <xsl:element name="ul">
                    <xsl:attribute name="id">
                        <![CDATA[accordion3]]>
                    </xsl:attribute>
                    <xsl:apply-templates select="/root/Products/Product">
                        <xsl:with-param name="prefix" select="''"/>
                    </xsl:apply-templates>
                </xsl:element>
            </xsl:template>

And here is where the product link is created:

    <xsl:template match="Product">
        <xsl:param name="prefix"></xsl:param>
        <xsl:param name="eName" select="aspdnsf:GetMLValue(Name)" />

            <xsl:if test="number(ParentEntityID) != 0">

                    <xsl:if test="EntityID = $CategoryID or descendant::Entity/EntityID = $CategoryID">
                        <xsl:attribute name="style">font-weight:bold</xsl:attribute>
                    </xsl:if>
                    <xsl:value-of select="$eName"/>

            </xsl:if>
            <xsl:if test="number(ParentEntityID) = 0">

                    <xsl:value-of select="$eName"/>

            </xsl:if>
            <xsl:if test="count(child::Entity)>0">

                    <xsl:apply-templates select="Product">
                        <xsl:with-param name="prefix" select="concat($prefix, '  ')"/>
                    </xsl:apply-templates>

            </xsl:if>

    </xsl:template>

EDIT: ADDED XML extract:

<Product>
  <ParentCategoryID>77</ParentCategoryID>
  <CategoryID>78</CategoryID>
  <Sort>\Box Product\Accessories\AA990F</Sort>
  <ProductID>299</ProductID>
  <Name>Air compressor</Name>
  <SEName>air-compressor</SEName>
</Product>

Body:
I am posting this answer because may someone face this problem in future..
Use this code to render products with categoies.

Example:

Category 1

.Product 1

.product 2

Category 2

.Product 1
.Product 2

<?xml version="1.0" standalone="yes" ?>
<package version="2.1" displayname="Simple Product" debug="false"
includeentityhelper="false">
 <query name="Products" rowElementName="Product">
<sql>
  <![CDATA[
            WITH Categories (ParentCategoryID, CategoryID, Name,
         ComputedLevel, Sort) AS
                (
                SELECT c.ParentCategoryID, c.CategoryID, c.Name, 0 AS
                   ComputedLevel, CAST('\'+c.Name AS NVARCHAR(255))
                FROM Category AS c
                WHERE ParentCategoryID =@CatID
                AND Deleted=0
                AND Published=1
                UNION ALL
                SELECT c.ParentCategoryID, c.CategoryID, c.Name,
              ComputedLevel + 1, CAST(s.Sort + '\'+c.Name AS
               NVARCHAR(255))
                FROM Category AS c
                INNER JOIN Categories AS s ON c.ParentCategoryID =
              s.CategoryID
                WHERE Deleted=0
                AND Published=1
                )

                SELECT ParentCategoryID, c.CategoryID,C.Name as
                CategoryName, Sort, p.ProductID, p.Name, p.SEName
                FROM Categories c (NOLOCK)
                LEFT JOIN ProductCategory pc (NOLOCK) ON pc.CategoryID =
                c.CategoryID
                JOIN Product p (NOLOCK) ON p.ProductID = pc.ProductID

                ORDER BY 3,5
                  ]]>
                    </sql>
                 <queryparam paramname="@CatID"
                  paramtype="runtime"   requestparamname="CatID"

sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@SecID"          paramtype="runtime"   requestparamname="SecID"                                         sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@ManID"          paramtype="runtime"   requestparamname="ManID"                                         sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@DistID"         paramtype="runtime"   requestparamname="DistID"                                        sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@GenreID"        paramtype="runtime"   requestparamname="GenreID"                                       sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@VectorID"       paramtype="runtime"   requestparamname="VectorID"                                      sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@locale"         paramtype="runtime"   requestparamname="LocaleSetting"                                 sqlDataType="varchar" defvalue="en-US"  validationpattern="" />
    <queryparam paramname="@CustLevelID"    paramtype="runtime"   requestparamname="CustomerLevelID"                               sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@AffID"          paramtype="runtime"   requestparamname="AffiliateID"                                   sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@ProdTypeID"     paramtype="runtime"   requestparamname="ProductTypeFilterID"                           sqlDataType="int"     defvalue="1"      validationpattern="" />
    <queryparam paramname="@pgnum"          paramtype="request"   requestparamname="pagenum"                                       sqlDataType="int"     defvalue="1"      validationpattern="" />
    <queryparam paramname="@InvFilter"      paramtype="appconfig" requestparamname="HideProductsWithLessThanThisInventoryLevel"    sqlDataType="int"     defvalue="0"      validationpattern="" />
    <queryparam paramname="@entityname"     paramtype="runtime"   requestparamname="EntityName"                                    sqlDataType="varchar" defvalue=""       validationpattern="" />
    <queryparam paramname="@StoreID"        paramtype="runtime"   requestparamname="StoreID"                                                           sqlDataType="int"       defvalue="1"      validationpattern="" />
    <queryparam paramname="@FilterProduct"  paramtype="runtime"   requestparamname="FilterProduct"                                                   sqlDataType="bit"     defvalue="0"      validationpattern="" />
  </query>

  <PackageTransform>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:aspdnsf="urn:aspdnsf" exclude-result-prefixes="aspdnsf">
      <xsl:output method="html" omit-xml-declaration="yes" />

      <xsl:param name="LocaleSetting" select="/root/Runtime/LocaleSetting" />
      <xsl:param name="WebConfigLocaleSetting" select="/root/Runtime/WebConfigLocaleSetting" />
      <xsl:param name="XmlPackageName" select="/root/System/XmlPackageName" />
      <xsl:param name="SecID">

        <xsl:variable name="ShowSubcatsInGrid" select="aspdnsf:AppConfig('ShowSubcatsInGrid')" />
        <xsl:variable name="EntityName" select="/root/Runtime/EntityName" />
        <xsl:variable name="EntityID" select="/root/Runtime/EntityID" />

        <xsl:variable name="CurrentEntity" select="/root/EntityHelpers/*[name()=$EntityName]/descendant::Entity[EntityID=$EntityID]" />

        <xsl:choose>
          <xsl:when test="count(/root/QueryString/sectionid) &gt; 0">
            <xsl:value-of select="/root/QueryString/sectionid" />
          </xsl:when>
          <xsl:otherwise>0</xsl:otherwise>
        </xsl:choose>
      </xsl:param>

      <xsl:param name="CategoryID">
        <xsl:choose>
          <xsl:when test="/root/System/PageName = 'showmanufacturer.aspx' or /root/System/PageName = 'showsection.aspx' or /root/System/PageName = 'showdistributor.aspx' or /root/System/PageName = 'showvector.aspx' or /root/System/PageName = 'showgenre.aspx'">0</xsl:when>
          <xsl:when test="/root/System/PageName = 'showcategory.aspx' and boolean(/root/QueryString/categoryid)">
            <xsl:value-of select="/root/QueryString/categoryid"/>
          </xsl:when>
          <xsl:when test="(/root/System/PageName = 'showcategory.aspx' or /root/System/PageName = 'showproduct.aspx') and boolean(/root/Cookies/LastViewedEntityInstanceID) and /root/Cookies/LastViewedEntityName = 'Category'">
            <xsl:value-of select="/root/Cookies/LastViewedEntityInstanceID"/>
          </xsl:when>
          <xsl:otherwise>0</xsl:otherwise>
        </xsl:choose>
      </xsl:param>

      <xsl:param name="AncestorID">

        <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
          <xsl:value-of select="ancestor::*/EntityID"/>
        </xsl:for-each>
      </xsl:param>

      <xsl:param name="ParentID">
        <xsl:for-each select="/root/EntityHelpers/Category//Entity[EntityID = $CategoryID]">
          <xsl:value-of select="parent::*/EntityID"/>
        </xsl:for-each>
      </xsl:param>

      <xsl:param name="CatID">

        <xsl:choose>
          <xsl:when test="count(/root/QueryString/categoryid) &gt; 0">
            <xsl:value-of select="/root/QueryString/categoryid" />
          </xsl:when>
          <xsl:otherwise>0</xsl:otherwise>
        </xsl:choose>
      </xsl:param>

      <xsl:template match="/">
        <xsl:element name="ul">
          <xsl:attribute name="id">
            <![CDATA[accordion3]]>
          </xsl:attribute>
          <xsl:apply-templates select="/root/Products/Product">
            <xsl:with-param name="prefix" select="''"/>
          </xsl:apply-templates>
        </xsl:element>
      </xsl:template>

      <xsl:template match="Product">
        <xsl:param name="prefix"></xsl:param>
        <xsl:param name="eName" select="aspdnsf:GetMLValue(Name)" />
         <xsl:variable name="oldname" select="'old'" />
        <li >
          <!--<xsl:value-of select="$prefix" />-->

          <xsl:if test="number(ParentEntityID) != 0">
            <!--<span class="catMark">&gt;&gt;</span>&#160;-->

            <!--<xsl:if test="$oldname != CategoryName">-->
          <xsl:if test ="not(preceding-sibling::Product[(CategoryName/text() = current()/CategoryName/text())])">
            <h1>
              <xsl:value-of select="CategoryName"/>
            </h1>
                 <!--<xsl:variable name="oldname" select="CategoryName" />-->
                <!--<xsl:copy>
                 <xsl:value-of name="oldname" select="CategoryName"/>
                </xsl:copy>-->

              </xsl:if>

            <a href="{concat('p-',ProductID,'-',SEName,'.aspx')}">
              <xsl:if test="EntityID = $CategoryID or descendant::Entity/EntityID = $CategoryID">
              <xsl:attribute name="style">font-weight:bold</xsl:attribute>
              </xsl:if>
              <xsl:value-of select="$eName"/>
            </a>

          </xsl:if>
          <xsl:if test="number(ParentEntityID) = 0">
            <div class="menuText">
              <xsl:value-of select="$eName"/>
            </div>
          </xsl:if>

          <xsl:if test="count(child::Product)&gt;0">

            <ul >
              <xsl:apply-templates select="Product">
                <xsl:with-param name="prefix" select="concat($prefix, '&#160;&#0160;')"/>
              </xsl:apply-templates>
            </ul>
          </xsl:if>
        </li>
      </xsl:template>

    </xsl:stylesheet>
  </PackageTransform>
</package>