问:
Display a div inside a table through JS and position absolute moves the table columns
I am playing around with jQuery in order to have a confirm box when I click on a delete link in a table.
I managed to make it work, but when the box is displayed, the columns are moving to the left which is not perfect.

I don't know where it comes from: my CSS, my JS, Foundation CSS?...
I created a JSFiddle so you can check the result. It happens when you click on Delete.

Here's the code in the JSFiddle:

$(document).ready(function(){

 // Confirm delete
    $('.delete-action').click(function() {
        //Get the path of the href
        var item_link = this.href;

        //Select the
 and get the width and height
        var item_section = $(this).closest('tr');
        var item_section_width = item_section.outerWidth();
        var item_section_height = item_section.outerHeight();

        //Add css to the

        item_section.css('position', 'relative');

        //Display the confirm box in the

        item_section.append('
\n\

Are you sure you want to delete this entry? OuiNon
\n\

');

        //Proceed with delete
        $('.delete-yes').click(function() {
            return true;
        });

        //Do not delete, remove the box
        $('.delete-no').click(function() {
            $('.delete-box').fadeOut(function() {
                $(this).remove();
            });

            return false;
        });

        return false;
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.delete-box {
  display: flex;
  padding: 0 10px;
  background-color: darkgrey;
}

.delete-box div {
  margin: auto;
}

.delete-box div a {
  display: inline-block;
  width: 60px;
  padding: 5px;
  margin: 0 5px;
  text-align: center;
  color: white;
}

.delete-box div .delete-yes {
  background-color: green;
}

.delete-box div .delete-yes:hover {
  background-color: darkgreen;
}

.delete-box div .delete-no {
  background-color: red;
}

.delete-box div .delete-no:hover {
  background-color: darkred;
}</code>```

<!DOCTYPE html>

 <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation-float.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

 <title>Confirm box for a delete row in a Table - jQuery</title>

Confirm box in a Table

      Title
      Last update
      Actions

      This is a title
      2017-07-08
       Edit -  Delete

      This is a title
      2017-07-08
       Edit -  Delete

      This is a title
      2017-07-08
       Edit -  Delete

```

Any idea where it can come from?

答:
I finally changed the way to do it, switching from a 'div' solution to a 'td' solution. Here's the result: https://jsfiddle.net/LLjebd76/3/

// Foundation
$(document).foundation();

// jQuery
$(document).ready(function(){

 // Confirm delete
    $('.delete-action').click(function() {
        //Get the path of the href
        var item_link = $(this).attr('href');

        //Select the
 and get the height
        var item_tr = $(this).closest('tr');
        var item_tr_height = item_tr.outerHeight();
        var item_tr_value = item_tr.html();

        //Display the confirm box in the

        item_tr.empty();
        item_tr.append('\
         Are you sure you want to delete this entry? YesNo\
        	');

        //Proceed with delete
        $('.delete-yes').click(function() {
            return true;
        });

        //Do not delete, remove the box
        $('.delete-no').click(function() {
            item_tr.empty().append(item_tr_value);

            return false;
        });

        return false;
    });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.delete-box {
  background-color: darkgrey;
  text-align: center;
}

.delete-box a {
  display: inline-block;
  width: 60px;
  margin: 0 5px;
  text-align: center;
  color: white;
}

.delete-box .delete-yes {
  background-color: green;
}

.delete-box .delete-yes:hover {
  background-color: darkgreen;
}

.delete-box .delete-no {
  background-color: red;
}

.delete-box .delete-no:hover {
  background-color: darkred;
}</code>```

<!DOCTYPE html>

 <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation-float.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="style.css">

 <title>Confirm box for a delete row in a Table - jQuery</title>

Confirm box in a Table

      Title
      Last update
      Actions

      This is a title 1
      2017-07-08
       Edit -  Delete

      This is a title 2
      2017-07-09
       Edit -  Delete

      This is a title 3
      2017-07-10
       Edit -  Delete

```

Body:
I am playing around with jQuery in order to have a confirm box when I click on a delete link in a table.
I managed to make it work, but when the box is displayed, the columns are moving to the left which is not perfect.

I don't know where it comes from: my CSS, my JS, Foundation CSS?...
I created a JSFiddle so you can check the result. It happens when you click on Delete.

Here's the code in the JSFiddle:

$(document).ready(function(){

 // Confirm delete
    $('.delete-action').click(function() {
        //Get the path of the href
        var item_link = this.href;

        //Select the
 and get the width and height
        var item_section = $(this).closest('tr');
        var item_section_width = item_section.outerWidth();
        var item_section_height = item_section.outerHeight();

        //Add css to the

        item_section.css('position', 'relative');

        //Display the confirm box in the

        item_section.append('
\n\

Are you sure you want to delete this entry? OuiNon
\n\

');

        //Proceed with delete
        $('.delete-yes').click(function() {
            return true;
        });

        //Do not delete, remove the box
        $('.delete-no').click(function() {
            $('.delete-box').fadeOut(function() {
                $(this).remove();
            });

            return false;
        });

        return false;
    });
});

.delete-box {
  display: flex;
  padding: 0 10px;
  background-color: darkgrey;
}

.delete-box div {
  margin: auto;
}

.delete-box div a {
  display: inline-block;
  width: 60px;
  padding: 5px;
  margin: 0 5px;
  text-align: center;
  color: white;
}

.delete-box div .delete-yes {
  background-color: green;
}

.delete-box div .delete-yes:hover {
  background-color: darkgreen;
}

.delete-box div .delete-no {
  background-color: red;
}

.delete-box div .delete-no:hover {
  background-color: darkred;
}

<!DOCTYPE html>

 <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation-float.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

 <title>Confirm box for a delete row in a Table - jQuery</title>

Confirm box in a Table

      Title
      Last update
      Actions

      This is a title
      2017-07-08
       Edit -  Delete

      This is a title
      2017-07-08
       Edit -  Delete

      This is a title
      2017-07-08
       Edit -  Delete

Any idea where it can come from?

Body:
I finally changed the way to do it, switching from a 'div' solution to a 'td' solution. Here's the result: https://jsfiddle.net/LLjebd76/3/

// Foundation
$(document).foundation();

// jQuery
$(document).ready(function(){

 // Confirm delete
    $('.delete-action').click(function() {
        //Get the path of the href
        var item_link = $(this).attr('href');

        //Select the <tr> and get the height
        var item_tr = $(this).closest('tr');
        var item_tr_height = item_tr.outerHeight();
        var item_tr_value = item_tr.html();

        //Display the confirm box in the <tr>
        item_tr.empty();
        item_tr.append('<td colspan="3" height="'+item_tr_height+'" class="delete-box">\
         Are you sure you want to delete this entry? <a href="'+item_link+'" class="delete-yes">Yes</a><a class="delete-no">No</a>\
        </td>');

        //Proceed with delete
        $('.delete-yes').click(function() {
            return true;
        });

        //Do not delete, remove the box
        $('.delete-no').click(function() {
            item_tr.empty().append(item_tr_value);

            return false;
        });

        return false;
    });
});

.delete-box {
  background-color: darkgrey;
  text-align: center;
}

.delete-box a {
  display: inline-block;
  width: 60px;
  margin: 0 5px;
  text-align: center;
  color: white;
}

.delete-box .delete-yes {
  background-color: green;
}

.delete-box .delete-yes:hover {
  background-color: darkgreen;
}

.delete-box .delete-no {
  background-color: red;
}

.delete-box .delete-no:hover {
  background-color: darkred;
}

<!DOCTYPE html>
<html>
<head>
 <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/css/foundation-float.min.css">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

    <link rel="stylesheet" href="style.css">

 <title>Confirm box for a delete row in a Table - jQuery</title>
</head>
<body>
 <div class="row">
  <div class="large-12 columns">
   <h1>Confirm box in a Table</h1>
   <table>
    <thead>
     <tr>
      <th>Title</th>
      <th>Last update</th>
      <th>Actions</th>
     </tr>
    </thead>
    <tbody>
     <tr>
      <td>This is a title 1</td>
      <td>2017-07-08</td>
      <td><a href=""><i class="fa fa-edit"> Edit</i></a> - <a href="" class="delete-action"><i class="fa fa-close"> Delete</i></a></td>
     </tr>
     <tr>
      <td>This is a title 2</td>
      <td>2017-07-09</td>
      <td><a href=""><i class="fa fa-edit"> Edit</i></a> - <a href="" class="delete-action"><i class="fa fa-close"> Delete</i></a></td>
     </tr>
     <tr>
      <td>This is a title 3</td>
      <td>2017-07-10</td>
      <td><a href=""><i class="fa fa-edit"> Edit</i></a> - <a href="" class="delete-action"><i class="fa fa-close"> Delete</i></a></td>
     </tr>
    </tbody>
   </table>
  </div>
 </div>

 <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.1/js/foundation.min.js"></script>
 <script type="text/javascript" src="script.js"></script>
</body>
</html>


来源: stackexchange

问:
NSTouchBar with multi-level NSPopoverTouchBarItem
I'm trying to make a simple NSTouchBar with 3 levels of NSPopoverTouchBarItem, so basically its like this:

I have the main NSTouchbar with 3 NSButton and 1 NSPopoverTouchBarItem which open the second NSTouchbar

The second NSTouchbar with 2 NSButton and 1 NSPopoverTouchBarItem which open the third NSTouchbar

The problem is when i try open the 3rd NSTouchbar, seems like the 2nd NSTouchbar is dismissed, and sometimes doesn't open the 3rd.

Also when opens the third one, when we close, we go to 1st NSTouchbar, not the 2nd NSTouchbar

Here is the code, should be simple, and should work (i'm using Xcode TouchBar Simulator)

```<code>#import "Window.h"

static NSTouchBarCustomizationIdentifier TouchBarCustomizationIdentifier    = @"TouchBarCustomizationIdentifier";

static NSTouchBarItemIdentifier NSTouchBarItemIdentifier1                   = @"NSTouchBarItemIdentifier1";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier2                   = @"NSTouchBarItemIdentifier2";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier3                   = @"NSTouchBarItemIdentifier3";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4                   = @"NSTouchBarItemIdentifier4";

static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_1                 = @"NSTouchBarItemIdentifier4_1";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_2                 = @"NSTouchBarItemIdentifier4_2";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_3                 = @"NSTouchBarItemIdentifier4_3";

static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_3_1               = @"NSTouchBarItemIdentifier4_3_1";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_3_2               = @"NSTouchBarItemIdentifier4_3_2";

@implementation Window

- (NSTouchBar*) makeTouchBar {

    _touchBar1 = [[NSTouchBar alloc] init];
    [_touchBar1 setDelegate:self];
    [_touchBar1 setCustomizationIdentifier:TouchBarCustomizationIdentifier];

    [_touchBar1 setDefaultItemIdentifiers:@[
                                            NSTouchBarItemIdentifier1,
                                            NSTouchBarItemIdentifier2,
                                            NSTouchBarItemIdentifier3,
                                            NSTouchBarItemIdentifier4,
                                            ]
     ];
    [_touchBar1 setCustomizationRequiredItemIdentifiers:@[
                                                          NSTouchBarItemIdentifier1,
                                                          NSTouchBarItemIdentifier2,
                                                          NSTouchBarItemIdentifier3,
                                                          NSTouchBarItemIdentifier4,
                                                          ]
     ];

    return _touchBar1;
}

- (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier {

    if ([identifier isEqual:NSTouchBarItemIdentifier1]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 1" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier2]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH1" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier3]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH1" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4]) {

        NSPopoverTouchBarItem *customTouchBarItem = [[NSPopoverTouchBarItem alloc] initWithIdentifier:identifier];
        [customTouchBarItem setCollapsedRepresentationLabel:@"OPEN TOUCH 2"];

        _touchBar2 = [[NSTouchBar alloc] init];
        [_touchBar2 setDelegate:self];
        [_touchBar2 setCustomizationIdentifier:TouchBarCustomizationIdentifier];

        [_touchBar2 setDefaultItemIdentifiers:@[
                                                NSTouchBarItemIdentifier4_1,
                                                NSTouchBarItemIdentifier4_2,
                                                NSTouchBarItemIdentifier4_3,
                                                ]
         ];
        [_touchBar2 setCustomizationRequiredItemIdentifiers:@[
                                                              NSTouchBarItemIdentifier4_1,
                                                              NSTouchBarItemIdentifier4_2,
                                                              NSTouchBarItemIdentifier4_3,
                                                              ]
         ];

        [customTouchBarItem setPopoverTouchBar:_touchBar2];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_1]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 2" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_2]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 2" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_3]) {

        NSPopoverTouchBarItem *customTouchBarItem = [[NSPopoverTouchBarItem alloc] initWithIdentifier:identifier];
        [customTouchBarItem setCollapsedRepresentationLabel:@"OPEN TOUCH 3"];

        _touchBar3 = [[NSTouchBar alloc] init];
        [_touchBar3 setDelegate:self];
        [_touchBar3 setCustomizationIdentifier:TouchBarCustomizationIdentifier];

        [_touchBar3 setDefaultItemIdentifiers:@[
                                                NSTouchBarItemIdentifier4_3_1,
                                                NSTouchBarItemIdentifier4_3_2,
                                                ]
         ];
        [_touchBar3 setCustomizationRequiredItemIdentifiers:@[
                                                              NSTouchBarItemIdentifier4_3_1,
                                                              NSTouchBarItemIdentifier4_3_2,
                                                              ]
         ];

        [customTouchBarItem setPopoverTouchBar:_touchBar3];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_3_1]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 3" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_3_2]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 3" target:self action:nil]];

        return customTouchBarItem;

    }

    return nil;
}

@end
</code>```

答:
Apple says popovers cannot have popovers, so you can only have a bar and a popover, not a popover inside a popover.

This is what they have posted in their forum to answer a similar question:

https://forums.developer.apple.com/thread/78730

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to make a simple NSTouchBar with 3 levels of NSPopoverTouchBarItem, so basically its like this:

I have the main NSTouchbar with 3 NSButton and 1 NSPopoverTouchBarItem which open the second NSTouchbar

The second NSTouchbar with 2 NSButton and 1 NSPopoverTouchBarItem which open the third NSTouchbar

The problem is when i try open the 3rd NSTouchbar, seems like the 2nd NSTouchbar is dismissed, and sometimes doesn't open the 3rd.

Also when opens the third one, when we close, we go to 1st NSTouchbar, not the 2nd NSTouchbar

Here is the code, should be simple, and should work (i'm using Xcode TouchBar Simulator)

#import "Window.h"

static NSTouchBarCustomizationIdentifier TouchBarCustomizationIdentifier    = @"TouchBarCustomizationIdentifier";

static NSTouchBarItemIdentifier NSTouchBarItemIdentifier1                   = @"NSTouchBarItemIdentifier1";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier2                   = @"NSTouchBarItemIdentifier2";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier3                   = @"NSTouchBarItemIdentifier3";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4                   = @"NSTouchBarItemIdentifier4";

static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_1                 = @"NSTouchBarItemIdentifier4_1";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_2                 = @"NSTouchBarItemIdentifier4_2";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_3                 = @"NSTouchBarItemIdentifier4_3";

static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_3_1               = @"NSTouchBarItemIdentifier4_3_1";
static NSTouchBarItemIdentifier NSTouchBarItemIdentifier4_3_2               = @"NSTouchBarItemIdentifier4_3_2";

@implementation Window

- (NSTouchBar*) makeTouchBar {

    _touchBar1 = [[NSTouchBar alloc] init];
    [_touchBar1 setDelegate:self];
    [_touchBar1 setCustomizationIdentifier:TouchBarCustomizationIdentifier];

    [_touchBar1 setDefaultItemIdentifiers:@[
                                            NSTouchBarItemIdentifier1,
                                            NSTouchBarItemIdentifier2,
                                            NSTouchBarItemIdentifier3,
                                            NSTouchBarItemIdentifier4,
                                            ]
     ];
    [_touchBar1 setCustomizationRequiredItemIdentifiers:@[
                                                          NSTouchBarItemIdentifier1,
                                                          NSTouchBarItemIdentifier2,
                                                          NSTouchBarItemIdentifier3,
                                                          NSTouchBarItemIdentifier4,
                                                          ]
     ];

    return _touchBar1;
}

- (nullable NSTouchBarItem *)touchBar:(NSTouchBar *)touchBar makeItemForIdentifier:(NSTouchBarItemIdentifier)identifier {

    if ([identifier isEqual:NSTouchBarItemIdentifier1]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];
        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 1" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier2]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH1" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier3]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH1" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4]) {

        NSPopoverTouchBarItem *customTouchBarItem = [[NSPopoverTouchBarItem alloc] initWithIdentifier:identifier];
        [customTouchBarItem setCollapsedRepresentationLabel:@"OPEN TOUCH 2"];

        _touchBar2 = [[NSTouchBar alloc] init];
        [_touchBar2 setDelegate:self];
        [_touchBar2 setCustomizationIdentifier:TouchBarCustomizationIdentifier];

        [_touchBar2 setDefaultItemIdentifiers:@[
                                                NSTouchBarItemIdentifier4_1,
                                                NSTouchBarItemIdentifier4_2,
                                                NSTouchBarItemIdentifier4_3,
                                                ]
         ];
        [_touchBar2 setCustomizationRequiredItemIdentifiers:@[
                                                              NSTouchBarItemIdentifier4_1,
                                                              NSTouchBarItemIdentifier4_2,
                                                              NSTouchBarItemIdentifier4_3,
                                                              ]
         ];

        [customTouchBarItem setPopoverTouchBar:_touchBar2];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_1]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 2" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_2]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 2" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_3]) {

        NSPopoverTouchBarItem *customTouchBarItem = [[NSPopoverTouchBarItem alloc] initWithIdentifier:identifier];
        [customTouchBarItem setCollapsedRepresentationLabel:@"OPEN TOUCH 3"];

        _touchBar3 = [[NSTouchBar alloc] init];
        [_touchBar3 setDelegate:self];
        [_touchBar3 setCustomizationIdentifier:TouchBarCustomizationIdentifier];

        [_touchBar3 setDefaultItemIdentifiers:@[
                                                NSTouchBarItemIdentifier4_3_1,
                                                NSTouchBarItemIdentifier4_3_2,
                                                ]
         ];
        [_touchBar3 setCustomizationRequiredItemIdentifiers:@[
                                                              NSTouchBarItemIdentifier4_3_1,
                                                              NSTouchBarItemIdentifier4_3_2,
                                                              ]
         ];

        [customTouchBarItem setPopoverTouchBar:_touchBar3];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_3_1]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 3" target:self action:nil]];

        return customTouchBarItem;

    } else if ([identifier isEqual:NSTouchBarItemIdentifier4_3_2]) {

        NSCustomTouchBarItem *customTouchBarItem = [[NSCustomTouchBarItem alloc] initWithIdentifier:identifier];

        [customTouchBarItem setView:[NSButton buttonWithTitle:@"IS TOUCH 3" target:self action:nil]];

        return customTouchBarItem;

    }

    return nil;
}

@end


问:
Locate the end of an XZ stream
I am currently trying to extract the inital RAM filesystem that is embedded in a kernel image, modify it, and repack the kernel image with it. You can search GitHub and find several projects that do this here. My problem with those scripts is that they are very specific or turn out to hard code values that I cannot use with the kernel image I am working with or they are just hard to reverse engineer. The kernel image I am working with uses XZ to compress the kernel and GZip to compress the initial RAM filesystem CPIO archive. The end of a GZip stream is easy to locate by looking for a particular string and those GitHub projects seem to need to know the exact end of these streams.

I am able to extract the compressed portion of the kernel like this:

```<code>offset=$(cat zImage | grep -aob $'\xFD\x37\x7A\x58\x5A\x00' | cut -d ":" -f 1 | sed -n 2p)
dd bs=1 skip=$offset if=zImage | xzcat > Image
</code>```

I can then extract the initial RAM filesystem CPIO archive from Image like this:

```<code>offset=$(cat "${1}" | grep -aob $'\x1F\x8B\x08' | cut -d ":" -f 1 | sed -n 2p)
dd bs=1 skip=$offset if=Image | zcat > initramfs.cpio
</code>```

Now, it seems from reading those GitHub scripts that one must know the end address of the compressed streams. How do I find the end of an XZ stream in shell script?

答:
The size of an xz file or stream is encoded within the Unpadded Size field within the xz header.

The Unpadded size field indicates the size of the Block excluding the Block Padding field.

i.e. Unpadded Size = size-of( Block Header + Compressed Data + CRC fields)

One quick method to obtain the size is using the xz tool itself as follows:

```<code>xz --robot --list <xz-file-or-stream> | cut -f 4 | sed -n 2p
</code>```

Reference: The xz file-format.

Note: Unpadded Size is stored using the encoding described in Section 1.2 Multibyte Integers of the xz file-format specification.
The value MUST never be zero; with the current structure of Blocks, the actual minimum value for Unpadded Size field is five.

Implementation note: Because the size of the Block Padding field is not included in Unpadded Size, calculating the total size of a Stream or doing random-access reading requires calculating the actual size of the Blocks by rounding Unpadded Sizes up to the next multiple of four.

Title: Locate the end of an XZ stream

Body:
I am currently trying to extract the inital RAM filesystem that is embedded in a kernel image, modify it, and repack the kernel image with it. You can search GitHub and find several projects that do this here. My problem with those scripts is that they are very specific or turn out to hard code values that I cannot use with the kernel image I am working with or they are just hard to reverse engineer. The kernel image I am working with uses XZ to compress the kernel and GZip to compress the initial RAM filesystem CPIO archive. The end of a GZip stream is easy to locate by looking for a particular string and those GitHub projects seem to need to know the exact end of these streams.

I am able to extract the compressed portion of the kernel like this:

offset=$(cat zImage | grep -aob $'\xFD\x37\x7A\x58\x5A\x00' | cut -d ":" -f 1 | sed -n 2p)
dd bs=1 skip=$offset if=zImage | xzcat > Image

I can then extract the initial RAM filesystem CPIO archive from Image like this:

offset=$(cat "${1}" | grep -aob $'\x1F\x8B\x08' | cut -d ":" -f 1 | sed -n 2p)
dd bs=1 skip=$offset if=Image | zcat > initramfs.cpio

Now, it seems from reading those GitHub scripts that one must know the end address of the compressed streams. How do I find the end of an XZ stream in shell script?

Body:
The size of an xz file or stream is encoded within the Unpadded Size field within the xz header.

The Unpadded size field indicates the size of the Block excluding the Block Padding field.

i.e. Unpadded Size = size-of( Block Header + Compressed Data + CRC fields)

One quick method to obtain the size is using the xz tool itself as follows:

xz --robot --list <xz-file-or-stream> | cut -f 4 | sed -n 2p

Reference: The xz file-format.

Note: Unpadded Size is stored using the encoding described in Section 1.2 Multibyte Integers of the xz file-format specification.
The value MUST never be zero; with the current structure of Blocks, the actual minimum value for Unpadded Size field is five.

Implementation note: Because the size of the Block Padding field is not included in Unpadded Size, calculating the total size of a Stream or doing random-access reading requires calculating the actual size of the Blocks by rounding Unpadded Sizes up to the next multiple of four.


问:
Laravel globally join the parent table and the children to be accessed in all views
I have three tables:

users: has id, name, email, password.

profiles : has id, user_id, age, sex.

addresses : has id, user_id, address, city, zip.

Is there any ways to join them to be used globally in all views instead of doing it in every controllers??

So, when I need the address in a view, I could access it by simply using {{Auth::user()->address}} or something like that

If it is possible, could you please give me an example on how to implement it?

答:
If you wants to use Auth like this then you have to define relations

User.php

```<code>public function address(){
 return $this->hasOne('YourAddressModel','user_id');
}

public function profile(){
   return $this->hasOne('YourProfileModel','user_id','id');
 }
</code>```

Body:
If you wants to use Auth like this then you have to define relations

User.php

public function address(){
 return $this->hasOne('YourAddressModel','user_id');
}

public function profile(){
   return $this->hasOne('YourProfileModel','user_id','id');
 }


问:
Create MS Excel Sheet
How can I create an MS Excel sheet and download it from a Moonlight/Silverlight app? Regards Lennie

Basically I want to run a report in the Siverlight client and allow the user to download the MS Excel report.

答:
I had to do this previously, its pretty time consuming but you can write it to a XML file on the client side.

A good place to start is to create a new excel sheet save it as an XML file and then you can work out which bits need to change and then work out a way to write the correct information to the XML file.

Although as I said it will take a fair bit of time!!

Edit-

Just found this for you to take a look at-
http://www.rshelby.com/post/creating-excel-worksheet-from-silverlight.aspx

ContentLicense: CC BY-SA 2.5

Title: Create MS Excel Sheet


问:
For every click different effect?
I have one problem. First - I HAVE AND I WILL HAVE JUST ONE BUTTON.
My problem is: How it can be for each button click different effect-animation.
So, when I first time click on button image goes down, then I second time click image goes from left to right, then I third time click image gone and then it repeat for fourth click image goes down(I can make animation left to right, animation down and then image gone.So I know how to do animation (effects), but I just do not know how to create for every click different effect on image)...</p>

答:
first read about ActioListeners

then simply create a listener that uses a counter!

Each time you click the button the listener increases that counter. And you use different animations based on the current value of the counter. When the "last" animation took place - simply reset the counter to start from scratch.

Title: For every click different effect?


问:
search suggestion functionality with angularjs not working
I am trying to run the below code on my system but not able to get the result. but same code i was running on js fiddler it was running.

this my index.html

```<code><div ng-app="myApp" ng-controller="myCtrl">
<div ng-app>
    <div ng-controller="MyController">
        <input type="search" ng-model="search" placeholder="Search...">
        <ul>
            <li ng-repeat="name in names | filter:search">
                {{ name }}
            </li>
        </ul>
    </div>
</div>
</code>```

script.js

```<code>var app = angular.module('MyModule', []);

app.controller('DefaultCtrl', function($scope) {
    $scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
});

app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});
</code>```

Also i want to get exaxct match if i enter 'A' only the words come which is start with the letter 'A' and so on...

答:
Replace this in your index.html

```<code><div ng-app="MyModule">
    <div ng-controller="DefaultCtrl">
        <input type="search" ng-model="search" placeholder="Search...">
        <ul>
            <li ng-repeat="name in names | filter:search">
                {{ name }}
            </li>
        </ul>
    </div>
</div>
</code>```

Body:
I am trying to run the below code on my system but not able to get the result. but same code i was running on js fiddler it was running.

this my index.html

        <input type="search" ng-model="search" placeholder="Search...">

                {{ name }}

script.js

var app = angular.module('MyModule', []);

app.controller('DefaultCtrl', function($scope) {
    $scope.names = ["john", "bill", "charlie", "robert", "alban", "oscar", "marie", "celine", "brad", "drew", "rebecca", "michel", "francis", "jean", "paul", "pierre", "nicolas", "alfred", "gerard", "louis", "albert", "edouard", "benoit", "guillaume", "nicolas", "joseph"];
});

app.directive('autoComplete', function($timeout) {
    return function(scope, iElement, iAttrs) {
            iElement.autocomplete({
                source: scope[iAttrs.uiItems],
                select: function() {
                    $timeout(function() {
                      iElement.trigger('input');
                    }, 0);
                }
            });
    };
});

Also i want to get exaxct match if i enter 'A' only the words come which is start with the letter 'A' and so on...

Body:
Replace this in your index.html

<div ng-app="MyModule">
    <div ng-controller="DefaultCtrl">
        <input type="search" ng-model="search" placeholder="Search...">
        <ul>
            <li ng-repeat="name in names | filter:search">
                {{ name }}
            </li>
        </ul>
    </div>
</div>


问:
ModuleNotFoundError: No module named 'ebaysdk'
I am trying to execute the below code, but I get an error as in the title. ebaysdk was installed using pip3, then easy_install and still the error, despite all dependencies being satisfied at the installation, yet no ebaysdk.py file, please see my code below:

```<code>import datetime
from ebaysdk.exception import ConnectionError
from ebaysdk.finding import Connection

try:
    api = Connection(appid=**<mykey>**, config_file='ebay.yaml')
    response = api.execute('findItemsAdvanced', {'keywords': 'legos'})

    assert(response.reply.ack == 'Success')
    assert(type(response.reply.timestamp) == datetime.datetime)
    assert(type(response.reply.searchResult.item) == list)

    item = response.reply.searchResult.item[0]
    assert(type(item.listingInfo.endTime) == datetime.datetime)
    assert(type(response.dict()) == dict)

except ConnectionError as e:
    print(e)
    print(e.response.dict())
</code>```

I am using Python 3.6 (Anaconda), working with timotheus' ebaysdk - https://github.com/timotheus/ebaysdk-python.

I would greatly appreciate your help.

答:
Problem solved.

Apart from 3.6 I also had 3.5.2 and 2.7. Got rid of all versions and re-installed clean 3.6.

Body:
I am trying to execute the below code, but I get an error as in the title. ebaysdk was installed using pip3, then easy_install and still the error, despite all dependencies being satisfied at the installation, yet no ebaysdk.py file, please see my code below:

import datetime
from ebaysdk.exception import ConnectionError
from ebaysdk.finding import Connection

try:
    api = Connection(appid=**<mykey>**, config_file='ebay.yaml')
    response = api.execute('findItemsAdvanced', {'keywords': 'legos'})

    assert(response.reply.ack == 'Success')
    assert(type(response.reply.timestamp) == datetime.datetime)
    assert(type(response.reply.searchResult.item) == list)

    item = response.reply.searchResult.item[0]
    assert(type(item.listingInfo.endTime) == datetime.datetime)
    assert(type(response.dict()) == dict)

except ConnectionError as e:
    print(e)
    print(e.response.dict())

I am using Python 3.6 (Anaconda), working with timotheus' ebaysdk - https://github.com/timotheus/ebaysdk-python.

I would greatly appreciate your help.


问:
How much memory uses an array with one high-index element?
Would running this code occupy about 4_000_000 bytes of memory?</p>

```<code>my uint32 @array;
@array[1_000_000] = 1;
</code>```

答:
If you assign element 1_000_000 and each element is 4 bytes, that would be 4_000_004 bytes of memory.  So strictly speaking, the answer is "No"  :-)

But less pedantically: native arrays are guaranteed to be laid out consecutively in memory, so such an assignment would at least allocate a single block of 4 x 1_000_001 = 4_000_004 bytes of memory.  As Christoph stated in his comment, if you want to make sure it is all it will ever allocate, you need to make it a shaped native array.  You will get upper bounds checks as a bonus as well.

Body:
Would running this code occupy about 4_000_000 bytes of memory?

my uint32 @array;
@array[1_000_000] = 1;


问:
Error: Missing where attribute in the options parameter passed to findOrCreate.
I'm trying to use sequelize findOrCreate function, but I'm getting this error:

```<code>Error: Missing where attribute in the options parameter passed to findOrCreate.
</code>```

This is my code:

```<code>var values = { slack_id: profile.id, name: profile.user };
var selector = { where: { slack_id: profile.id } };
User.findOrCreate(values, selector)
            .then(function() {
                return done(err, user);
            });
</code>```

答:
```<code> Missing where attribute in the options parameter passed to
 findOrCreate. Please note that the API has changed, and is now options
 only (an object with where, defaults keys, transaction etc.)
</code>```

You should switch the arguments so that the object containing the where clause is first, not second. The second argument is the place for default keys.

```<code>User.findOrCreate(selector, values)
        .then(function() {
            return done(err, user);
        });
</code>```

Body:
I'm trying to use sequelize findOrCreate function, but I'm getting this error:

Error: Missing where attribute in the options parameter passed to findOrCreate.

This is my code:

var values = { slack_id: profile.id, name: profile.user };
var selector = { where: { slack_id: profile.id } };
User.findOrCreate(values, selector)
            .then(function() {
                return done(err, user);
            });

Body:
 Missing where attribute in the options parameter passed to
 findOrCreate. Please note that the API has changed, and is now options
 only (an object with where, defaults keys, transaction etc.)

You should switch the arguments so that the object containing the where clause is first, not second. The second argument is the place for default keys.

User.findOrCreate(selector, values)
        .then(function() {
            return done(err, user);
        });


问:
getwindowhandles in selenium
Im getting:
AttributeError: 'WebDriver' object has no attribute 'getwindowhandles'

when trying

```<code> Whandles = driver.getWindowHandles()
 print(Whandles)
</code>```

these are my imports:

```<code>import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from ui.css import Ui_Dialog
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
import time
</code>```

Am I missing something?

答:
The exception is telling you that there is no method getWindowHandles() on the driver class. What you need is

```<code>Whandles = driver.window_handles
</code>```

When you see this type of exception, do a print(dir(driver)) to see what methods are supported by the class.

Title: getwindowhandles in selenium

Body:
Im getting:
AttributeError: 'WebDriver' object has no attribute 'getwindowhandles'

when trying

 Whandles = driver.getWindowHandles()
 print(Whandles)

these are my imports:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from ui.css import Ui_Dialog
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
import time

Am I missing something?

Body:
The exception is telling you that there is no method getWindowHandles() on the driver class. What you need is

Whandles = driver.window_handles

When you see this type of exception, do a print(dir(driver)) to see what methods are supported by the class.


问:
How to stop the error message, If JSON file failed to open stream
This is the error, i am getting

Warning: file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

Now, you may founder, what is inside that link?

That page contain this line only

{"status_code":34,"status_message":"The resource you requested could not be found."}

So, I think this is a valid page (which i can open in browser). I just want PHP to stop giving this error, if it failed to open stream.

This is my JSON code

```<code> $response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
    $response = json_decode($response, true);
}
</code>```

Edit: It is not duplicate of that question. That question is related to email and password, where mine is not

答:
try coreect or incorrect option
if (response === "correct") {
}</p>

Body:
This is the error, i am getting

Warning: file_get_contents(https://api.themoviedb.org/3/movie/39740?api_key=522cec78237f49axxxxxxxxxxx6d1e0c834a): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found

Now, you may founder, what is inside that link?

That page contain this line only

{"status_code":34,"status_message":"The resource you requested could not be found."}

So, I think this is a valid page (which i can open in browser). I just want PHP to stop giving this error, if it failed to open stream.

This is my JSON code

 $response = file_get_contents("https://api.themoviedb.org/3/movie/".$requestsDone."?api_key=522cec782xxxx6f6d1e0c834a");
if ($response != FALSE) {
    $response = json_decode($response, true);
}

Edit: It is not duplicate of that question. That question is related to email and password, where mine is not


问:
portable password dialog in javascript
I have a web page, and am trying to add password protection to it, so, if say a user presses a 'send' button, but was not authenticated, a dialog would appear asking for a password.   I originally thought of using prompt to ask for the password, and came across how to take input as password in javascript promt box.  It appears that prompt does not hide the text (which I would want).

I could create a custom dialog box, but at that point, I'm concerned there might be some corner cases where varous browsers might block the dialog box from appearing (mainly I'm concerned with phones/browsers with ad-blockers, etc).   Am I going to run into trouble, or is there another way to prompt for passwords?

答:
you can use a .htaccess file to protect your page

```<code><Files page_to_protect.php>
AuthUserFile /www/.htpasswd
AuthGroupFile /dev/null
AuthName "the message that you want display"
AuthType Basic
Require valid-user
</Files>
</code>```

and this is the .htpasswd file :

```<code>your_name:your_passwd
</code>```

finally, just add this below to your button, and it will works perfectly

```<code><a href="page_to_protect.php"></a>
</code>```

if you are not on linux, you can create the .htaccess and .htpasswd files with Notepad++

Title: portable password dialog in javascript

Body:
you can use a .htaccess file to protect your page

<Files page_to_protect.php>
AuthUserFile /www/.htpasswd
AuthGroupFile /dev/null
AuthName "the message that you want display"
AuthType Basic
Require valid-user
</Files>

and this is the .htpasswd file :

your_name:your_passwd

finally, just add this below to your button, and it will works perfectly

<a href="page_to_protect.php"></a>

if you are not on linux, you can create the .htaccess and .htpasswd files with Notepad++


问:
Home brew Apache error_log child pid * exit signal Floating point exception (8) on mac osx 10.11 AMP stack
every time a enable a module in Drupal 7, refresh the page, i get this

This page isn’t working

localhost didn’t send any data.

ERR_EMPTY_RESPONSE

my local dev is homebrew's Apache2.4, php7 on a mac osx 10.11

答:
Switching back to homebrew's php56 solved this, and now i don't have any SIGFPE in my apache logs. Now i can enable any Druapl7 module, and works like charm!.

Problem: Yes, i had homebrew's php71, i think Maybe one of the php scripts is broken, either by design or a subtly corrupt file hence getting apache logging SIGFPE ("exit signal Floating point exception (8)")

You can install sphp to switch from php71 back and forth to php56. click here to read about sphp


问:
JavaScript - How to place asterisk in the right side of the text box?
I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.

This is my code:

```<code>[<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>
<style type="text/css">
body { font-family:arial, helvetica, sans-serif; font-weight:bold; font-size:13px; color:#000; text-align:left; margin:3px 0px; }
input { text-align:center; border:2px solid #CCC; }
#wrap  { width:400px; height:200px; margin:20px; padding:10px;  }
#une { margin-top:10px; }
#reg {margin-top:10px; }
.a13B { color:#F00; }
.cntr { text-align:center; }
</style>
</head>

<body>

<div id="wrap">
  <form id="regform" name="registerationform" method="POST">
    <table border="1" cellpadding="0" cellspacing="0" style="border-collapse: collapse" width="300">
      <tr>
        <td>First Name: </td>
        <td class="cntr">
        <input type="text" name="fnametxt" size="20"></td>
      </tr>
      <tr>
        <td>Second Name: </td>
        <td class="cntr">
        <input type="text" name="snametxt" size="20"> </td>
      </tr>
      <tr>
        <td>User Name:</td>
        <td class="cntr">
        <input type="text" name="unametxt" size="20"> </td>
      </tr>
      <tr>
        <td>Email Address: </td>
        <td class="cntr">
        <input type="text" name="emailtxt" size="20"> </td>
      </tr>
      <tr>
        <td>Password : </td>
        <td class="cntr"><input type="password" name="pwdtxt" size="20"> </td>
      </tr>
      <tr>
        <td>Confirm : </td>
        <td class="cntr"><input type="password" name="cpwdtxt" size="20"> </td>
      </tr>
    </table>
    <input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
  </form>
  <div id="une" class="a13B">
  </div>
</div>
<!-- end wrap -->
<script type="text/javascript">
var uneObj=document.getElementById("une"); // object ref to msg line
var currentBrdObj;
//
function regvalidate(formObj)
{ uneObj.innerHTML=""; // clear msg line before resubmitting
 // gather object ref to input boxes
  var allInputs=document.getElementById("regform").getElementsByTagName("input");
 // check if value of box is ""
  for(var i=0;i<allInputs.length;i++)
    { if(allInputs\[i\].name !="reg")    // ignore submit button
       { if(allInputs\[i\].value=="")
         { uneObj.innerHTML=msg\[i\];
           if(currentBrdObj){currentBrdObj.style.border="2px solid #CCC"; }
           allInputs\[i\].style.border="2px solid #F00";
           currentBrdObj=allInputs\[i\];
           allInputs\[i\].onclick=function(){ this.style.border="2px solid #CCC"; }
           return;
     } } }
// check if password and confirm are the same
  if((formObj.pwdtxt.value) != (formObj.cpwdtxt.value))
   { uneObj.innerHTML = msg\[msg.length-1\];       // last msg in array
     formObj.pwdtxt.value = ""; formObj.pwdtxt.style.border="";
     formObj.cpwdtxt.value = ""; formObj.cpwdtxt.style.border="";
     return;
    }
// all ok so submit form
 uneObj.innerHTML = "All ok so submitting form";
  formObj.submit();
}
// -----
 var msg =\["*","*",
          "*","*",
          "*","*"\];
     msg\[msg.length\]="Passwords must be equal.<br>Please type a password";

      //
        </script>

</body>

</html>][1]
</code>```

@PawanKumar
Here is your code:

```<code>   <html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script>
$(document).ready(function() {
  $('#submitBtn').on('click', function(e) {
    debugger;
    e.preventDefault();
    var fields = document.getElementsByTagName('input');
    for (var i = 0; i < fields.length; i++) {
      if (fields[i].hasAttribute('required')) {
        if (fields[i].value == "") {
          fields[i].classList.add('redBorder');
          $(fields[i]).after('*');
        } else {
          fields[i].classList.remove('redBorder');
        }
      }
    }
  });
});

</script>

<style>

.redBorder {
  border: 2px solid red;
  border-radius: 2px;
}

</style>

</head>

<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>

</html>
</code>```

答:
With the help of jquery after() method, you can achieve this.

```<code>$(fields[i]).after("<span class='redColor'>*</span>");
</code>```

I have also added code to show red border for required input field.

Note: If you use <form> tag, then HTML5 will automatically does the validation and your script will not execute, so to prevent that use novalidate attribute in the form tag or just remove the form tag.

$(document).ready(function() {
  $('#submitBtn').on('click', function(e) {
    e.preventDefault();
    var fields = document.getElementsByTagName('input');
    for (var i = 0; i < fields.length; i++) {
      if (fields[i].hasAttribute('required')) {
        if (fields[i].value == "") {
          fields[i].classList.add('redBorder');
          $(fields[i]).after("*");
        } else {
          fields[i].classList.remove('redBorder');
        }
      }
    }
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.redBorder {
  border: 2px solid red;
  border-radius: 2px;
}

.redColor{
  color:red;
}</code>```

<form novalidate>
<input type="text" placeholder="first name" required/>

<input type="text" placeholder="last name" />

<button id="submitBtn" value="Submit">Submit</button>
</form>```

Body:
I want to place asterisk in the right side of the each text box individually when I am submitting the empty form/field. The code is working but asterisk is displaying in the end of the form.

This is my code:

[

<meta http-equiv="Content-Type" content="text/html; charset=windows-1252" />
<title></title>

  <form id="regform" name="registerationform" method="POST">

        First Name:

        <input type="text" name="fnametxt" size="20">

        Second Name:

        <input type="text" name="snametxt" size="20">

        User Name:

        <input type="text" name="unametxt" size="20">

        Email Address:

        <input type="text" name="emailtxt" size="20">

        Password :
        <input type="password" name="pwdtxt" size="20">

        Confirm :
        <input type="password" name="cpwdtxt" size="20">

    <input id="reg" name="reg" type="button" onclick="regvalidate(this.form)" value="Register Now">
  </form>

][1]

@PawanKumar
Here is your code:

<form novalidate>
<input type="text" placeholder="first name" required/>

<input type="text" placeholder="last name" />

<button id="submitBtn" value="Submit">Submit</button>
</form>

Body:
With the help of jquery after() method, you can achieve this.

$(fields[i]).after("<span class='redColor'>*</span>");

I have also added code to show red border for required input field.

Note: If you use <form> tag, then HTML5 will automatically does the validation and your script will not execute, so to prevent that use novalidate attribute in the form tag or just remove the form tag.

$(document).ready(function() {
  $('#submitBtn').on('click', function(e) {
    e.preventDefault();
    var fields = document.getElementsByTagName('input');
    for (var i = 0; i < fields.length; i++) {
      if (fields[i].hasAttribute('required')) {
        if (fields[i].value == "") {
          fields[i].classList.add('redBorder');
          $(fields[i]).after("<span class='redColor'>*</span>");
        } else {
          fields[i].classList.remove('redBorder');
        }
      }
    }
  });
});

.redBorder {
  border: 2px solid red;
  border-radius: 2px;
}

.redColor{
  color:red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form novalidate>
<input type="text" placeholder="first name" required/><br/><br/>
<input type="text" placeholder="last name" /><br/><br/>
<button id="submitBtn" value="Submit">Submit</button>
</form>


问:
Developing a RIA with Django - what technology stack?
I need to develop a web application with the following requirements:

Desktop like UI on the client side

Application deployment

Scalability (i.e. distributing the service on multiple servers)

What I thought of so far (as I love Python but haven't done much web development yet):

Django

Fabric (think I've read somewhere it's suited for this)

What I'm missing is:

How to create rich clients (probably need some javascript libraries for that)?

How to distribute the service?

答:
Rich Internet Application: Javascript to do stuff asynchronously (AJAX). If you want a desktop-like interface on the web, it seems currently CoffeeScript is the way to go. It's a language that compiles into Javascript and adapted for rich interfaces.

Deployment: fabric (I think it's used to deploy Python apps).

Distribution: you deploy the code to one server.If you need to scale it up, you just need some additional servers (of course if you have specific usages like very high load on a database, you'll also need to add more database servers etc. But you get the idea).


问:
Run PowerShell custom function in new window
```<code>Function Check-PC
{
$PC = Read-Host "PC Name"
If($PC -eq "exit"){EXIT}
Else{
Write-Host "Pinging $PC to confirm status..."
PING -n 1 $PC
}
</code>```

This is a snippet of a function I have written into a PowerShell script.  I would like the function to run in a new instance of PowerShell, not in the main window.

Is it possible to run this in a separate process of PowerShell without writing it as a separate script and calling the script? Something like this:

```<code>$x= Start-Process powershell | Check-PC
</code>```

I need to keep everything in one script if possible.

答:
Note: It is the involvement of Start-Process that complicates the solution significantly - see below. If powershell were invoked directly from PowerShell, you could safely pass a script block as follows:

powershell ${function:Check-PC}  # !! Does NOT work with Start-Process
```
<p><code>${function:Check-PC}</code> is an instance of variable namespace notation: it returns the function's <em>body</em> as a <em>script block</em> (<code>[scriptblock]</code> instance); it is the more concise and faster equivalent of <br><code>Get-Content Function:Check-PC</code>.</p>
<p>If you needed to pass (positional-only) arguments to the script block, you'd have to append <code>-Args</code>, followed by the arguments as an <em>array</em> (<code>,</code>-separated).</p>
<hr />
<h3><code>Start-Process</code> solution with an auxiliary self-deleting temporary file:</h3>
<p>See the bottom half of this answer to a related question.</p>
<hr />
<h3><code>Start-Process</code> solution with <code>-EncodedCommand</code> and Base64 encoding:</h3>
<pre class="lang-sh prettyprint-override"><code>Start-Process powershell -args '-noprofile', '-noexit', '-EncodedCommand',
  ([Convert]::ToBase64String(
     [Text.Encoding]::Unicode.GetBytes(
       (Get-Command -Type Function Check-PC).Definition
     )
  ))
</code>```

The new powershell instance will not see your current session's definitions (unless they're defined in your profiles), so you must pass the body of your function to it (the source code to execute).

(Get-Command -Type Function Check-PC).Definition returns the body of your function definition as a string.

The string needs escaping, however, in order to be passed to the new Powershell process unmodified.

" instances embedded in the string are stripped, unless they are either represented as \" or tripled (""").

(\" rather than the usual `" is needed to escape double quotes in this case, because PowerShell expects \" when passing a command to the powershell.exe executable.)

Similarly, if the string as a whole or a double-quoted string inside the function body ends in (a non-empty run of) \, that \ would be interpreted as an escape character, so the \ must be doubled.Thanks, PetSerAl.

The most robust way to bypass these quoting (escaping) headaches is to use a Base64-encoded string in combination with the -EncodedCommand parameter:

[Convert]::ToBase64String() creates a Base64-encoded string from a [byte[]] array.

[Text.Encoding]::Unicode.GetBytes() converts the (internally UTF-16 -
"Unicode") string to a [byte[]] array.

Note: To also pass arguments, you have two options:

You can "bake" them into the -EncodedCommand argument, assuming you can call a command to pass them to there - see below, which shows how to define your function as such in the new session, so you can call it by name with arguments.Thanks, Abraham Zinala

The advantage of this approach is that you can pass named arguments this way. The disadvantage is that you are limited to arguments that have string-literal representations.

You can use the (currently undocumented) -EncodedArguments parameter, to which you must similarly pass a Base64-encoded string, albeit based on the CLIXML representation of the array of arguments to pass

The advantage of this approach is that you can pass a wider array of data types, within the limits of the type fidelity that CLIXML serialization can provide - see this answer; the disadvantage is that only positional arguments are supported this way (although you could work around that by passing a hashtable that the target code then uses for splatting with the ultimate target command).

Here's a simplified, self-contained example, which uses Write-Output to echo the (invariably positional) arguments received:

$command = 'Write-Output $args'
$argList = 'foo', 42

Start-Process powershell -args '-noprofile', '-noexit',
  '-EncodedCommand',
    ([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))),
  '-EncodedArguments',
    ([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes(
      [System.Management.Automation.PSSerializer]::Serialize($argList)
    )))
```
<hr />
<p><strong>In case you want to pass the <em>complete</em> function, so it can be called <em>by name</em> in order to pass <em>arguments</em> as part of the command string</strong>, a little more work is needed.</p>
<pre class="lang-sh prettyprint-override"><code># Simply wrapping the body in `function <name> { ... }` is enough.
$func = (Get-Command -Type Function Check-PC)
$wholeFuncDef = 'Function ' + $func.Name + " {`n" + $func.Definition + "`n}"

Start-Process powershell -args '-noprofile', '-noexit', '-EncodedCommand', `
  ([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes("$wholeFuncDef; Check-PC")))
</code>```

As stated above, you can "bake" any arguments to pass to your function - assuming they can be represented as string literals - into the -EncodedCommand argument, simply by appending them inside the "$wholeFuncDef; Check-PC" string above; e.g.,

"$wholeFuncDef; Check-PC -Foo Bar -Baz Quux"

Start-Process solution with regex-based escaping of the source code to pass:

PetSerAl suggests the following alternative, which uses a regex to perform the escaping.
The solution is more concise, but somewhat mind-bending:

Start-Process powershell -args '-noprofile', '-noexit', '-Command', `
  ('"' +
   ((Get-Command -Type Function Check-PC).Definition -replace '"|\\(?=\\*("|$))', '\$&') +
   '"')
```

"|\\(?=\\*("|$)) matches every " instance and every nonempty run of \ chars. - character by character - that directly precedes a " char. or the very end of the string.

\\ is needed in the context of a regex to escape a single, literal \.

(?=\\*("|$)) is a positive look-ahead assertion that matches \ only if followed by " or the end of the string ($), either directly, or with further \ instances in between (\\*).  Note that since assertions do not contribute to the match, the \ chars., if there are multiple ones, are still matched one by one.

\$& replaces each matched character with a \ followed by the character itself ($&) - see this answer for the constructs you can use in the replacement string of a -replace expression.

Enclosing the result in "..." ('"' + ... + '"') is needed to prevent whitespace normalization; without it, any run of more than one space char. and/or tab char. would be normalized to a single space, because the entire string wouldn't be recognized as a single argument.

Note that if you were to invoke powershell directly, PowerShell would generally automatically enclose the string in "..." behind the scenes, because it does so for arguments that contain whitespace when calling an external utility (a native command-line application), which is what powershell.exe is - unlike the Start-Process cmdlet.

PetSerAl points out that the automatic double-quoting mechanism is not quite that simple, however (the specific content of the string matters with respect to whether automatic double-quoting is applied), and that the specific behavior changed in v5, and again (slightly) in v6.

Body:
Function Check-PC
{
$PC = Read-Host "PC Name"
If($PC -eq "exit"){EXIT}
Else{
Write-Host "Pinging $PC to confirm status..."
PING -n 1 $PC
}

This is a snippet of a function I have written into a PowerShell script.  I would like the function to run in a new instance of PowerShell, not in the main window.

Is it possible to run this in a separate process of PowerShell without writing it as a separate script and calling the script? Something like this:

$x= Start-Process powershell | Check-PC

I need to keep everything in one script if possible.

Body:
Note: It is the involvement of Start-Process that complicates the solution significantly - see below. If powershell were invoked directly from PowerShell, you could safely pass a script block as follows:

powershell ${function:Check-PC}  # !! Does NOT work with Start-Process

${function:Check-PC} is an instance of variable namespace notation: it returns the function's body as a script block ([scriptblock] instance); it is the more concise and faster equivalent of
Get-Content Function:Check-PC.

If you needed to pass (positional-only) arguments to the script block, you'd have to append -Args, followed by the arguments as an array (,-separated).

Start-Process solution with an auxiliary self-deleting temporary file:

See the bottom half of this answer to a related question.

Start-Process solution with -EncodedCommand and Base64 encoding:

Start-Process powershell -args '-noprofile', '-noexit', '-EncodedCommand',
  ([Convert]::ToBase64String(
     [Text.Encoding]::Unicode.GetBytes(
       (Get-Command -Type Function Check-PC).Definition
     )
  ))

The new powershell instance will not see your current session's definitions (unless they're defined in your profiles), so you must pass the body of your function to it (the source code to execute).

(Get-Command -Type Function Check-PC).Definition returns the body of your function definition as a string.

The string needs escaping, however, in order to be passed to the new Powershell process unmodified.

" instances embedded in the string are stripped, unless they are either represented as \" or tripled (""").

(\" rather than the usual `" is needed to escape double quotes in this case, because PowerShell expects \" when passing a command to the powershell.exe executable.)

Similarly, if the string as a whole or a double-quoted string inside the function body ends in (a non-empty run of) \, that \ would be interpreted as an escape character, so the \ must be doubled.Thanks, PetSerAl.

The most robust way to bypass these quoting (escaping) headaches is to use a Base64-encoded string in combination with the -EncodedCommand parameter:

[Convert]::ToBase64String() creates a Base64-encoded string from a [byte[]] array.

[Text.Encoding]::Unicode.GetBytes() converts the (internally UTF-16 -
"Unicode") string to a [byte[]] array.

Note: To also pass arguments, you have two options:

You can "bake" them into the -EncodedCommand argument, assuming you can call a command to pass them to there - see below, which shows how to define your function as such in the new session, so you can call it by name with arguments.Thanks, Abraham Zinala

The advantage of this approach is that you can pass named arguments this way. The disadvantage is that you are limited to arguments that have string-literal representations.

You can use the (currently undocumented) -EncodedArguments parameter, to which you must similarly pass a Base64-encoded string, albeit based on the CLIXML representation of the array of arguments to pass

The advantage of this approach is that you can pass a wider array of data types, within the limits of the type fidelity that CLIXML serialization can provide - see this answer; the disadvantage is that only positional arguments are supported this way (although you could work around that by passing a hashtable that the target code then uses for splatting with the ultimate target command).

Here's a simplified, self-contained example, which uses Write-Output to echo the (invariably positional) arguments received:

$command = 'Write-Output $args'
$argList = 'foo', 42

Start-Process powershell -args '-noprofile', '-noexit',
  '-EncodedCommand',
    ([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))),
  '-EncodedArguments',
    ([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes(
      [System.Management.Automation.PSSerializer]::Serialize($argList)
    )))

In case you want to pass the complete function, so it can be called by name in order to pass arguments as part of the command string, a little more work is needed.

# Simply wrapping the body in `function <name> { ... }` is enough.
$func = (Get-Command -Type Function Check-PC)
$wholeFuncDef = 'Function ' + $func.Name + " {`n" + $func.Definition + "`n}"

Start-Process powershell -args '-noprofile', '-noexit', '-EncodedCommand', `
  ([Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes("$wholeFuncDef; Check-PC")))

As stated above, you can "bake" any arguments to pass to your function - assuming they can be represented as string literals - into the -EncodedCommand argument, simply by appending them inside the "$wholeFuncDef; Check-PC" string above; e.g.,

"$wholeFuncDef; Check-PC -Foo Bar -Baz Quux"

Start-Process solution with regex-based escaping of the source code to pass:

PetSerAl suggests the following alternative, which uses a regex to perform the escaping.
The solution is more concise, but somewhat mind-bending:

Start-Process powershell -args '-noprofile', '-noexit', '-Command', `
  ('"' +
   ((Get-Command -Type Function Check-PC).Definition -replace '"|\\(?=\\*("|$))', '\$&') +
   '"')

"|\\(?=\\*("|$)) matches every " instance and every nonempty run of \ chars. - character by character - that directly precedes a " char. or the very end of the string.

\\ is needed in the context of a regex to escape a single, literal \.

(?=\\*("|$)) is a positive look-ahead assertion that matches \ only if followed by " or the end of the string ($), either directly, or with further \ instances in between (\\*).  Note that since assertions do not contribute to the match, the \ chars., if there are multiple ones, are still matched one by one.

\$& replaces each matched character with a \ followed by the character itself ($&) - see this answer for the constructs you can use in the replacement string of a -replace expression.

Enclosing the result in "..." ('"' + ... + '"') is needed to prevent whitespace normalization; without it, any run of more than one space char. and/or tab char. would be normalized to a single space, because the entire string wouldn't be recognized as a single argument.

Note that if you were to invoke powershell directly, PowerShell would generally automatically enclose the string in "..." behind the scenes, because it does so for arguments that contain whitespace when calling an external utility (a native command-line application), which is what powershell.exe is - unlike the Start-Process cmdlet.

PetSerAl points out that the automatic double-quoting mechanism is not quite that simple, however (the specific content of the string matters with respect to whether automatic double-quoting is applied), and that the specific behavior changed in v5, and again (slightly) in v6.

ContentLicense: CC BY-SA 4.0


问:
Loading data in view after click the button without reload all data in page asp.net mvc
I need to load all of comments after click button "all comments" without reload page.
I have "News" page with comments, after load page we can see one comment below the text news. All data situated in table rows. I have two rows. One row have button "All comments", second row have textbox from comments and button "Add new comment".
I need after click button "All comments" load all list comments (dynamic load rows with data) without reload page. And I need to add comment in database after click button "Add new comment" without reload page too.
I don't know how to do this.

I have combined model:

```<code>using System.Collections.Generic;

namespace NarkomApp.Models

{
    public class News_CommentsModel
    {
        public NEWS newsModel { get; set; }
    public List<COMMENTS> commentsModel { get; set; }

    public List<NEWS> recomendNewsModel { get; set; }
    public List<NEWS> waterShutOffModel { get; set; }
    }
}
</code>```

Code view:

```<code><tr class="trDiscussion">

                    <td colspan="2">
                        <div class="gray"></div>
                        <div class="interesting">
                            <p>Обсуждение</p>
                        </div>
                    </td>

                </tr>

                <tr class="trComments">

                    <td width="100%" height="auto" colspan="2">
                        <div class="comments">

                            @{
                                if (Model.commentsModel.Count != 0)
                                {
                                    for (int i = 0; i < Model.commentsModel.Count; i++)
                                    {
                                        <p>@Model.commentsModel[i].sUserName</p>
                                        <p><a class="date-comment">@Model.commentsModel[i].vDateTime</a></p>
                                        <p class="text-comment">@Model.commentsModel[i].vComment</p>
                                    }

                                }
                                else
                                {
                                    <p>Комментариев нет</p>
                                }
                            }

                        </div>
                    </td>

                </tr>

                <tr class="trButtonShowAllComments">

                    <td colspan="2" height="50px">
                        <div>
                            <a class="comm" role="button" href="#">Все комментарии</a>
                        </div>
                    </td>

                </tr>

                <tr class="trAddNewComment">

                    <td width="100%" height="auto" colspan="2">
                        @{
                            if (Session["iIdUsers"] == null)
                            {
                                <div class="new-comment">
                                    Вы не авторизированы, для того, чтобы оставлять коментарии войдите под своим аккаунтом: @Html.ActionLink("Войти", "LogIn", "Home")
                                </div>
                            }
                            else
                            {
                                <div class="new-comment">
                                    <p>Новый комментарий:</p>
                                </div>
                                <textarea class="message" size="40" name="search" placeholder=""></textarea>
                                <div>
                                    <a class="send" role="button" href="#">Отправить</a>
                                </div>
                            }
                        }
                    </td>
</code>```

答: Think you should read about Asp.net WebApi, or doing some tricky stuff by implementing api function inside your regular mvc controller, which would return page with only json-serialized data. And of course use ajax(or just XmlHttpRequest if you don't want to load external library) to retrieve tha data from apropreate api action</p>

Body:
I need to load all of comments after click button "all comments" without reload page.
I have "News" page with comments, after load page we can see one comment below the text news. All data situated in table rows. I have two rows. One row have button "All comments", second row have textbox from comments and button "Add new comment".
I need after click button "All comments" load all list comments (dynamic load rows with data) without reload page. And I need to add comment in database after click button "Add new comment" without reload page too.
I don't know how to do this.

I have combined model:

using System.Collections.Generic;

namespace NarkomApp.Models

{
    public class News_CommentsModel
    {
        public NEWS newsModel { get; set; }
    public List<COMMENTS> commentsModel { get; set; }

    public List<NEWS> recomendNewsModel { get; set; }
    public List<NEWS> waterShutOffModel { get; set; }
    }
}

Code view:

Обсуждение

                            @{
                                if (Model.commentsModel.Count != 0)
                                {
                                    for (int i = 0; i < Model.commentsModel.Count; i++)
                                    {

@Model.commentsModel[i].sUserName

@Model.commentsModel[i].vDateTime

@Model.commentsModel[i].vComment

                                    }

                                }
                                else
                                {

Комментариев нет

                                }
                            }

                            Все комментарии

                        @{
                            if (Session["iIdUsers"] == null)
                            {

                                    Вы не авторизированы, для того, чтобы оставлять коментарии войдите под своим аккаунтом: @Html.ActionLink("Войти", "LogIn", "Home")

                            }
                            else
                            {

Новый комментарий:

                                <textarea class="message" size="40" name="search" placeholder=""></textarea>

                                    Отправить

                            }
                        }


问:
Is way to upload header comma in csv?
Hello Friend i have text array with comma selerated with double coutes but when i push record in csv that comma seperated value convert into two header can you please help me to solved this issue .

please find bellow string.
for example : i need "South West, London & Support Office L1" in one colume

```<code>$datestr ='First Name,Last Name,Company,Type,Email,Attendance Status,Invited By,Payroll      No,Pharmacy No,Pharmacy Name,RM,RSM,Accomodation Friday,Accomodation Saturday,Job_Title,"Business Partner Session","Awards Evening","North & Central L1","North & Central L2","South East L1","South East & Warehouse L2","South West, London & Support Office L1","South West, London and Support Office L2';

$sessstr = "First Name,"."Last Name,"."Company,"."Type,"."Email,"."Attendance Status,"."Invited By,"."Payroll No,"."Pharmacy No,"."Pharmacy Name,"."RM,"."RSM,"."Accomodation Friday,"."Accomodation Saturday,"."Job_Title,";
        $datestr = "Jaikishan, Keswani,Day Lewis,jaikishan.keswani@daylewisplc.co.uk,Yes,Colin,,,1,,,,Yes,Yes,PHP Developer,";
        foreach($sessions as $k=>$ses){
            $sessstr .= '"'.$ses['session_name'].'",';
            $datestr .= 'Yes,';
        }
        $datestr = substr($datestr,0,-1);
        $sessstr = substr($sessstr,0,-1);

        $sessstr = $sessstr.",European Welcome Dinner,"."Accommodation By Invitation Letter,"."Notes,"."Awards Evening Food Option,"."Dietary Requirements";
        $datestr = $datestr.",,,,,";

        header('Content-Type: application/excel');
        header('Content-Disposition: attachment; filename="sample.csv"');
        $data = array(
                $sessstr,
                $datestr
        );

        $fp = fopen('php://output', 'w');

        foreach ( $data as $line ) {
            $val = explode(",", $line);

            fputcsv($fp, $val);
        }
        fclose($fp);
</code>```

答:
If you're using PHPs CSV functions you should put your data in arrays:</p>

```<code>$datestr =['First Name','Last Name','Company','Type','Email','Attendance Status','Invited By','Payroll      No','Pharmacy No','Pharmacy Name','RM','RSM','Accomodation Friday','Accomodation Saturday','Job_Title','Business Partner Session',"Awards Evening","North & Central L1","North & Central L2","South East L1","South East & Warehouse L2","South West, London & Support Office L1","South West, London and Support Office L2"];

$sessstr = ["First Name","Last Name","Company","Type","Email","Attendance Status","Invited By","Payroll No","Pharmacy No","Pharmacy Name","RM","RSM","Accomodation Friday","Accomodation Saturday","Job_Title" ];
$datestr = ["Jaikishan", "Keswani","Day Lewis","jaikishan.keswani@daylewisplc.co.uk","Yes","Colin","","","1","","","","Yes","Yes","PHP Developer"];
 foreach($sessions as $k=>$ses){
        $sessstr[] = $ses['session_name'];
        $datestr[] = 'Yes';
    }
    //$datestr = substr($datestr,0,-1);
    //$sessstr = substr($sessstr,0,-1);

    $sessstr = array_merge($sessstr,["European Welcome Dinner","Accommodation By Invitation Letter","Notes","Awards Evening Food Option","Dietary Requirements" ];
    $datestr = array_merge($datestr,[ "","","","","","" ]);

    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="sample.csv"');
    $data = array(
            $sessstr,
            $datestr
    );

    $fp = fopen('php://output', 'w');

    foreach ( $data as $line ) {
        fputcsv($fp, $val);
    }
    fclose($fp);
</code>```

Title: Is way to upload header comma in csv?

Body:
Hello Friend i have text array with comma selerated with double coutes but when i push record in csv that comma seperated value convert into two header can you please help me to solved this issue .

please find bellow string.
for example : i need "South West, London & Support Office L1" in one colume

$datestr ='First Name,Last Name,Company,Type,Email,Attendance Status,Invited By,Payroll      No,Pharmacy No,Pharmacy Name,RM,RSM,Accomodation Friday,Accomodation Saturday,Job_Title,"Business Partner Session","Awards Evening","North & Central L1","North & Central L2","South East L1","South East & Warehouse L2","South West, London & Support Office L1","South West, London and Support Office L2';

$sessstr = "First Name,"."Last Name,"."Company,"."Type,"."Email,"."Attendance Status,"."Invited By,"."Payroll No,"."Pharmacy No,"."Pharmacy Name,"."RM,"."RSM,"."Accomodation Friday,"."Accomodation Saturday,"."Job_Title,";
        $datestr = "Jaikishan, Keswani,Day Lewis,jaikishan.keswani@daylewisplc.co.uk,Yes,Colin,,,1,,,,Yes,Yes,PHP Developer,";
        foreach($sessions as $k=>$ses){
            $sessstr .= '"'.$ses['session_name'].'",';
            $datestr .= 'Yes,';
        }
        $datestr = substr($datestr,0,-1);
        $sessstr = substr($sessstr,0,-1);

        $sessstr = $sessstr.",European Welcome Dinner,"."Accommodation By Invitation Letter,"."Notes,"."Awards Evening Food Option,"."Dietary Requirements";
        $datestr = $datestr.",,,,,";

        header('Content-Type: application/excel');
        header('Content-Disposition: attachment; filename="sample.csv"');
        $data = array(
                $sessstr,
                $datestr
        );

        $fp = fopen('php://output', 'w');

        foreach ( $data as $line ) {
            $val = explode(",", $line);

            fputcsv($fp, $val);
        }
        fclose($fp);

Body:
If you're using PHPs CSV functions you should put your data in arrays:

$datestr =['First Name','Last Name','Company','Type','Email','Attendance Status','Invited By','Payroll      No','Pharmacy No','Pharmacy Name','RM','RSM','Accomodation Friday','Accomodation Saturday','Job_Title','Business Partner Session',"Awards Evening","North & Central L1","North & Central L2","South East L1","South East & Warehouse L2","South West, London & Support Office L1","South West, London and Support Office L2"];

$sessstr = ["First Name","Last Name","Company","Type","Email","Attendance Status","Invited By","Payroll No","Pharmacy No","Pharmacy Name","RM","RSM","Accomodation Friday","Accomodation Saturday","Job_Title" ];
$datestr = ["Jaikishan", "Keswani","Day Lewis","jaikishan.keswani@daylewisplc.co.uk","Yes","Colin","","","1","","","","Yes","Yes","PHP Developer"];
 foreach($sessions as $k=>$ses){
        $sessstr[] = $ses['session_name'];
        $datestr[] = 'Yes';
    }
    //$datestr = substr($datestr,0,-1);
    //$sessstr = substr($sessstr,0,-1);

    $sessstr = array_merge($sessstr,["European Welcome Dinner","Accommodation By Invitation Letter","Notes","Awards Evening Food Option","Dietary Requirements" ];
    $datestr = array_merge($datestr,[ "","","","","","" ]);

    header('Content-Type: application/excel');
    header('Content-Disposition: attachment; filename="sample.csv"');
    $data = array(
            $sessstr,
            $datestr
    );

    $fp = fopen('php://output', 'w');

    foreach ( $data as $line ) {
        fputcsv($fp, $val);
    }
    fclose($fp);


问:
tensorflow.python.framework.errors_impl.InvalidArgumentError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool'
I am trying to implement a neural network used for image classification with Keras and Tensorflow, according to the tutorial from here.

I added the following code:

```<code>from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 150, 150)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
</code>```

However, the problem is that I am getting:

```<code>Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py", line 671, in _call_cpp_shape_fn_impl
16.4s
3
    input_tensors_as_shapes, status)
  File "/opt/conda/lib/python3.6/contextlib.py", line 89, in __exit__
    next(self.gen)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,1,148,32].

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "../src/script.py", line 49, in <module>
    model.add(MaxPooling2D(pool_size=(2, 2)))
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/models.py", line 469, in add
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/engine/topology.py", line 596, in __call__
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/layers/pooling.py", line 154, in call
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/layers/pooling.py", line 217, in _pooling_function
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/backend/tensorflow_backend.py", line 3378, in pool2d
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py", line 1769, in max_pool
16.4s
4
    name=name)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/gen_nn_ops.py", line 1605, in _max_pool
    data_format=data_format, name=name)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2508, in create_op
    set_shapes_for_outputs(ret)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1873, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1823, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py", line 610, in call_cpp_shape_fn
    debug_python_shape_fn, require_shape_fn)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py", line 676, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,1,148,32].
</code>```

After that, I looked at a possible answer and I changed the last line to this:

```<code>model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="tf"))
</code>```

But after this change I getting the same error.

Any idea what could be wrong?

答:
The code you provided was written with assuming that your backend is Theano. In case of Tensorflow you should change your input to have shape (width, height, channels) so you should change this line:

```<code>model.add(Conv2D(32, (3, 3), input_shape=(150, 150, 3)))
</code>```

Your problem comes from that after the convolution (with valid padding) your output has shape(1, 148, 32) so it's impossible to apply MaxPooling2D with stride (2, 2) which is a default value.

Body:
I am trying to implement a neural network used for image classification with Keras and Tensorflow, according to the tutorial from here.

I added the following code:

from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense

model = Sequential()
model.add(Conv2D(32, (3, 3), input_shape=(3, 150, 150)))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))

However, the problem is that I am getting:

Traceback (most recent call last):
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py", line 671, in _call_cpp_shape_fn_impl
16.4s
3
    input_tensors_as_shapes, status)
  File "/opt/conda/lib/python3.6/contextlib.py", line 89, in __exit__
    next(self.gen)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 466, in raise_exception_on_not_ok_status
    pywrap_tensorflow.TF_GetCode(status))
tensorflow.python.framework.errors_impl.InvalidArgumentError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,1,148,32].

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "../src/script.py", line 49, in <module>
    model.add(MaxPooling2D(pool_size=(2, 2)))
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/models.py", line 469, in add
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/engine/topology.py", line 596, in __call__
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/layers/pooling.py", line 154, in call
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/layers/pooling.py", line 217, in _pooling_function
  File "/opt/conda/lib/python3.6/site-packages/Keras-2.0.5-py3.6.egg/keras/backend/tensorflow_backend.py", line 3378, in pool2d
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/nn_ops.py", line 1769, in max_pool
16.4s
4
    name=name)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/ops/gen_nn_ops.py", line 1605, in _max_pool
    data_format=data_format, name=name)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/op_def_library.py", line 767, in apply_op
    op_def=op_def)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 2508, in create_op
    set_shapes_for_outputs(ret)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1873, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/ops.py", line 1823, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py", line 610, in call_cpp_shape_fn
    debug_python_shape_fn, require_shape_fn)
  File "/opt/conda/lib/python3.6/site-packages/tensorflow/python/framework/common_shapes.py", line 676, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Negative dimension size caused by subtracting 2 from 1 for 'max_pooling2d_1/MaxPool' (op: 'MaxPool') with input shapes: [?,1,148,32].

After that, I looked at a possible answer and I changed the last line to this:

model.add(MaxPooling2D(pool_size=(2, 2), dim_ordering="tf"))

But after this change I getting the same error.

Any idea what could be wrong?

Body:
The code you provided was written with assuming that your backend is Theano. In case of Tensorflow you should change your input to have shape (width, height, channels) so you should change this line:

model.add(Conv2D(32, (3, 3), input_shape=(150, 150, 3)))

Your problem comes from that after the convolution (with valid padding) your output has shape(1, 148, 32) so it's impossible to apply MaxPooling2D with stride (2, 2) which is a default value.