问:
Angular 4 - using if else in template error
I am displaying posts with their comments, and for posts with no comments I would like to display a message that there are no comments for that post, so I have tried to set it up like this:

```<code><li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.Summary }}
      <ul *ngIf="currentPost == post && commentsVisible">
        <li *ngIf="currentPost.comments.length > 0;else message" *ngFor="let comment of currentPost.comments" class="comment">
            <p>{{ comment.Name }}</p>
            <p>{{ comment.TemplateName }}</p>
            <p>{{ comment.CreatedByUserName }}</p>
            <p>{{ comment.Preview }}</p>
        </li>
        <ng-template #message>No comments for {{ post.Title }}</ng-template>
      </ul>
  </li>
</code>```

I get an error:

```<code>Unhandled Promise rejection: Template parse errors:
Can't have multiple template bindings on one element. Use only one attribute named 'template'
</code>```

答:
I believe it is complaining about this line.

 0;else message" *ngFor="let comment of currentPost.comments" class="comment">

You can't have *ngIf and *ngFor on the same element.

This should work:

```<code><li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.Summary }}
        <ul *ngIf="currentPost == post && commentsVisible">
          <ng-container *ngIf="currentPost.comments.length > 0;else message">
            <li *ngFor="let comment of currentPost.comments" class="comment">
                <p>{{ comment.Name }}</p>
                <p>{{ comment.TemplateName }}</p>
                <p>{{ comment.CreatedByUserName }}</p>
                <p>{{ comment.Preview }}</p>
            </li>
         </ng-container>
        <ng-template #message><li>No comments for {{ post.Title }}</li></ng-template>
      </ul>
  </li>
</code>```

More info about why this error occurs:  (Joy Clay's comment)

Just to add a little more context - all structural directives (i.e.
  the ones that begin with a *) compile down to template attributes,
  which both explains why you can't have multiple, and why the error
  message is what it is.

https://angular.io/docs/ts/latest/guide/structural-directives.html#!#asterisk

Body:
I am displaying posts with their comments, and for posts with no comments I would like to display a message that there are no comments for that post, so I have tried to set it up like this:

      {{ post.Summary }}

 0;else message" *ngFor="let comment of currentPost.comments" class="comment">

{{ comment.Name }}

{{ comment.TemplateName }}

{{ comment.CreatedByUserName }}

{{ comment.Preview }}

        <ng-template #message>No comments for {{ post.Title }}</ng-template>

I get an error:

Unhandled Promise rejection: Template parse errors:
Can't have multiple template bindings on one element. Use only one attribute named 'template'

Body:
I believe it is complaining about this line.

<li *ngIf="currentPost.comments.length > 0;else message" *ngFor="let comment of currentPost.comments" class="comment">

You can't have *ngIf and *ngFor on the same element.

This should work:

<li *ngFor="let post of posts" (click)="select(post)" >
      {{ post.Summary }}
        <ul *ngIf="currentPost == post && commentsVisible">
          <ng-container *ngIf="currentPost.comments.length > 0;else message">
            <li *ngFor="let comment of currentPost.comments" class="comment">
                <p>{{ comment.Name }}</p>
                <p>{{ comment.TemplateName }}</p>
                <p>{{ comment.CreatedByUserName }}</p>
                <p>{{ comment.Preview }}</p>
            </li>
         </ng-container>
        <ng-template #message><li>No comments for {{ post.Title }}</li></ng-template>
      </ul>
  </li>

More info about why this error occurs:  (Joy Clay's comment)

Just to add a little more context - all structural directives (i.e.
  the ones that begin with a *) compile down to template attributes,
  which both explains why you can't have multiple, and why the error
  message is what it is.

https://angular.io/docs/ts/latest/guide/structural-directives.html#!#asterisk


来源: stackexchange

问:
How OrderBy afterwards HasMany and BelongsTo Relationships
I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

```<code>Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();
</code>```

Here is a screenshot of my json:

How do I order content for review table IDs?

答: You can try with a raw query or you can use ->orderBy() directly on review function.

ContentLicense: CC BY-SA 3.0

Body:
I created a relationship between the "Review, Games and Info" tables, unfortunately, though, the main table is Games, and he orders me all for Games, While I would like to order the ID of "review" table.

Models: Review
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id_gioco', 'id');
    }
Models: Giochi
    public function review()
    {
            return $this->belongsTo('App\Models\Review', 'id', 'id_gioco');
    }
    public function infogiochi()
    {
            return $this->belongsTo('App\Models\InfoGiochi', 'id', 'id_gioco');
    }
Models: InfoGiochi
    public function games()
    {
        return $this->hasMany('App\Models\Giochi', 'id', 'id_gioco');
    }
Controller:
$review = Giochi::with('Review','InfoGiochi')->orderBy('id','DESC')->get();

Here is a screenshot of my json:

How do I order content for review table IDs?


问:
What is the Type This struct is Inheriting From?
So this example from: http://en.cppreference.com/w/cpp/utility/variant/visit declares the specialized type:

```<code>template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
</code>```

Which is constructed as an r-value here:

```<code>std::visit(overloaded {
    [](auto arg) { std::cout << arg << ' '; },
    [](double arg) { std::cout << std::fixed << arg << ' '; },
    [](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}, v);
</code>```

I'm trying to figure out how this works. What is the type that overloaded inherits from here? It seems like an array of lambdas but I don't see how that would have an operator(). Can someone explain how the inheritance is working here?

答:
overloaded inherits from each lambda individually and each lambda has a call operator. You therefore create a struct that has all call operators in one overload set. As long as they are not ambiguous the right one will automatically be picked.

You can imagine the variadic template to expand to

```<code>struct overloaded :
    // inherits from
    decltype([](auto arg) { std::cout << arg << ' '; }),
    decltype([](double arg) { std::cout << std::fixed << arg << ' '; }),
    decltype([](const std::string& arg) { std::cout << std::quoted(arg) << ' '; })

    // has three operator()s
    {
        using decltype([](auto arg) { std::cout << arg << ' '; })::operator();
        using decltype([](double arg) { std::cout << std::fixed << arg << ' '; })::operator();
        using decltype([](const std::string& arg) { std::cout << std::quoted(arg) << ' '; })::operator();
    };
</code>```

Except in real code it wouldn't work because the lambdas with the same body would still have different types.

It creates 1 overloaded type with multiple inheritance per instantiation.

Body:
So this example from: http://en.cppreference.com/w/cpp/utility/variant/visit declares the specialized type:

template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;

Which is constructed as an r-value here:

std::visit(overloaded {
    [](auto arg) { std::cout << arg << ' '; },
    [](double arg) { std::cout << std::fixed << arg << ' '; },
    [](const std::string& arg) { std::cout << std::quoted(arg) << ' '; },
}, v);

I'm trying to figure out how this works. What is the type that overloaded inherits from here? It seems like an array of lambdas but I don't see how that would have an operator(). Can someone explain how the inheritance is working here?

Body:
overloaded inherits from each lambda individually and each lambda has a call operator. You therefore create a struct that has all call operators in one overload set. As long as they are not ambiguous the right one will automatically be picked.

You can imagine the variadic template to expand to

struct overloaded :
    // inherits from
    decltype([](auto arg) { std::cout << arg << ' '; }),
    decltype([](double arg) { std::cout << std::fixed << arg << ' '; }),
    decltype([](const std::string& arg) { std::cout << std::quoted(arg) << ' '; })

    // has three operator()s
    {
        using decltype([](auto arg) { std::cout << arg << ' '; })::operator();
        using decltype([](double arg) { std::cout << std::fixed << arg << ' '; })::operator();
        using decltype([](const std::string& arg) { std::cout << std::quoted(arg) << ' '; })::operator();
    };

Except in real code it wouldn't work because the lambdas with the same body would still have different types.

It creates 1 overloaded type with multiple inheritance per instantiation.


问:
I need to add a DataGridView to the form dynamically
```<code>private void btnShowCausali_Click(object sender, EventArgs e)
{
    DataGridView Dati = new DataGridView();
    Dati.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
    Dati.Location = new System.Drawing.Point(120, 40);
    Dati.Name = "Dati";
    Dati.RowTemplate.Height = 24;
    Dati.Size = new System.Drawing.Size(979, 458);
    Dati.TabIndex = 1;
    Dati.Visible = true;
    Dati.Columns.Add("id", "ID");
    Dati.Columns.Add("causaliname", "Nome Causale");
    Dati.Columns.Add("Identificationcode", "Codice Identificativo");
    Dati.Columns.Add("expired", "Data di Scadenza");
    grpDatore.Controls.Add(Dati);
}
</code>```

When I run this code the DataGridView does not appear on the form. Just in case it could create problem, the button btnShowCausali get created on the form load.

```<code>public void Form1_Load(object sender, EventArgs e)
{
    Button btnShowCausali = new Button();
    btnShowCausali.Text = "Causali";
    btnShowCausali.Location = new Point(20, 20);
    btnShowCausali.Size = new Size(120, 40);
}
</code>```

By the way, I don't know why the button actually gets created but the DataGridView does not.

答:
First of all, if the button is created dynamically, add it to the UI.

```<code>Button btnShowCausali = new Button();
btnShowCausali.Text = "Causali";
btnShowCausali.Location = new Point(20, 20); // Make shure there aren't other controls in this point
btnShowCausali.Size = new Size(120, 40);
this.Controls.Add(btnShowCausali); //Adding the button to the form
</code>```

Then, you have to attach an event handler for the Click event of the button. In short, you have to tell to the button what to do when it is clicked. You have two options to add an event handler for the click event:

Code: add btnShowCausali.Click += btnShowCausali_Click; after the InitializeComponent function call (in the constructor) or in the Load event of the form. Then add the function btnShowCausali_Click:

```<code>private void btnShowCausali_Click(object sender, EventArgs e)
{
     DataGridView Dati = new DataGridView();
    Dati.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
    Dati.Location = new System.Drawing.Point(120, 40);
    Dati.Name = "Dati";
    Dati.RowTemplate.Height = 24;
    Dati.Size = new System.Drawing.Size(979, 458);
    Dati.TabIndex = 1;
    Dati.Visible = true;
    Dati.Columns.Add("id", "ID");
    Dati.Columns.Add("causaliname", "Nome Causale");
    Dati.Columns.Add("Identificationcode", "Codice Identificativo");
    Dati.Columns.Add("expired", "Data di Scadenza");
    grpDatore.Controls.Add(Dati); // DataGridView added to grpDatore, not form. Make shure grpDatore is visible.
}
</code>```

Designer: double click on the button. Visual Studio will do the magic for you.

Body:
private void btnShowCausali_Click(object sender, EventArgs e)
{
    DataGridView Dati = new DataGridView();
    Dati.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
    Dati.Location = new System.Drawing.Point(120, 40);
    Dati.Name = "Dati";
    Dati.RowTemplate.Height = 24;
    Dati.Size = new System.Drawing.Size(979, 458);
    Dati.TabIndex = 1;
    Dati.Visible = true;
    Dati.Columns.Add("id", "ID");
    Dati.Columns.Add("causaliname", "Nome Causale");
    Dati.Columns.Add("Identificationcode", "Codice Identificativo");
    Dati.Columns.Add("expired", "Data di Scadenza");
    grpDatore.Controls.Add(Dati);
}

When I run this code the DataGridView does not appear on the form. Just in case it could create problem, the button btnShowCausali get created on the form load.

public void Form1_Load(object sender, EventArgs e)
{
    Button btnShowCausali = new Button();
    btnShowCausali.Text = "Causali";
    btnShowCausali.Location = new Point(20, 20);
    btnShowCausali.Size = new Size(120, 40);
}

By the way, I don't know why the button actually gets created but the DataGridView does not.

Body:
First of all, if the button is created dynamically, add it to the UI.

Button btnShowCausali = new Button();
btnShowCausali.Text = "Causali";
btnShowCausali.Location = new Point(20, 20); // Make shure there aren't other controls in this point
btnShowCausali.Size = new Size(120, 40);
this.Controls.Add(btnShowCausali); //Adding the button to the form

Then, you have to attach an event handler for the Click event of the button. In short, you have to tell to the button what to do when it is clicked. You have two options to add an event handler for the click event:

Code: add btnShowCausali.Click += btnShowCausali_Click; after the InitializeComponent function call (in the constructor) or in the Load event of the form. Then add the function btnShowCausali_Click:

private void btnShowCausali_Click(object sender, EventArgs e)
{
     DataGridView Dati = new DataGridView();
    Dati.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
    Dati.Location = new System.Drawing.Point(120, 40);
    Dati.Name = "Dati";
    Dati.RowTemplate.Height = 24;
    Dati.Size = new System.Drawing.Size(979, 458);
    Dati.TabIndex = 1;
    Dati.Visible = true;
    Dati.Columns.Add("id", "ID");
    Dati.Columns.Add("causaliname", "Nome Causale");
    Dati.Columns.Add("Identificationcode", "Codice Identificativo");
    Dati.Columns.Add("expired", "Data di Scadenza");
    grpDatore.Controls.Add(Dati); // DataGridView added to grpDatore, not form. Make shure grpDatore is visible.
}

Designer: double click on the button. Visual Studio will do the magic for you.


问:
Inserting Select from HTML to mysql
so i have this table in my html

```<code><form method = "POST" action="admin_event.php">
<table class = "table" id="dynamic_admin_add_price">
                                                        <thead>
                                                        <th>Deadline </th>
                                                        <th>Register Date</th>
                                                        <th>Price</th>
                                                        <th></th>
                                                        <th></th>
                                                        </thead>

                                                        <tbody>
                                                        <tr>
                                                            <td>
                                                                <select name="admin_add_deadline[]" class="form-control">
                                                                    <option value="early_bird">Early Bird</option>
                                                                    <option value="middle">Middle</option>
                                                                    <option value="normal">Normal</option>
                                                                </select>
                                                            </td>
                                                            <td><input type="text" name="admin_add_register_date[]" class="form-control registerDate" required></td>
                                                            <td><label>Rp.</label></td>
                                                            <td><input type="number" name="admin_add_price[]" class="form-control" value=""  required></td>
                                                            <td><button type="submit" name="button_add_price" id="price" class="btn btn-success">Add more deadlines</button></td>
                                                            <!--<td><button type="button" name=button_remove_event_time id="remove_event-time" class="btn btn-danger" disabled>Remove</button></td>-->
                                                        </tr>
                                                        </tbody>
                                                    </table>

 <button type="submit" class="btn btn-primary" name="admin_add_event_datas">Save</button>
</form>
</code>```

And i have created the javascript so that the user can add as many rows as they want

```<code>    $('#add_price').click(function(){
    j++;
    $('#dynamic_admin_add_price').append(
        '<tr id="row2'+j+'">' +
        '<td><select name="admin_add_deadline[]" class="form-control"><option value="early_bird">Early Bird</option><option value="middle">Middle</option><option value="normal">Normal</option></select></td>'+
        '<td><input type="text" name="admin_add_register_date[]" class="form-control registerDate" required></td>' +
        '<td><label>Rp.</label></td>' +
        '<td><input type="number" name="admin_add_price[]" class="form-control" value="" required></td>' +
        '<td><button type="submit" name="button_remove_event_time" id="'+j+'" class="btn btn-danger btn_remove2" required>Remove</button></td>' +
        '</tr>');
});

$(document).on('click', '.btn_remove2', function(){
    var button_id = $(this).attr("id");
    $('#row2'+button_id+'').remove();
});
</code>```

The adding rows work fine and the rest of the data can be inputted into the mysql, EXCEPT for the select fields,where it returns incorrectly and doesn't get any input at all from the non-static rows.

What i want to do is that if the user chose early bird, it gave the number 1 in the php, 2 for the middle option, and 3 for the normal ones, as it matches the id_deadline in another table that is used as the foreign key in the table i want to insert the data to. This is the snippet of the php script(i only put the one for the deadline):

```<code>if(isset($_POST['admin_add_deadline'])){
$deadline = $_POST['admin_add_deadline'];

$one = 1;
$two = 2;
$three = 3;
if($deadline == 'early_bird'){

        $deadline = $one;
}

if($deadline == 'middle'){
        $deadline = $two;
}

else{
$deadline = $three
}

}
</code>```

and this is the foreach to insert the data

```<code>    foreach ($register_date as $key => $value) {

    $post_register_date = $db->real_escape_string($value);

    $post_insert_price = $db->real_escape_string($register_price[$key]);

    $post_deadline = $deadline[$key];

    $query = "INSERT INTO register_time(id_event, id_deadline, register_date, price, created_at, status)
                          VALUES('$row_id_event','$post_deadline', '$post_register_date', '$post_insert_price', '$time', '$status')";

    if(mysqli_query($db, $query)){
        $succ = "New record created successfully";
    }

    else{
        echo "Error: " . $query . "<br>" . mysqli_error($db);
    }

}
</code>```

Again, the problem is that if i have 3 rows generated and i clicked the submit button, the inserted value for the id_deadline column in the table will always be 3 for the first row, and the other 2 rows will return an error as the value is '' for the id_deadline in the insert query

Can you guys help me with this problem?Thank you, i hope my question is clear enough.

EDIT: Fixing the typos

答:
You have many errors in your code

Missing a double quotation mark in HTML action

```<code><form method = "POST" action="admin_event.php">
</code>```

In your HTML

```<code>$('#add_price').click(function(){
</code>```

doesn't exist in HTML, change for this:

```<code> <td><a  id="add_price" id="price" class="btn btn-success">Add more deadlines</a></td>
</code>```

In your jQuery, define var j:

```<code>var j = 0;
</code>```

In your PHP put this in to view the data:

```<code>if(isset($_POST)){
    echo "```";
    var_dump($_POST);
    die;
}
```

<p>My code works:<br>
<img src="https://i.stack.imgur.com/fABwD.png" alt="form"></p>

```array(4) {
  ["admin_add_deadline"]=>
  array(4) {
    [0]=>
    string(10) "early_bird"
    [1]=>
    string(6) "middle"
    [2]=>
    string(6) "normal"
    [3]=>
    string(6) "middle"
  }
  ["admin_add_register_date"]=>
  array(4) {
    [0]=>
    string(3) "one"
    [1]=>
    string(3) "two"
    [2]=>
    string(5) "three"
    [3]=>
    string(4) "four"
  }
  ["admin_add_price"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
    [3]=>
    string(1) "4"
  }
  ["admin_add_event_datas"]=>
  string(0) ""
}
```

Title: Inserting Select from HTML to mysql

Body:
so i have this table in my html

<form method = "POST" action="admin_event.php">

                                                        Deadline
                                                        Register Date
                                                        Price

                                                                <select name="admin_add_deadline[]" class="form-control">
                                                                    <option value="early_bird">Early Bird</option>
                                                                    <option value="middle">Middle</option>
                                                                    <option value="normal">Normal</option>
                                                                </select>

                                                            <input type="text" name="admin_add_register_date[]" class="form-control registerDate" required>
                                                            Rp.
                                                            <input type="number" name="admin_add_price[]" class="form-control" value=""  required>
                                                            <button type="submit" name="button_add_price" id="price" class="btn btn-success">Add more deadlines</button>

 <button type="submit" class="btn btn-primary" name="admin_add_event_datas">Save</button>
</form>

And i have created the javascript so that the user can add as many rows as they want

    $('#add_price').click(function(){
    j++;
    $('#dynamic_admin_add_price').append(
        '
' +
        '<select name="admin_add_deadline[]" class="form-control"><option value="early_bird">Early Bird</option><option value="middle">Middle</option><option value="normal">Normal</option></select>	'+
        '<input type="text" name="admin_add_register_date[]" class="form-control registerDate" required>	' +
        'Rp.	' +
        '<input type="number" name="admin_add_price[]" class="form-control" value="" required>	' +
        '<button type="submit" name="button_remove_event_time" id="'+j+'" class="btn btn-danger btn_remove2" required>Remove</button>	' +
        '
');
});

$(document).on('click', '.btn_remove2', function(){
    var button_id = $(this).attr("id");
    $('#row2'+button_id+'').remove();
});

The adding rows work fine and the rest of the data can be inputted into the mysql, EXCEPT for the select fields,where it returns incorrectly and doesn't get any input at all from the non-static rows.

What i want to do is that if the user chose early bird, it gave the number 1 in the php, 2 for the middle option, and 3 for the normal ones, as it matches the id_deadline in another table that is used as the foreign key in the table i want to insert the data to. This is the snippet of the php script(i only put the one for the deadline):

if(isset($_POST['admin_add_deadline'])){
$deadline = $_POST['admin_add_deadline'];

$one = 1;
$two = 2;
$three = 3;
if($deadline == 'early_bird'){

        $deadline = $one;
}

if($deadline == 'middle'){
        $deadline = $two;
}

else{
$deadline = $three
}

}

and this is the foreach to insert the data

    foreach ($register_date as $key => $value) {

    $post_register_date = $db->real_escape_string($value);

    $post_insert_price = $db->real_escape_string($register_price[$key]);

    $post_deadline = $deadline[$key];

    $query = "INSERT INTO register_time(id_event, id_deadline, register_date, price, created_at, status)
                          VALUES('$row_id_event','$post_deadline', '$post_register_date', '$post_insert_price', '$time', '$status')";

    if(mysqli_query($db, $query)){
        $succ = "New record created successfully";
    }

    else{
        echo "Error: " . $query . "
" . mysqli_error($db);
    }

}

Again, the problem is that if i have 3 rows generated and i clicked the submit button, the inserted value for the id_deadline column in the table will always be 3 for the first row, and the other 2 rows will return an error as the value is '' for the id_deadline in the insert query

Can you guys help me with this problem?Thank you, i hope my question is clear enough.

EDIT: Fixing the typos

Body:
You have many errors in your code

Missing a double quotation mark in HTML action

<form method = "POST" action="admin_event.php">

In your HTML

$('#add_price').click(function(){

doesn't exist in HTML, change for this:

 <td><a  id="add_price" id="price" class="btn btn-success">Add more deadlines</a></td>

In your jQuery, define var j:

var j = 0;

In your PHP put this in to view the data:

if(isset($_POST)){
    echo "<pre>";
    var_dump($_POST);
    die;
}

My code works:

array(4) {
  ["admin_add_deadline"]=>
  array(4) {
    [0]=>
    string(10) "early_bird"
    [1]=>
    string(6) "middle"
    [2]=>
    string(6) "normal"
    [3]=>
    string(6) "middle"
  }
  ["admin_add_register_date"]=>
  array(4) {
    [0]=>
    string(3) "one"
    [1]=>
    string(3) "two"
    [2]=>
    string(5) "three"
    [3]=>
    string(4) "four"
  }
  ["admin_add_price"]=>
  array(4) {
    [0]=>
    string(1) "1"
    [1]=>
    string(1) "2"
    [2]=>
    string(1) "3"
    [3]=>
    string(1) "4"
  }
  ["admin_add_event_datas"]=>
  string(0) ""
}


问:
Appended href Attribute not Working - Javascript
I'm setting up an alert that will slide in at the top of a page.  In the code the href attribute doesn't seem to be adding the web address. I'm not getting any errors in my console, but can't seem to find out what is causing this.  When you click on the 'Go to Google' button I've set up as a test, it should take you to Google, but it doesn't?  The code and Codepen are below, any help would be amazing.

Codepen is here: https://codepen.io/emilychews/pen/ZyGrrR

HTML

```<code><div id="header">Original Header</div>
</code>```

CSS

```<code>   * {font-family: arial;
 line-height: 100px;}

#header {width: 100%;
height: 100px;
background: red;
color: white;
text-align: center;}

div#newBar {
  width: 100%;
  height: 50px;
  background-color: blue;
  line-height: 50px;
  text-align: center;
  color: white;
}

div#topbar_button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 11%;
  height: 54%;
  background: white;
  position: relative;
  bottom: 41PX;
  margin-left: 75%;
  color: blue;
  border-radius: 2px;
}
</code>```

JAVASCRIPT

```<code>// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };
</code>```

答:
In addition to what other said, you also needed to add "https://" to the URL, at least in CodePen.
Corrected JavaScript

```<code>// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'https://www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    anchorTag.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };
</code>```

In the CSS, you could add #topbar_button a { text-decoration: none } to get rid of the underline.

Body:
I'm setting up an alert that will slide in at the top of a page.  In the code the href attribute doesn't seem to be adding the web address. I'm not getting any errors in my console, but can't seem to find out what is causing this.  When you click on the 'Go to Google' button I've set up as a test, it should take you to Google, but it doesn't?  The code and Codepen are below, any help would be amazing.

Codepen is here: https://codepen.io/emilychews/pen/ZyGrrR

HTML

Original Header

CSS

   * {font-family: arial;
 line-height: 100px;}

#header {width: 100%;
height: 100px;
background: red;
color: white;
text-align: center;}

div#newBar {
  width: 100%;
  height: 50px;
  background-color: blue;
  line-height: 50px;
  text-align: center;
  color: white;
}

div#topbar_button {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 11%;
  height: 54%;
  background: white;
  position: relative;
  bottom: 41PX;
  margin-left: 75%;
  color: blue;
  border-radius: 2px;
}

JAVASCRIPT

// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    topBarButton.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };

Body:
In addition to what other said, you also needed to add "https://" to the URL, at least in CodePen.
Corrected JavaScript

// window.onload = function() {

var header = document.getElementById('header');

var newBar = document.createElement('div');
newBar.id = "newBar";

var newBarText = document.createTextNode("Click on the link to go to Google");
newBar.appendChild(newBarText);

// create button and anchor tag and append
var topBarButton = document.createElement('div');
    topBarButton.id = "topbar_button";
var anchorTag = document.createElement('a');
    anchorTag.setAttribute('href', 'https://www.google.co.uk');
    topBarButton.appendChild(anchorTag);
    anchorTag.innerHTML = "Visit Google";

newBar.appendChild(topBarButton);

// append new top bar to header
var header = document.getElementById('header');
header.parentNode.insertBefore(newBar, header);

// };

In the CSS, you could add #topbar_button a { text-decoration: none } to get rid of the underline.


问:
Associative array: how to get the key of the current element which is an array
I have an array

```<code>Array (
      [0] => Array ( [2006] => Array ( [0] => 12 ) )
      [1] => Array ( [2004] => Array ( [0] => 12 [1] => 6 ) )
)
</code>```

How do I get the year so I can generate the folllowing using unordered list

```<code>2006
    December
2004
    December
    June
</code>```

答:
Pretty sure that you can use

```<code>foreach($key, $value in $array) {
}
</code>```

Or something fairly similar. It's been a while since I've used PHP.

Body:
I have an array

Array (
      [0] => Array ( [2006] => Array ( [0] => 12 ) )
      [1] => Array ( [2004] => Array ( [0] => 12 [1] => 6 ) )
)

How do I get the year so I can generate the folllowing using unordered list

2006
    December
2004
    December
    June

Body:
Pretty sure that you can use

foreach($key, $value in $array) {
}

Or something fairly similar. It's been a while since I've used PHP.

ContentLicense: CC BY-SA 2.5


问:
Asp Date to Javascript Function
Why is my date, when passed to the javascript function performing math operations on the values??

HTML:

```<code><td><button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button></td>
</code>```

where Session("ECN") = '1111' and datStart3 = "6/02/2017"

Whenever I click this button, I my ajax request is for:

```<code>http://*****/apqp/updateDate.asp?ECN=1111&Date=0.001487357461576599
</code>```

I want date to = "6/02/2017" (I have also tried replacing the '/' with '-' or 'a' with no luck)

The Javascript function:

```<code>function ChangeDate(strECN, strDate)
{
    // Get an xmlHTTPRequest object.  Jump out with an error if the object can't be created.
    xmlHTTP = getXMLHTTPObject();
    if(xmlHTTP == null){
        alert("Your browser does not support AJAX!");
        return;
    }

    strURL = './updateDate.asp?ECN=' + strECN + '&Date=' + strDate;

    // Setup the xmlHTTP object, open it & send the request.
    xmlHTTP.open("GET", strURL, false);
    xmlHTTP.send(null);

    // Display the line items.
    window.location.reload();
}
</code>```

答:
Wow, Im an idiot.

Just realized that I was passing it in as a Integer.

Putting '' around datStart3 in the HTML portion of :

```<code><td><button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button></td>
</code>```

fixes it.

Title: Asp Date to Javascript Function

Body:
Why is my date, when passed to the javascript function performing math operations on the values??

HTML:

<button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button>

where Session("ECN") = '1111' and datStart3 = "6/02/2017"

Whenever I click this button, I my ajax request is for:

http://*****/apqp/updateDate.asp?ECN=1111&Date=0.001487357461576599

I want date to = "6/02/2017" (I have also tried replacing the '/' with '-' or 'a' with no luck)

The Javascript function:

function ChangeDate(strECN, strDate)
{
    // Get an xmlHTTPRequest object.  Jump out with an error if the object can't be created.
    xmlHTTP = getXMLHTTPObject();
    if(xmlHTTP == null){
        alert("Your browser does not support AJAX!");
        return;
    }

    strURL = './updateDate.asp?ECN=' + strECN + '&Date=' + strDate;

    // Setup the xmlHTTP object, open it & send the request.
    xmlHTTP.open("GET", strURL, false);
    xmlHTTP.send(null);

    // Display the line items.
    window.location.reload();
}

Body:
Wow, Im an idiot.

Just realized that I was passing it in as a Integer.

Putting '' around datStart3 in the HTML portion of :

<td><button type="submit" form="frmParams" onclick="ChangeDate(<% =Session("ECN") %>, <% =datStart3 %>);" value="Submit">Click Me To Change Date</button></td>

fixes it.


问:
Angular 2 *ngFor and dynamic field
Here a little code:

```<code><div *ngFor="let field of fields">
  <div>
    <label>{{field}}</label><input name="item.field" [(ngModel)]="item.field">
  </div>
</div>
</code>```

"fields" is a list of string equals to each field of "item" object
"item" is an object with several property.

i want to generate a dynamic form using this simple *ngFor and write something like:

"item.field"

Am i doing it wrong ?

Thx you !

答:
Try using square bracket notation:</p>

```<code><div *ngFor="let field of fields">
    <div>
        <label>{{field}}</label><input name="item[field]" [(ngModel)]="item[field]">
    </div>
</div>
</code>```

Title: Angular 2 *ngFor and dynamic field

Body:
Here a little code:

    {{field}}<input name="item.field" [(ngModel)]="item.field">

"fields" is a list of string equals to each field of "item" object
"item" is an object with several property.

i want to generate a dynamic form using this simple *ngFor and write something like:

"item.field"

Am i doing it wrong ?

Thx you !

Body:
Try using square bracket notation:

<div *ngFor="let field of fields">
    <div>
        <label>{{field}}</label><input name="item[field]" [(ngModel)]="item[field]">
    </div>
</div>


问:
Print only the first page of each group
My report adds a page break and resets a custom page number whenever a group changes. How can I print only the first page of each group?</p>

答:
Crystal itself doesn't have a great way for you to programmatically print specific pages. But there are a few ways to make this kind of work:

Easy: Make a formula that generates a list of which pages are ones you want to print. (It might output something like 1,2,5,7,9, which you could copy and paste into the Page Range when you go to print.)

Medium: Make a modified version of this report that excludes any data you don't want to print. Figure out a maximum number of records that fit on a page (for example, 18) and only take the first 18 per group. (This might be easier to set up with a custom SQL statement in Crystal.)

Difficult: Same as option 2, but you write suppression formulas for everything on your report. If Page Number > 1, the entire page goes blank. After printing you just remove the blank pages from the file. Tedious, but no ink wasted...

Title: Print only the first page of each group


问:
Where to fill out SQLite if user input isn't needed? (Beginner)
I have done a lot of research about the SQLite database, and have already created a SQLite custom helper that extended SQLiteOpenHelper. However, I don't understand where to actually create the database and fill it out. I am trying to have the database be created immediately; I have all the information that needs to be inserted. In other words, no user input is required to fill it out.

Is the best practice to create an individual java class or activity that fills out the database, that can then be accessed by the activities?

Thanks - did a lot of research on creating the database and helper, just having trouble understanding this.

答:
I am trying to have the database be created immediately; I have all the information that needs to be inserted.

Create the SQLite database on your development machine. Package it in assets/ and use SQLiteAssetHelper to ship it with your app. Then, you can query from that data (e.g., to display it to the user).


问:
Using instance variables/methods within Reactive Framework subscription in Javascript
I've got an object in JS in which I'm trying to test out the Reactive Framework In an event subscription I'd like to call an instance method of the enclosing class where the subscription is defined, like this;

```<code>function MyClass()
{
    var DoSomething = function(a,b) { ... }

    var InstanceVariable = 1;

    this.uiEvent = uiDiv.jqueryUiWidget("widget")
        .toObservable("change")
        .Subscribe(
                function (event)
                {
                    // Want to call the instance method in the enclosing class
                    DoSomething(1,2);
                });

    this.uiEvent2 = uiDiv.jqueryUiWidget("widget")
        .toObservable("change")
        .Subscribe(
                function (event)
                {
                    // Want to use the instance variable within here
                    alert(InstanceVariable);
                });
}
</code>```

How can I do this (since the "this" scope is that of the subscription)? Do I have to pass the function/variable through when setting up the subscription in some way?

If I attempt to do this, I get an error in all browsers saying that the instance variables or methods don't exist: "this" within the scope of the function where I want to call the instance members refers to the Observer and so has functions of OnNext, OnCompleted etc.

Many Thanks,

Paul

答:
Seems to me like your code should work. If you are having any problems I suggest you describe them. However, if you are asking how it works, then you should know about closures. From Wikipedia:

In computer science, a closure is a first-class function with free variables that are bound in the lexical environment. Such a function is said to be "closed over" its free variables. A closure is defined within the scope of its free variables, and the extent of those variables is at least as long as the lifetime of the closure itself. The explicit use of closures is associated with functional programming and with languages such as ML and Lisp. Closures are used to implement continuation passing style, and in this manner, hide state. Constructs such as objects and control structures can thus be implemented with closures.

This means that DoSomething and InstanceVariable are accessible from any method that is defined within the scope where they are defined. There will be a new "instance" of these variables each time the MyClass constructor is called.

Body:
I've got an object in JS in which I'm trying to test out the Reactive Framework In an event subscription I'd like to call an instance method of the enclosing class where the subscription is defined, like this;

function MyClass()
{
    var DoSomething = function(a,b) { ... }

    var InstanceVariable = 1;

    this.uiEvent = uiDiv.jqueryUiWidget("widget")
        .toObservable("change")
        .Subscribe(
                function (event)
                {
                    // Want to call the instance method in the enclosing class
                    DoSomething(1,2);
                });

    this.uiEvent2 = uiDiv.jqueryUiWidget("widget")
        .toObservable("change")
        .Subscribe(
                function (event)
                {
                    // Want to use the instance variable within here
                    alert(InstanceVariable);
                });
}

How can I do this (since the "this" scope is that of the subscription)? Do I have to pass the function/variable through when setting up the subscription in some way?

If I attempt to do this, I get an error in all browsers saying that the instance variables or methods don't exist: "this" within the scope of the function where I want to call the instance members refers to the Observer and so has functions of OnNext, OnCompleted etc.

Many Thanks,

Paul


问:
get text in between text using regex
I want to extract the text in between the %3A.

Here is the sample phrase :

```<code>http://www.sample.com/res?ccode=1232&note=sampletext&token=12Add-12sre-24Aod-23343-34kdi%3A3232121%3ATVLOPQUI%3AIOOPDA%3AKKKKK%3A&ltr=23232
</code>```

I tried below expression:

```<code>[&]{1}token[=]{1}([a-zA-Z0-9-%]*)(%3A(.*?)%3A){1}
</code>```

but the expected phrase is : 3232121

whereas, it is capturing the invalid thing.

Can you please suggest me, how to do that in better way

答:
Assuming that there are no literal & inside the params, you may use the following pattern:

```<code>[&?]token=[^&%]*%3A([^%&]+)
</code>```

See the regex demo

Details:

[&?]token= - a &token= or ?token= substring

[^&%]* -  zero or more chars other than & and %

%3A - a %3A substring

([^%&]+) - Group 1 capturing 1 or more chars other than % and &.

Title: get text in between text using regex

Body:
I want to extract the text in between the %3A.

Here is the sample phrase :

http://www.sample.com/res?ccode=1232&note=sampletext&token=12Add-12sre-24Aod-23343-34kdi%3A3232121%3ATVLOPQUI%3AIOOPDA%3AKKKKK%3A&ltr=23232

I tried below expression:

[&]{1}token[=]{1}([a-zA-Z0-9-%]*)(%3A(.*?)%3A){1}

but the expected phrase is : 3232121

whereas, it is capturing the invalid thing.

Can you please suggest me, how to do that in better way

Body:
Assuming that there are no literal & inside the params, you may use the following pattern:

[&?]token=[^&%]*%3A([^%&]+)

See the regex demo

Details:

[&?]token= - a &token= or ?token= substring

[^&%]* -  zero or more chars other than & and %

%3A - a %3A substring

([^%&]+) - Group 1 capturing 1 or more chars other than % and &.


问:
Convert list into a list of 2-tuples
I have a list:

```<code>list = [1, 2, 3]
</code>```

I want to get this list and add a tuple so this list becomes like this

```<code>T_list = [(1,x), (2, x), (3,x)]
</code>```

How do I do it?

答:
A list comprehension would do the trick:

```<code>t_list = [(y,x) for y in original_list]
</code>```

Also, the commenter is right. Don't name your lists list. It's a built in function. Using it for something else could cause problems down the line.

Title: Convert list into a list of 2-tuples

Body:
I have a list:

list = [1, 2, 3]

I want to get this list and add a tuple so this list becomes like this

T_list = [(1,x), (2, x), (3,x)]

How do I do it?

Body:
A list comprehension would do the trick:

t_list = [(y,x) for y in original_list]

Also, the commenter is right. Don't name your lists list. It's a built in function. Using it for something else could cause problems down the line.


问:
text file inside class folder, yet cannot find it

As you can see, the file is right inside the same folder where the class file is. While I tried to have it print the path to it, that is a bummer because no matter what name I type it will always type a full path to that invented file name. The file is comma separated, that I copied pasted into gedit and tried all kinds of extensions, csv, txt and no extension.

What I am trying to do is import it into an array, but the error is clear, no such file or directory.

答:
You can try getting the path of the root folder from System.getProperty(). Then just append underlying folder names till the required filename.

```<code>private static String CLASS_PATH = System.getProperty("user.dir");
public static String FILE_PATH= CLASS_PATH + File.separator + "Source Packages"+ File.separator + "javaapplication2"+ File.separator + "pedidos.txt";
</code>```

Body:
You can try getting the path of the root folder from System.getProperty(). Then just append underlying folder names till the required filename.

private static String CLASS_PATH = System.getProperty("user.dir");
public static String FILE_PATH= CLASS_PATH + File.separator + "Source Packages"+ File.separator + "javaapplication2"+ File.separator + "pedidos.txt";


答:
You need to use a wrapping div, only one ng statement per element.</p>

```<code><li *ngFor="let post of posts" (click)="select(post)" >
    {{ post.Summary }}
    <ul *ngIf="currentPost == post && commentsVisible">
    <li *ngFor="let comment of currentPost.comments" class="comment">
        <span *ngIf="currentPost.comments.length > 0;else message">
            <p>{{ comment.Name }}</p>
            <p>{{ comment.TemplateName }}</p>
            <p>{{ comment.CreatedByUserName }}</p>
            <p>{{ comment.Preview }}</p>
        </span>
    </li>
    <ng-template #message>No comments for {{ post.Title }}</ng-template>
    </ul>
</li>
</code>```

Title: Angular 4 - using if else in template error

Body:
I am displaying posts with their comments, and for posts with no comments I would like to display a message that there are no comments for that post, so I have tried to set it up like this:

      {{ post.Summary }}

 0;else message" *ngFor="let comment of currentPost.comments" class="comment">

{{ comment.Name }}

{{ comment.TemplateName }}

{{ comment.CreatedByUserName }}

{{ comment.Preview }}

        <ng-template #message>No comments for {{ post.Title }}</ng-template>

I get an error:

Unhandled Promise rejection: Template parse errors:
Can't have multiple template bindings on one element. Use only one attribute named 'template'

Body:
You need to use a wrapping div, only one ng statement per element.

<li *ngFor="let post of posts" (click)="select(post)" >
    {{ post.Summary }}
    <ul *ngIf="currentPost == post && commentsVisible">
    <li *ngFor="let comment of currentPost.comments" class="comment">
        <span *ngIf="currentPost.comments.length > 0;else message">
            <p>{{ comment.Name }}</p>
            <p>{{ comment.TemplateName }}</p>
            <p>{{ comment.CreatedByUserName }}</p>
            <p>{{ comment.Preview }}</p>
        </span>
    </li>
    <ng-template #message>No comments for {{ post.Title }}</ng-template>
    </ul>
</li>


问:
Resizing yellow box on Eclipse and keeping it sized
I've been trying to resize the yellow box that appears when I press Ctrl+Shift+I over a variable or so, but every time I resize it, it comes to its actual size again.
I know it's possible to resize and keep it this size, but can't remember how. Can you guys remind me?

Thanks.

答:
I've done a good deal of development on the Eclipse platform.  When an Eclipse developer provides a popup like this they have the option of providing a menu that will let the end user (you in this case) save the size.  In this case it appears that the developer choose not to expose this menu.

Also, I searched my Eclipse preferences and there is no option to turn this on.

Someone else might be able to provide a different solution but, I think you're out of luck.

Best regards.


问:
Display camera preview on a circular surface (porthole effect)
I want to display the camera preview onto a circular surface (similar to a porthole view). I would also need the area surrounding the preview to be empty (transparent), so I believe masking would not help.

I've tried creating a drawable shape and then setting it as the background of a SurfaceView but it doesn't work.

Any ideas if it can be done and how?

答:
I achieved it by extending the surface view and override:</p>

```<code>@Override
protected void dispatchDraw(Canvas canvas) {
    clipPath = new Path();
    //TODO: define the circle you actually want
    clipPath.addCircle((float) dpToPx(100), (float) dpToPx(100), (float) dpToPx(100), Path.Direction.CW);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

    canvas.clipPath(clipPath);
    canvas.drawPath(clipPath, paint);
   this.setZOrderOnTop(true);
    super.dispatchDraw(canvas);
}
</code>```

Body:
I achieved it by extending the surface view and override:

@Override
protected void dispatchDraw(Canvas canvas) {
    clipPath = new Path();
    //TODO: define the circle you actually want
    clipPath.addCircle((float) dpToPx(100), (float) dpToPx(100), (float) dpToPx(100), Path.Direction.CW);

    Paint paint = new Paint();
    paint.setAntiAlias(true);
    paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));

    canvas.clipPath(clipPath);
    canvas.drawPath(clipPath, paint);
   this.setZOrderOnTop(true);
    super.dispatchDraw(canvas);
}


问:
docker bridge network using docker-compose can't access VPN resources
Environment:

Ubuntu 17.04

Docker version 17.03.1-ce, build c6d412e

docker-compose version 1.14.0-rc1, build c18a7ad

I'm connected to a Juniper VPN using openconnect and while docker can access the docker repo inside the VPN to download images, containers running on docker-compose can't access anything inside of it. Trying with actual IPs doesn't work either so it's not just a DNS issue.

I've tried restarting docker, but didn't work. Any ideas on how to troubleshoot or fix this?

答:
Installed dnsmasq and configured docker to point to the docker0 address as it's DNS provider:

```<code>$ cat /etc/docker/daemon.json
{
  "dns": ["172.17.0.1"]
}
</code>```

This still requires me to restart dnsmasq whenever I connect to the VPN or to update this info whenever the docker0 address changes, but it's definitely better than not doing anything.

Body:
Installed dnsmasq and configured docker to point to the docker0 address as it's DNS provider:

$ cat /etc/docker/daemon.json
{
  "dns": ["172.17.0.1"]
}

This still requires me to restart dnsmasq whenever I connect to the VPN or to update this info whenever the docker0 address changes, but it's definitely better than not doing anything.


问:
SQL Comparison query
I am doing practice queries to improve my SQL skills (I'm a beginner) and I ran into this problem that I need help with using the Northwind database. The requested query should:

Give the name of employees and the city where they live for employees who have
sold to customers in the same city.

What I wrote for this was:

```<code>    USE Northwind;
    SELECT DISTINCT FirstName, LastName, e.City
    FROM Employees e
    INNER JOIN Orders o ON e.EmployeeID = O.EmployeeID
    INNER JOIN Customers c ON o.CustomerID = c.CustomerID
    INNER JOIN Customers ON c.City = e.City
    WHERE e.City = ANY(SELECT Customers.City FROM Customers);
</code>```

I am returned 6 employees but I am not sure that they are correct and I believe that my WHERE statement is the wrong one as well.

Basically my question is, am I using the correct join statements and how do I go about filtering results with the WHERE statement? I'm not exactly sure how to compare one specific record with other records. Coming from a Java background I am used to for-loops that can check each individual "object" (record) with a specific field from another "object". In this case I am wondering how I can check the City attribute of each record from the Employees table with the City attribute of the records on the Customers table. Any and all advice is appreciated, thanks!

答:
I think you only need to join the customer table once and have both requirements (being on the same order and same city as the employee) as your join requisites e.g

```<code> SELECT DISTINCT FirstName, LastName, e.City
    FROM Employees e
    INNER JOIN Orders o ON e.EmployeeID = O.EmployeeID
    INNER JOIN Customers c ON o.CustomerID = c.CustomerID AND c.City = e.City
</code>```

Alternatively you can just join the customer on the order id and filter the city requirement in the where clause. Performance-wise there shouldn't be any difference however if you are going to look back on the script at some point it may help you to remember

```<code> SELECT DISTINCT FirstName, LastName, e.City
    FROM Employees e
    INNER JOIN Orders o ON e.EmployeeID = O.EmployeeID
    INNER JOIN Customers c ON o.CustomerID = c.CustomerID
    WHERE e.City = C.City
</code>```

I think the important part to get your head round is that after you have joined the table it is effectively one table with columns from both (or more with multiple joins). The inner join conditions will filter out rows that do not have a match between the two tables and then you are left to compare columns

Title: SQL Comparison query

Body:
I am doing practice queries to improve my SQL skills (I'm a beginner) and I ran into this problem that I need help with using the Northwind database. The requested query should:

Give the name of employees and the city where they live for employees who have
sold to customers in the same city.

What I wrote for this was:

    USE Northwind;
    SELECT DISTINCT FirstName, LastName, e.City
    FROM Employees e
    INNER JOIN Orders o ON e.EmployeeID = O.EmployeeID
    INNER JOIN Customers c ON o.CustomerID = c.CustomerID
    INNER JOIN Customers ON c.City = e.City
    WHERE e.City = ANY(SELECT Customers.City FROM Customers);

I am returned 6 employees but I am not sure that they are correct and I believe that my WHERE statement is the wrong one as well.

Basically my question is, am I using the correct join statements and how do I go about filtering results with the WHERE statement? I'm not exactly sure how to compare one specific record with other records. Coming from a Java background I am used to for-loops that can check each individual "object" (record) with a specific field from another "object". In this case I am wondering how I can check the City attribute of each record from the Employees table with the City attribute of the records on the Customers table. Any and all advice is appreciated, thanks!

Body:
I think you only need to join the customer table once and have both requirements (being on the same order and same city as the employee) as your join requisites e.g

 SELECT DISTINCT FirstName, LastName, e.City
    FROM Employees e
    INNER JOIN Orders o ON e.EmployeeID = O.EmployeeID
    INNER JOIN Customers c ON o.CustomerID = c.CustomerID AND c.City = e.City

Alternatively you can just join the customer on the order id and filter the city requirement in the where clause. Performance-wise there shouldn't be any difference however if you are going to look back on the script at some point it may help you to remember

 SELECT DISTINCT FirstName, LastName, e.City
    FROM Employees e
    INNER JOIN Orders o ON e.EmployeeID = O.EmployeeID
    INNER JOIN Customers c ON o.CustomerID = c.CustomerID
    WHERE e.City = C.City

I think the important part to get your head round is that after you have joined the table it is effectively one table with columns from both (or more with multiple joins). The inner join conditions will filter out rows that do not have a match between the two tables and then you are left to compare columns


问:
Hide div when a class is added via JS
I am working with fullPage.js where an active class is added to a li via JS.

What I would like to do is, when a li (#menu li:last-child) has active class, hide #menu. But, due to the active class was added via JS, the code doesn't work:

```<code>$(window).on("scroll",function() {
    if ($('li:last-child').hasClass("active")) {
        $("#menu").hide();
    }
})
</code>```

This is my HTML:

```<code><ul id="menu">
    <li data-menuanchor="slide1"><a href="#slide1"><span></span></a></li>
    <li data-menuanchor="slide2"><a href="#slide2"><span></span></a></li>
</ul>

<div id="fullpage">
    <div class="section" id="section0">
        <div class="intro">
            <h1>Slide 1</h1>
        </div>
    </div>
    <div class="section" id="section1">
        <div class="intro">
            <h1>Slide 2</h1>
        </div>
    </div>
</div>
</code>```

答:
Change below line - </p>

```<code>("#menu").hide();
</code>```

<p>to </p>

```<code>$("#menu").hide();
</code>```

Title: Hide div when a class is added via JS

Body:
I am working with fullPage.js where an active class is added to a li via JS.

What I would like to do is, when a li (#menu li:last-child) has active class, hide #menu. But, due to the active class was added via JS, the code doesn't work:

$(window).on("scroll",function() {
    if ($('li:last-child').hasClass("active")) {
        $("#menu").hide();
    }
})

This is my HTML:

Slide 1

Slide 2

Body:
Change below line -

("#menu").hide();

to

$("#menu").hide();


问:
My ReSharper Gutter Icons for Unit Tests aren't showing
I've installed ReSharper 4.1 and Gallio 3.0.5, but I don't get the gutter icons for unit tests.  The tests seem to run fine in the Test Explorer, but I don't have icons next to the tests in code.  What could be causing this?  I previously had the MbUnit 2.4 ReSharper plugin installed, but it should be uninstalled now.</p>

答: Another really late answer here, but if you don't have Resharper Code Analysis enabled then the gutter icons won't show up. Had to help a teammate figure this out yesterday.

OwnerDisplayName: Lance Fisher

ContentLicense: CC BY-SA 4.0


问:
Fullcalendar create mutiple events based on the dates mentioned in the modal
I have a modal which has two event dates how to create two events in fullcalendar when clicked on add button.I tried this.

```<code>$('#btnAdd').on('click', function (e) {
$('#interviewModal').modal('hide');
var arr = new Array();
var event = {
title : $('#txtTitle').val(),
start : $('#txtStartDate').val(),
end : $('#txtEndDate').val(),
allDay: false,
stick : true
}

var event2 = {
title : $('#txtTitle').val(),
start : $('#txtStartDate2').val(),
end : $('#txtEndDate2').val(),
allDay : false,
stick : true
}

arr.push(event);
arr.push(event2)

e.preventDefault();

$('#calendar').fullCalendar('renderEvent',arr);
});

Also my modal looks like this
</code>```

Modal Picture

答:
Use "renderEvents" instead of "renderEvent". https://fullcalendar.io/docs/event_rendering/renderEvents/

```<code>$('#calendar').fullCalendar('renderEvents', arr, true);
</code>```

This accepts an array of events, instead of a single one.

Body:
I have a modal which has two event dates how to create two events in fullcalendar when clicked on add button.I tried this.

$('#btnAdd').on('click', function (e) {
$('#interviewModal').modal('hide');
var arr = new Array();
var event = {
title : $('#txtTitle').val(),
start : $('#txtStartDate').val(),
end : $('#txtEndDate').val(),
allDay: false,
stick : true
}

var event2 = {
title : $('#txtTitle').val(),
start : $('#txtStartDate2').val(),
end : $('#txtEndDate2').val(),
allDay : false,
stick : true
}

arr.push(event);
arr.push(event2)

e.preventDefault();

$('#calendar').fullCalendar('renderEvent',arr);
});

Also my modal looks like this

Modal Picture

Body:
Use "renderEvents" instead of "renderEvent". https://fullcalendar.io/docs/event_rendering/renderEvents/

$('#calendar').fullCalendar('renderEvents', arr, true);

This accepts an array of events, instead of a single one.


问:
How to automatically accept Alerts with Appium -- permissions Android 6.0
Environment:

OS Windows 7

Appium 1.4.16.1

Android emulator 6.0

I need to accept any permission alerts(Android 6.0 -- sms,location and etc) automatically.

What I tried:

Use driver.switchTo().alert().accept();

Result:

org.openqa.selenium.WebDriverException: Not yet implemented. Please help us: http://appium.io/get-involved.html

Set capabilities:

capabilities.setCapability("autoGrantPermissions", "true");
capabilities.setCapability("autoAcceptAlerts", "true");

Result: it doesn't work

答:
It wont work in appium.If your alert contains 'ALLOW' button.Try to use below code:

```<code>driver.findElementByAccessibilityId("ALLOW").click();
</code>```

This will click on "ALLOW" button which means accepting the alert.

Body:
It wont work in appium.If your alert contains 'ALLOW' button.Try to use below code:

driver.findElementByAccessibilityId("ALLOW").click();

This will click on "ALLOW" button which means accepting the alert.


问:
How to fill ContextMenuStrip in XAML?
I've created WPF application with NotifyIcon to work in tray.

```<code>public partial class MainWindow : Window
{
    public NotifyIcon NotifyIcon { get; } = new NotifyIcon
    {
        Icon = Properties.Resources.status_on_ico,
        Visible = true
    };

    public MainWindow()
    {
        InitializeComponent();

        NotifyIcon.ContextMenuStrip = MyContextMenuStrip;
        NotifyIcon.Click += NotifyIcon_Click;
    }

    private void Window_Closing(object sender, CancelEventArgs e)
    {
        e.Cancel = true;
        WindowState = WindowState.Minimized;
    }

    private void NotifyIcon_Click(object sender, EventArgs e)
    {
        Show();
    }
}
</code>```

XAML of main window is nothing special and not relevant.

I want to create ContextMenuStrip of NotifyIcon in XAML (I know how to do it code behind but don't want it).

Here is what I've managed.

```<code><WindowsFormsHost>
    <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
        <wf:ContextMenuStrip.Items>
            <!-- How to add items here? -->
        </wf:ContextMenuStrip.Items>
    </wf:ContextMenuStrip>
</WindowsFormsHost>
</code>```

The question is how to add items to ContextMenuStrip.Items with Name and Click event handlers in XAML?

答:
The question is how to add items to ContextMenuStrip.Items with Name and Click event handlers in XAML?

Try this:

```<code><WindowsFormsHost>
    <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
        <wf:ContextMenuStrip.Items>
            <wf:ToolStripMenuItem Text="test1" Click="It_Click" />
            <wf:ToolStripMenuItem Text="test2" />
        </wf:ContextMenuStrip.Items>
    </wf:ContextMenuStrip>
</WindowsFormsHost>
</code>```

```<code>private void It_Click(object sender, EventArgs e)
{
    MessageBox.Show("click!");
}
</code>```

Title: How to fill ContextMenuStrip in XAML?

Body:
I've created WPF application with NotifyIcon to work in tray.

public partial class MainWindow : Window
{
    public NotifyIcon NotifyIcon { get; } = new NotifyIcon
    {
        Icon = Properties.Resources.status_on_ico,
        Visible = true
    };

    public MainWindow()
    {
        InitializeComponent();

        NotifyIcon.ContextMenuStrip = MyContextMenuStrip;
        NotifyIcon.Click += NotifyIcon_Click;
    }

    private void Window_Closing(object sender, CancelEventArgs e)
    {
        e.Cancel = true;
        WindowState = WindowState.Minimized;
    }

    private void NotifyIcon_Click(object sender, EventArgs e)
    {
        Show();
    }
}

XAML of main window is nothing special and not relevant.

I want to create ContextMenuStrip of NotifyIcon in XAML (I know how to do it code behind but don't want it).

Here is what I've managed.

<WindowsFormsHost>
    <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
        <wf:ContextMenuStrip.Items>

        </wf:ContextMenuStrip.Items>
    </wf:ContextMenuStrip>
</WindowsFormsHost>

The question is how to add items to ContextMenuStrip.Items with Name and Click event handlers in XAML?

Body:
The question is how to add items to ContextMenuStrip.Items with Name and Click event handlers in XAML?

Try this:

<WindowsFormsHost>
    <wf:ContextMenuStrip x:Name="MyContextMenuStrip" TopLevel="False">
        <wf:ContextMenuStrip.Items>
            <wf:ToolStripMenuItem Text="test1" Click="It_Click" />
            <wf:ToolStripMenuItem Text="test2" />
        </wf:ContextMenuStrip.Items>
    </wf:ContextMenuStrip>
</WindowsFormsHost>

private void It_Click(object sender, EventArgs e)
{
    MessageBox.Show("click!");
}


Title: sed regexp, number reformatting: how to escape for bash

Body:
I have a working (in macOS app Patterns) RegExp that reformats GeoJSON MultiPolygon coordinates, but don't know how to escape it for sed.

The file I'm working on is over 90 Mb in size, so bash terminal looks like the ideal place and sed the perfect tool for the job.

Search Text Example:

[[[379017.735,6940036.7955],[379009.8431,6940042.5761],[379000.4869,6940048.9545],[378991.5455,6940057.8128],[378984.0665,6940066.0744],[378974.7072,6940076.2152],[378962.8639,6940090.5283],[378954.5822,6940101.4028],[378947.9369,6940111.3128],[378941.4564,6940119.5094],[378936.2565,6940128.1229],[378927.6089,6940141.4764],[378919.6611,6940154.0312],[378917.21,6940158.7053],[378913.7614,6940163.4443],[378913.6515,6940163.5893],[378911.4453,6940166.3531],

Desired outcome:

[[[37.9017735,69.400367955],[37.90098431,69.400425761],[37.90004869,69.400489545],[37.89915455,69.400578128],[37.89840665,69.400660744],[37.89747072,69.400762152],[37.89628639,69.400905283],[37.89545822,69.401014028],[37.89479369,69.401113128],[37.89414564,69.401195094],[37.89362565,69.401281229],[37.89276089,69.401414764],[37.89196611,69.401540312],[37.891721,69.401587053],[37.89137614,69.401634443],[37.89136515,69.401635893],[37.89114453,69.401663531],

My current RegExp:

((?:\[)[0-9]{2})([0-9]+)(\.)([0-9]+)(,)([0-9]{2})([0-9]+)(\.)([0-9]+(?:\]))

and reformatting:

$1\.$2$4,$6.$7$9

The command should be something along these lines:

sed -i -e 's/ The RegExp escaped /$1\.$2$4,$6.$7$9/g' large_file.geojson

But what should be escaped in the RegExp to make it work?
My attempts always complain of being unbalanced.

I'm sorry if this has already been answered elsewhere, but I couldn't find even after extensive searching.

Edit: 2017-01-07: I didn't make it clear that the file contains properties other than just the GPS-points. One of the other example values picked from GeoJSON Feature properties is "35.642.1.001_001", which should be left unchanged. The braces check in my original regex is there for this reason.

Body:
A simple sed will do it:

$ echo "$var"
[[[379017.735,6940036.7955],[379009.8431,6940042.5761],[379000.4869,6940048.9545],[378991.5455,6940057.8128],[378984.0665,6940066.0744],[378974.7072,6940076.2152],[378962.8639,6940090.5283],[378954.5822,6940101.4028],[378947.9369,6940111.3128],[378941.4564,6940119.5094],[378936.2565,6940128.1229],[378927.6089,6940141.4764],[378919.6611,6940154.0312],[378917.21,6940158.7053],[378913.7614,6940163.4443],[378913.6515,6940163.5893],[378911.4453,6940166.3531],

$ echo "$var" | sed  's/\([0-9]\{3\}\)\./.\1/g'
[[[379.017735,6940.0367955],[379.0098431,6940.0425761],[379.0004869,6940.0489545],[378.9915455,6940.0578128],[378.9840665,6940.0660744],[378.9747072,6940.0762152],[378.9628639,6940.0905283],[378.9545822,6940.1014028],[378.9479369,6940.1113128],[378.9414564,6940.1195094],[378.9362565,6940.1281229],[378.9276089,6940.1414764],[378.9196611,6940.1540312],[378.91721,6940.1587053],[378.9137614,6940.1634443],[378.9136515,6940.1635893],[378.9114453,6940.1663531],


问:
DocuSign Embeded API Instant Sign Without Authentication from DocuSign
I need to create an application where user could sign the document on my website without any docusign authentication I guess just like LoanCo Sample Demo.

I'm using Embedded Signing and following the steps listed here, and getting the URI on EnvelopeViews: createRecipient call, but when I'm trying to access that URI it redirect to "/Signing/SessionTimeout.aspx" and says "SESSION ENDED" and then nothing happens, attaching the snapshot of "session ended" page.

Here is the create envelopes request JSON.

```<code>{
  "documents": [
    {
      "documentBase64": "<Base64BytesHere>",
      "documentId": "1",
      "fileExtension": "pdf",
      "name": "PDF Doc"
    }
  ],
  "emailSubject": "Doc Sign",
  "recipients": {
    "signers": [
      {
        "clientUserId": "clientUserId",
        "email": "examble@email.com",
        "name": "Shah",
        "recipientId": "1",
        "tabs": {
          "signHereTabs": [
            {
              "documentId": "1",
              "pageNumber": "1",
              "tabLabel": "Sign Here",
              "xPosition": "100",
              "yPosition": "100"
            }
          ]
        }
      }
    ]
  }
}
</code>```

Here is my createRecipient request JSON.

```<code>{
  "authenticationMethod": "email",
  "email": "examle@email.com",
  "returnUrl": "https://localhost/index.php",
  "userName": "Shah"
}
</code>```

答:
After the envelope is created, use the createRecipient:EnvelopeViews api to retrieve the Signing URL.

In your request you are missing the clientUserId parameter.

Request

```<code>{
  "userName": "Shah",
  "email": "examble@email.com",
  "clientUserId": "clientUserId",
  "authenticationMethod": "email",
  "returnUrl": "https://localhost/index.php"
}
</code>```

Body:
I need to create an application where user could sign the document on my website without any docusign authentication I guess just like LoanCo Sample Demo.

I'm using Embedded Signing and following the steps listed here, and getting the URI on EnvelopeViews: createRecipient call, but when I'm trying to access that URI it redirect to "/Signing/SessionTimeout.aspx" and says "SESSION ENDED" and then nothing happens, attaching the snapshot of "session ended" page.

Here is the create envelopes request JSON.

{
  "documents": [
    {
      "documentBase64": "<Base64BytesHere>",
      "documentId": "1",
      "fileExtension": "pdf",
      "name": "PDF Doc"
    }
  ],
  "emailSubject": "Doc Sign",
  "recipients": {
    "signers": [
      {
        "clientUserId": "clientUserId",
        "email": "examble@email.com",
        "name": "Shah",
        "recipientId": "1",
        "tabs": {
          "signHereTabs": [
            {
              "documentId": "1",
              "pageNumber": "1",
              "tabLabel": "Sign Here",
              "xPosition": "100",
              "yPosition": "100"
            }
          ]
        }
      }
    ]
  }
}

Here is my createRecipient request JSON.

{
  "authenticationMethod": "email",
  "email": "examle@email.com",
  "returnUrl": "https://localhost/index.php",
  "userName": "Shah"
}

Body:
After the envelope is created, use the createRecipient:EnvelopeViews api to retrieve the Signing URL.

In your request you are missing the clientUserId parameter.

Request

{
  "userName": "Shah",
  "email": "examble@email.com",
  "clientUserId": "clientUserId",
  "authenticationMethod": "email",
  "returnUrl": "https://localhost/index.php"
}


问:
RBF neural networks
I would like to apply RBF neural networks to teach my system.
I have a system with an input:

```<code>|    1    2    3    4    5    6 ...   32 |    33 |
| 1000 0001 0010 0100 1000 1000 ... 0100 | 0 0 1 |
</code>```

You have to read this without the "|" character. I just wanted you to see that the last three elements in the input are staying together. The result have to be a number between 1-32, which has the value "1000" in the input. In my training set I will always have a result for an array of this kind. What kind of functions can I use for the teaching algorithm? Can you point me please to the right way?

If you can't understand my description please don't hesitate to ask about it. Thank you guys for your help!

答:
Using RBF network for this seems like a weird solution. But if you have your heart set on it:
(it is entirely possible that I totally misunderstood the problem you want to solve).

You might want to put it in terms of classification and train 32 binary classifiers that determine if the "1000" is at each of the 32 entries. Or more in "neural network" terms have 32*4 entries and 32 ouputs.

One efficent way to train an RBF network is to use an SVM with an RBF kernel. One good implementation of this is LIBSVM.

Title: RBF neural networks

Body:
I would like to apply RBF neural networks to teach my system.
I have a system with an input:

|    1    2    3    4    5    6 ...   32 |    33 |
| 1000 0001 0010 0100 1000 1000 ... 0100 | 0 0 1 |

You have to read this without the "|" character. I just wanted you to see that the last three elements in the input are staying together. The result have to be a number between 1-32, which has the value "1000" in the input. In my training set I will always have a result for an array of this kind. What kind of functions can I use for the teaching algorithm? Can you point me please to the right way?

If you can't understand my description please don't hesitate to ask about it. Thank you guys for your help!


问:
Mysqli Undefined index array json
i have notice with sum metode : "Undefined index: PGW maximum active subscribers "

$a=mysqli_query($koneksi, "SELECT sum(`PGW maximum active subscribers`) as count FROM ggsn_4g_pdp_max");
 $b=mysqli_query($koneksi, "SELECT sum('SGW maximum active subscribers') as count FROM ggsn_4g_pdp_max");
 $c=mysqli_query($koneksi, "SELECT sum('SPGW maximum active subscribers') as count FROM ggsn_4g_pdp_max");

    $pgw_array=array();
    $sgw_array=array();
    $spgw_array=array();

    while($r=mysqli_fetch_array($a)){
        $pgw_array[]= $r["PGW maximum active subscribers"];
 }
 while($g=mysqli_fetch_array($b)){
        $sgw_array[]= $g["SGW maximum active subscribers"];
 }
  while($n=mysqli_fetch_array($c)){
        $spgw_array[]= $n["SPGW maximum active subscribers"];
 }```

how i can fixed...?please

答: You must use the alias count: $r["count"]

Title: Mysqli Undefined index array json

Body:
i have notice with sum metode : "Undefined index: PGW maximum active subscribers "

$a=mysqli_query($koneksi, "SELECT sum(`PGW maximum active subscribers`) as count FROM ggsn_4g_pdp_max");
 $b=mysqli_query($koneksi, "SELECT sum('SGW maximum active subscribers') as count FROM ggsn_4g_pdp_max");
 $c=mysqli_query($koneksi, "SELECT sum('SPGW maximum active subscribers') as count FROM ggsn_4g_pdp_max");

    $pgw_array=array();
    $sgw_array=array();
    $spgw_array=array();

    while($r=mysqli_fetch_array($a)){
        $pgw_array[]= $r["PGW maximum active subscribers"];
 }
 while($g=mysqli_fetch_array($b)){
        $sgw_array[]= $g["SGW maximum active subscribers"];
 }
  while($n=mysqli_fetch_array($c)){
        $spgw_array[]= $n["SPGW maximum active subscribers"];
 }

how i can fixed...?please


问:
How can I simulate two fast clicks on a submit button in Capybara?
I have a bug in my app which occurs if a user clicks the submit button of a form very quickly twice in a row. I can reliably reproduce this on production and in my development environment.

Is it possible for me to reproduce this with Capybara/poltergeist/phantomjs?

find("#my-button").double_click, find("#my-button").click.click, execute_script("$('#register-button').click().click();"), and other variations with execute_script do not work.

Everything I tried only caused my server-side code to be invoked once, even though console.log logging showed that click was indeed invoked twice. So I suspect there's something fundamentally missing from the capabilities of capybara and poltergeist simulate this behavior.

Is there a way to somehow invoke phantomJS at a lower level and achieve this?

I did try increasing the concurrency of my web server, it didn't help.

capybara 2.14.0

rails 5.1.0

poltergeist 1.15.0

phantomjs 2.1.1

答:
Taking a slightly different approach here: what is the fix to this bug? Would it be easier to test the fix, rather than test that these actions can't be carried out?

For example, if the fix is to use Rails UJS disable-with on an <input type=submit>, then your test could be something like:

```<code># replace `your_path` as required
visit your_path

# important: this stops the submission so the page doesn't change;
# but crucially doesn't stop UJS from doing its thing
execute_script("$('form').submit(function() { event.preventDefault() })")

# replace 'Submit form' and 'Processing...' text as appropriate
click_button('Submit form')
expect(page).to have_button('Processing...', disabled: true)
</code>```

Body:
Taking a slightly different approach here: what is the fix to this bug? Would it be easier to test the fix, rather than test that these actions can't be carried out?

For example, if the fix is to use Rails UJS disable-with on an <input type=submit>, then your test could be something like:

# replace `your_path` as required
visit your_path

# important: this stops the submission so the page doesn't change;
# but crucially doesn't stop UJS from doing its thing
execute_script("$('form').submit(function() { event.preventDefault() })")

# replace 'Submit form' and 'Processing...' text as appropriate
click_button('Submit form')
expect(page).to have_button('Processing...', disabled: true)


问:
How to set proper codeigniter base url?
when I had my site on development environment - it was url: testurl.com

Now on production server my codeigniter app's address has to be someurl.com/mysite/

I moved it there, and everytime I'm trying to run some function, example /home/test - it gets me into someurl.com/home/test - which is WRONG.

It has to be someurl.com/mysite/home/test - How to fix it? I did set

```<code>$config['base_url'] = someurl.com/mysite/
</code>```

答:
```<code>Base url set in CodeIgniter for all url

$config['base_url'] = "http://".$_SERVER['HTTP_HOST']."/";
</code>```

Title: How to set proper codeigniter base url?

Body:
when I had my site on development environment - it was url: testurl.com

Now on production server my codeigniter app's address has to be someurl.com/mysite/

I moved it there, and everytime I'm trying to run some function, example /home/test - it gets me into someurl.com/home/test - which is WRONG.

It has to be someurl.com/mysite/home/test - How to fix it? I did set

$config['base_url'] = someurl.com/mysite/


答: The file needs to be placed at the root folder of your project.</p>

Title: text file inside class folder, yet cannot find it

Body:
As you can see, the file is right inside the same folder where the class file is. While I tried to have it print the path to it, that is a bummer because no matter what name I type it will always type a full path to that invented file name. The file is comma separated, that I copied pasted into gedit and tried all kinds of extensions, csv, txt and no extension.

What I am trying to do is import it into an array, but the error is clear, no such file or directory.


问:
Best Practice setup for Parameter Sets
I'm trying to setup parameter sets but I'm unsure if that's the best practice approch to what I'm trying to do.  The setup I'm looking for is the following:

```<code>$FolderSetup - Not Manditory.  [ValidateSet("Yes", "No"] Default is "No"
    If "Yes" is used, then no following parameters should be able to be selected
$OSVersion - Manditory.  [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")].
    If "All" is used, then no following parameters should be able to be selected

$InputFile - Not Manditory - User inputs location of file
$OutputFolder - Not Manditory.  - User inputs desired output location
    $InputFile must be used before $OutputFolder can be used.
</code>```

Examples:

```<code>SinglePackage -FolderSetup 'Yes'
    #No Other Parameters can be used
SinglePackage -OSVersion 'All'
    #No Other Parameters can be used
SinglePackage -OSVersion '2008SP2'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt' -OutputFolder 'C:\Temp\MyFolder'
SinglePackage -OSVersion '2008SP2' -OutputFolder 'C:\Temp\MyFolder'
    #Not Allowed.  Must have -InputFile if using -OutputFolder
</code>```

答:
Here is how you do params you asked for...</p>

```<code>Function TEST(){
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [switch]$FolderSetup,

        [Parameter(Position=1, Mandatory=$false)]
        [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")]
        [string]$OSVersion,

        [Parameter(ParameterSetName="InputFiles", Mandatory=$false)]
        [string]$InputFile,

        [Parameter(ParameterSetName="InputFiles", Mandatory=$false)]
        [string]$OutputFolder
    )

}
</code>```

Title: Best Practice setup for Parameter Sets

Body:
I'm trying to setup parameter sets but I'm unsure if that's the best practice approch to what I'm trying to do.  The setup I'm looking for is the following:

$FolderSetup - Not Manditory.  [ValidateSet("Yes", "No"] Default is "No"
    If "Yes" is used, then no following parameters should be able to be selected
$OSVersion - Manditory.  [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")].
    If "All" is used, then no following parameters should be able to be selected

$InputFile - Not Manditory - User inputs location of file
$OutputFolder - Not Manditory.  - User inputs desired output location
    $InputFile must be used before $OutputFolder can be used.

Examples:

SinglePackage -FolderSetup 'Yes'
    #No Other Parameters can be used
SinglePackage -OSVersion 'All'
    #No Other Parameters can be used
SinglePackage -OSVersion '2008SP2'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt'
SinglePackage -OSVersion '2008SP2' -InputFile 'C:\Temp\MyFile.txt' -OutputFolder 'C:\Temp\MyFolder'
SinglePackage -OSVersion '2008SP2' -OutputFolder 'C:\Temp\MyFolder'
    #Not Allowed.  Must have -InputFile if using -OutputFolder

Body:
Here is how you do params you asked for...

Function TEST(){
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [switch]$FolderSetup,

        [Parameter(Position=1, Mandatory=$false)]
        [ValidateSet("2008SP2", "2008R2", "2012R2", "2016", "All")]
        [string]$OSVersion,

        [Parameter(ParameterSetName="InputFiles", Mandatory=$false)]
        [string]$InputFile,

        [Parameter(ParameterSetName="InputFiles", Mandatory=$false)]
        [string]$OutputFolder
    )

}


问:
Elasticsearch script_fields to update another field?
Is there a way to use the output of an ElasticSearch script_fields to update another variable in the index?

I have an index in ElasticSearch 1.x which has timestamp enabled, but not stored. (See below for mapping)

This means that the timestamp can be accessed for searches, or using script_fields like -

```<code>GET twitter/_search
{
     "script_fields": {
       "script1": {
          "script": "_fields['_timestamp']"
        }
  }
}
</code>```

I need to extract this timestamp field, and store it in the index. It is easy enough to write a script to copy any other field e.g. (I am using the update API)

```<code>ctx._source.t1=ctx._source.message
</code>```

But how can I use the value from the script_fields output to update another field in the index? I want the field 'tcopy' to get the value of the timestamp for each document.

Further, I tried to use java to get the values as below, but it returned null.

```<code>SearchResponse response = client.prepareSearch("twitter")
                .setQuery(QueryBuilders.matchAllQuery())
                .addScriptField("test", "doc['_timestamp'].value")
                .execute().actionGet();
</code>```

The mapping

```<code> {
         "mappings": {
             "tweet": {
                "_timestamp": {
                   "enabled": true,
                   "doc_values" : true
                },
                "properties": {
                   "message": {
                      "type": "string"
                   },
                   "user": {
                      "type": "string"
                   },
                   "tcopy": {
                      "type": "long"
                   }
                }
             }
          }
    }
</code>```

答:
The _timestamp field can be accessed using java. Then, we can use the Update API to set the new field. The request would look like

```<code>SearchResponse response = client.prepareSearch("twitter2")
                .setQuery(QueryBuilders.matchAllQuery())
                .addScriptField("test", "doc['_timestamp'].value")
                .execute().actionGet();
</code>```

Then I can use UpdateRequestBuilder with a script that uses this value to update the index

Body:
Is there a way to use the output of an ElasticSearch script_fields to update another variable in the index?

I have an index in ElasticSearch 1.x which has timestamp enabled, but not stored. (See below for mapping)

This means that the timestamp can be accessed for searches, or using script_fields like -

GET twitter/_search
{
     "script_fields": {
       "script1": {
          "script": "_fields['_timestamp']"
        }
  }
}

I need to extract this timestamp field, and store it in the index. It is easy enough to write a script to copy any other field e.g. (I am using the update API)

ctx._source.t1=ctx._source.message

But how can I use the value from the script_fields output to update another field in the index? I want the field 'tcopy' to get the value of the timestamp for each document.

Further, I tried to use java to get the values as below, but it returned null.

SearchResponse response = client.prepareSearch("twitter")
                .setQuery(QueryBuilders.matchAllQuery())
                .addScriptField("test", "doc['_timestamp'].value")
                .execute().actionGet();

The mapping

 {
         "mappings": {
             "tweet": {
                "_timestamp": {
                   "enabled": true,
                   "doc_values" : true
                },
                "properties": {
                   "message": {
                      "type": "string"
                   },
                   "user": {
                      "type": "string"
                   },
                   "tcopy": {
                      "type": "long"
                   }
                }
             }
          }
    }

Body:
The _timestamp field can be accessed using java. Then, we can use the Update API to set the new field. The request would look like

SearchResponse response = client.prepareSearch("twitter2")
                .setQuery(QueryBuilders.matchAllQuery())
                .addScriptField("test", "doc['_timestamp'].value")
                .execute().actionGet();

Then I can use UpdateRequestBuilder with a script that uses this value to update the index


问:
How to check which field in a table a foreign key references
A foreign key is a field (or collection of fields) in one table that uniquely identifies a row of another table or the same table. In simpler words, the foreign key is defined in a second table, but it refers to the primary key in the first table.

I'm using SQL Developer but I can't seem to find which column in my table holds the foreign key to the other table. When I click on the table, a bunch of tabs show up, among which is the Constraints tab. Here, I can see the foreign key, but I don't see which columns are involved in it.

答: Open Constraints tab. When you click one of the foreign key constraint name, columns wihch is used in the foreign key references will be seen in the Columns view at the bottom of Constraints Tab</p>


问:
How can I align some text vertically in the middle of an HTML image?
I have this:
http://jsfiddle.net/8KWtH/

I would like to move the > so it is in the middle vertically of the two images.

How can i do this?

答:
You can set your images to have vertical-align:middle; but that will make the > start from the middle. so it will still go up a little.

example: http://jsfiddle.net/8KWtH/14/

Applying the vertical align to the span as well makes it perfect.

example: http://jsfiddle.net/8KWtH/22/


问:
Basic HTTP Authentication not working in Google App Engine
I'm building a backend system for my mobile app. I want to protect the content with a basic HTTP Auth.

I have written the following code and it runs like a breeze on localhost.

```<code>if ($_SERVER['PHP_AUTH_USER'] != 'admin@denda.in' && $_SERVER['PHP_AUTH_PW'] != '11test11') {
    header('WWW-Authenticate: Basic realm="Denda Backend"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Wrong credentials :-(";
    exit;
}
</code>```

But this does not work when I upload the app to GAE. I keep getting the same dialog box. Could not find any reliable help online as well.

thanks,
Krish

答:
I know it's an old question but it's nice to know it</p>

```<code>if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $nobasic = substr($_SERVER['HTTP_AUTHORIZATION'],6);            // removing 'Basic ' from the string
    $decoded = base64_decode($nobasic);                                   // decoding string with user:password
    list($client_user, $client_pass) = explode(':',$decoded);
    if ($client_user == "user" && $client_pass == "password") {
        // Successfully authenticated
    } else {
        // Authentication failed, username or password are wrong
        header('WWW-Authenticate: Basic realm="site"');
        header('HTTP/1.0 401 Unauthorized');
        echo "Wrong credentials :-(";
        exit;
    }
} else {
    // Not authenticated as there is no appropriate header in HTTP request
    header('WWW-Authenticate: Basic realm="site"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Wrong credentials :-(";
    exit;
}
</code>```

Body:
I'm building a backend system for my mobile app. I want to protect the content with a basic HTTP Auth.

I have written the following code and it runs like a breeze on localhost.

if ($_SERVER['PHP_AUTH_USER'] != 'admin@denda.in' && $_SERVER['PHP_AUTH_PW'] != '11test11') {
    header('WWW-Authenticate: Basic realm="Denda Backend"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Wrong credentials :-(";
    exit;
}

But this does not work when I upload the app to GAE. I keep getting the same dialog box. Could not find any reliable help online as well.

thanks,
Krish

Body:
I know it's an old question but it's nice to know it

if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
    $nobasic = substr($_SERVER['HTTP_AUTHORIZATION'],6);            // removing 'Basic ' from the string
    $decoded = base64_decode($nobasic);                                   // decoding string with user:password
    list($client_user, $client_pass) = explode(':',$decoded);
    if ($client_user == "user" && $client_pass == "password") {
        // Successfully authenticated
    } else {
        // Authentication failed, username or password are wrong
        header('WWW-Authenticate: Basic realm="site"');
        header('HTTP/1.0 401 Unauthorized');
        echo "Wrong credentials :-(";
        exit;
    }
} else {
    // Not authenticated as there is no appropriate header in HTTP request
    header('WWW-Authenticate: Basic realm="site"');
    header('HTTP/1.0 401 Unauthorized');
    echo "Wrong credentials :-(";
    exit;
}


问:
Minimize an Eclipse RCP tray application
I have an Eclipse RCP tray application. When I run it from Eclipse IDE environment it runs fine. But when it runs as an Eclipse product (standalone exe) it always show a title bar with three buttons (min/max/close) as you see below. I am running Windows 10. Why? How can I suppress this small window/shell.

I am calling the following method from preWindowOpen.

```<code>   private void minimize() {
        IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
        configurer.setInitialSize(new Point(50, 0));
        configurer.setShowCoolBar(false);
        configurer.setShowStatusLine(false);
        configurer.setShowMenuBar(false);
        configurer.setShellStyle(0);

        configurer.getWindow().getShell().setVisible(false);
        configurer.getWindow().getShell().setMinimized(true);
    }
</code>```

答: The code works in Eclipse Helios but is failing in Neon. I believe some of libraries has changed regarding minimizing a window.</p>

Body:
I have an Eclipse RCP tray application. When I run it from Eclipse IDE environment it runs fine. But when it runs as an Eclipse product (standalone exe) it always show a title bar with three buttons (min/max/close) as you see below. I am running Windows 10. Why? How can I suppress this small window/shell.

I am calling the following method from preWindowOpen.

   private void minimize() {
        IWorkbenchWindowConfigurer configurer = getWindowConfigurer();
        configurer.setInitialSize(new Point(50, 0));
        configurer.setShowCoolBar(false);
        configurer.setShowStatusLine(false);
        configurer.setShowMenuBar(false);
        configurer.setShellStyle(0);

        configurer.getWindow().getShell().setVisible(false);
        configurer.getWindow().getShell().setMinimized(true);
    }