问:
mod-rewrite recursive loop
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
</code>```

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

```<code>RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

```<code>RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]
</code>```

None of the two url work.

答:
try using L

```<code>[L]
</code>```

instead of

```<code>[PT]
</code>```

Title: mod-rewrite recursive loop

Body:
I want to change my website's dynamic urls to Search Engine Friendly URL's

Now the urls like this www.website.com/news.php?id=127591 ,
I want it became this www.website.com/news/127591/this-is-article-subject

I added this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]

in my .htaccess file. Everything from /news.php?id=123 change to /new/123/this-is-article-subject

The problem is, now I have two links refer to the same contents. Both /news.php?id=123 and /new/123/this-is-article-subject are the exactly duplicate content

It is said that search engine will punish this if they found duplicated contents.

I check the answers online and found this,

RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

HTTP 301 permanent redirect from the old URL to the new URL.

But this still have problem. When I put those three lines together, it not works.

RewriteRule ^news/([0-9]+) /news.php?id=$1 [PT]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

I guess the reason is the recursive loop. How could I solve this kind of problem?

Thanks!

Update

I changed to this

RewriteRule ^news/([0-9]+) /news.php?id=$1 [L]
RewriteCond %{QUERY_STRING} ^id=([0-9]+)
RewriteRule ^news\.php /news/%1? [R=301,L]

None of the two url work.

Body:
try using L

[L]

instead of

[PT]


来源: stackexchange

问:
How to empty form fields after onSubmit in React JS
I am trying to empty/clear my form fields after I click submit button using onSubmit event handler in react js

This is my code and it do the work well (submitting form) but not clearing the inputs even after I set states

This is my react App.js

```<code>import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import CreateToDo from "./components/creat-todo.component";
import EditToDo from "./components/edit-todos.component";
import ToDoList from "./components/todos-list.component";

class App extends Component {
  render() {
    return (
      <Router>
        <div className="container">

          <nav className="navbar navbar-expand-lg navbar-light bg-light">
            <Link to="/" className="navbar-brand">MERN-Stack Todo App</Link>
            <div className="collapase navbar-collapse">
              <ul className="navbar-nav mr-auto">
                <li className="navbar-item">
                  <Link to="/" className="nav-link">ToDos</Link>
                </li>
                <li className="navbar-item">
                  <Link to="/create" className="nav-link">Create ToDos</Link>
                </li>
              </ul>
            </div>
          </nav>

          <h2>MERN-Stack Todo App</h2>
          {/* when localhost starts without any additional url extensions */}
          {/* TODO list component should be loaded exactly */}
          <Route path="/" exact component={ToDoList} />
          <Route path="/edit/:id" component={EditToDo} />
          <Route path="/create" component={CreateToDo} />
        </div>
      </Router>
    );
  }
}

export default App;
</code>```

This is creat-todo.component.jsx component

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

export default class CreateToDo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };

    this.onChangeToDoDescription = this.onChangeToDoDescription.bind(this);
    this.onChangeToDoPriority = this.onChangeToDoPriority.bind(this);
    this.onChangeToDoResponsible = this.onChangeToDoResponsible.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChangeToDoDescription(e) {
    this.setState({
      todo_description: e.target.value
    });
  }

  onChangeToDoResponsible(e) {
    this.setState({
      todo_responsible: e.target.value
    });
  }

  onChangeToDoPriority(e) {
    this.setState({
      todo_priority: e.target.value
    });
  }

  onSubmit(e) {
    e.preventDefault();

    console.log(`Form Submitted`);
    console.log(`Todo Description: ${this.state.todo_description}`);
    console.log(`Todo Responsible: ${this.state.todo_responsible}`);
    console.log(`Todo Priority: ${this.state.todo_priority}`);
    console.log(`Todo Completed: ${this.state.todo_completed}`);

    const newToDo = {
        todo_description: this.state.todo_description,
        todo_responsible: this.state.todo_responsible,
        todo_priority: this.state.todo_priority,
        todo_completed: this.state.todo_completed,
    }

    axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
    });

    this.setState = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };
  }

  render() {
    return (
      <div style={{ marginTop: 20 }}>
        <form onSubmit={this.onSubmit}>
          <div className="form-group">
            <label htmlFor="description">Description: </label>
            <input
              value={this.state.todo_description}
              onChange={this.onChangeToDoDescription}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />
          </div>

          <div className="form-group">
            <label htmlFor="description">Responsible: </label>
            <input
              value={this.state.todo_responsible}
              onChange={this.onChangeToDoResponsible}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />
          </div>

          <div className="form-check">
            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityLow"
              value="Low"
              checked={this.state.todo_priority === 'Low'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityLow">
              Low
            </label>

            <br/>

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityMedium"
              value="Medium"
              checked={this.state.todo_priority === 'Medium'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityMedium">
              Medium
            </label>

            <br/>

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityHigh"
              value="High"
              checked={this.state.todo_priority === 'High'}
              onChange={this.onChangeToDoPriority}
            />
            <label className="form-check-label" htmlFor="priorityHigh">
              High
            </label>

            <br />

            <button type="submit" onSubmit={this.onSubmit} className="btn btn-primary btn-sm">Save ToDo</button>

          </div>
        </form>
      </div>
    );
  }
}
</code>```

Can someone tell me what's wrong?

答:
You have to make setState inside axios promise : </p>

```<code>axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
this.setState = ({
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    })
    });
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to empty/clear my form fields after I click submit button using onSubmit event handler in react js

This is my code and it do the work well (submitting form) but not clearing the inputs even after I set states

This is my react App.js

import React, { Component } from "react";
import "bootstrap/dist/css/bootstrap.css";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";

import CreateToDo from "./components/creat-todo.component";
import EditToDo from "./components/edit-todos.component";
import ToDoList from "./components/todos-list.component";

class App extends Component {
  render() {
    return (
      <Router>

            <Link to="/" className="navbar-brand">MERN-Stack Todo App</Link>

                  <Link to="/" className="nav-link">ToDos</Link>

                  <Link to="/create" className="nav-link">Create ToDos</Link>

MERN-Stack Todo App

          {/* when localhost starts without any additional url extensions */}
          {/* TODO list component should be loaded exactly */}
          <Route path="/" exact component={ToDoList} />
          <Route path="/edit/:id" component={EditToDo} />
          <Route path="/create" component={CreateToDo} />

      </Router>
    );
  }
}

export default App;

This is creat-todo.component.jsx component

import React, { Component } from "react";
import axios from 'axios';

export default class CreateToDo extends Component {
  constructor(props) {
    super(props);

    this.state = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };

    this.onChangeToDoDescription = this.onChangeToDoDescription.bind(this);
    this.onChangeToDoPriority = this.onChangeToDoPriority.bind(this);
    this.onChangeToDoResponsible = this.onChangeToDoResponsible.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
  }

  onChangeToDoDescription(e) {
    this.setState({
      todo_description: e.target.value
    });
  }

  onChangeToDoResponsible(e) {
    this.setState({
      todo_responsible: e.target.value
    });
  }

  onChangeToDoPriority(e) {
    this.setState({
      todo_priority: e.target.value
    });
  }

  onSubmit(e) {
    e.preventDefault();

    console.log(`Form Submitted`);
    console.log(`Todo Description: ${this.state.todo_description}`);
    console.log(`Todo Responsible: ${this.state.todo_responsible}`);
    console.log(`Todo Priority: ${this.state.todo_priority}`);
    console.log(`Todo Completed: ${this.state.todo_completed}`);

    const newToDo = {
        todo_description: this.state.todo_description,
        todo_responsible: this.state.todo_responsible,
        todo_priority: this.state.todo_priority,
        todo_completed: this.state.todo_completed,
    }

    axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
    });

    this.setState = {
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    };
  }

  render() {
    return (

        <form onSubmit={this.onSubmit}>

            Description:
            <input
              value={this.state.todo_description}
              onChange={this.onChangeToDoDescription}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />

            Responsible:
            <input
              value={this.state.todo_responsible}
              onChange={this.onChangeToDoResponsible}
              type="text"
              className="form-control"
              id="description"
              aria-describedby="emailHelp"
              placeholder="Enter email"
            />

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityLow"
              value="Low"
              checked={this.state.todo_priority === 'Low'}
              onChange={this.onChangeToDoPriority}
            />

              Low

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityMedium"
              value="Medium"
              checked={this.state.todo_priority === 'Medium'}
              onChange={this.onChangeToDoPriority}
            />

              Medium

            <input
              className="form-check-input"
              type="radio"
              name="priorityOptions"
              id="priorityHigh"
              value="High"
              checked={this.state.todo_priority === 'High'}
              onChange={this.onChangeToDoPriority}
            />

              High

            <button type="submit" onSubmit={this.onSubmit} className="btn btn-primary btn-sm">Save ToDo</button>

        </form>

    );
  }
}

Can someone tell me what's wrong?

Body:
You have to make setState inside axios promise :

axios.post('http://localhost:4000/todos/add', newToDo)
    .then(res => {
        console.log(res.data);
this.setState = ({
      todo_description: "",
      todo_responsible: "",
      todo_priority: "",
      todo_completed: false
    })
    });


问:
How to remove unused using namespaces
I am using visual studio 2010 and was wondering if there is a way to automatically remove all the namespaces that aren't being used at the the top of the page e.g.

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
</code>```

in the above example System.Collections.Generic is not being used is there a way to know that without trial and error.

答: For VS 2019, VS 2022 or ReSharper. If you add an unused using to the top of a file such as using System.IO; a light bulb appears. Clicking on the light bulb gives the option to remove the unused usings from either the file, folder, project or entire solution.

ContentLicense: CC BY-SA 3.0

Title: How to remove unused using namespaces

Body:
I am using visual studio 2010 and was wondering if there is a way to automatically remove all the namespaces that aren't being used at the the top of the page e.g.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

in the above example System.Collections.Generic is not being used is there a way to know that without trial and error.


问:
How can I integrate free google translate api with codeigniter without being blocked?
I'm trying to integrate Google translate Api with codeigniter at first it works but after few requests I'm getting this error 302 Moved it seems like server blocked my ip address.

<?php

class GoogleTranslate
{
    public static function translate($source, $target, $text)
    {

        $response = self::requestTranslation($source, $target, $text);
        $translation = self::getSentencesFromJSON($response);
        return $translation;
    }

    protected static function requestTranslation($source, $target, $text)
    {
        $url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";

        $fields = array(
            'sl' => urlencode($source),
            'tl' => urlencode($target),
            'q' => urlencode($text)
        );

        $fields_string = "";
        foreach ($fields as $key => $value) {
            $fields_string .= $key . '=' . $value . '&';
        }
        rtrim($fields_string, '&');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
       $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
        protected static function getSentencesFromJSON($json)
    {
        $sentencesArray = json_decode($json, true);
        $sentences = "";

        foreach ($sentencesArray["sentences"] as $s) {
            $sentences .= isset($s["trans"]) ? $s["trans"] : '';
        }

        return $sentences;
    }
}
```

<pre class="lang-php prettyprint-override"><code>$trans = new GoogleTranslate();
$result = $trans->translate($source, $target, $text);
</code>```

I use an array containing many texts that should be translated.
How can I use Google translate Api without being blocked?

答:
Use official Google Translate API, see https://cloud.google.com/translate/docs/

Each month Google give you 10$ credit for free. It means 500 000 translated characters per month for free.

Body:
I'm trying to integrate Google translate Api with codeigniter at first it works but after few requests I'm getting this error 302 Moved it seems like server blocked my ip address.

<?php

class GoogleTranslate
{
    public static function translate($source, $target, $text)
    {

        $response = self::requestTranslation($source, $target, $text);
        $translation = self::getSentencesFromJSON($response);
        return $translation;
    }

    protected static function requestTranslation($source, $target, $text)
    {
        $url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";

        $fields = array(
            'sl' => urlencode($source),
            'tl' => urlencode($target),
            'q' => urlencode($text)
        );

        $fields_string = "";
        foreach ($fields as $key => $value) {
            $fields_string .= $key . '=' . $value . '&';
        }
        rtrim($fields_string, '&');
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, count($fields));
        curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
       $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
        protected static function getSentencesFromJSON($json)
    {
        $sentencesArray = json_decode($json, true);
        $sentences = "";

        foreach ($sentencesArray["sentences"] as $s) {
            $sentences .= isset($s["trans"]) ? $s["trans"] : '';
        }

        return $sentences;
    }
}

$trans = new GoogleTranslate();
$result = $trans->translate($source, $target, $text);

I use an array containing many texts that should be translated.
How can I use Google translate Api without being blocked?


问:
Cannot define 'through' relationship on two models which share a base class in Django
I've got a 'set' model, which has a many to many relationship to the 'Item' model. The issue is that 'set' is a subclass of Item (everything is an Item on the project).

It works fine, until I try to create a 'through' relationship to an intermediary model called 'order', which I'm defining so I can order the 'Items' inside the 'Set'.

When I try to define the relationship, I get this error:

```<code>ERRORS:
curate.Set.items_: (fields.E001) Field names must not end with an underscore.
curate.order.set: (fields.E304) Reverse accessor for 'order.set' clashes with reverse accessor for 'order.item'.
        HINT: Add or change a related_name argument to the definition for 'order.set' or 'order.item'.
</code>```

I've tried adding a related_name to Order.set, and also Order.item, but it doesn't seem to work. I can get migrations to be happy, but then when I try to migrate I get an error saying:

```<code>ValueError: Cannot alter field curate.Set.items into curate.Set.items - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)
</code>```

models.py

```<code>
class Item(models.Model, AdminVideoMixin):

    title = models.TextField(max_length=5000)
    slug = models.SlugField(max_length=5000, default='')
   ...

class Video(Item):
    video_embed = EmbedVideoField(max_length=500)
    ...

class Article(Item):
    authors = models.CharField(max_length=10000)
    ...

class Podcast(Item):
    categories = models.CharField(max_length=5000, null=True, blank=True,)
    ...

class Episode(Item):
    author = models.CharField(max_length=10000, null=True,blank=True,)
    ...

class Set(Item):
    items = models.ManyToManyField(Item, related_name='setItems', max_length=5000, through='Order')
    front_page = models.BooleanField(max_length=300, blank=False, default=False, null=False)

class order(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE,)
    set = models.ForeignKey(Set, on_delete=models.CASCADE,)
    order = models.CharField(max_length=64, default=0)
</code>```

答:
You can't change a ManyToMany field to use a through relationship once it has been created. This is because the through table will now contain extra fields that cannot be populated by the standard ManyToMany relationship (this is the same reason why you can't use add, clear, remove, delete when using a through table). You will need to create a new ManyToMany field on Set that uses the through relationship and then populate it with the data from Set.items before removing Set.items.

Docs on through tables

If you need to have the new field called items you can do the following:

Change items to items_old in the Set model, you will need to change the related_name as well if you would like that to be the same (make and run the migration)

Add the new items field with the through relationship (make and run the migration)

Populate the new items field with the data from items_old

```<code>set_items = Set.objects.filter(items__isnull=False)
Order.objects.bulk_create([
    Order(item=item, set=s)
    for s in set_items
    for item in s.items.all()
])
</code>```

Remove items_old from Set

NB - Like katoozi mentioned in his comment, you probably shouldn't have fields named set

Body:
I've got a 'set' model, which has a many to many relationship to the 'Item' model. The issue is that 'set' is a subclass of Item (everything is an Item on the project).

It works fine, until I try to create a 'through' relationship to an intermediary model called 'order', which I'm defining so I can order the 'Items' inside the 'Set'.

When I try to define the relationship, I get this error:

ERRORS:
curate.Set.items_: (fields.E001) Field names must not end with an underscore.
curate.order.set: (fields.E304) Reverse accessor for 'order.set' clashes with reverse accessor for 'order.item'.
        HINT: Add or change a related_name argument to the definition for 'order.set' or 'order.item'.

I've tried adding a related_name to Order.set, and also Order.item, but it doesn't seem to work. I can get migrations to be happy, but then when I try to migrate I get an error saying:

ValueError: Cannot alter field curate.Set.items into curate.Set.items - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields)

models.py

class Item(models.Model, AdminVideoMixin):

    title = models.TextField(max_length=5000)
    slug = models.SlugField(max_length=5000, default='')
   ...

class Video(Item):
    video_embed = EmbedVideoField(max_length=500)
    ...

class Article(Item):
    authors = models.CharField(max_length=10000)
    ...

class Podcast(Item):
    categories = models.CharField(max_length=5000, null=True, blank=True,)
    ...

class Episode(Item):
    author = models.CharField(max_length=10000, null=True,blank=True,)
    ...

class Set(Item):
    items = models.ManyToManyField(Item, related_name='setItems', max_length=5000, through='Order')
    front_page = models.BooleanField(max_length=300, blank=False, default=False, null=False)

class order(models.Model):
    item = models.ForeignKey(Item, on_delete=models.CASCADE,)
    set = models.ForeignKey(Set, on_delete=models.CASCADE,)
    order = models.CharField(max_length=64, default=0)

Body:
You can't change a ManyToMany field to use a through relationship once it has been created. This is because the through table will now contain extra fields that cannot be populated by the standard ManyToMany relationship (this is the same reason why you can't use add, clear, remove, delete when using a through table). You will need to create a new ManyToMany field on Set that uses the through relationship and then populate it with the data from Set.items before removing Set.items.

Docs on through tables

If you need to have the new field called items you can do the following:

Change items to items_old in the Set model, you will need to change the related_name as well if you would like that to be the same (make and run the migration)

Add the new items field with the through relationship (make and run the migration)

Populate the new items field with the data from items_old

set_items = Set.objects.filter(items__isnull=False)
Order.objects.bulk_create([
    Order(item=item, set=s)
    for s in set_items
    for item in s.items.all()
])

Remove items_old from Set

NB - Like katoozi mentioned in his comment, you probably shouldn't have fields named set


问:
Error Invalid grant: refresh token is invalid in getRefreshToken
I want to implement the function getRefreshToken with the oauth2-server module in Nodejs. I already implemented the whole password grant type successfull. But now I want to implement the refresh_token grant. I'm facing a problem by implementing the getRefreshToken function in the models.

If I call the refresh_token route with the grant_type: refresh_token and the refresh_token I'm getting back the error message:

"Invalid grant: refresh token is invalid".

I never check if the refreshToken is valid/expired or not. I just want to implement a dummy function which should return me a new accessToken.

What am I doing wrong?

```<code>getRefreshToken: (refreshToken, callback) => {
    const token = {
        refreshToken: refreshToken,
        client: 'client1',
        user: 'UserIdXY'
    }

    callback(false, token);
}
</code>```

答:
According to the docs you should change client: 'client1', to

```<code>client: {id: 'client1'},
</code>```

Body:
I want to implement the function getRefreshToken with the oauth2-server module in Nodejs. I already implemented the whole password grant type successfull. But now I want to implement the refresh_token grant. I'm facing a problem by implementing the getRefreshToken function in the models.

If I call the refresh_token route with the grant_type: refresh_token and the refresh_token I'm getting back the error message:

"Invalid grant: refresh token is invalid".

I never check if the refreshToken is valid/expired or not. I just want to implement a dummy function which should return me a new accessToken.

What am I doing wrong?

getRefreshToken: (refreshToken, callback) => {
    const token = {
        refreshToken: refreshToken,
        client: 'client1',
        user: 'UserIdXY'
    }

    callback(false, token);
}

Body:
According to the docs you should change client: 'client1', to

client: {id: 'client1'},


问:
Why *this* is not *this*?
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

```<code><html>
<head>
<script type="text/javascript">
var EpisodeFeedParser = function(url){
    this.url = url;
    this.didStartCallback = null;
};
EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
};

var EpisodeController = function(){
    this.episodes = new Array();
    this.parser = null; //lazy
};
EpisodeController.prototype.parserDidStart = function(parser){
    console.log("here *this* is not of type EpisodeController but it is EpisodeFeedParser Why?");
    this.testEpi(); //**********ERROR HERE!***********
};
EpisodeController.prototype.fetchEpisodes = function(urlString){
    if(urlString !== undefined){
        if(parser === undefined){
            var parser = new EpisodeFeedParser(urlString);
            parser.didStartCallback = this.parserDidStart;
            this.parser = parser;
        }
        this.parser.parse();
    }
};
EpisodeController.prototype.testEpi = function(){
console.log("it worked!");
};

function testEpisode(){
    var controller = new EpisodeController();
    controller.fetchEpisodes("myurl");
}
</script>
</head>
<body>
<button type="button" onclick="testEpisode()">press me</button>
</body>
</html>
</code>```

答:
this passed to didStartCallback in

```<code>EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);
</code>```

is of type EpisodeFeedParser

and in EpisodeController.prototype.fetchEpisodes you affect EpisodeController.parserDidStart to parser.didStartCallback:

```<code>parser.didStartCallback = this.parserDidStart;
</code>```

so this.didStartCallback(this); is in fact EpisodeController.parserDidStart(this)

and we saw at the beginning that this last this was of type EpisodeFeedParser.

Q.E.D

Title: Why *this* is not *this*?

Body:
I just wrote this piece of code to represent this error that is killing me (Grrr!)

I wonder why when I get error: method undefined I have checked in Safari and this variable inside parserDidStart() method is not of type EpisodeController it is of type EpisodeFeedParser why is this?

<button type="button" onclick="testEpisode()">press me</button>

Body:
this passed to didStartCallback in

EpisodeFeedParser.prototype.parse = function(doc){
    this.didStartCallback(this);

is of type EpisodeFeedParser

and in EpisodeController.prototype.fetchEpisodes you affect EpisodeController.parserDidStart to parser.didStartCallback:

parser.didStartCallback = this.parserDidStart;

so this.didStartCallback(this); is in fact EpisodeController.parserDidStart(this)

and we saw at the beginning that this last this was of type EpisodeFeedParser.

Q.E.D


问:
Is there a way to pass translatable strings dynamically into an Angular component?
I want to make an Angular component with configurable, translatable input options.

End behavior: I can input a list of objects to a component, and have an option to display translatable strings, based on the values in the component.

<my-component [options]="options"></my-component>

```<code><div class="my-component">
  <div class="option" *ngFor="let option of options">
    <span>{{ option.title }}</span>
  </div>
</div>
</code>```

However, since I'm using Angular's i18n directive, everything translatable needs to be in HTML.

Issue to have this any other way is open since 2016, so safe to say it's not coming soon.

I tried a ng-content approach:

```<code>interface TranslateChildOption {
  title: string;
  i18nTitle: string;
}

translatableOptions: TranslateChildOption[] = [
    { title: 'Jou 1', i18nTitle: 'selector-jou-1'},
    { title: 'Jou 2', i18nTitle: 'selector-jou-2'},
]
</code>```

Inside the parent component:

```<code><translatechild [options]="translatableOptions">
  <span type="selector-jou-1">Bonjou 1</span>
  <span type="selector-jou-2">Bonjou 2</span>
</translatechild>
</code>```

Inside the child component:

```<code><div *ngFor="let item of options">
  <span>{{ item.title }}</span> | <ng-content [select]="item.i18nTitle"></ng-content>
</div>
</code>```

But apparently ng-content is only for static content projection, so can't bind a value to the select property. It's another issue that's open from 2016.

Is there a way to do this (sanely), without resorting to hacky behaviour?

答:
Figured something out. This is a compromise on top of a compromise for passing translatable options via @Input decorator

Everyone who wants translatable options to pass them into a component defines a custom x-translator component

using the let-x="value" syntax the translator is given the type to look for. It's passed into the selector via <ng-template>

Inside the selector component, the passed <ng-template> is retreived and rendered using ngTemplateOutlet and TemplateRef in the *ngFor loop, and given context for the current item at hand, to give the translatable label type to each instance of selector-translator in the *ngFor.

Inside the selector-translator component, the label type inputted does an *ngIf to look for which translatable html string to display

If there's need for any static text, they can be done in html using <ng-content select="[type]='selector-name'" i18n></ng-content>

https://stackblitz.com/edit/angular-i18n-porno

Body:
I want to make an Angular component with configurable, translatable input options.

End behavior: I can input a list of objects to a component, and have an option to display translatable strings, based on the values in the component.

<my-component [options]="options"></my-component>

    {{ option.title }}

However, since I'm using Angular's i18n directive, everything translatable needs to be in HTML.

Issue to have this any other way is open since 2016, so safe to say it's not coming soon.

I tried a ng-content approach:

interface TranslateChildOption {
  title: string;
  i18nTitle: string;
}

translatableOptions: TranslateChildOption[] = [
    { title: 'Jou 1', i18nTitle: 'selector-jou-1'},
    { title: 'Jou 2', i18nTitle: 'selector-jou-2'},
]

Inside the parent component:

<translatechild [options]="translatableOptions">
  Bonjou 1
  Bonjou 2
</translatechild>

Inside the child component:

  {{ item.title }} | <ng-content [select]="item.i18nTitle"></ng-content>

But apparently ng-content is only for static content projection, so can't bind a value to the select property. It's another issue that's open from 2016.

Is there a way to do this (sanely), without resorting to hacky behaviour?


问:
How do merge two branches with related changes into master?
In GIT I have 2 BRANCHES and a MASTER.

BRANCH1 is checked out from master and it have some commits to be merged with master and merging of BRANCH1 will take some time because of some testing reasons.

In that time I've to work on another Branch which is BRANCH2. So BRANCH2 should have the commits of BRANCH1 as I'll do some changes upon BRANCH1's commits, then BRANCH2 will also be merged with MASTER after sometime when BRANCH1 merged with the master (BRANCH1 will be merged first).

checkout from BRANCH1 then do some commits then merge it master after BRANCH1 merged for sometime.

(OR) checkout from MASTER then rebase it with BRANCH1 then do some commits then merge it MASTER.

So What is the best option I can do for working on BRANCH2 with BRANCH1 change then merging it with MASTER?

Any suggestions are welcome and
Thanks...

答:
Whenever you are ready to merge branch2, you should rebase it onto branch1 (if branch1 is not yet merge, or on top of master (if branch1 was already merged)

That way:

you resolve the conflicts locally, by replaying branch2 commits on top of master

the final merge will be a fast-forward (trivial) one.

That is, starting situation:

```<code>m--m--m
       \
        b1 --b1--b1--b1
              \
               b2--b2
</code>```

Once you are ready, b1 might have evolved and been merged to master:

```<code>m--m--m--m--m---------------M--m--m (master)
       \                   /
        b1 --b1--b1--b1--b1         (branch1)
              \
               b2--b2--b2--b2       (branch2)
</code>```

A rebase --onto will be enough:

```<code>git rebase --onto master $(git merge-base branch1 branch2) branch2

m--m--m--m--m---------------M--m--m--b2'--b2'--b2'--b2' (branch2)
       \                   /    (master)
        b1 --b1--b1--b1--b1         (branch1)
</code>```

Then a merge master will be trivial

Body:
Whenever you are ready to merge branch2, you should rebase it onto branch1 (if branch1 is not yet merge, or on top of master (if branch1 was already merged)

That way:

you resolve the conflicts locally, by replaying branch2 commits on top of master

the final merge will be a fast-forward (trivial) one.

That is, starting situation:

m--m--m
       \
        b1 --b1--b1--b1
              \
               b2--b2

Once you are ready, b1 might have evolved and been merged to master:

m--m--m--m--m---------------M--m--m (master)
       \                   /
        b1 --b1--b1--b1--b1         (branch1)
              \
               b2--b2--b2--b2       (branch2)

A rebase --onto will be enough:

git rebase --onto master $(git merge-base branch1 branch2) branch2

m--m--m--m--m---------------M--m--m--b2'--b2'--b2'--b2' (branch2)
       \                   /    (master)
        b1 --b1--b1--b1--b1         (branch1)

Then a merge master will be trivial


问:
Cannot find Chrome binary when executing a selenium (testng) test in jenkins on windows 7
I have a basic login test with selenium and testng. When executed from eclipse, it works as expected and invoke Google Chrome. If executed from TESTNG command line, it works fine too.

This is my @Before:

```<code>@BeforeMethod
public void setUp() throws Exception {
 File file = new File("C:/Selenium-driver/chromedriver.exe");
 System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
 driver = new ChromeDriver();
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }
</code>```

However, if I execute the same test thru Jenkins it says:

```<code>Building in workspace C:\EclipsePortable\Data\workspace\GS_TESTNG
[G_TESTNG] $ cmd /c call C:\Windows\TEMP\hudson9049518275115936054.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>_test_login_cmd.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>cd C:\EclipsePortable\Data\workspace\G_TESTNG

C:\EclipsePortable\Data\workspace\G_TESTNG>java -cp C:\EclipsePortable\Data\workspace\G_TESTNG\lib\*;C:\EclipsePortable\Data\workspace\G_TESTNG\bin org.testng.TestNG testng.xml
...
... TestNG 6.9.9 by Cédric Beust (cedric@beust.com)
...

[TestNG] Running:
  C:\EclipsePortable\Data\workspace\G_TESTNG\testng.xml

Starting ChromeDriver 2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30) on port 36257
Only local connections are allowed.
FAILED CONFIGURATION: @BeforeMethod setUp
org.openqa.selenium.WebDriverException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 664 milliseconds
Build info: version: '2.51.0', revision: '1af067d', time: '2016-02-05 19:15:17'
System info: host: 'NMTLA12810', ip: '192.168.0.179', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_102'
Driver info: org.openqa.selenium.chrome.ChromeDriver
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:159)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:116)
        at com.test.TestA.setUp(TestA.java:33)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
        at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
        at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
        at org.testng.internal.Invoker.invokeMethod(Invoker.java:585)
        at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
        at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
        at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
        at org.testng.TestRunner.privateRun(TestRunner.java:774)
        at org.testng.TestRunner.run(TestRunner.java:624)
        at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
        at org.testng.SuiteRunner.run(SuiteRunner.java:261)
        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
        at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
        at org.testng.TestNG.run(TestNG.java:1048)
        at org.testng.TestNG.privateMain(TestNG.java:1355)
        at org.testng.TestNG.main(TestNG.java:1324)

SKIPPED CONFIGURATION: @AfterClass tearDown
SKIPPED: testGooglePageTitleInChrome

===============================================
    TestNG Test Group
    Tests run: 1, Failures: 0, Skips: 1
    Configuration Failures: 1, Skips: 1
===============================================

===============================================
Main Test Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@7fbe847c: 16 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@759ebb3d: 78 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@ba8a1dc: 59 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@1c655221: 5 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1edf1c96: 16 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
Build step 'Exécuter une ligne de commande batch Windows' marked build as failure
Finished: FAILURE
</code>```

答:
The problem is these lines in your code:

```<code>File file = new File("C:/Selenium-driver/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
</code>```

This is a massive anti-pattern that I regularly see.  The webdriver.chrome.driver environmental variable was designed so that you could install your chromedriver binaries on multiple systems in different places, and then set the environmental variable on each system so that if a selenium test is ever run on that system it will automatically pick up the location of the binary.

By hard coding this environmental variable via code you are ignoring any preconfigured environmental variable that was set up when the build agent was built, you are not using it in the way it was intended.

If you insist on doing it this way you should always check to see if the env variable is already set before you set it, this way you will not overwrite the existing env variable.  You will also need to make sure that the file path you have hard coded exists on your build agent (the secondary cause of your error is that it doesn't) so that if the env variable isn't set, you are actually setting a valid path to the chromedriver binary.

Body:
I have a basic login test with selenium and testng. When executed from eclipse, it works as expected and invoke Google Chrome. If executed from TESTNG command line, it works fine too.

This is my @Before:

@BeforeMethod
public void setUp() throws Exception {
 File file = new File("C:/Selenium-driver/chromedriver.exe");
 System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
 driver = new ChromeDriver();
 driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 }

However, if I execute the same test thru Jenkins it says:

Building in workspace C:\EclipsePortable\Data\workspace\GS_TESTNG
[G_TESTNG] $ cmd /c call C:\Windows\TEMP\hudson9049518275115936054.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>_test_login_cmd.bat

C:\EclipsePortable\Data\workspace\G_TESTNG>cd C:\EclipsePortable\Data\workspace\G_TESTNG

C:\EclipsePortable\Data\workspace\G_TESTNG>java -cp C:\EclipsePortable\Data\workspace\G_TESTNG\lib\*;C:\EclipsePortable\Data\workspace\G_TESTNG\bin org.testng.TestNG testng.xml
...
... TestNG 6.9.9 by Cédric Beust (cedric@beust.com)
...

[TestNG] Running:
  C:\EclipsePortable\Data\workspace\G_TESTNG\testng.xml

Starting ChromeDriver 2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30) on port 36257
Only local connections are allowed.
FAILED CONFIGURATION: @BeforeMethod setUp
org.openqa.selenium.WebDriverException: unknown error: cannot find Chrome binary
  (Driver info: chromedriver=2.26.436362 (5476ec6bf7ccbada1734a0cdec7d570bb042aa30),platform=Windows NT 6.1.7601 SP1 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 664 milliseconds
Build info: version: '2.51.0', revision: '1af067d', time: '2016-02-05 19:15:17'
System info: host: 'NMTLA12810', ip: '192.168.0.179', os.name: 'Windows 7', os.arch: 'amd64', os.version: '6.1', java.version: '1.8.0_102'
Driver info: org.openqa.selenium.chrome.ChromeDriver
        at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
        at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
        at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
        at java.lang.reflect.Constructor.newInstance(Unknown Source)
        at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
        at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
        at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:678)
        at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:249)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
        at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:144)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:170)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:159)
        at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:116)
        at com.test.TestA.setUp(TestA.java:33)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
        at java.lang.reflect.Method.invoke(Unknown Source)
        at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
        at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
        at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
        at org.testng.internal.Invoker.invokeMethod(Invoker.java:585)
        at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:816)
        at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1124)
        at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
        at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:108)
        at org.testng.TestRunner.privateRun(TestRunner.java:774)
        at org.testng.TestRunner.run(TestRunner.java:624)
        at org.testng.SuiteRunner.runTest(SuiteRunner.java:359)
        at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:354)
        at org.testng.SuiteRunner.privateRun(SuiteRunner.java:312)
        at org.testng.SuiteRunner.run(SuiteRunner.java:261)
        at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
        at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
        at org.testng.TestNG.runSuitesSequentially(TestNG.java:1215)
        at org.testng.TestNG.runSuitesLocally(TestNG.java:1140)
        at org.testng.TestNG.run(TestNG.java:1048)
        at org.testng.TestNG.privateMain(TestNG.java:1355)
        at org.testng.TestNG.main(TestNG.java:1324)

SKIPPED CONFIGURATION: @AfterClass tearDown
SKIPPED: testGooglePageTitleInChrome

===============================================
    TestNG Test Group
    Tests run: 1, Failures: 0, Skips: 1
    Configuration Failures: 1, Skips: 1
===============================================

===============================================
Main Test Suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================

[TestNG] Time taken by org.testng.reporters.JUnitReportReporter@7fbe847c: 16 ms
[TestNG] Time taken by org.testng.reporters.jq.Main@759ebb3d: 78 ms
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter@ba8a1dc: 59 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter@1c655221: 5 ms
[TestNG] Time taken by org.testng.reporters.EmailableReporter2@1edf1c96: 16 ms
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 0 ms
Build step 'Exécuter une ligne de commande batch Windows' marked build as failure
Finished: FAILURE

Body:
The problem is these lines in your code:

File file = new File("C:/Selenium-driver/chromedriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());

This is a massive anti-pattern that I regularly see.  The webdriver.chrome.driver environmental variable was designed so that you could install your chromedriver binaries on multiple systems in different places, and then set the environmental variable on each system so that if a selenium test is ever run on that system it will automatically pick up the location of the binary.

By hard coding this environmental variable via code you are ignoring any preconfigured environmental variable that was set up when the build agent was built, you are not using it in the way it was intended.

If you insist on doing it this way you should always check to see if the env variable is already set before you set it, this way you will not overwrite the existing env variable.  You will also need to make sure that the file path you have hard coded exists on your build agent (the secondary cause of your error is that it doesn't) so that if the env variable isn't set, you are actually setting a valid path to the chromedriver binary.


问:
Is it possible to compile go code without builtin library that can run on a machine without operating system
Like C compile flags -fno-pic -O -nostdinc -c -static -fno-builtin -fno-strict-aliasing -m32 -fno-stack-protector can compile codes into pure ELF without library rely on unique system. Is there a possible way GO can do that?

答:
Simple answer is no. Go relies on the operating system (Windows, linux, macOS, BSD). Go has a runtime designed to work on specific environments https://github.com/golang/go/wiki/MinimumRequirements.

There are some open source projects that will help you achieve it, but I wouldn't put them in production as they support a limited number of hardware chips and they are not supported in the same way as the standard library. Some examples are:

https://github.com/ziutek/emgo

https://github.com/tinygo-org/tinygo

These frameworks/libraries will help you run Go code on bare metal.


问:
Compile-time wildcards in cmake install targets
I'm new to cmake and I'm finding it very frustrating. I am trying to use wildcards in file paths that are evaluated when the build runs, not when the build is generated.

I have created a build that uses SWIG to generate Java wrappers for some C++ code. I can write the commands to generate the native code, compile it, and produce a working shared library, and even use the INSTALL command to install that shared library correctly. What I can't figure out how to do is to write an INSTALL command that can copy all *.java files generated by SWIG into that same install location.

It seems that cmake's FILE GLOB command does the globbing when cmake is executed, and not when the build actually runs. Of course, when cmake is executed, SWIG hasn't run yet, and the Java files don't exist.

Is there a way to do what I want? Am I going about things wrong? It seems like this is such a fundamental part of what Makefiles need to do, I'm really surprised not to find an easy way to do it.

答:
you can use install(SCRIPT swigInstaller.cmake) or install(DIRECTORY) both of which supports doing file globing at install time. You can read more about the install command at:

http://cmake.org/cmake/help/cmake-2-8-docs.html#command:install


问:
Adjust cite format and style in RMarkdown
I hope you are having a great time. I am working on RMarkdown for a report and I would like to ask a style related question. I am running the next code in a .Rmd file:

```<code>---
bibliography: bb.bib
fontsize: 11pt
nocite: '@*'
output: pdf_document
link-citations: true
---
\newpage

\section{Testing}\label{sec1}
```{r}
summary(cars)
```
\section{Demo}
This was done using @shiina and we will use some info from Section \ref{sec1} to do.
```{r}
summary(iris)
```
\section{References}
</code>```

Everything is working fine, and I get this:

In previous graph in circle is a citation I did but I would like to change the style. In this case, only the year makes hyperlink to bibliography while the autor part Shiina and Birge does not link to bibliography.

Is it possible to adjust the style of citation so that I can have this: Shiina and Birge, 2004 with both the autor and year linked to bibliography. Or would it be possible something like this: [Shiina and Birge, 2004] because RMarkdown uses () instead of []. I do not how to set that style in RMarkdown.

The content of bb.bib file is the next:

```<code>@article {shiina,
author = {Shiina, Takayuki and Birge, John R.},
title = {Stochastic unit commitment problem},
journal = {International Transactions in Operational Research},
volume = {11},
number = {1},
publisher = {Blackwell Publishing},
pages = {19--32},
year = {2004},
}

@book{groewe2001,
  title={Stochastic unit commitment in hydro-thermal power production planning},
  author={Gr{\"o}we-Kuska, N. and R{\"o}misch, W.},
  year={2001},
  series = { Preprints aus dem Institut f{\"u}r Mathematik },
  publisher = { Humboldt-Universit{\"a}t zu Berlin, Institut f{\"u}r Mathematik },
}
</code>```

Many thanks for your help.

答:
You can add a csl field to your YAML header as a link to a csl file which defines the style:

```<code>---
bibliography: bb.bib
fontsize: 11pt
nocite: '@*'
csl: cslfilename.csl
output: pdf_document
link-citations: true
---
</code>```

See here for further examples. There is a long list of csl files on Github and all of them are modifiable.

Body:
I hope you are having a great time. I am working on RMarkdown for a report and I would like to ask a style related question. I am running the next code in a .Rmd file:

---
bibliography: bb.bib
fontsize: 11pt
nocite: '@*'
output: pdf_document
link-citations: true
---
\newpage

\section{Testing}\label{sec1}
```{r}
summary(cars)
```
\section{Demo}
This was done using @shiina and we will use some info from Section \ref{sec1} to do.
```{r}
summary(iris)
```
\section{References}

Everything is working fine, and I get this:

In previous graph in circle is a citation I did but I would like to change the style. In this case, only the year makes hyperlink to bibliography while the autor part Shiina and Birge does not link to bibliography.

Is it possible to adjust the style of citation so that I can have this: Shiina and Birge, 2004 with both the autor and year linked to bibliography. Or would it be possible something like this: [Shiina and Birge, 2004] because RMarkdown uses () instead of []. I do not how to set that style in RMarkdown.

The content of bb.bib file is the next:

@article {shiina,
author = {Shiina, Takayuki and Birge, John R.},
title = {Stochastic unit commitment problem},
journal = {International Transactions in Operational Research},
volume = {11},
number = {1},
publisher = {Blackwell Publishing},
pages = {19--32},
year = {2004},
}

@book{groewe2001,
  title={Stochastic unit commitment in hydro-thermal power production planning},
  author={Gr{\"o}we-Kuska, N. and R{\"o}misch, W.},
  year={2001},
  series = { Preprints aus dem Institut f{\"u}r Mathematik },
  publisher = { Humboldt-Universit{\"a}t zu Berlin, Institut f{\"u}r Mathematik },
}

Many thanks for your help.

Body:
You can add a csl field to your YAML header as a link to a csl file which defines the style:

---
bibliography: bb.bib
fontsize: 11pt
nocite: '@*'
csl: cslfilename.csl
output: pdf_document
link-citations: true
---

See here for further examples. There is a long list of csl files on Github and all of them are modifiable.


问:
How do I turn off the mysql password validation?
It seems that I may have inadvertently loaded the password validation plugin in MySQL 5.7. This plugin seems to force all passwords to comply to certain rules.

I would like to turn this off.

I've tried changing the validate_password_length variable as suggested here to no avail.

```<code>mysql> SET GLOBAL validate_password_length=4;
Query OK, 0 rows affected (0.00 sec)

mysql> SET PASSWORD FOR 'app' = PASSWORD('abcd');
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
</code>```

I would like to either unload the plugin or neuter it somehow.

答:
Uninstall:

```<code>mysql> uninstall plugin validate_password;
</code>```

An uninstalled plugin is not displayed by show plugins;

Install:

```<code>mysql> install plugin validate_password SONAME 'validate_password.so';
</code>```

Disabled by configuration:

```<code>[mysqld]
validate_password = OFF
</code>```

A plugin can be disabled by configuration only if installed.

Body:
It seems that I may have inadvertently loaded the password validation plugin in MySQL 5.7. This plugin seems to force all passwords to comply to certain rules.

I would like to turn this off.

I've tried changing the validate_password_length variable as suggested here to no avail.

mysql> SET GLOBAL validate_password_length=4;
Query OK, 0 rows affected (0.00 sec)

mysql> SET PASSWORD FOR 'app' = PASSWORD('abcd');
ERROR 1819 (HY000): Your password does not satisfy the current policy requirements

I would like to either unload the plugin or neuter it somehow.

Body:
Uninstall:

mysql> uninstall plugin validate_password;

An uninstalled plugin is not displayed by show plugins;

Install:

mysql> install plugin validate_password SONAME 'validate_password.so';

Disabled by configuration:

[mysqld]
validate_password = OFF

A plugin can be disabled by configuration only if installed.


问:
Accessing namespace Within XML to parse the correct data PHP/Laravel
I'm currently trying to parse some sweet sweet XML, only to realise that i have no idea how to access the namespacing, i need to parse the English.

is anyone so kind a to help a brother out x

link to xml = https://xml.inmobalia.com/361/e55d03759a1004da29b3e364faaff2e1.xml

for example

```<code><property>
    <descriptions>
        <property_desc lang="en">
        </property_desc>
        <property_desc lang="es">
        </property_desc>
    </descriptions>
</property>
</code>```

PHP - here what I've tried

```<code>foreach ($data as $key => $val) {
    $filterd[$key]['main_advert_1'] = json_encode([
        "main_advert" => (isset($val['descriptions']['long_description']['en'])
            and !empty($val['descriptions']['long_description']['en'])
        )
        ? $val['descriptions']['long_description']['en'] : "N.A"]);
}
</code>```

答:
No idea whether Laravel has it's own methods for dealing with XML but using the vanilla DOMDocument and DOMXPath in PHP it is a simple task to extract the desired items.

The below loads a locally saved copy of the XML data - but you could use the url instead in the call $dom->load( $url ) etc

```<code><?php
    $file='c:/wwwroot/files/xml/e55d03759a1004da29b3e364faaff2e1.xml';
    define('br','<br />');

    libxml_use_internal_errors( true );
    $dom=new DOMDocument;
    $dom->validateOnParse=false;
    $dom->recover=true;
    $dom->strictErrorChecking=false;
    $dom->load( $file );
    libxml_clear_errors();

    $xp=new DOMXPath( $dom );
    $col=$xp->query('//descriptions/long_description[@lang="en"]');

    if( $col->length > 0 ){
        foreach( $col as $node )echo $node->tagName . ' ' .$node->nodeValue . br;
    }
?>
</code>```

Body:
I'm currently trying to parse some sweet sweet XML, only to realise that i have no idea how to access the namespacing, i need to parse the English.

is anyone so kind a to help a brother out x

link to xml = https://xml.inmobalia.com/361/e55d03759a1004da29b3e364faaff2e1.xml

for example

<property>
    <descriptions>
        <property_desc lang="en">
        </property_desc>
        <property_desc lang="es">
        </property_desc>
    </descriptions>
</property>

PHP - here what I've tried

foreach ($data as $key => $val) {
    $filterd[$key]['main_advert_1'] = json_encode([
        "main_advert" => (isset($val['descriptions']['long_description']['en'])
            and !empty($val['descriptions']['long_description']['en'])
        )
        ? $val['descriptions']['long_description']['en'] : "N.A"]);
}

Body:
No idea whether Laravel has it's own methods for dealing with XML but using the vanilla DOMDocument and DOMXPath in PHP it is a simple task to extract the desired items.

The below loads a locally saved copy of the XML data - but you could use the url instead in the call $dom->load( $url ) etc

<?php
    $file='c:/wwwroot/files/xml/e55d03759a1004da29b3e364faaff2e1.xml';
    define('br','<br />');

    libxml_use_internal_errors( true );
    $dom=new DOMDocument;
    $dom->validateOnParse=false;
    $dom->recover=true;
    $dom->strictErrorChecking=false;
    $dom->load( $file );
    libxml_clear_errors();

    $xp=new DOMXPath( $dom );
    $col=$xp->query('//descriptions/long_description[@lang="en"]');

    if( $col->length > 0 ){
        foreach( $col as $node )echo $node->tagName . ' ' .$node->nodeValue . br;
    }
?>


问:
Get  Title and Print as caption using javascript
I have the following function to take the title of a.preview and append it inside of p#preview, some AJAX content which is generated on hover.  This is a small piece of what's happening overall, but the variable c in the following script should be the title of a.preview.  For some reason, I'm getting a null response.  The title is printing elsewhere so I know that's not the problem, it's either in the variable definition or in the calling of the variable.  Any debug suggestions?

```<code>$("a.preview").hover(function(e){
    this.t = this.title;
    this.title = "";
    var c = (this.t != "") ? "<br/>" + this.t : "";
    $("body").append("<p id='preview'><img src='"+ this.href +"' alt='Image preview ... Loading' />"+ c +"</p>");
    $("#preview")
            .hide()
        .css("top",(e.pageY - yOffset) + "px")
        .css("left",(e.pageX + xOffset) + "px")
        .fadeIn("2000");
},
</code>```

答:
Have a look at this on Fiddle:
http://jsfiddle.net/jsNcn/

Looks fine to me?

Title: Get <a> Title and Print as caption using javascript

Body:
I have the following function to take the title of a.preview and append it inside of p#preview, some AJAX content which is generated on hover.  This is a small piece of what's happening overall, but the variable c in the following script should be the title of a.preview.  For some reason, I'm getting a null response.  The title is printing elsewhere so I know that's not the problem, it's either in the variable definition or in the calling of the variable.  Any debug suggestions?

$("a.preview").hover(function(e){
    this.t = this.title;
    this.title = "";
    var c = (this.t != "") ? "
" + this.t : "";
    $("body").append("
"+ c +"
");
    $("#preview")
            .hide()
        .css("top",(e.pageY - yOffset) + "px")
        .css("left",(e.pageX + xOffset) + "px")
        .fadeIn("2000");
},


问:
How to capture images and attach them to Cucumber Reports (Jenkins) using Selenium Hub, Node and Remote Webdriver?
Currently I'm triggering my automation tests in the cloud using a Ubuntu instance.

The Ubuntu instance has a Jenkins instance running and also Selenium Hub and Node. It seems the screenshot images dont get saved within the builds\3\cucumber-html-reports\embeddings on a ubuntu system however on a windows system this issue does not exist.

I have currently added the below logic to capture and attach images to the Jenkins Cucumber reports however currently the images are not getting attached to the reports:

```<code>@After
public void after(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            WebDriver augmentedDriver = new Augmenter().augment(getDriver());
            byte[] s = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.BYTES);
            scenario.embed(s, "image/png");
</code>```

Example Report (Generated in Jenkins), please note the images are getting saved and attached to the reports when running the tests locally.

答:
I do not have direct answer for ubuntu problem. But, try adding path of captured images to your cucumber report as html links.</p>

```<code>@After
public void after(Scenario scenario){
   if (scenario.isFailed()) {
        try {
            WebDriver augmentedDriver = new Augmenter().augment(getDriver());
            File path = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(path,new File(localRepoPath));
            String html = "<html><body><a href=\">" + localRepoPath + "\"> screenshot </a></body></html>";
            scenario.embed(html.getBytes(), "text/html");
       }catch(Exception e){
          // Do Something
       }
  }
}
</code>```

Body:
Currently I'm triggering my automation tests in the cloud using a Ubuntu instance.

The Ubuntu instance has a Jenkins instance running and also Selenium Hub and Node. It seems the screenshot images dont get saved within the builds\3\cucumber-html-reports\embeddings on a ubuntu system however on a windows system this issue does not exist.

I have currently added the below logic to capture and attach images to the Jenkins Cucumber reports however currently the images are not getting attached to the reports:

@After
public void after(Scenario scenario) {
    if (scenario.isFailed()) {
        try {
            WebDriver augmentedDriver = new Augmenter().augment(getDriver());
            byte[] s = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.BYTES);
            scenario.embed(s, "image/png");

Example Report (Generated in Jenkins), please note the images are getting saved and attached to the reports when running the tests locally.

Body:
I do not have direct answer for ubuntu problem. But, try adding path of captured images to your cucumber report as html links.

@After
public void after(Scenario scenario){
   if (scenario.isFailed()) {
        try {
            WebDriver augmentedDriver = new Augmenter().augment(getDriver());
            File path = ((TakesScreenshot)augmentedDriver).getScreenshotAs(OutputType.FILE);
            FileUtils.copyFile(path,new File(localRepoPath));
            String html = "<html><body><a href=\">" + localRepoPath + "\"> screenshot </a></body></html>";
            scenario.embed(html.getBytes(), "text/html");
       }catch(Exception e){
          // Do Something
       }
  }
}


问:
Why doesn't document.addEventListener('load', function) work in a greasemonkey script?
It doesn't give an error, and I put a console.log('loaded userscript wifi-autologin'), the console.log works, but the intended effect of the document.addEventListener doesn't happen. After doing a bit more debugging, making it print that the addEventListener was called, I discovered that it wasn't being called.

Source of script:

```<code>// ==UserScript==
// @name        wifi-autologin
// @namespace   lf-ns
// @description Hopefully autologins to a captive portal
// @include     *://1.1.1.1/*
// @version     1
// @run-at document-end
// ==/UserScript==

document.addEventListener('load', submitAction);
</code>```

答:
To get the value of my drop down box on page load, I use

```<code>document.addEventListener('DOMContentLoaded',fnName);
</code>```

Hope this helps some one.

Body:
It doesn't give an error, and I put a console.log('loaded userscript wifi-autologin'), the console.log works, but the intended effect of the document.addEventListener doesn't happen. After doing a bit more debugging, making it print that the addEventListener was called, I discovered that it wasn't being called.

Source of script:

// ==UserScript==
// @name        wifi-autologin
// @namespace   lf-ns
// @description Hopefully autologins to a captive portal
// @include     *://1.1.1.1/*
// @version     1
// @run-at document-end
// ==/UserScript==

document.addEventListener('load', submitAction);

Body:
To get the value of my drop down box on page load, I use

document.addEventListener('DOMContentLoaded',fnName);

Hope this helps some one.


问:
AttributeError: 'list' object has no attribute 'h3' ( Beautifulsoup )
I am a beginner in Web-scraping and I am following this tutorial ( https://www.dataquest.io/blog/web-scraping-beautifulsoup/ ) to extract movie data, I think that I have badly defined " first_movie " !

this is the code

```<code>  from requests import get
  from bs4 import BeautifulSoup

  first_movie =[]

  url = 'http://www.imdb.com/search/title?
  release_date=2017&sort=num_votes,desc&page=1'
  response = get(url)
  html_soup = BeautifulSoup(response.text, 'html.parser')
  type(html_soup)

  movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

  first_name = first_movie.h3.a.text
</code>```

I get this error :

```<code>Traceback (most recent call last):
File "mov1.py", line 13, in <module>
first_name = first_movie.h3.a.text
AttributeError: 'list' object has no attribute 'h3'
</code>```

答:
find_all always returns a list.

Replace your code :

```<code>first_name = first_movie.h3.a.text
</code>```

To

```<code>for movie in movie_containers:
  print(movie.find("h3").find("a").text)
</code>```

O/P:

```<code>Valerian and the City of a Thousand Planets
Baywatch
Darkest Hour
American Made
La Casa de Papel
Mindhunter
Transformers: The Last Knight
The Handmaid's Tale
The Lego Batman Movie
The Disaster Artist
</code>```

Body:
I am a beginner in Web-scraping and I am following this tutorial ( https://www.dataquest.io/blog/web-scraping-beautifulsoup/ ) to extract movie data, I think that I have badly defined " first_movie " !

this is the code

  from requests import get
  from bs4 import BeautifulSoup

  first_movie =[]

  url = 'http://www.imdb.com/search/title?
  release_date=2017&sort=num_votes,desc&page=1'
  response = get(url)
  html_soup = BeautifulSoup(response.text, 'html.parser')
  type(html_soup)

  movie_containers = html_soup.find_all('div', class_ = 'lister-item mode-advanced')

  first_name = first_movie.h3.a.text

I get this error :

Traceback (most recent call last):
File "mov1.py", line 13, in <module>
first_name = first_movie.h3.a.text
AttributeError: 'list' object has no attribute 'h3'

Body:
find_all always returns a list.

Replace your code :

first_name = first_movie.h3.a.text

To

for movie in movie_containers:
  print(movie.find("h3").find("a").text)

O/P:

Valerian and the City of a Thousand Planets
Baywatch
Darkest Hour
American Made
La Casa de Papel
Mindhunter
Transformers: The Last Knight
The Handmaid's Tale
The Lego Batman Movie
The Disaster Artist


问:
Is it possible to have icon centered in constraint layout unless overlapping textview
I am trying to keep an icon centered inside a constraint layout while making it always stay over some text view that is on the bottom of the constraint layout (this is a very simplified version of my actual issue but represents the problem equally). The text in the bottom can be large enough to go over the center of the layout, in which case I want the icon to be shifted upwards.

In order to relate the icon's bottom to both the center and the text view's top, I am using a guideline in the center of the layout and a barrier to catch the top of the text view or the top of the guideline, whichever is higher.

The problem is that half the icon is under the guideline so the text still is overlapped by the icon. And the icon only shifts upward when the text view's top goes over the guideline. Alternatively, I can set the bottom of the icon on top of the guideline, so the text view is never overlapped, but the icon is not exactly centered.

This is the current status of the layout with all the items:

```<code><androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_play"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/barrier"
        app:layout_constraintBottom_toBottomOf="@id/barrier"
        />

    <androidx.constraintlayout.widget.Barrier
        android:id="@+id/barrier"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:barrierDirection="top"
        app:constraint_referenced_ids="guide,text" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guide"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Possimus nulla molestias maxime. Distinctio perferendis veniam modi sint numquam dolores esse. Minus consequuntur mollitia asperiores praesentium non minus. Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Et dolor sit voluptatem fugit."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

I found a (not great) solution, which is adding top padding to the text view half the size of the image view. I would prefer to avoid such a hack and find a good implementation instead. Is it possible?

To help understand the issue, here are some images from the UI designer in Android Studio:

The hopeful result with short text:

Which causes problems when text is long:

If an icon is not centered when the text is short:

We don't get the problem when the text is long:

答:
Set the paddingTop of TextView to the half of ImageView

```<code><TextView
    android:id="@+id/text"
    android:paddingTop="20dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Possimus nulla molestias maxime. Distinctio perferendis veniam modi sint numquam dolores esse. Minus consequuntur mollitia asperiores praesentium non minus. Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Et dolor sit voluptatem fugit."
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>
</code>```

Body:
I am trying to keep an icon centered inside a constraint layout while making it always stay over some text view that is on the bottom of the constraint layout (this is a very simplified version of my actual issue but represents the problem equally). The text in the bottom can be large enough to go over the center of the layout, in which case I want the icon to be shifted upwards.

In order to relate the icon's bottom to both the center and the text view's top, I am using a guideline in the center of the layout and a barrier to catch the top of the text view or the top of the guideline, whichever is higher.

The problem is that half the icon is under the guideline so the text still is overlapped by the icon. And the icon only shifts upward when the text view's top goes over the guideline. Alternatively, I can set the bottom of the icon on top of the guideline, so the text view is never overlapped, but the icon is not exactly centered.

This is the current status of the layout with all the items:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_play"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/barrier"
        app:layout_constraintBottom_toBottomOf="@id/barrier"
        />

    <androidx.constraintlayout.widget.Barrier
        android:id="@+id/barrier"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:barrierDirection="top"
        app:constraint_referenced_ids="guide,text" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guide"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Possimus nulla molestias maxime. Distinctio perferendis veniam modi sint numquam dolores esse. Minus consequuntur mollitia asperiores praesentium non minus. Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Et dolor sit voluptatem fugit."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

I found a (not great) solution, which is adding top padding to the text view half the size of the image view. I would prefer to avoid such a hack and find a good implementation instead. Is it possible?

To help understand the issue, here are some images from the UI designer in Android Studio:

The hopeful result with short text:

Which causes problems when text is long:

If an icon is not centered when the text is short:

We don't get the problem when the text is long:

Body:
Set the paddingTop of TextView to the half of ImageView

<TextView
    android:id="@+id/text"
    android:paddingTop="20dp"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Possimus nulla molestias maxime. Distinctio perferendis veniam modi sint numquam dolores esse. Minus consequuntur mollitia asperiores praesentium non minus. Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Et dolor sit voluptatem fugit."
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"/>


问:
'FirebaseCore/FirebaseCore.h' file not found in RNFIRMessaging.h
In Podfile, when using use_frameworks! globally to integrate swift pods in my react native project, Firebase pod files starts giving error
Firebase pods:-

```<code>pod 'Firebase'
pod 'Firebase/Messaging'
</code>```

Error :-

'FirebaseCore/FirebaseCore.h' file not found in RNFIRMessaging.h

issue gets resolved when comment out use_frameworks! in podfile but then i am unable to install swift pods. also tried :modular_headers => true for specific swift pods but pod file is not installing.

Swift pods i am trying to install are :-

```<code> pod 'Kite-Print-SDK'
 pod 'PayPal-iOS-SDK/Core'
</code>```

please help me out to resolve this issue..

答:
I actually had a similar problem,
my solution was to change the code manually wherever there was that error.

change

```<code>import <FirebaseCore/FirebaseCore.h>
</code>```

to

```<code>import <FirebaseCore.h>
</code>```

Body:
In Podfile, when using use_frameworks! globally to integrate swift pods in my react native project, Firebase pod files starts giving error
Firebase pods:-

pod 'Firebase'
pod 'Firebase/Messaging'

Error :-

'FirebaseCore/FirebaseCore.h' file not found in RNFIRMessaging.h

issue gets resolved when comment out use_frameworks! in podfile but then i am unable to install swift pods. also tried :modular_headers => true for specific swift pods but pod file is not installing.

Swift pods i am trying to install are :-

 pod 'Kite-Print-SDK'
 pod 'PayPal-iOS-SDK/Core'

please help me out to resolve this issue..

Body:
I actually had a similar problem,
my solution was to change the code manually wherever there was that error.

change

import <FirebaseCore/FirebaseCore.h>

to

import <FirebaseCore.h>


问:
pandas: how do I select first row in each GROUP BY group?
Basically the same as Select first row in each GROUP BY group? only in pandas.

```<code>df = pd.DataFrame({'A' : ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
                'B' : ['3', '1', '2', '4','2', '4', '1', '3'],
                    })
</code>```

Sorting looks promising:

```<code>df.sort('B')

     A  B
1  foo  1
6  bar  1
2  foo  2
4  bar  2
0  foo  3
7  bar  3
3  foo  4
5  bar  4
</code>```

But then first won't give the desired result...
    df.groupby('A').first()

```<code>     B
A
bar  2
foo  3
</code>```

答:
Use a sort method and then keep the first value using .drop_duplicates() with its keep argument set to 'first' (default). This approach has the benefit that it keeps your index.

Example:

```<code>df.sort_values('B', ascending=True) \
  .drop_duplicates('A', keep='first')
</code>```

Output:

```<code>    A   B
1   foo 1
6   bar 1
</code>```

You don’t need a GroupBy in this case because there is no need to run a calculation on each group (see: split-apply-combine pattern).

Body:
Basically the same as Select first row in each GROUP BY group? only in pandas.

df = pd.DataFrame({'A' : ['foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar'],
                'B' : ['3', '1', '2', '4','2', '4', '1', '3'],
                    })

Sorting looks promising:

df.sort('B')

     A  B
1  foo  1
6  bar  1
2  foo  2
4  bar  2
0  foo  3
7  bar  3
3  foo  4
5  bar  4

But then first won't give the desired result...
    df.groupby('A').first()

     B
A
bar  2
foo  3

Body:
Use a sort method and then keep the first value using .drop_duplicates() with its keep argument set to 'first' (default). This approach has the benefit that it keeps your index.

Example:

df.sort_values('B', ascending=True) \
  .drop_duplicates('A', keep='first')

Output:

    A   B
1   foo 1
6   bar 1

You don’t need a GroupBy in this case because there is no need to run a calculation on each group (see: split-apply-combine pattern).


问:
All data not getting imported from website to excel
I want to import restaurant data like Restaurant name, phone number & website to excel but unfortunately I am getting only one page (first page) however I want data from any range which I define like page-1 to page-3 or page-2 to page-5 in separate sheets for each page. Sample output file is attached of what output I am getting for the time being.

```<code>    Sub Webscraping()
        'Declaration
     Dim ie As InternetExplorer
     Dim ht As HTMLDocument
    'Initialization
     Set ie = New InternetExplorer
     ie.Visible = True

'Open a url
ie.navigate ("https://www.yellowpages.com/atlanta-ga/restaurants")

'Set ht = ie.document
'MsgBox ht.getElementsByClassName("ot_lrp_bname_free_center")

'Alternative Approach for wait

Do Until ie.readyState = READYSTATE_COMPLETE
    DoEvents
Loop

'Initialize the document

Set ht = ie.document

'Set elems = ht.getElementsByClassName("list-title")
Set elems = ht.getElementsByClassName("business-name")
'Set elems = ht.getElementsByClassName("website-lrp icon-link ot_lrp_website_text_free_center")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 1).Value = elem.innerText
    i = i + 1

    'Debug.Print (elem.innerText)
Next

Set elems = ht.getElementsByClassName("phone primary")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 2).Value = elem.innerText
    i = i + 1

   'Debug.Print (elem.innerText)
Next
Set elems = ht.getElementsByClassName("links")
i = 1
For Each elem In elems

    Set link = elem.ChildNodes.Item(0)
    Sheet1.Cells(i, 3).Value = link.href
    i = i + 1
Next

'Set internetdata = ie.document
'Set div_result = internetdata.getElementById("ctl00_gvMain_ctl03_hlTitle")
'Set header_links = div_result.getElementsByTagName("a")
'For Each h In header_links
'Set link = h.ChildNodes.Item(0)
'Worksheets("Stocks").Cells(Range("L" & Rows.Count).End(xlUp).Row + 1, 12) = link.href
 End Sub
</code>```

This is the work which have been done but struggling to get the required ouput

答:
The pages are concatenated onto end of url. I would use xhr issues requests in a loop over given page range and regex out the json which contains the required info (it is in one of the script tags). This method is very fast and more than offsets use of regex. I also re-use objects where possible.

I use jsonconverter.bas to handle the json and parse out required info (there is a lot more info in the json including the reviews). After downloading the .bas and adding to a module called JsonConverter in your project, you need to go VBE > Tools > References > Add reference to Microsoft Scripting Runtime.

Helper functions are used to test whether page to write out to already exists or needs creating, as well as one to write out json results to an array and dump the array out in one go to sheet (efficiency gain). The structure is left so it is easy to extend the retrieved info if more info is desired e.g. the review.

There may be some work to do on ensuring works for pages that don't exist. I have simply used status code of response at present to filter these out.

NOTES:

As a sanity check I would use InternetExplorer to go to page 1 and extract the total results count. I would divide that by results per page (currently 30) to calculate total pages. This would give me lbound and ubound values (min and max for possible pages). Then switch to xmlhttp to actually retrieve. See additional helper function at end.

Code:

```<code>Option Explicit
Public Sub GetRestuarantInfo()
    Dim s As String, re As Object, p As String, page As Long, r As String, json As Object
    Const START_PAGE As Long = 2
    Const END_PAGE As Long = 4
    Const RESULTS_PER_PAGE As Long = 30

    p = "\[{""@context"".*?\]"
    Set re = CreateObject("VBScript.RegExp")

    Application.ScreenUpdating = False

    With CreateObject("MSXML2.XMLHTTP")

        For page = START_PAGE To END_PAGE
            .Open "GET", "https://www.yellowpages.com/atlanta-ga/restaurants?page=" & page, False
            .send
            If .Status = 200 Then
                s = .responseText
                r = GetValue(re, s, p)
                If r <> "Not Found" Then
                    Set json = JsonConverter.ParseJson(r)
                    WriteOutResults page, RESULTS_PER_PAGE, json
                End If
            End If
        Next
    End With
    Application.ScreenUpdating = True
End Sub
Public Sub WriteOutResults(ByVal page As Long, ByVal RESULTS_PER_PAGE As Long, ByVal json As Object)
    Dim sheetName As String, results(), r As Long, headers(), ws As Worksheet
    ReDim results(1 To RESULTS_PER_PAGE, 1 To 3)

    sheetName = "page" & page
    headers = Array("Name", "Website", "Tel")
    If Not WorksheetExists(sheetName) Then
        Set ws = ThisWorkbook.Worksheets.Add
        ws.Name = sheetName
    Else
        ThisWorkbook.Worksheets(sheetName).Cells.ClearContents
    End If
    With ws
        Dim review As Object
        For Each review In json  'collection of dictionaries
            r = r + 1
            results(r, 1) = review("name")
            results(r, 2) = review("url")
            results(r, 3) = review("telephone")
        Next
        .Cells(1, 1).Resize(1, UBound(headers) + 1) = headers
        .Cells(2, 1).Resize(UBound(results, 1), UBound(results, 2)) = results
    End With
End Sub

Public Function GetValue(ByVal re As Object, inputString As String, ByVal pattern As String) As String
'https://regex101.com/r/M9oRON/1
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = pattern
        If .Test(inputString) Then
            GetValue = .Execute(inputString)(0)
        Else
            GetValue = "Not found"
        End If
    End With
End Function

Public Function WorksheetExists(ByVal sName As String) As Boolean  '@Rory https://stackoverflow.com/a/28473714/6241235
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function
</code>```

Helper function to return number of pages

```<code>'VBE > Tools > References: Microsoft Internet Controls
Public Function GetNumberOfPages(ByVal RESULTS_PER_PAGE As Long) As Variant
    Dim ie As Object, totalResults As Long
    On Error GoTo errhand
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = False
        .Navigate2 "https://www.yellowpages.com/atlanta-ga/restaurants?page=1"

        While .Busy Or .readyState < 4: DoEvents: Wend

        With .document
            totalResults = Replace$(Replace$(.querySelector(".pagination  p").innerText, "We found", vbNullString), "results", vbNullString)
            GetNumberOfPages = totalResults / RESULTS_PER_PAGE
            ie.Quit
            Exit Function
        End With
    End With
errhand:
    If Err.Number <> 0 Then
        GetNumberOfPages = CVErr(xlErrNA)
    End If
End Function
</code>```

Regex explanation:

Try it here.

Body:
I want to import restaurant data like Restaurant name, phone number & website to excel but unfortunately I am getting only one page (first page) however I want data from any range which I define like page-1 to page-3 or page-2 to page-5 in separate sheets for each page. Sample output file is attached of what output I am getting for the time being.

    Sub Webscraping()
        'Declaration
     Dim ie As InternetExplorer
     Dim ht As HTMLDocument
    'Initialization
     Set ie = New InternetExplorer
     ie.Visible = True

'Open a url
ie.navigate ("https://www.yellowpages.com/atlanta-ga/restaurants")

'Set ht = ie.document
'MsgBox ht.getElementsByClassName("ot_lrp_bname_free_center")

'Alternative Approach for wait

Do Until ie.readyState = READYSTATE_COMPLETE
    DoEvents
Loop

'Initialize the document

Set ht = ie.document

'Set elems = ht.getElementsByClassName("list-title")
Set elems = ht.getElementsByClassName("business-name")
'Set elems = ht.getElementsByClassName("website-lrp icon-link ot_lrp_website_text_free_center")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 1).Value = elem.innerText
    i = i + 1

    'Debug.Print (elem.innerText)
Next

Set elems = ht.getElementsByClassName("phone primary")

i = 1
For Each elem In elems
    Sheet1.Cells(i, 2).Value = elem.innerText
    i = i + 1

   'Debug.Print (elem.innerText)
Next
Set elems = ht.getElementsByClassName("links")
i = 1
For Each elem In elems

    Set link = elem.ChildNodes.Item(0)
    Sheet1.Cells(i, 3).Value = link.href
    i = i + 1
Next

'Set internetdata = ie.document
'Set div_result = internetdata.getElementById("ctl00_gvMain_ctl03_hlTitle")
'Set header_links = div_result.getElementsByTagName("a")
'For Each h In header_links
'Set link = h.ChildNodes.Item(0)
'Worksheets("Stocks").Cells(Range("L" & Rows.Count).End(xlUp).Row + 1, 12) = link.href
 End Sub

This is the work which have been done but struggling to get the required ouput

Body:
The pages are concatenated onto end of url. I would use xhr issues requests in a loop over given page range and regex out the json which contains the required info (it is in one of the script tags). This method is very fast and more than offsets use of regex. I also re-use objects where possible.

I use jsonconverter.bas to handle the json and parse out required info (there is a lot more info in the json including the reviews). After downloading the .bas and adding to a module called JsonConverter in your project, you need to go VBE > Tools > References > Add reference to Microsoft Scripting Runtime.

Helper functions are used to test whether page to write out to already exists or needs creating, as well as one to write out json results to an array and dump the array out in one go to sheet (efficiency gain). The structure is left so it is easy to extend the retrieved info if more info is desired e.g. the review.

There may be some work to do on ensuring works for pages that don't exist. I have simply used status code of response at present to filter these out.

NOTES:

As a sanity check I would use InternetExplorer to go to page 1 and extract the total results count. I would divide that by results per page (currently 30) to calculate total pages. This would give me lbound and ubound values (min and max for possible pages). Then switch to xmlhttp to actually retrieve. See additional helper function at end.

Code:

Option Explicit
Public Sub GetRestuarantInfo()
    Dim s As String, re As Object, p As String, page As Long, r As String, json As Object
    Const START_PAGE As Long = 2
    Const END_PAGE As Long = 4
    Const RESULTS_PER_PAGE As Long = 30

    p = "\[{""@context"".*?\]"
    Set re = CreateObject("VBScript.RegExp")

    Application.ScreenUpdating = False

    With CreateObject("MSXML2.XMLHTTP")

        For page = START_PAGE To END_PAGE
            .Open "GET", "https://www.yellowpages.com/atlanta-ga/restaurants?page=" & page, False
            .send
            If .Status = 200 Then
                s = .responseText
                r = GetValue(re, s, p)
                If r <> "Not Found" Then
                    Set json = JsonConverter.ParseJson(r)
                    WriteOutResults page, RESULTS_PER_PAGE, json
                End If
            End If
        Next
    End With
    Application.ScreenUpdating = True
End Sub
Public Sub WriteOutResults(ByVal page As Long, ByVal RESULTS_PER_PAGE As Long, ByVal json As Object)
    Dim sheetName As String, results(), r As Long, headers(), ws As Worksheet
    ReDim results(1 To RESULTS_PER_PAGE, 1 To 3)

    sheetName = "page" & page
    headers = Array("Name", "Website", "Tel")
    If Not WorksheetExists(sheetName) Then
        Set ws = ThisWorkbook.Worksheets.Add
        ws.Name = sheetName
    Else
        ThisWorkbook.Worksheets(sheetName).Cells.ClearContents
    End If
    With ws
        Dim review As Object
        For Each review In json  'collection of dictionaries
            r = r + 1
            results(r, 1) = review("name")
            results(r, 2) = review("url")
            results(r, 3) = review("telephone")
        Next
        .Cells(1, 1).Resize(1, UBound(headers) + 1) = headers
        .Cells(2, 1).Resize(UBound(results, 1), UBound(results, 2)) = results
    End With
End Sub

Public Function GetValue(ByVal re As Object, inputString As String, ByVal pattern As String) As String
'https://regex101.com/r/M9oRON/1
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .pattern = pattern
        If .Test(inputString) Then
            GetValue = .Execute(inputString)(0)
        Else
            GetValue = "Not found"
        End If
    End With
End Function

Public Function WorksheetExists(ByVal sName As String) As Boolean  '@Rory https://stackoverflow.com/a/28473714/6241235
    WorksheetExists = Evaluate("ISREF('" & sName & "'!A1)")
End Function

Helper function to return number of pages

'VBE > Tools > References: Microsoft Internet Controls
Public Function GetNumberOfPages(ByVal RESULTS_PER_PAGE As Long) As Variant
    Dim ie As Object, totalResults As Long
    On Error GoTo errhand
    Set ie = CreateObject("InternetExplorer.Application")
    With ie
        .Visible = False
        .Navigate2 "https://www.yellowpages.com/atlanta-ga/restaurants?page=1"

        While .Busy Or .readyState < 4: DoEvents: Wend

        With .document
            totalResults = Replace$(Replace$(.querySelector(".pagination  p").innerText, "We found", vbNullString), "results", vbNullString)
            GetNumberOfPages = totalResults / RESULTS_PER_PAGE
            ie.Quit
            Exit Function
        End With
    End With
errhand:
    If Err.Number <> 0 Then
        GetNumberOfPages = CVErr(xlErrNA)
    End If
End Function

Regex explanation:

Try it here.