问:
iOS: MFMailComposeViewController not getting closed
I am using MFMailComposeViewController in my application to compose a feedback E-Mail. The MFMailComposeViewController gets displayed, but can't be closed.

Method used to open the MFMailComposeViewController modal window:

```<code>-(IBAction) feedbackBtnClicked:(id)sender {

    // Dismiss the Old View Controller
    [self dismissViewControllerAnimated:NO completion:NULL];

    // Present the New View Controller
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
        mail.mailComposeDelegate = self;
        [mail setSubject:@"Sample Subject"];
        [mail setMessageBody:@"Here is some main text in the email!" isHTML:NO];
        [mail setToRecipients:@[@"example@mail.com"]];

        [self presentViewController:mail animated:YES completion:NULL];
    }
    else
    {
        NSLog(@"This device cannot send email");
    }
}
</code>```

Here is what happens, when clicking on the buttons:

Senden (Send) - The E-Mail gets sent, but the modal window stays open; clicking on that button multiple times results in sending multiple E-Mails without the modal window ever getting closed.
Abbrechen (Cancel) - Nothing happens

How to dismiss make sure the MFMailComposeViewController gets dismissed after clicking on those buttons?

答:
You need to implement the MFMailComposeViewControllerDelegate method mailComposeController:didFinishWithResult:error:, and dismiss the mail view controller…

```<code>- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result
{
  [self dismissViewControllerAnimated:YES completion:NULL];
}
</code>```

Body:
I am using MFMailComposeViewController in my application to compose a feedback E-Mail. The MFMailComposeViewController gets displayed, but can't be closed.

Method used to open the MFMailComposeViewController modal window:

-(IBAction) feedbackBtnClicked:(id)sender {

    // Dismiss the Old View Controller
    [self dismissViewControllerAnimated:NO completion:NULL];

    // Present the New View Controller
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mail = [[MFMailComposeViewController alloc] init];
        mail.mailComposeDelegate = self;
        [mail setSubject:@"Sample Subject"];
        [mail setMessageBody:@"Here is some main text in the email!" isHTML:NO];
        [mail setToRecipients:@[@"example@mail.com"]];

        [self presentViewController:mail animated:YES completion:NULL];
    }
    else
    {
        NSLog(@"This device cannot send email");
    }
}

Here is what happens, when clicking on the buttons:

Senden (Send) - The E-Mail gets sent, but the modal window stays open; clicking on that button multiple times results in sending multiple E-Mails without the modal window ever getting closed.
Abbrechen (Cancel) - Nothing happens

How to dismiss make sure the MFMailComposeViewController gets dismissed after clicking on those buttons?

Body:
You need to implement the MFMailComposeViewControllerDelegate method mailComposeController:didFinishWithResult:error:, and dismiss the mail view controller…

- (void)messageComposeViewController:(MFMessageComposeViewController *)controller
                 didFinishWithResult:(MessageComposeResult)result
{
  [self dismissViewControllerAnimated:YES completion:NULL];
}


来源: stackexchange

问:
How to remove margin-left and margin-right of col class in bootstrap?
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

```<code><div class="container">
    <div class="row">
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
        <div class="col-sm-6">
            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
        </div>
        <div class="col-sm-3">
            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
        </div>
    </div>
</div>
</code>```

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

答:
I misunderstood your question, here is the correct answer:

If you want the images to look like this:

Corrected images next to each other

instead of like this:

old images using your code for example

You need to delete the padding from the Col-sm that bootstrap has.

how?

Is not a good practice to delete the padding from the entire col-sm class.. so i would rather create a class for this particular case named (I dont know) "no-padding". and do this:

```<code><div class="container">
<div class="row">
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
    <div class="col-sm-6 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
    </div>
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
</div>
</code>```

And now in your CSS:

```<code>no-padding {
padding: 0px;
}
</code>```

That should fix the images from having spaces between them.

ContentLicense: CC BY-SA 3.0

Body:
I am new to bootstrap. I put 3 images side by side but they are not adjacent. There is a margin between them. This is picture

I want to eliminate the margins so that the images are adjacent. The center image size is 1200x400 and both left and right images size is 600x400. And also I've used img-responsive class. what is the actual problem?
Here is the code

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />

            <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />

Also you notice in picture, these pictures are not vertically aligned properly how to fix it.

Thanks!

Body:
I misunderstood your question, here is the correct answer:

If you want the images to look like this:

Corrected images next to each other

instead of like this:

old images using your code for example

You need to delete the padding from the Col-sm that bootstrap has.

how?

Is not a good practice to delete the padding from the entire col-sm class.. so i would rather create a class for this particular case named (I dont know) "no-padding". and do this:

<div class="container">
<div class="row">
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
    <div class="col-sm-6 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/center1.jpg" runat="server" />
    </div>
    <div class="col-sm-3 no-padding">
        <asp:Image CssClass="img-responsive" ImageUrl="images/right.jpeg" runat="server" />
    </div>
</div>

And now in your CSS:

no-padding {
padding: 0px;
}

That should fix the images from having spaces between them.


问:
How to set up Electron with React and TypeScript?
I'm coding an app with Electron, React (jsx) with Babel. I switched to TypeScript this evening and I can't figure out how to make everything work. Npm packets set up either React or TypeScript, but not both, and not with Electron. (I also have to implement webpack.)

My question is: what is the minimal structure of folders, files and packets to make everything work? I just want to display a hello world on the main window using a React component written in TypeScript.
Currently, my packets are Electron, React, ReactDOM, TypeScript.

答:
First of all i followed this tutorial on the official Website of Typescript: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html

If you follow every step you will end up with a dist folder that contains a bundle.js (with the bundled code that Webpack receives from Typescript) and a src folder that containes the .tsx files. Typescript supports React out of the box, just add "jsx": "react" to the tsconfig.json and renane your file .tsx instead of .ts. After that add index.js to the root folder(copied from here: https://github.com/electron/electron-quick-start/blob/master/main.js).

Install electron locally npm install electron --save-dev or globally npm install -g electron

Run webpack with webpack while in the app folder (to generate the ./dist/bundle.js file)

Run electron with electron . while in the app folder

The important thing to notice is the entry point of webpack: its ./src/index.tsx while electron entry point is ./index.js. Electron load index.js that loads index.html that loads ./dist/bundle.js. We can transtale index.js to index.ts but then we would have to change the entry point of webpack.

ContentLicense: CC BY-SA 4.0


问:
Angular Material layout conflicts with my original CSS
I just started to learn Angular Material. The problem is that after I include the Angular Material script, my original CSS gets messed up. The margin-top simply doesn't work, no matter what value I set.

Could anyone help me?

My login form CSS is like this:

```<code>#login {
width: 300px;
height: 240px;
margin-left: auto;
margin-right: auto;
margin-top: 100px;
background: #EEEEEF;
padding: 30px 30px 0px 30px;
}
</code>```

The margin-top conflicts with Angular Material. How should I solve that?

答:
try to keep important for margin-top:100px !important;
If not solved try to keep your code so that we can help you</p>

Body:
I just started to learn Angular Material. The problem is that after I include the Angular Material script, my original CSS gets messed up. The margin-top simply doesn't work, no matter what value I set.

Could anyone help me?

My login form CSS is like this:

#login {
width: 300px;
height: 240px;
margin-left: auto;
margin-right: auto;
margin-top: 100px;
background: #EEEEEF;
padding: 30px 30px 0px 30px;
}

The margin-top conflicts with Angular Material. How should I solve that?


问:
how to mark row on gridview by any value?
i have gridview that contain:

```<code>Fname|Born
aa   |03/05
bb   |19/01
cc   |03/08
dd   |19/01
</code>```

if today is: 19/01/2011  how to mark in red color the 2 rows that Satisfies the condition ?

in C# asp.net

thanks for any help

答:
```<code>this.MyGridView.RowDataBound += (s, ea) =>
{
 if (ea.Row.Cells[1].Text.Contains(string.Format("{0}/0{1}", DateTime.Now.Day, DateTime.Now.Month)))
 {
  ea.Row.BackColor = Color.Red;
 }
};
this.MyGridView.DataBind();
</code>```

This does what you want.

Notice the string.format has a 0 which shouldn't be there. This is because DateTime.Now.Month returns 1 instead of 01.

[edit]

Noticed sometime ago that there's a better way to compare the date to your value using

```<code>if (ea.Row.Cells[1].Text.Contains(DateTime.Now.ToString(MM/dd)))
</code>```

ContentLicense: CC BY-SA 2.5

Body:
i have gridview that contain:

Fname|Born
aa   |03/05
bb   |19/01
cc   |03/08
dd   |19/01

if today is: 19/01/2011  how to mark in red color the 2 rows that Satisfies the condition ?

in C# asp.net

thanks for any help

Body:
this.MyGridView.RowDataBound += (s, ea) =>
{
 if (ea.Row.Cells[1].Text.Contains(string.Format("{0}/0{1}", DateTime.Now.Day, DateTime.Now.Month)))
 {
  ea.Row.BackColor = Color.Red;
 }
};
this.MyGridView.DataBind();

This does what you want.

Notice the string.format has a 0 which shouldn't be there. This is because DateTime.Now.Month returns 1 instead of 01.

[edit]

Noticed sometime ago that there's a better way to compare the date to your value using

if (ea.Row.Cells[1].Text.Contains(DateTime.Now.ToString(MM/dd)))


问:
How can i get my program to remove from end of list instead of start in python
```<code>class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current.data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([x for x in self])

    def __len__(self):
        return self.size

    def pop(self):
        data = self.head.data
        self.head = self.head.next
        return data

if __name__ == '__main__':
    list = Stack()

    reply = 0

    while reply!="5":

        print("1. Add to list")
        print("2. Display list")
        print("3. Size of list")
        print("4. Remove from list")
        print("5. Exit")

        reply = int(input("what would you like to do?"))

        if reply == 1:
            data = input("Add an element:")
            list.append(data)
        if reply == 2:
            print(list)
        if reply == 3:
            print(len(list))
        if reply == 4:
            list.pop()

        if reply == 5:
            print("good bye")
</code>```

I'm a fairly new to python , and for a class assignment i have been asked to implement a stack linked list with interface, i understand the basics of a linked list however, when i press 4 it should remove the last element which i have inputted , however it removes the first which is not (stack - last in first out)
Any help would be appreciated .

答:
This seems to work, but i had to make some additional changes to your code

```<code>class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current # change here, return object instead of object data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([str(x.data) for x in self]) # change here

    def __len__(self):
        return self.size

    def pop(self):
        # find last element while keeping track of item next to last
        # set new tail to next to last item and set the next item
        # in the new tail to none

        if self.head == self.tail:
            returnval = self.head
            self.head = None
            self.tail = None
            return returnval
        old_tail_data = self.tail.data
        previous = self.head
        for thing in self:
            if thing != self.tail:
                previous = thing
            if thing == self.tail:
                previous.next = None
                self.tail = previous

        return old_tail_data

if __name__ == '__main__':
    list = Stack()
    list.append('ha')
    list.append('ho')
    list.append('go')
    list.pop()
    print(list)
</code>```

Example use

```<code>list = Stack()
list.append('ha')
list.append('ho')
list.append('go')
list.pop()
list.pop()
print(list) # should return [ha]
list.append('new1')
list.append('new2')
print(list) # should return [ha,new1,new2]
</code>```

with the Menu

The menu code

```<code>list = Stack()

reply = 0

while reply!="5":

    print("1. Add to list")
    print("2. Display list")
    print("3. Size of list")
    print("4. Remove from list")
    print("5. Exit")

    reply = int(input("what would you like to do?"))

    if reply == 1:
        data = input("Add an element:")
        list.append(data)
    if reply == 2:
        print(list)
    if reply == 3:
        print(len(list))
    if reply == 4:
        list.pop()

    if reply == 5:
        print("good bye")
</code>```

Body:
class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current.data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([x for x in self])

    def __len__(self):
        return self.size

    def pop(self):
        data = self.head.data
        self.head = self.head.next
        return data

if __name__ == '__main__':
    list = Stack()

    reply = 0

    while reply!="5":

        print("1. Add to list")
        print("2. Display list")
        print("3. Size of list")
        print("4. Remove from list")
        print("5. Exit")

        reply = int(input("what would you like to do?"))

        if reply == 1:
            data = input("Add an element:")
            list.append(data)
        if reply == 2:
            print(list)
        if reply == 3:
            print(len(list))
        if reply == 4:
            list.pop()

        if reply == 5:
            print("good bye")

I'm a fairly new to python , and for a class assignment i have been asked to implement a stack linked list with interface, i understand the basics of a linked list however, when i press 4 it should remove the last element which i have inputted , however it removes the first which is not (stack - last in first out)
Any help would be appreciated .

Body:
This seems to work, but i had to make some additional changes to your code

class Node:
    def __init__(self):
        self.data = None
        self.next = None

class Stack:

    def __init__(self):
        self.size = 0
        self.head = None
        self.tail = None

    def append(self, data):
        node = Node()
        node.data = data
        if not self.head:
            self.head = node
            self.tail = node
            self.size = 1
            return
        self.tail.next = node
        self.tail = node
        self.size += 1

    def __repr__(self):
        return 'Stack(%s)' % str(self)

    def __iter__(self):
        current = self.head
        while current:
            yield current # change here, return object instead of object data
            current = current.next

    def __str__(self):
        return '[%s]' % ', '.join([str(x.data) for x in self]) # change here

    def __len__(self):
        return self.size

    def pop(self):
        # find last element while keeping track of item next to last
        # set new tail to next to last item and set the next item
        # in the new tail to none

        if self.head == self.tail:
            returnval = self.head
            self.head = None
            self.tail = None
            return returnval
        old_tail_data = self.tail.data
        previous = self.head
        for thing in self:
            if thing != self.tail:
                previous = thing
            if thing == self.tail:
                previous.next = None
                self.tail = previous

        return old_tail_data

if __name__ == '__main__':
    list = Stack()
    list.append('ha')
    list.append('ho')
    list.append('go')
    list.pop()
    print(list)

Example use

list = Stack()
list.append('ha')
list.append('ho')
list.append('go')
list.pop()
list.pop()
print(list) # should return [ha]
list.append('new1')
list.append('new2')
print(list) # should return [ha,new1,new2]

with the Menu

The menu code

list = Stack()

reply = 0

while reply!="5":

    print("1. Add to list")
    print("2. Display list")
    print("3. Size of list")
    print("4. Remove from list")
    print("5. Exit")

    reply = int(input("what would you like to do?"))

    if reply == 1:
        data = input("Add an element:")
        list.append(data)
    if reply == 2:
        print(list)
    if reply == 3:
        print(len(list))
    if reply == 4:
        list.pop()

    if reply == 5:
        print("good bye")


问:
Why should a blank final variable be explicitly initialised in all constructors?
I have just started reading Java. One thing I find confusing is that a blank final variable should be initialized in all constructors of a class. If I have a class with 3 constructors and I initialise a blank final variable in one constructor, why do I need to initialise the same blank final variable in other two constructors also ?</p>

答:
This is because only one constructor is executed when an instance of your class is created.

I prefer to have one constructor which serves as the most common constructor, and call this from the other constructors. In one constructor, you can call another constructor of the same class via this(...). Example:

```<code>class MyClass {

    private final int a;

    private final String b;

    private double c;

    /**
     * Most common constructor.
     */
    public MyClass(int a, String b, double c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public MyClass(int a, String b) {
        this(a, b, 0.0);
    }

    public MyClass(double c) {
        this(0, null, c);
    }

    // other constructors as needed

}
</code>```

This way, you have focused the responsibility to initialize the instance in one constructor. The other constructors rely on that one.

Body:
This is because only one constructor is executed when an instance of your class is created.

I prefer to have one constructor which serves as the most common constructor, and call this from the other constructors. In one constructor, you can call another constructor of the same class via this(...). Example:

class MyClass {

    private final int a;

    private final String b;

    private double c;

    /**
     * Most common constructor.
     */
    public MyClass(int a, String b, double c) {
        this.a = a;
        this.b = b;
        this.c = c;
    }

    public MyClass(int a, String b) {
        this(a, b, 0.0);
    }

    public MyClass(double c) {
        this(0, null, c);
    }

    // other constructors as needed

}

This way, you have focused the responsibility to initialize the instance in one constructor. The other constructors rely on that one.


问:
Java free code signing service
I have a Java application (actually JWS, Java Web Start).

That application is signed by self-signed certificate, created by myself. As expected, when clients try running that application they are getting warning messages and actually have to manually import my certificate (.cer file) into "Signer CA" certificate list of their Java control panel.
Only after they manually import my self-signed certificate, warnings are gone.

As you can imagine that's a problem because - it's a technical thing and clients need assistance from my side to have it done.

As my application is not earning not even nearly enough to cover yearly expenses for paid certificate, i started looking for free alternatives. I tried with "Let's encrypt" free certificate, but regardless of that, when my clients start the application signed by "Let's encrypt" free certificate, same thing happens - warnings about self-signed certificate again and i'm back to square one!

What should i do? Seems like free "Let's encrypt" certificates are not trusted  by Java automatically. Which trusted free code signing certificate should i use?

Additional info about my app: it's not an open source project, it's built using jdk8u122, clients are running it using jre8u155. Application is built by Ant script that's using jarsigner provided by JDK and "signjar" Ant task.

答:
There isn't a free alternative to do this. The whole idea of the signing by a trusted authority is that your application is that:

Authentication, Verifying who the author of the software is.

Integrity Verifying that the software hasn’t been tampered with since it was signed.

Title: Java free code signing service


问:
Cannot read Request.Content in ASP.NET WebApi controller
I am writing a proxy using WebApi in a TransferMode.Streamed HttpSelfHostConfiguration exe.

When I use fiddler to post to my ApiController, for some reason I cannot read the Request.Content - it returns "" even if I have POSTed data

```<code>public class ApiProxyController : ApiController
{

    public Task<HttpResponseMessage> Post(string path)
    {
        return Request.Content.ReadAsStringAsync().ContinueWith(s =>
        {
            var content = new StringContent(s.Result); //s.Result is ""
                CopyHeaders(Request.Content.Headers, content.Headers);
            return Proxy(path, content);
        }).Unwrap();
    }

    private Task<HttpResponseMessage> Proxy(string path, HttpContent content)
    {
        ...
    }
}
</code>```

Here is my web request

```<code>POST http://localhost:3001/api/values HTTP/1.1
Host: localhost:3001
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type: application/json
Content-Length: 26

{ "text":"dfsadfsadfsadf"}
</code>```

What I am doing wrong? Why is s.Result coming back as the empty string rather than the raw json?

答:
Request.Content.ReadAsStreamAsync().Result.Seek( 0, System.IO.SeekOrigin.Begin)

new System.IO.StreamReader(Request.Content.ReadAsStreamAsync().Result).ReadToEnd()

Body:
I am writing a proxy using WebApi in a TransferMode.Streamed HttpSelfHostConfiguration exe.

When I use fiddler to post to my ApiController, for some reason I cannot read the Request.Content - it returns "" even if I have POSTed data

public class ApiProxyController : ApiController
{

    public Task<HttpResponseMessage> Post(string path)
    {
        return Request.Content.ReadAsStringAsync().ContinueWith(s =>
        {
            var content = new StringContent(s.Result); //s.Result is ""
                CopyHeaders(Request.Content.Headers, content.Headers);
            return Proxy(path, content);
        }).Unwrap();
    }

    private Task<HttpResponseMessage> Proxy(string path, HttpContent content)
    {
        ...
    }
}

Here is my web request

POST http://localhost:3001/api/values HTTP/1.1
Host: localhost:3001
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Content-Type: application/json
Content-Length: 26

{ "text":"dfsadfsadfsadf"}

What I am doing wrong? Why is s.Result coming back as the empty string rather than the raw json?


问:
Intent - if activity is running, bring it to front, else start a new one (from notification)
My app has notifications, which - obviously - without any flags, start a new activity every time so I get multiple same activities running on top of each other, which is just wrong.

What I want it to do is to bring the activity specified in the notifications pending intent, to the front if it is already running, otherwise start it.

So far, the intent/pending intent for that notification I have is

```<code>private static PendingIntent prepareIntent(Context context) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
</code>```

and weirdly, it sometimes works, sometimes it doesn't... I feel like I've already tried every single combination of flags.

答:
I know it is old, but nothing from the above were fitting to my application.

Without changing manifests and other configuration, here is the code to bring your app back to front - or opening it when it is closed

```<code>Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
notificationIntent.setPackage(null); // The golden row !!!
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
</code>```

Body:
My app has notifications, which - obviously - without any flags, start a new activity every time so I get multiple same activities running on top of each other, which is just wrong.

What I want it to do is to bring the activity specified in the notifications pending intent, to the front if it is already running, otherwise start it.

So far, the intent/pending intent for that notification I have is

private static PendingIntent prepareIntent(Context context) {
    Intent intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);

    return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

and weirdly, it sometimes works, sometimes it doesn't... I feel like I've already tried every single combination of flags.

Body:
I know it is old, but nothing from the above were fitting to my application.

Without changing manifests and other configuration, here is the code to bring your app back to front - or opening it when it is closed

Intent notificationIntent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName());
notificationIntent.setPackage(null); // The golden row !!!
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);


问:
Django query table to find Item that only exist in Parent field
I been struggling with doing a query to get the rows where a Item only exsist in Parnet field and not Child field.

This is the models.

```<code>class Item(models.Model):
    text = models.CharField()

class ItemRelations(models.Model):
    child = models.ForeignKey('Item', related_name='itemchild')
    parent = models.ForeignKey('Item', related_name='itemparent')
</code>```

So I only want to filter out the Items that are not a child, but is a Parent. I call it the firstParent.

I tried so many different ways. I want to accomplish something like this.

```<code>firstParent = Item.objects.filter(ItemRelations_parent__is=self).exclude(ItemRelations_child__is=self)
</code>```

Is it possible. Or does one have to make several queries and loops to manage this?

答:
I'd suggest using the isnull filter for readability.

firstParent = Item.objects.filter(itemparent=self, itemchild__isnull=True)

In the specific example you've given in this comment, Item.pk is the attribute on the Item class.  You want the item instance, not the class.

I believe, re-reading, that the question is:

Show the Item where the Item is a parent, but not a child.  In that case:

firstParent = Item.objects.filter(itemparent__isnull=False, itemchild__isnull=True) will give you the queryset of objects that match that.

You may, subsequently wish to filter it further to match other aspects.  Remember that django querysets are lazy. Don't confuse making several filters with making actual queries/database hits.

QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated.

Body:
I been struggling with doing a query to get the rows where a Item only exsist in Parnet field and not Child field.

This is the models.

class Item(models.Model):
    text = models.CharField()

class ItemRelations(models.Model):
    child = models.ForeignKey('Item', related_name='itemchild')
    parent = models.ForeignKey('Item', related_name='itemparent')

So I only want to filter out the Items that are not a child, but is a Parent. I call it the firstParent.

I tried so many different ways. I want to accomplish something like this.

firstParent = Item.objects.filter(ItemRelations_parent__is=self).exclude(ItemRelations_child__is=self)

Is it possible. Or does one have to make several queries and loops to manage this?


问:
Android - Add UNDO SnackBar to Swipe to delete
I have successfully implemented the swipe to delete action within my recyclerView.

The list I inflate the recyclerView with is locally stored and isn't in any database.

What I tried to do is to save the element to a temporary variable and if the user presses the undo button, I would restore it.

This is my code:

```<code>override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

                    val position = viewHolder.adapterPosition //get position which is swipe

                    if (direction == ItemTouchHelper.LEFT) {  //if swipe left
                        val tmp = activeSubs[position] //temporary variable
                        activeSubs.removeAt(position)
                        adapter!!.removeItem(position)

                        val layout = find<View>(R.id.active_subs_recycler)
                        Snackbar.make(layout, "Subscription Deleted", Snackbar.LENGTH_LONG)
                                .setAction("Undo", { _ ->
                                    activeSubs.add(position-1, tmp)
                                    adapter!!.notifyDataSetChanged()
                                })
                    }
                }
</code>```

My problem is that the SnackBar isn't shown at all, but the element is saved in the temporary variable and deleted from the list.

What am I doing wrong?

P.S. I've looked into other answers here on SO but they suggested to use a Dialog. I really need to use a Snackbar though

答:
After setAction you forgot to call .show() so your code will be like this:

```<code> Snackbar.make(layout, "Subscription Deleted", Snackbar.LENGTH_LONG)
                                .setAction("Undo", { _ ->
                                    activeSubs.add(position-1, tmp)
                                    adapter!!.notifyDataSetChanged()
                                })
.show()
</code>```

For example, I have achieved your goal using this scenario.
  In Main Activity

```<code> tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tempValue = etUsername.getText().toString();
                etUsername.setText("");
                Snackbar.make(view, "Subscription Deleted", Snackbar.LENGTH_LONG)
                        .setAction("Undo", new editTextListener())
                .show();
            }
        });
</code>```

Used inner class for listener:

```<code>private class editTextListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            etUsername.setText(tempValue);
        }
    }
</code>```

Body:
I have successfully implemented the swipe to delete action within my recyclerView.

The list I inflate the recyclerView with is locally stored and isn't in any database.

What I tried to do is to save the element to a temporary variable and if the user presses the undo button, I would restore it.

This is my code:

override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {

                    val position = viewHolder.adapterPosition //get position which is swipe

                    if (direction == ItemTouchHelper.LEFT) {  //if swipe left
                        val tmp = activeSubs[position] //temporary variable
                        activeSubs.removeAt(position)
                        adapter!!.removeItem(position)

                        val layout = find<View>(R.id.active_subs_recycler)
                        Snackbar.make(layout, "Subscription Deleted", Snackbar.LENGTH_LONG)
                                .setAction("Undo", { _ ->
                                    activeSubs.add(position-1, tmp)
                                    adapter!!.notifyDataSetChanged()
                                })
                    }
                }

My problem is that the SnackBar isn't shown at all, but the element is saved in the temporary variable and deleted from the list.

What am I doing wrong?

P.S. I've looked into other answers here on SO but they suggested to use a Dialog. I really need to use a Snackbar though

Body:
After setAction you forgot to call .show() so your code will be like this:

 Snackbar.make(layout, "Subscription Deleted", Snackbar.LENGTH_LONG)
                                .setAction("Undo", { _ ->
                                    activeSubs.add(position-1, tmp)
                                    adapter!!.notifyDataSetChanged()
                                })
.show()

For example, I have achieved your goal using this scenario.
  In Main Activity

 tvTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tempValue = etUsername.getText().toString();
                etUsername.setText("");
                Snackbar.make(view, "Subscription Deleted", Snackbar.LENGTH_LONG)
                        .setAction("Undo", new editTextListener())
                .show();
            }
        });

Used inner class for listener:

private class editTextListener implements View.OnClickListener {
        @Override
        public void onClick(View view) {
            etUsername.setText(tempValue);
        }
    }


问:
React Router 4 dynamic components loaded on the fly from database
I'm migrating to React Router 4.11 from 2.5.1. In the older version, my ISOMORPHIC/UNIVERSAL app retrieves the routes/components dynamically from a database at startup and I want to retain that same functionality with 4.11.

In the 2.5.1 version of react-router, I was able to load routes & components dynamically from the database by calling _createRouter with the routes parameter being the data retrieved from my db as such:

```<code>////////////////////////
// from client entry.js
////////////////////////
async function main() {
  const result = await _createRouter(routes)
  ReactDOM.render(
      <Provider store={store} key="provider">
        <Router history={history}>
          {result}
        </Router>
      </Provider>
    dest
 );
}

//////////////////////
// from shared modules
//////////////////////
function _createRouter(routes) {
     const childRoutes = [ // static routes, ie Home, ForgotPassword, etc];

      ////////////////////////
      // crucial part here
      ////////////////////////
      routes.map(route => {
        const currComponent = require('../../client/components/' + route.route + '.js');
        const obj = {
          path: route.route,
          component: currComponent
        };
        childRoutes.push(obj)
      });

      childRoutes.push({path: '*', component: NotFoundComponent});
      return { path: '', component: .APP, childRoutes: childRoutes };
    }
</code>```

I am frustrated that I cannot find any docs on performing the same event in 4.11. Every example shows the routes hard coded like so:

```<code>render() {
    return (
          <Route path='/' component={Home} />
          <Route path='/home' component={About} />
          <Route path='/topics' component={Topics} />
   )
}
</code>```

This does not appear real-world to me especially for large apps.

Can anyone point me in the direction of accomplishing the same success I had in  2.5.1 with 4.11  insofar as being able to dynamically load my routes/components on the fly from a database?

Thanks much !

答:
Maybe this code is the solution to this issue.   "dynamic route import component"</p>

```<code>import React, {
    Component
} from "react";

const Containers = () => ( < div className = "containers" > Containers < /div>);

class ComponentFactory extends Component{constructor(props){super(props);this.state={RouteComponent:Containers}}
    componentWillMount() {
        const name = this.props.page;
        import ('../pages/' + name + '/index').then(RouteComponent => {
            return this.setState({
                RouteComponent: RouteComponent.default
            })
        }).catch(err => console.log('Failed to load Component', err))
    }
    render() {
        const {RouteComponent } = this.state;
        return (<RouteComponent { ...this.props  }/> );
    }
}
export default ComponentFactory

 <Route path="/:page"
        render={rest => <ComponentFactory
        page={rest.match.params.page}
        {...rest}/>}/>
</code>```

Body:
I'm migrating to React Router 4.11 from 2.5.1. In the older version, my ISOMORPHIC/UNIVERSAL app retrieves the routes/components dynamically from a database at startup and I want to retain that same functionality with 4.11.

In the 2.5.1 version of react-router, I was able to load routes & components dynamically from the database by calling _createRouter with the routes parameter being the data retrieved from my db as such:

////////////////////////
// from client entry.js
////////////////////////
async function main() {
  const result = await _createRouter(routes)
  ReactDOM.render(
      <Provider store={store} key="provider">
        <Router history={history}>
          {result}
        </Router>
      </Provider>
    dest
 );
}

//////////////////////
// from shared modules
//////////////////////
function _createRouter(routes) {
     const childRoutes = [ // static routes, ie Home, ForgotPassword, etc];

      ////////////////////////
      // crucial part here
      ////////////////////////
      routes.map(route => {
        const currComponent = require('../../client/components/' + route.route + '.js');
        const obj = {
          path: route.route,
          component: currComponent
        };
        childRoutes.push(obj)
      });

      childRoutes.push({path: '*', component: NotFoundComponent});
      return { path: '', component: .APP, childRoutes: childRoutes };
    }

I am frustrated that I cannot find any docs on performing the same event in 4.11. Every example shows the routes hard coded like so:

render() {
    return (
          <Route path='/' component={Home} />
          <Route path='/home' component={About} />
          <Route path='/topics' component={Topics} />
   )
}

This does not appear real-world to me especially for large apps.

Can anyone point me in the direction of accomplishing the same success I had in  2.5.1 with 4.11  insofar as being able to dynamically load my routes/components on the fly from a database?

Thanks much !

Body:
Maybe this code is the solution to this issue.   "dynamic route import component"

import React, {
    Component
} from "react";

const Containers = () => ( < div className = "containers" > Containers < /div>);

class ComponentFactory extends Component{constructor(props){super(props);this.state={RouteComponent:Containers}}
    componentWillMount() {
        const name = this.props.page;
        import ('../pages/' + name + '/index').then(RouteComponent => {
            return this.setState({
                RouteComponent: RouteComponent.default
            })
        }).catch(err => console.log('Failed to load Component', err))
    }
    render() {
        const {RouteComponent } = this.state;
        return (<RouteComponent { ...this.props  }/> );
    }
}
export default ComponentFactory

 <Route path="/:page"
        render={rest => <ComponentFactory
        page={rest.match.params.page}
        {...rest}/>}/>


问:
Mocking HttpRequest and HttpResponse for MVC Application
I'm currently writing some unit tests to check the functionality and correct workings of the ASP MVC application that we have written.
In this MVC Application, I'm using a special ActionFilterAttribute that allows for authentication when making requests to the MVC Application.

The code for this ActionFilterAttribute is this:

```<code>using System;
using System.Security.Authentication;
using System.Text;
using System.Web.Mvc;
using TenForce.Execution.Framework;
using TenForce.Execution.Api2.Implementation;

namespace TenForce.Execution.Web.Filters
{
     /// <summary>
     /// This class defines a custom Authentication attribute that can be applied on      controllers.
     /// This results in authentication occurring on all actions that are beeing defined in the controller
     /// who implements this filter.
     /// </summary>
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
     public class AuthenticationFilter : ActionFilterAttribute
     {
         #region IAuthorizationFilter Members

         /// <summary>
         /// This function get's called by the Mvc framework prior to performing any actions on
         /// the controller. The function will check if a call is authorized by the caller.
    /// The function will extract the username and password from the HTTP headers send by
    /// the caller and will validate these against the database to see if there is a valid
    /// account for the user.
    /// If the user can be found in the database, operations will resume, otherwise the action
    /// is canceled.
    /// </summary>
    /// <param name="filterContext">The context for the filter.</param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Call the base operations first.
        base.OnActionExecuting(filterContext);

        // Surround the entire authentication process with a try-catch to prevent errors from
        // breaking the code.
        try
        {
            // Extract the custom authorization header from the HTTP headers.
            string customAuthHeader = Encoding.UTF8.GetString(Convert.FromBase64String(filterContext.RequestContext.HttpContext.Request.Headers["TenForce-Auth"]));

            // Split the header in the subcomponents.
            string[] components = customAuthHeader.Split('|');

            // Check if both components are present.
            if (components.Length >= 2)
            {
                // This header consists of 2 parts, the username and password, seperate by a vertical pipe.
                string username = components[0] ?? string.Empty;
                string password = components[1] ?? string.Empty;
                string databaseId = Authenticator.ConstructDatabaseId(filterContext.HttpContext.Request.RawUrl);

                // Validate the user against the database.
                if (Authenticator.Authenticate(username, password, databaseId))
                {
                    // The request is valid, so add the custom header to inform the request was
                    // authorized.
                    AllowRequest(filterContext);
                    return;
                }

                throw new InvalidCredentialException(@"The provided username & password combination is invalid. Username : " + username);
            }

            // If we reach this point, the authorization request is no longer valid.
            throw new InvalidCredentialException(@"Insufficient parameters supplied for a valid authentication.");
        }
        catch (Exception ex)
        {
            // Log the exception that has occurred.
            Logger.Log(GetType(), ex);

            // Cancel the request, as we could not properly process it.
            CancelRequest(filterContext);
        }
    }

    #endregion

    #region Private Methods

    /// <summary>
    /// Cancels the Athorization and adds the custom tenforce header to the response to
    /// inform the caller that his call has been denied.
    /// </summary>
    /// <param name="authContext">The authorizationContxt that needs to be canceled.</param>
    private static void CancelRequest(ActionExecutingContext authContext)
    {
        authContext.Result = new HttpUnauthorizedResult();
        if (!authContext.RequestContext.HttpContext.Request.ServerVariables[@"SERVER_SOFTWARE"].Contains(@"Microsoft-IIS/7."))
            authContext.HttpContext.Response.AddHeader(@"Tenforce-RAuth", @"DENIED");
        else
            authContext.HttpContext.Response.Headers.Add(@"Tenforce-RAuth", @"DENIED");
    }

    /// <summary>
    /// Allows the Authorization and adds the custom tenforce header to the response to
    /// inform the claler that his call has been allowed.
    /// </summary>
    /// <param name="authContext">The authorizationContext that needs to be allowed.</param>
    private static void AllowRequest(ActionExecutingContext authContext)
    {
        authContext.Result = null;
        if (!authContext.RequestContext.HttpContext.Request.ServerVariables[@"SERVER_SOFTWARE"].Contains(@"Microsoft-IIS/7."))
            authContext.HttpContext.Response.AddHeader(@"Tenforce-RAuth", @"OK");
        else
            authContext.HttpContext.Response.Headers.Add(@"Tenforce-RAuth", @"OK");
    }

    #endregion
    }
}
</code>```

The problem I'm currently facing is that I can't seem to properly mock the section with the response headers. I've written a UnitTest that mocks a HttpRequest and HttpResponse object and calls the attribute function with the request. I can follow the successful login path branch in the code for an IIS7 simulation as this relies on properties, but when I try to follow the IIS6 branch in a login, I'm getting null pointer exceptions.

I use the following code to construct the MoQ objects:

```<code>/// <summary>
    /// This function is called before running each test and configures the various properties
    /// of the test class so that each test will run with the same settings initialy.
    /// The function will configure the Mock Framework object so that they simulate a proper
    /// web request on the ActionFilter of a Controller.
    /// </summary>
    [SetUp]
    protected void TestSetup()
    {
        // Construct the Mock object required for the test.
        HttpRequest = new Mock<HttpRequestBase>();
        HttpResponse = new Mock<HttpResponseBase>();
        HttpContext = new Mock<HttpContextBase>();
        ActionContext = new Mock<ActionExecutingContext>();
        Filter = new Web.Filters.AuthenticationFilter();

        // Configure the properties to modify the headers, request and response
        // objects starting from the HttpContext base object.
        // Also create the custom header collection and set the test URI.
        ActionContext.SetupGet(c => c.HttpContext).Returns(HttpContext.Object);
        HttpContext.SetupGet(r => r.Request).Returns(HttpRequest.Object);
        HttpContext.SetupGet(r => r.Response).Returns(HttpResponse.Object);
        HttpResponse.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection());
        HttpRequest.SetupGet(r => r.RawUrl).Returns(@"http://test.tenforce.tst");
    }
</code>```

The actuall test looks like this:

```<code>/// <summary>
    /// <para>This test will call the ActionFilter and perform a standard authorization request against the
    /// database using the credentials of the system administrator account. The test relies on the MoQ
    /// framework to mock several of the key components in the MVC Framework such as the HttpRequest,
    /// HttpResponse and HttpContext objects.</para>
    /// <para>The test expects the authentication to succeed, and relies on the IIS6 implementation.</para>
    /// </summary>
    [Test, MaxDuration]
    public void SuccessfullAuthenticationOnIis6()
    {
        // Configure the Authentication header of the request, so that a valid authentication
        // can take place. We want valid login credentials when the filter requests the header.
        HttpRequest.SetupGet(r => r.Headers).Returns(new System.Net.WebHeaderCollection { { @"TenForce-Auth", CorrectAuthToken } });
        HttpRequest.SetupGet(r => r.ServerVariables).Returns(
            new System.Collections.Specialized.NameValueCollection { { @"SERVER_SOFTWARE", @"Microsoft-IIS/6.0" } });
        HttpResponse.SetupGet(r => r.Headers).Returns(new System.Collections.Specialized.NameValueCollection());
        HttpResponse.Setup(r => r.AddHeader(@"TenForce-RAuth", @"OK"));

        // Call the action on the filter and check the response.
        Filter.OnActionExecuting(ActionContext.Object);

        // Check the ActionResult to null and that the response header contains the correct value.
        Assert.IsTrue(ActionContext.Object.Result == null);
        Assert.IsTrue(ActionContext.Object.HttpContext.Response.Headers["TenForce-RAuth"].Equals(@"OK"));
    }
</code>```

The last assert is failing because the header is not beeing set. I've used the debugger to step through the code and the filter does actually set the header, so I think that the MoQ object is not properly configured to handle the request.

Could someone please shed some light on how I can get my HttpResponse to accept the Headers.Add() request?

答:
Seems i've found it. I had to add the following line to my setup to delegate the call of the moq to the implementation:

```<code>HttpResponse.Setup(r => r.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((x,y) => HttpResponse.Object.Headers.Add(x, y));
</code>```

Rather simple, but you have to know it...

Body:
I'm currently writing some unit tests to check the functionality and correct workings of the ASP MVC application that we have written.
In this MVC Application, I'm using a special ActionFilterAttribute that allows for authentication when making requests to the MVC Application.

The code for this ActionFilterAttribute is this:

using System;
using System.Security.Authentication;
using System.Text;
using System.Web.Mvc;
using TenForce.Execution.Framework;
using TenForce.Execution.Api2.Implementation;

namespace TenForce.Execution.Web.Filters
{
     ///
     /// This class defines a custom Authentication attribute that can be applied on      controllers.
     /// This results in authentication occurring on all actions that are beeing defined in the controller
     /// who implements this filter.
     ///
     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
     public class AuthenticationFilter : ActionFilterAttribute
     {
         #region IAuthorizationFilter Members

         ///
         /// This function get's called by the Mvc framework prior to performing any actions on
         /// the controller. The function will check if a call is authorized by the caller.
    /// The function will extract the username and password from the HTTP headers send by
    /// the caller and will validate these against the database to see if there is a valid
    /// account for the user.
    /// If the user can be found in the database, operations will resume, otherwise the action
    /// is canceled.
    ///
    /// <param name="filterContext">The context for the filter.</param>
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Call the base operations first.
        base.OnActionExecuting(filterContext);

        // Surround the entire authentication process with a try-catch to prevent errors from
        // breaking the code.
        try
        {
            // Extract the custom authorization header from the HTTP headers.
            string customAuthHeader = Encoding.UTF8.GetString(Convert.FromBase64String(filterContext.RequestContext.HttpContext.Request.Headers["TenForce-Auth"]));

            // Split the header in the subcomponents.
            string[] components = customAuthHeader.Split('|');

            // Check if both components are present.
            if (components.Length >= 2)
            {
                // This header consists of 2 parts, the username and password, seperate by a vertical pipe.
                string username = components[0] ?? string.Empty;
                string password = components[1] ?? string.Empty;
                string databaseId = Authenticator.ConstructDatabaseId(filterContext.HttpContext.Request.RawUrl);

                // Validate the user against the database.
                if (Authenticator.Authenticate(username, password, databaseId))
                {
                    // The request is valid, so add the custom header to inform the request was
                    // authorized.
                    AllowRequest(filterContext);
                    return;
                }

                throw new InvalidCredentialException(@"The provided username & password combination is invalid. Username : " + username);
            }

            // If we reach this point, the authorization request is no longer valid.
            throw new InvalidCredentialException(@"Insufficient parameters supplied for a valid authentication.");
        }
        catch (Exception ex)
        {
            // Log the exception that has occurred.
            Logger.Log(GetType(), ex);

            // Cancel the request, as we could not properly process it.
            CancelRequest(filterContext);
        }
    }

    #endregion

    #region Private Methods

    ///
    /// Cancels the Athorization and adds the custom tenforce header to the response to
    /// inform the caller that his call has been denied.
    ///
    /// <param name="authContext">The authorizationContxt that needs to be canceled.</param>
    private static void CancelRequest(ActionExecutingContext authContext)
    {
        authContext.Result = new HttpUnauthorizedResult();
        if (!authContext.RequestContext.HttpContext.Request.ServerVariables[@"SERVER_SOFTWARE"].Contains(@"Microsoft-IIS/7."))
            authContext.HttpContext.Response.AddHeader(@"Tenforce-RAuth", @"DENIED");
        else
            authContext.HttpContext.Response.Headers.Add(@"Tenforce-RAuth", @"DENIED");
    }

    ///
    /// Allows the Authorization and adds the custom tenforce header to the response to
    /// inform the claler that his call has been allowed.
    ///
    /// <param name="authContext">The authorizationContext that needs to be allowed.</param>
    private static void AllowRequest(ActionExecutingContext authContext)
    {
        authContext.Result = null;
        if (!authContext.RequestContext.HttpContext.Request.ServerVariables[@"SERVER_SOFTWARE"].Contains(@"Microsoft-IIS/7."))
            authContext.HttpContext.Response.AddHeader(@"Tenforce-RAuth", @"OK");
        else
            authContext.HttpContext.Response.Headers.Add(@"Tenforce-RAuth", @"OK");
    }

    #endregion
    }
}

The problem I'm currently facing is that I can't seem to properly mock the section with the response headers. I've written a UnitTest that mocks a HttpRequest and HttpResponse object and calls the attribute function with the request. I can follow the successful login path branch in the code for an IIS7 simulation as this relies on properties, but when I try to follow the IIS6 branch in a login, I'm getting null pointer exceptions.

I use the following code to construct the MoQ objects:

///
    /// This function is called before running each test and configures the various properties
    /// of the test class so that each test will run with the same settings initialy.
    /// The function will configure the Mock Framework object so that they simulate a proper
    /// web request on the ActionFilter of a Controller.
    ///
    [SetUp]
    protected void TestSetup()
    {
        // Construct the Mock object required for the test.
        HttpRequest = new Mock<HttpRequestBase>();
        HttpResponse = new Mock<HttpResponseBase>();
        HttpContext = new Mock<HttpContextBase>();
        ActionContext = new Mock<ActionExecutingContext>();
        Filter = new Web.Filters.AuthenticationFilter();

        // Configure the properties to modify the headers, request and response
        // objects starting from the HttpContext base object.
        // Also create the custom header collection and set the test URI.
        ActionContext.SetupGet(c => c.HttpContext).Returns(HttpContext.Object);
        HttpContext.SetupGet(r => r.Request).Returns(HttpRequest.Object);
        HttpContext.SetupGet(r => r.Response).Returns(HttpResponse.Object);
        HttpResponse.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection());
        HttpRequest.SetupGet(r => r.RawUrl).Returns(@"http://test.tenforce.tst");
    }

The actuall test looks like this:

///
    /// <para>This test will call the ActionFilter and perform a standard authorization request against the
    /// database using the credentials of the system administrator account. The test relies on the MoQ
    /// framework to mock several of the key components in the MVC Framework such as the HttpRequest,
    /// HttpResponse and HttpContext objects.</para>
    /// <para>The test expects the authentication to succeed, and relies on the IIS6 implementation.</para>
    ///
    [Test, MaxDuration]
    public void SuccessfullAuthenticationOnIis6()
    {
        // Configure the Authentication header of the request, so that a valid authentication
        // can take place. We want valid login credentials when the filter requests the header.
        HttpRequest.SetupGet(r => r.Headers).Returns(new System.Net.WebHeaderCollection { { @"TenForce-Auth", CorrectAuthToken } });
        HttpRequest.SetupGet(r => r.ServerVariables).Returns(
            new System.Collections.Specialized.NameValueCollection { { @"SERVER_SOFTWARE", @"Microsoft-IIS/6.0" } });
        HttpResponse.SetupGet(r => r.Headers).Returns(new System.Collections.Specialized.NameValueCollection());
        HttpResponse.Setup(r => r.AddHeader(@"TenForce-RAuth", @"OK"));

        // Call the action on the filter and check the response.
        Filter.OnActionExecuting(ActionContext.Object);

        // Check the ActionResult to null and that the response header contains the correct value.
        Assert.IsTrue(ActionContext.Object.Result == null);
        Assert.IsTrue(ActionContext.Object.HttpContext.Response.Headers["TenForce-RAuth"].Equals(@"OK"));
    }

The last assert is failing because the header is not beeing set. I've used the debugger to step through the code and the filter does actually set the header, so I think that the MoQ object is not properly configured to handle the request.

Could someone please shed some light on how I can get my HttpResponse to accept the Headers.Add() request?

Body:
Seems i've found it. I had to add the following line to my setup to delegate the call of the moq to the implementation:

HttpResponse.Setup(r => r.AddHeader(It.IsAny<string>(), It.IsAny<string>())).Callback<string, string>((x,y) => HttpResponse.Object.Headers.Add(x, y));

Rather simple, but you have to know it...


问:
JavaFX initialize array of TextFields
I am trying to create array of TextFields in JavaFX but getting error.
I have 10 TextFields: path1, path2... path10.

```<code>//initialization
@FXML
private TextField path1,path2,path3,path4,path5,path6,path7,path8,path9,path10;
@FXML
private TextField[] paths = {path1,path2,path3,path4,path5,path6,path7,path8,path9,path10};
</code>```

However, when I write

```<code>String text = paths[0].getText();
paths[1].setText(name);
</code>```

This first line gets me NullPointerException.

The solution I found is to use Initizlizatior of my Сontroller, but this is so ugly:

```<code>public void initialize(URL fxmlFileColation, ResourceBundle resources) {
    paths[0] = path1;
    paths[1] = path2;
    paths[2] = path3;
    paths[3] = path4;
    paths[4] = path5;
    paths[5] = path6;
    paths[6] = path7;
    paths[7] = path8;
    paths[8] = path9;
    paths[9] = path10;
}
</code>```

How can I get rid of manual assinment in many lines and make

```<code>@FXML
 private TextField[] paths = {path1,path2,path3,path4,path5,path6,path7,path8,path9,path10};
</code>```

work?

答:
A simple solution i use</p>

```<code> TextField[] txt = new TextField[beanFields.length];
 for (int i=0; i<=beanFields.length-1; i++) {
                TextField textField = new TextField();
                txt[i] = textField;
                textField.setPrefWidth(200);
                textField.setPrefHeight(32);
    }
</code>```

Title: JavaFX initialize array of TextFields

Body:
I am trying to create array of TextFields in JavaFX but getting error.
I have 10 TextFields: path1, path2... path10.

//initialization
@FXML
private TextField path1,path2,path3,path4,path5,path6,path7,path8,path9,path10;
@FXML
private TextField[] paths = {path1,path2,path3,path4,path5,path6,path7,path8,path9,path10};

However, when I write

String text = paths[0].getText();
paths[1].setText(name);

This first line gets me NullPointerException.

The solution I found is to use Initizlizatior of my Сontroller, but this is so ugly:

public void initialize(URL fxmlFileColation, ResourceBundle resources) {
    paths[0] = path1;
    paths[1] = path2;
    paths[2] = path3;
    paths[3] = path4;
    paths[4] = path5;
    paths[5] = path6;
    paths[6] = path7;
    paths[7] = path8;
    paths[8] = path9;
    paths[9] = path10;
}

How can I get rid of manual assinment in many lines and make

@FXML
 private TextField[] paths = {path1,path2,path3,path4,path5,path6,path7,path8,path9,path10};

work?

Body:
A simple solution i use

 TextField[] txt = new TextField[beanFields.length];
 for (int i=0; i<=beanFields.length-1; i++) {
                TextField textField = new TextField();
                txt[i] = textField;
                textField.setPrefWidth(200);
                textField.setPrefHeight(32);
    }


问:
How to choose best imputed data using mice
Using mice package I imputed a dataset like:

imp <- mice(nhanes)
```
<p>It generates 5 imputed datasets for each variables:</p>
<pre class="lang-r prettyprint-override"><code>imp$imp$bmi
#      1    2    3    4    5
#1  35.3 30.1 26.3 28.7 27.2
#3  30.1 22.0 30.1 28.7 22.0
#4  21.7 27.2 25.5 24.9 21.7
#6  24.9 25.5 24.9 27.5 22.5
#10 20.4 33.2 26.3 27.2 27.4
#11 22.0 27.2 27.2 30.1 22.0
#12 27.4 20.4 27.2 27.2 20.4
#16 30.1 30.1 27.2 22.5 29.6
#21 27.4 27.2 26.3 22.0 30.1
</code>```

So I do not understand how to choose the best imputed data.

For example for bmi (above) what of 5 columns will be the best choice ?

Thank you

答:
There isn't a best dataset.
Selecting a single dataset would only account for within dataset variation/error but not the between-imputed-datasets variation.

This is why analysis such as regression should utilise the with and pool commands when working with imputed data.

Body:
Using mice package I imputed a dataset like:

imp <- mice(nhanes)

It generates 5 imputed datasets for each variables:

imp$imp$bmi
#      1    2    3    4    5
#1  35.3 30.1 26.3 28.7 27.2
#3  30.1 22.0 30.1 28.7 22.0
#4  21.7 27.2 25.5 24.9 21.7
#6  24.9 25.5 24.9 27.5 22.5
#10 20.4 33.2 26.3 27.2 27.4
#11 22.0 27.2 27.2 30.1 22.0
#12 27.4 20.4 27.2 27.2 20.4
#16 30.1 30.1 27.2 22.5 29.6
#21 27.4 27.2 26.3 22.0 30.1

So I do not understand how to choose the best imputed data.

For example for bmi (above) what of 5 columns will be the best choice ?

Thank you


问:
Converting Python 3 String of Bytes of Unicode - `str(utf8_encoded_str)` back to unicode
Well, let me introduce the problem first.

I've got some data via POST/GET requests. The data were UTF-8 encoded string. Little did I know that, and converted it just by str() method. And now I have full database of "nonsense data" and couldn't find a way back.

Example code:

unicode_str - this is the string I should obtain

encoded_str - this is the string I got with POST/GET requests - initial data

bad_str - the data I have in the Database at the moment and I need to get unicode from.

So apparently I know how to convert:
unicode_str =(encode)=> encoded_str =(str)=> bad_str

But I couldn't come up with solution back:
bad_str =(???)=> encoded_str =(decode)=> unicode_str

```<code>In [1]: unicode_str = 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [2]: unicode_str
Out[2]: 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [3]: encoded_str = unicode_str.encode("UTF-8")

In [4]: encoded_str
Out[4]: b'P\xc5\x99\xc3\xadli\xc5\xa1 \xc5\xbelu\xc5\xa5ou\xc4\x8dk\xc3\xbd k\xc5\xaf\xc5\x88 \xc3\xbap\xc4\x9bl \xc4\x8f\xc3\xa1belsk\xc3\xa9 \xc3\xb3dy'

In [5]: bad_str = str(encoded_str)

In [6]: bad_str
Out[6]: "b'P\\xc5\\x99\\xc3\\xadli\\xc5\\xa1 \\xc5\\xbelu\\xc5\\xa5ou\\xc4\\x8dk\\xc3\\xbd k\\xc5\\xaf\\xc5\\x88 \\xc3\\xbap\\xc4\\x9bl \\xc4\\x8f\\xc3\\xa1belsk\\xc3\\xa9 \\xc3\\xb3dy'"

In [7]: new_encoded_str = some_magical_function_here(bad_str) ???
</code>```

答:
You turned a bytes object to a string, which is just a representation of the bytes object. You can obtain the original bytes object by using ast.literal_eval() (credits to Mark Tolonen for the suggestion), then a simple decode() will do the job.

```<code>>>> import ast
>>> ast.literal_eval(bad_str).decode('utf-8')
'Příliš žluťoučký kůň úpěl ďábelské ódy'
</code>```

Since you were the one who generated the strings, using eval() would be safe, but why not be safer?

Body:
Well, let me introduce the problem first.

I've got some data via POST/GET requests. The data were UTF-8 encoded string. Little did I know that, and converted it just by str() method. And now I have full database of "nonsense data" and couldn't find a way back.

Example code:

unicode_str - this is the string I should obtain

encoded_str - this is the string I got with POST/GET requests - initial data

bad_str - the data I have in the Database at the moment and I need to get unicode from.

So apparently I know how to convert:
unicode_str =(encode)=> encoded_str =(str)=> bad_str

But I couldn't come up with solution back:
bad_str =(???)=> encoded_str =(decode)=> unicode_str

In [1]: unicode_str = 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [2]: unicode_str
Out[2]: 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [3]: encoded_str = unicode_str.encode("UTF-8")

In [4]: encoded_str
Out[4]: b'P\xc5\x99\xc3\xadli\xc5\xa1 \xc5\xbelu\xc5\xa5ou\xc4\x8dk\xc3\xbd k\xc5\xaf\xc5\x88 \xc3\xbap\xc4\x9bl \xc4\x8f\xc3\xa1belsk\xc3\xa9 \xc3\xb3dy'

In [5]: bad_str = str(encoded_str)

In [6]: bad_str
Out[6]: "b'P\\xc5\\x99\\xc3\\xadli\\xc5\\xa1 \\xc5\\xbelu\\xc5\\xa5ou\\xc4\\x8dk\\xc3\\xbd k\\xc5\\xaf\\xc5\\x88 \\xc3\\xbap\\xc4\\x9bl \\xc4\\x8f\\xc3\\xa1belsk\\xc3\\xa9 \\xc3\\xb3dy'"

In [7]: new_encoded_str = some_magical_function_here(bad_str) ???

Body:
You turned a bytes object to a string, which is just a representation of the bytes object. You can obtain the original bytes object by using ast.literal_eval() (credits to Mark Tolonen for the suggestion), then a simple decode() will do the job.

>>> import ast
>>> ast.literal_eval(bad_str).decode('utf-8')
'Příliš žluťoučký kůň úpěl ďábelské ódy'

Since you were the one who generated the strings, using eval() would be safe, but why not be safer?


问:
Port 445 in use by "Unable to open process" with PID 4! in xampp and Apache is not working
```<code>Initializing Control Panel
5:52:00 PM  [main]  Windows Version: Windows 7 Professional SP1 32-bit
5:52:00 PM  [main]  XAMPP Version: 5.6.31
5:52:00 PM  [main]  Control Panel Version: 3.2.2  [ Compiled: Nov 12th 2015 ]
5:52:00 PM  [main]  Running with Administrator rights - good!
5:52:00 PM  [main]  XAMPP Installation Directory: "c:\xampp\"
5:52:00 PM  [main]  Checking for prerequisites
5:52:50 PM  [main]  All prerequisites found
5:52:50 PM  [main]  Initializing Modules
5:52:50 PM  [Apache]    Problem detected!
5:52:50 PM  [Apache]    Port 445 in use by "Unable to open process" with PID 4!
5:52:50 PM  [Apache]    Apache WILL NOT start without the configured ports free!
5:52:50 PM  [Apache]    You need to uninstall/disable/reconfigure the blocking application
5:52:50 PM  [Apache]    or reconfigure Apache and the Control Panel to listen on a different port
5:52:50 PM  [main]  Starting Check-Timer
5:52:50 PM  [main]  Control Panel Ready
5:53:03 PM  [Apache]    Problem detected!
5:53:03 PM  [Apache]    Port 445 in use by "Unable to open process" with PID 4!
5:53:03 PM  [Apache]    Apache WILL NOT start without the configured ports free!
5:53:03 PM  [Apache]    You need to uninstall/disable/reconfigure the blocking application
5:53:03 PM  [Apache]    or reconfigure Apache and the Control Panel to listen on a different port
</code>```

I m getting as Port 445 in use by "Unable to open process" with PID 4! in xampp and Apache is not working
what is the error it is showing ?

答: The error indicates that port 445 is already in use. Try to use 443, if it is SSL you want. You should find your http.conf in C:\xampp\apache\conf\extra</p>

Body:
Initializing Control Panel
5:52:00 PM  [main]  Windows Version: Windows 7 Professional SP1 32-bit
5:52:00 PM  [main]  XAMPP Version: 5.6.31
5:52:00 PM  [main]  Control Panel Version: 3.2.2  [ Compiled: Nov 12th 2015 ]
5:52:00 PM  [main]  Running with Administrator rights - good!
5:52:00 PM  [main]  XAMPP Installation Directory: "c:\xampp\"
5:52:00 PM  [main]  Checking for prerequisites
5:52:50 PM  [main]  All prerequisites found
5:52:50 PM  [main]  Initializing Modules
5:52:50 PM  [Apache]    Problem detected!
5:52:50 PM  [Apache]    Port 445 in use by "Unable to open process" with PID 4!
5:52:50 PM  [Apache]    Apache WILL NOT start without the configured ports free!
5:52:50 PM  [Apache]    You need to uninstall/disable/reconfigure the blocking application
5:52:50 PM  [Apache]    or reconfigure Apache and the Control Panel to listen on a different port
5:52:50 PM  [main]  Starting Check-Timer
5:52:50 PM  [main]  Control Panel Ready
5:53:03 PM  [Apache]    Problem detected!
5:53:03 PM  [Apache]    Port 445 in use by "Unable to open process" with PID 4!
5:53:03 PM  [Apache]    Apache WILL NOT start without the configured ports free!
5:53:03 PM  [Apache]    You need to uninstall/disable/reconfigure the blocking application
5:53:03 PM  [Apache]    or reconfigure Apache and the Control Panel to listen on a different port

I m getting as Port 445 in use by "Unable to open process" with PID 4! in xampp and Apache is not working
what is the error it is showing ?


问:
Making inner html content jump down instead of outer one
I have days of the week, and timestamps which can be in any number

When timestamps number increases or we shrink the browser, the expected behavior is to make timestamps jump down like this

However, the behavior is like this

Here is my simplified HTML codes for one day; Monday

```<code><div class="form-group">
    <button class="btn btn-secondary days">
         Monday
         <span class="sprite-1-arrow-black-right"></span>
     </button>
     <div class="timestamps">
         <div class="timestamp">
             00:00 am - 00:00 pm
          </div>
          <div class="timestamp">
            00:00 am - 00:00 pm
           </div>
     </div>
 </div>
</code>```

in simplified css/sass

```<code>.days {
        display: inline-block;
}
.timestamps {
       display:inline-block;
}
.timestamp {
       display: inline-block;
}
</code>```

I think, there should be flex solution, but I don't know how!

答:
Wrap everything in a flex container. By default it will have flex-wrap: nowrap.

Then wrap your timestamps in a nested flex container. Give this container flex-wrap: wrap.

Now the primary container does not wrap, but the timestamp items will wrap.

.form-group {
  display: flex;
}

.timestamps {
  display: flex;
  flex-wrap: wrap;
}

button {
  align-self: flex-start; /* override `stretch` default */
}

.timestamp {
  white-space: nowrap;    /* prevent text nodes from wrapping */
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="form-group">
  <button class="btn btn-secondary days">
    Monday
    <span class="sprite-1-arrow-black-right"></span>
  </button>
  <div class="timestamps">
    <div class="timestamp">00:00 am - 00:00 pm</div>
    <div class="timestamp">00:00 am - 00:00 pm</div>
  </div>
</div></code>```

jsFiddle demo

Body:
I have days of the week, and timestamps which can be in any number

When timestamps number increases or we shrink the browser, the expected behavior is to make timestamps jump down like this

However, the behavior is like this

Here is my simplified HTML codes for one day; Monday

    <button class="btn btn-secondary days">
         Monday

     </button>

             00:00 am - 00:00 pm

            00:00 am - 00:00 pm

in simplified css/sass

.days {
        display: inline-block;
}
.timestamps {
       display:inline-block;
}
.timestamp {
       display: inline-block;
}

I think, there should be flex solution, but I don't know how!

Body:
Wrap everything in a flex container. By default it will have flex-wrap: nowrap.

Then wrap your timestamps in a nested flex container. Give this container flex-wrap: wrap.

Now the primary container does not wrap, but the timestamp items will wrap.

.form-group {
  display: flex;
}

.timestamps {
  display: flex;
  flex-wrap: wrap;
}

button {
  align-self: flex-start; /* override `stretch` default */
}

.timestamp {
  white-space: nowrap;    /* prevent text nodes from wrapping */
}

<div class="form-group">
  <button class="btn btn-secondary days">
    Monday
    <span class="sprite-1-arrow-black-right"></span>
  </button>
  <div class="timestamps">
    <div class="timestamp">00:00 am - 00:00 pm</div>
    <div class="timestamp">00:00 am - 00:00 pm</div>
  </div>
</div>

jsFiddle demo


问:
Is there a way to setup a minimal rubygems mirror (with only last versions)
I want to build a rubygems mirror accesible for some servers at work (that don't have Internet access), so I started like everybody seems to do:

```<code> $ cat gemmirror.config
 ---
 - from: http://gems.rubyforge.org
 to: /data/rubygems/mirror

 $ gem mirror --config-file=gemmirror.config
</code>```

The mirror starts syncing well. OK. But wait, it downloads the whole content of http://gems.rubyforge.org! I mean all the existing versions of every single gem. Wow. After a couple of hours I'm still downloading the gems that begin with the letter "L" ...

Not to mention the disk-space the mirror is going to take.

Now my question: is there a way to setup a "mini" rubygems server, like CPAN::Mini allows for Perl: such a mirror would contain only the latest version of every gems. This is in 99.9% of the cases what people want, I guess (at least this would be perfectly good enough for me there).

I've googled a lot and sadly, I cannot find any reference to that.

If someone can point me to the way to do that, I'd appreciate very much.

Thanks!

答:
Not really what you are asking for, but perhaps one way to tackle this, is to setup a caching http proxy that will cache the gems as they are requested, which should subsequent requests hit the cache.

Something like squid should do the job.

Then each client configures the gem proxy to use squid, so all gem downloads go through it and hopefully are in the cache 99% of the time...

Although if you use bundler, seems it has issues with the proxy settings :(

Body:
I want to build a rubygems mirror accesible for some servers at work (that don't have Internet access), so I started like everybody seems to do:

 $ cat gemmirror.config
 ---
 - from: http://gems.rubyforge.org
 to: /data/rubygems/mirror

 $ gem mirror --config-file=gemmirror.config

The mirror starts syncing well. OK. But wait, it downloads the whole content of http://gems.rubyforge.org! I mean all the existing versions of every single gem. Wow. After a couple of hours I'm still downloading the gems that begin with the letter "L" ...

Not to mention the disk-space the mirror is going to take.

Now my question: is there a way to setup a "mini" rubygems server, like CPAN::Mini allows for Perl: such a mirror would contain only the latest version of every gems. This is in 99.9% of the cases what people want, I guess (at least this would be perfectly good enough for me there).

I've googled a lot and sadly, I cannot find any reference to that.

If someone can point me to the way to do that, I'd appreciate very much.

Thanks!


问:
Select based on another select using php Not working
Select based on another select using PHP not working only when a new row is added.

For demo visit here (See steps for demo)

There are two rows when the page is loaded, they are working as wanted. (Service option is as per item option)

Click on the Add Row button, one more row will be added

The newly inserted row is not working. (Service select is not giving any options, as first two gives)

What I tried:

```<code><?php require_once '../home.php' ?>
<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
        ob_clean();

        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
        if( $action && $id && !is_nan( $id ) ){

            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmt->bindParam(':irn',$id);
            $stmt->execute();
            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmtin->bindParam(':irn',$id);
            $stmtin->execute();
            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );

            if( $stmt->rowCount() > 0 ){
                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
                 }
            }
        }
        exit();
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type='text/javascript' charset='utf-8'>
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }
            function createmenu(r,o,h){
                o.menu.innerHTML=r;
            }

            function bindEvents(){
                var oSelItem=document.querySelector('select[name="item1"]');
                var oSelService=document.querySelector('select[name="service1"]');
                oSelItem.onchange=function(e){

                    var method='post';
                    var url=location.href;
                    var params={
                        'action':'get_dependant_menu',
                        'id':this.options[ this.options.selectedIndex ].value
                    };
                    var opts={
                        menu:oSelService
                    };
                    ajax.call( this, method, url, params, createmenu, opts );
                }.bind( oSelItem );
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents,false );
        </script>
</head>
<body>
<form method="post" action="invoice_form.php" id="item_sel">

    <table id="chiru_inv" class="table table-striped table-hover table-bordered table-responsive">
   <tr>
    <td colspan="3">
      <input type="text" name="customer" value="" placeholder="Customer Name">
    </td>
  </tr>
  <tr>
    <th>Item</th>
    <th>Service</th>
    <th>Qty</th>

  </tr>

    <tr>
      <td>
      <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
            <?php

                //$sql='select * from `item` order by `Sr` asc;';
                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select></td>

      <td><select class="country" name="service1">
</select></td>
<td><input type="text" name="qty1" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
      <td>
      <select name='item2' class='country'>
            <option>Select Item</option>
            <?php

                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select></td>

      <td><select class="country" name="service2">
</select></td>
<td><input type="text" name="qty2" value="" placeholder="Quantity"></td>
    </tr>
    <tr>
        <td colspan="3"><button type="submit" name="btnsave" class="btn btn-default">
        <span class="glyphicon glyphicon-save"></span>   Save
        </button>
        </td>
    </tr>
</table>
    <input type="button" class="add-row" value="Add Row">
</form>
<div id="markup_model" class="hide">
  <table>
    <tr>
      <td>
        <select name="nameitem" class="country">
                    <option>Select Item</option>
                    <?php
                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                        $stmt->execute();

                        if( $stmt->rowCount() > 0 ){
                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                            }
                        }
                    ?>
                </select>
      </td>
      <td>
        <select class="country" name="namewhat"></select>
      </td>
      <td>
        <input type="text" name="nameqty" value="" placeholder="Quantity" />
      </td>
    </tr>
  </table>
</div>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
  var cont = 3
  var qty = "qty"
  var item = "item"
  var what = "service"

  $(".add-row").click(function() {
    var nameqty = qty + cont;
    var nameitem = item + cont;
    var namewhat = what + cont;

    var markup = $('#markup_model tbody');

    $(markup).find('.country:eq(0)').attr('name', nameitem);
    $(markup).find('.country:eq(1)').attr('name', namewhat);
    $(markup).find('input').attr('name', nameqty);

    $(markup.html()).insertBefore($('button[type="submit"]').closest("tr"));

    cont++;
  });
});
</script>
<script type='text/javascript' charset='utf-8'>
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }
            function createmenu(r,o,h){
                o.menu.innerHTML=r;
            }

            function bindEvents(){
                var oSelItem2=document.querySelector('select[name="item2"]');
                var oSelService2=document.querySelector('select[name="service2"]');
                oSelItem2.onchange=function(e){

                    var method='post';
                    var url=location.href;
                    var params={
                        'action':'get_dependant_menu',
                        'id':this.options[ this.options.selectedIndex ].value
                    };
                    var opts={
                        menu:oSelService2
                    };
                    ajax.call( this, method, url, params, createmenu, opts );
                }.bind( oSelItem2 );
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents,false );
        </script>
        <script type='text/javascript' charset='utf-8'>
            function ajax(m,u,p,c,o){
                var xhr=new XMLHttpRequest();
                xhr.onreadystatechange=function(){
                    if( xhr.readyState==4 && xhr.status==200 )c.call( this, xhr.response, o, xhr.getAllResponseHeaders() );
                };

                var params=[];
                for( var n in p )params.push(n+'='+p[n]);

                switch( m.toLowerCase() ){
                    case 'post': p=params.join('&'); break;
                    case 'get': u+='?'+params.join('&'); p=null; break;
                }

                xhr.open( m.toUpperCase(), u, true );
                xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                xhr.send( p );
            }
            function createmenu(r,o,h){
                o.menu.innerHTML=r;
            }

            function bindEvents(){
                var oSelItem3=document.querySelector('select[name="item3"]');
                var oSelService3=document.querySelector('select[name="service3"]');
                oSelItem3.onchange=function(e){

                    var method='post';
                    var url=location.href;
                    var params={
                        'action':'get_dependant_menu',
                        'id':this.options[ this.options.selectedIndex ].value
                    };
                    var opts={
                        menu:oSelService3
                    };
                    ajax.call( this, method, url, params, createmenu, opts );
                }.bind( oSelItem3 );
            }
            document.addEventListener( 'DOMContentLoaded', bindEvents,false );
        </script>

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

答:
You've really to change the logic here, I'm sorry but dealing with dynamic content statically will not work in this case... what if we have line 4 and 5 and 10.. you need really to give all set of elements a common class then attach the event using the event delegation on() so the new elements added dynamically will also binded.

Example, change country class to item in the item columns, and country class to service in the service column :

```<code>$('body').on('change', '.item', function(){
   //You're ajax logic here
   //Try to use `$.post()` instead
   //Target the related service list like
   var related_service_select = $(this).closest('tr').find('.service');
   //Now you can fill it with the server side response
});
</code>```

Hope this helps.

Body:
Select based on another select using PHP not working only when a new row is added.

For demo visit here (See steps for demo)

There are two rows when the page is loaded, they are working as wanted. (Service option is as per item option)

Click on the Add Row button, one more row will be added

The newly inserted row is not working. (Service select is not giving any options, as first two gives)

What I tried:

<?php require_once '../home.php' ?>
<?php

    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'], $_POST['id'] ) && $_POST['action']=='get_dependant_menu' ){
        ob_clean();

        $action=filter_input( INPUT_POST, 'action', FILTER_SANITIZE_STRING );
        $id=filter_input( INPUT_POST, 'id', FILTER_SANITIZE_STRING );
        if( $action && $id && !is_nan( $id ) ){

            $stmt=$user_home->runQuery("SELECT * FROM service WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmt->bindParam(':irn',$id);
            $stmt->execute();
            $stmtin=$user_home->runQuery("SELECT * FROM item WHERE IRN=:irn ORDER BY Sr ASC ");
            $stmtin->bindParam(':irn',$id);
            $stmtin->execute();
            $rowin=$stmtin->fetch( PDO::FETCH_ASSOC );

            if( $stmt->rowCount() > 0 ){
                echo "<option value='Select Service'>Select Service ({$rowin['Name']})</option>";
                 while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                    echo "<option value='{$row['SRN']}'>{$row['Name']}</option>";
                 }
            }
        }
        exit();
    }
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<form method="post" action="invoice_form.php" id="item_sel">

      <input type="text" name="customer" value="" placeholder="Customer Name">

    Item
    Service
    Qty

      <select name='item1' class='country'>
            <option value="Select Item">Select Item</option>
            <?php

                //$sql='select * from `item` order by `Sr` asc;';
                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select>

      <select class="country" name="service1">
</select>
<input type="text" name="qty1" value="" placeholder="Quantity">

      <select name='item2' class='country'>
            <option>Select Item</option>
            <?php

                $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                $stmt->execute();

                if( $stmt->rowCount() > 0 ){
                    while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                        echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                    }
                }

            ?>
</select>

      <select class="country" name="service2">
</select>
<input type="text" name="qty2" value="" placeholder="Quantity">

        <button type="submit" name="btnsave" class="btn btn-default">
           Save
        </button>

    <input type="button" class="add-row" value="Add Row">
</form>

        <select name="nameitem" class="country">
                    <option>Select Item</option>
                    <?php
                        $stmt=$user_home->runQuery("SELECT * FROM item ORDER BY Sr ASC ");
                        $stmt->execute();

                        if( $stmt->rowCount() > 0 ){
                            while( $row=$stmt->fetch( PDO::FETCH_ASSOC ) ){
                                echo "<option value='{$row['IRN']}'>{$row['Name']}</option>";
                            }
                        }
                    ?>
                </select>

        <select class="country" name="namewhat"></select>

        <input type="text" name="nameqty" value="" placeholder="Quantity" />

Body:
You've really to change the logic here, I'm sorry but dealing with dynamic content statically will not work in this case... what if we have line 4 and 5 and 10.. you need really to give all set of elements a common class then attach the event using the event delegation on() so the new elements added dynamically will also binded.

Example, change country class to item in the item columns, and country class to service in the service column :

$('body').on('change', '.item', function(){
   //You're ajax logic here
   //Try to use `$.post()` instead
   //Target the related service list like
   var related_service_select = $(this).closest('tr').find('.service');
   //Now you can fill it with the server side response
});

Hope this helps.


问:
Bootstrap 4 nav pills are not working

                    Driver Details

                    Register Driver

              asdsdd

ffffffffffffffffffffffffffff

```

Hello, I'm using nav-pills in bootstrap but for some reason it is not working properly, Please take a look at the code above, I haven't included bootstrap in the above fiddle

答:
```<code><ul class="nav nav-pills">
                <li class="nav-item">
                <a class="nav-link active" data-toggle="pill" href="#driver-details-tab">Driver Details</a>
                </li>
                <li class="nav-item">
                <a class="nav-link" data-toggle="pill" href="#erer">Register Driver</a>
                </li>
            </ul>
    <div class="tab-content">
      <div class="container-fluid drivers-main tab-pane active" id="driver-details-tab" role="tabpanel">
          asdsdd
      </div>
      <div class="container-fluid drivers-main tab-pane active" id="erer" role="tabpanel"> fff</div>
    </div>
</code>```

Check that out! Don't forget to include the # sign before the id name in href as well!

Title: Bootstrap 4 nav pills are not working

Body:
                    Driver Details

                    Register Driver

              asdsdd

ffffffffffffffffffffffffffff

Hello, I'm using nav-pills in bootstrap but for some reason it is not working properly, Please take a look at the code above, I haven't included bootstrap in the above fiddle

Body:
<ul class="nav nav-pills">
                <li class="nav-item">
                <a class="nav-link active" data-toggle="pill" href="#driver-details-tab">Driver Details</a>
                </li>
                <li class="nav-item">
                <a class="nav-link" data-toggle="pill" href="#erer">Register Driver</a>
                </li>
            </ul>
    <div class="tab-content">
      <div class="container-fluid drivers-main tab-pane active" id="driver-details-tab" role="tabpanel">
          asdsdd
      </div>
      <div class="container-fluid drivers-main tab-pane active" id="erer" role="tabpanel"> fff</div>
    </div>

Check that out! Don't forget to include the # sign before the id name in href as well!