问:
"Check your module classpath for missing or conflicting dependencies" is gone when internet is connected
I recently updated to Android Studio version 3.6. When I started a new project the gradle build took some time and I got this error Check your module class-path for missing or conflicting dependencies.
I just randomly turned my internet connection to ON and the error was gone.
Can someone tell me why this would have happened ?

答:
missing or conflicting dependencies

The formar should have happened when your internet connection was off-line. Because Gradle couldn't reach the library, it thought that was missing.


来源: stackexchange

问:
Using the len() function with unicode values
Python newbie here.
I have an excel file with 5000 rows and 1 columns.
I'm importing them into Python and will then use if...else
statements to check for specific conditions.

So my data looks like: (in excel)

```<code>Kansas
Colorado
Missouri
Iowa
New York
New Mexico
mycar
car
thisisacar
...
</code>```

There here is the code to import it into Python and the conditional
statements.

```<code>import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()
sh = wb.sheet_by_index(0)

for item in sh.col(0):
    value = unicode(item.value)
    if value.startswith("car"):
        print value
        if len(value) == 3:
            print value
</code>```

The idea is to print everything with "car", and then print
value when it only has a length of 3.

The if len(value) == 3 doesn't seem to work. help!

答:
Your code doesn't work for mycar and thisisacar.

Maybe you should try something like:

```<code>x = (value.strip() for value in sh.col(0) if 'car' in value)
for i in x:
    print i
    if len(i) == 3:
        print i
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Python newbie here.
I have an excel file with 5000 rows and 1 columns.
I'm importing them into Python and will then use if...else
statements to check for specific conditions.

So my data looks like: (in excel)

Kansas
Colorado
Missouri
Iowa
New York
New Mexico
mycar
car
thisisacar
...

There here is the code to import it into Python and the conditional
statements.

import xlrd
wb = xlrd.open_workbook("file.xls")

wb.sheet_names()
sh = wb.sheet_by_index(0)

for item in sh.col(0):
    value = unicode(item.value)
    if value.startswith("car"):
        print value
        if len(value) == 3:
            print value

The idea is to print everything with "car", and then print
value when it only has a length of 3.

The if len(value) == 3 doesn't seem to work. help!

Body:
Your code doesn't work for mycar and thisisacar.

Maybe you should try something like:

x = (value.strip() for value in sh.col(0) if 'car' in value)
for i in x:
    print i
    if len(i) == 3:
        print i


问:
How to display certain part of chart.js as dotted while rest as bold?
I am new to this.

I want to display the last block of the line chart (from 2020/05/27 to 2020/05/29) as a dotted line with different color as compared to rest of the chart.

In short I want to highlight the last block of the chart readings than the rest.

 var ctx = document.getElementById('myChart').getContext('2d');
        var data_array = [307.65, 309.54, 307.71, 314.96, 313.14, 319.23, 316.85, 318.89, 316.73, 318.11, 319.55];
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['2020/05/13', '2020/05/14', '2020/05/15', '2020/05/18', '2020/05/19', '2020/05/20', '2020/05/21', '2020/05/22', '2020/05/26', '2020/05/27', '2020/05/29'],
                datasets: [{
                    label: 'Count',
                    data: data_array,
                    lineTension: 0,
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                    ],
                    borderWidth: 5
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            min: Math.round(Math.floor(Math.min.apply(this, data_array) - 50)/ 10) * 10,
                            max: Math.round(Math.floor(Math.max.apply(this, data_array) + 50)/ 10) * 10
                        }
                    }]
                }
            }
        });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.min.js"></script>

    <title>CodeWithHarry</title>
</head>

<body>

    <canvas id="myChart" width="1000" height="1000"></canvas>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"
        integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"
        integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy"
        crossorigin="anonymous"></script>
</body>

</html></code>```

PFA the chart screenshot for reference...

Please guide me in the right direction.

答:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the beforeDraw hook to draw lines of different style between different datapoints using text directly on the canvas using CanvasRenderingContext2D.

In case the last data point shall be of different color as well, you can define dataset.borderColor as an array. It should contain an entry for each value, all being identical except the last one. This can be done with Array.map() as follows.

```<code>borderColor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),
</code>```

Please have a look at the runnable code snippet below.

const data_array = [307.65, 309.54, 307.71, 314.96, 313.14, 319.23, 316.85, 318.89, 316.73, 318.11, 319.55];

var myChart = new Chart('myChart', {
  type: 'line',
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      data_array.forEach((value, index) => {
        if (index > 0) {
          var valueFrom = data_array[index - 1];
          var xFrom = xAxis.getPixelForTick(index - 1);
          var yFrom = yAxis.getPixelForValue(valueFrom);
          var xTo = xAxis.getPixelForTick(index);
          var yTo = yAxis.getPixelForValue(value);
          ctx.lineWidth = 5;
          if (index + 1 == data_array.length) {
            ctx.setLineDash([5, 5]);
            ctx.strokeStyle = 'rgb(0, 0, 255)';
          } else {
            ctx.strokeStyle = 'rgb(255, 99, 132)';
          }
          ctx.beginPath();
          ctx.moveTo(xFrom, yFrom);
          ctx.lineTo(xTo, yTo);
          ctx.stroke();
        }
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ['2020/05/13', '2020/05/14', '2020/05/15', '2020/05/18', '2020/05/19', '2020/05/20', '2020/05/21', '2020/05/22', '2020/05/26', '2020/05/27', '2020/05/29'],
    datasets: [{
      label: 'Count',
      data: data_array,
      tension: 0,
      showLine: false,
      borderColor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),
      borderWidth: 5
    }]
  },
  options: {
    animation: {
        duration: 0
    }
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas></code>```

ContentLicense: CC BY-SA 4.0

Body:
I am new to this.

I want to display the last block of the line chart (from 2020/05/27 to 2020/05/29) as a dotted line with different color as compared to rest of the chart.

In short I want to highlight the last block of the chart readings than the rest.

 var ctx = document.getElementById('myChart').getContext('2d');
        var data_array = [307.65, 309.54, 307.71, 314.96, 313.14, 319.23, 316.85, 318.89, 316.73, 318.11, 319.55];
        var myChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['2020/05/13', '2020/05/14', '2020/05/15', '2020/05/18', '2020/05/19', '2020/05/20', '2020/05/21', '2020/05/22', '2020/05/26', '2020/05/27', '2020/05/29'],
                datasets: [{
                    label: 'Count',
                    data: data_array,
                    lineTension: 0,
                    borderColor: [
                        'rgba(255, 99, 132, 1)',
                    ],
                    borderWidth: 5
                }]
            },
            options: {
                scales: {
                    yAxes: [{
                        ticks: {
                            min: Math.round(Math.floor(Math.min.apply(this, data_array) - 50)/ 10) * 10,
                            max: Math.round(Math.floor(Math.max.apply(this, data_array) + 50)/ 10) * 10
                        }
                    }]
                }
            }
        });

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
        integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

    <title>CodeWithHarry</title>

    <canvas id="myChart" width="1000" height="1000"></canvas>

PFA the chart screenshot for reference...

Please guide me in the right direction.

Body:
The Plugin Core API offers a range of hooks that may be used for performing custom code. You can use the beforeDraw hook to draw lines of different style between different datapoints using text directly on the canvas using CanvasRenderingContext2D.

In case the last data point shall be of different color as well, you can define dataset.borderColor as an array. It should contain an entry for each value, all being identical except the last one. This can be done with Array.map() as follows.

borderColor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),

Please have a look at the runnable code snippet below.

const data_array = [307.65, 309.54, 307.71, 314.96, 313.14, 319.23, 316.85, 318.89, 316.73, 318.11, 319.55];

var myChart = new Chart('myChart', {
  type: 'line',
  plugins: [{
    beforeDraw: chart => {
      var ctx = chart.chart.ctx;
      ctx.save();
      var xAxis = chart.scales['x-axis-0'];
      var yAxis = chart.scales['y-axis-0'];
      data_array.forEach((value, index) => {
        if (index > 0) {
          var valueFrom = data_array[index - 1];
          var xFrom = xAxis.getPixelForTick(index - 1);
          var yFrom = yAxis.getPixelForValue(valueFrom);
          var xTo = xAxis.getPixelForTick(index);
          var yTo = yAxis.getPixelForValue(value);
          ctx.lineWidth = 5;
          if (index + 1 == data_array.length) {
            ctx.setLineDash([5, 5]);
            ctx.strokeStyle = 'rgb(0, 0, 255)';
          } else {
            ctx.strokeStyle = 'rgb(255, 99, 132)';
          }
          ctx.beginPath();
          ctx.moveTo(xFrom, yFrom);
          ctx.lineTo(xTo, yTo);
          ctx.stroke();
        }
      });
      ctx.restore();
    }
  }],
  data: {
    labels: ['2020/05/13', '2020/05/14', '2020/05/15', '2020/05/18', '2020/05/19', '2020/05/20', '2020/05/21', '2020/05/22', '2020/05/26', '2020/05/27', '2020/05/29'],
    datasets: [{
      label: 'Count',
      data: data_array,
      tension: 0,
      showLine: false,
      borderColor: data_array.map((v, i) => i + 1 == data_array.length ? 'rgb(0, 0, 255)' : 'rgba(255, 99, 132)'),
      borderWidth: 5
    }]
  },
  options: {
    animation: {
        duration: 0
    }
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart" height="100"></canvas>


问:
How to replace array element with respect to Index on another array
I have one array which contains values array1 = [a,b,c,d,e,f,g] and another array contains index of array1 and the value to be replaced array2 = [[2,u],[3,x],[6,z]].

Now I want to replace value of array1 with respect to array2 please not array2 consist of [array1_position, value_to_be_replaced]

Now my new arra1 should look like this array1 = [a,b,u,x,e,f,z].

I can do this with for loop but its again time consuming. what trick can i use to replace the value quickly. I am just learning about arrays and have a little knowledge on it.

答:
you could do this</p>

```<code>array2.forEach(arr => {
   const [index, replaced] = arr;
   array1[index] = replaced;
});
</code>```

Body:
you could do this

array2.forEach(arr => {
   const [index, replaced] = arr;
   array1[index] = replaced;
});


问:
Records from the table is not displayed in the front end
I am new to Laravel and ReactJS, am trying to achieve a CRUD operation, I am trying to display the 4 rows from the table but am able to insert records into the table but not able to read. Any help is appreciated.
Laravel Framework 7.10.3
PHP 7.4.5
Composer version 1.10.6
Mysql
And following is the code details

DisplayProduct.js

```<code>import React, {Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router';
import TableRow from './TableRow';
import MyGlobleSetting from './MyGlobleSetting';

class DisplayProduct extends Component {
  constructor(props) {
       super(props);
       this.state = {value: '', products: ''};
     }
     componentDidMount(){
       axios.get(MyGlobleSetting.url + '/api/products')
       .then(response => {
         this.setState({ products: response.data });
        console.log(response.data);
        console.log(this.state.products);
       })
       .catch(function (error) {
         console.log(error);
       })
     }

     tabRow(){
       if(this.state.products instanceof Array){
         return this.state.products.map(function(object, i){
            return <TableRow obj={object} key={i} />;
         })
       }
     }

  render(){
    return (
      <div>
        <h1>Products</h1>

        <div className="row">
          <div className="col-md-10"></div>
          <div className="col-md-2">
            <Link to="/add-item">Create Product</Link>
          </div>
        </div><br />

        <table className="table table-hover">
            <thead>
            <tr>
                <td>ID</td>
                <td>Product Title</td>
                <td>Product Body</td>
                <td width="200px">Actions</td>
            </tr>
            </thead>
            <tbody>
          {this.tabRow()}
            </tbody>
        </table>
    </div>
    )
  }
}
export default DisplayProduct;
</code>```

TableRow.js

```<code>import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router';
import axios from 'axios';
import MyGlobleSetting from './MyGlobleSetting';

class TableRow extends Component {
 constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(event) {
    event.preventDefault();
    let uri = MyGlobleSetting.url + `/api/products/${this.props.obj.id}`;
    axios.delete(uri);
      browserHistory.push('/display-item');
  }
  render() {
    return (
        <tr>
          <td>
            {this.props.obj.id}
          </td>
          <td>
            {this.props.obj.title}
          </td>
          <td>
            {this.props.obj.body}
          </td>
          <td>
          <form onSubmit={this.handleSubmit}>
            <Link to={"edit/"+this.props.obj.id} className="btn btn-primary">Edit</Link>
           <input type="submit" value="Delete" className="btn btn-danger"/>
         </form>
          </td>
        </tr>
    );
  }
}

export default TableRow;
</code>```

welcome.blade.php

```<code><!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel ReactJS CRUD Example</title>
         <link href="{{mix('css/app.css')}}" rel="stylesheet" type="text/css">
    </head>
    <body>
        <div id='crud-app'></div>
       <script src="{{mix('js/app.js')}}" ></script>
    </body>
</html>
</code>```

ProductController.php

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::all();
        return response()->json($products);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $product = new Product([
          'title' => $request->get('title'),
          'body' => $request->get('body')
        ]);
        $product->save();

        return response()->json('Product Added Successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = Product::find($id);
        return response()->json($product);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $product = Product::find($id);
        $product->title = $request->get('title');
        $product->body = $request->get('body');
        $product->save();

        return response()->json('Product Updated Successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
      $product = Product::find($id);
      $product->delete();

      return response()->json('Product Deleted Successfully.');
    }
}
?>

</code>```

Master.js

```<code>import React, {Component} from 'react';
import { Router, Route, Link } from 'react-router';

class Master extends Component {
  render(){
    return (
      <div className="container">
        <nav className="navbar navbar-default">
          <div className="container-fluid">
            <div className="navbar-header">
              <a className="navbar-brand" href="/">Products Maintenance</a>
            </div>
            <ul className="nav navbar-nav">
              <li><Link to="/">Home</Link></li>
              <li><Link to="add-item">Create Product</Link></li>
              <li><Link to="display-item">Products</Link></li>
            </ul>
          </div>
      </nav>
          <div>
              {this.props.children}
          </div>
      </div>
    )
  }
}
export default Master
</code>```

app.js

```<code>require('./bootstrap');
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import Master from './components/Master';
import CreateProduct from './components/CreateProduct';
import DisplayProduct from './components/DisplayProduct';
import UpdateProduct from './components/UpdateProduct';

render(
  <Router history={browserHistory}>
      <Route path="/" component={Master} >
        <Route path="/add-item" component={CreateProduct} />
        <Route path="/display-item" component={ DisplayProduct} />
        <Route path="/edit/:id" component={UpdateProduct} />
      </Route>
    </Router>,
        document.getElementById('crud-app'));
</code>```

答:
UPDATED CODE

In your main js file, lets say App.js component you will have a router set already for this link

```<code><li><Link to="display-item">Products</Link></li>
</code>```

The router will looks something like this

```<code><Route path="/display-item" exact component={DisplayProduct} />
</code>```

Include your DisplayProduct.js component and this way when you click products link you will be able to show whole component.

I have used this way and it's working see if it helps you too.

```<code>import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

class App extends Component {
render () {
    return (
        <BrowserRouter>
            <div>
                <Header />
                <Switch>
                    <Route path="/student" exact component={Student} />
                    <Route path="/classes" exact component={Classes} />
                </Switch>
            </div>
        </BrowserRouter>
    )
}
}

if (document.getElementById('app')) {
   ReactDOM.render(<App />, document.getElementById('app'));
}
</code>```

I see in your code that you don't have a
 for rendering in your render method, you need to have it atleast one. Also I think you have included document.getElement.... inside your render method, that may be causing the problem.

Body:
I am new to Laravel and ReactJS, am trying to achieve a CRUD operation, I am trying to display the 4 rows from the table but am able to insert records into the table but not able to read. Any help is appreciated.
Laravel Framework 7.10.3
PHP 7.4.5
Composer version 1.10.6
Mysql
And following is the code details

DisplayProduct.js

import React, {Component} from 'react';
import axios from 'axios';
import { Link } from 'react-router';
import TableRow from './TableRow';
import MyGlobleSetting from './MyGlobleSetting';

class DisplayProduct extends Component {
  constructor(props) {
       super(props);
       this.state = {value: '', products: ''};
     }
     componentDidMount(){
       axios.get(MyGlobleSetting.url + '/api/products')
       .then(response => {
         this.setState({ products: response.data });
        console.log(response.data);
        console.log(this.state.products);
       })
       .catch(function (error) {
         console.log(error);
       })
     }

     tabRow(){
       if(this.state.products instanceof Array){
         return this.state.products.map(function(object, i){
            return <TableRow obj={object} key={i} />;
         })
       }
     }

  render(){
    return (

Products

            <Link to="/add-item">Create Product</Link>

                ID
                Product Title
                Product Body
                Actions

          {this.tabRow()}

    )
  }
}
export default DisplayProduct;

TableRow.js

import React, { Component } from 'react';
import { Link, browserHistory } from 'react-router';
import axios from 'axios';
import MyGlobleSetting from './MyGlobleSetting';

class TableRow extends Component {
 constructor(props) {
      super(props);
      this.handleSubmit = this.handleSubmit.bind(this);
  }
  handleSubmit(event) {
    event.preventDefault();
    let uri = MyGlobleSetting.url + `/api/products/${this.props.obj.id}`;
    axios.delete(uri);
      browserHistory.push('/display-item');
  }
  render() {
    return (

            {this.props.obj.id}

            {this.props.obj.title}

            {this.props.obj.body}

          <form onSubmit={this.handleSubmit}>
            <Link to={"edit/"+this.props.obj.id} className="btn btn-primary">Edit</Link>
           <input type="submit" value="Delete" className="btn btn-danger"/>
         </form>

    );
  }
}

export default TableRow;

welcome.blade.php

<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Laravel ReactJS CRUD Example</title>
         <link href="{{mix('css/app.css')}}" rel="stylesheet" type="text/css">

ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = Product::all();
        return response()->json($products);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $product = new Product([
          'title' => $request->get('title'),
          'body' => $request->get('body')
        ]);
        $product->save();

        return response()->json('Product Added Successfully.');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $product = Product::find($id);
        return response()->json($product);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $product = Product::find($id);
        $product->title = $request->get('title');
        $product->body = $request->get('body');
        $product->save();

        return response()->json('Product Updated Successfully.');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
      $product = Product::find($id);
      $product->delete();

      return response()->json('Product Deleted Successfully.');
    }
}
?>

Master.js

import React, {Component} from 'react';
import { Router, Route, Link } from 'react-router';

class Master extends Component {
  render(){
    return (

              Products Maintenance

<Link to="/">Home</Link>

<Link to="add-item">Create Product</Link>

<Link to="display-item">Products</Link>

              {this.props.children}

    )
  }
}
export default Master

app.js

require('./bootstrap');
import React from 'react';
import { render } from 'react-dom';
import { Router, Route, browserHistory } from 'react-router';
import Master from './components/Master';
import CreateProduct from './components/CreateProduct';
import DisplayProduct from './components/DisplayProduct';
import UpdateProduct from './components/UpdateProduct';

render(
  <Router history={browserHistory}>
      <Route path="/" component={Master} >
        <Route path="/add-item" component={CreateProduct} />
        <Route path="/display-item" component={ DisplayProduct} />
        <Route path="/edit/:id" component={UpdateProduct} />
      </Route>
    </Router>,
        document.getElementById('crud-app'));

Body:
UPDATED CODE

In your main js file, lets say App.js component you will have a router set already for this link

<li><Link to="display-item">Products</Link></li>

The router will looks something like this

<Route path="/display-item" exact component={DisplayProduct} />

Include your DisplayProduct.js component and this way when you click products link you will be able to show whole component.

I have used this way and it's working see if it helps you too.

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'

class App extends Component {
render () {
    return (
        <BrowserRouter>
            <div>
                <Header />
                <Switch>
                    <Route path="/student" exact component={Student} />
                    <Route path="/classes" exact component={Classes} />
                </Switch>
            </div>
        </BrowserRouter>
    )
}
}

if (document.getElementById('app')) {
   ReactDOM.render(<App />, document.getElementById('app'));
}

I see in your code that you don't have a <div> for rendering in your render method, you need to have it atleast one. Also I think you have included document.getElement.... inside your render method, that may be causing the problem.


问:
Tensorflow 2.0 (Keras) classification with restricted classes

Problem background

I have a basic classification problem, classifying each row into one of 20 classes.

However, there is a twist. For every row, only some of those 20 classes are valid - and this is known upfront.

In tensorflow 1.0, I have been nullifying the logits of the impossible classes. The only modfication is the loss function:

```<code>def getLoss(logits, y, restrictions):
    logits = tf.where(restrictions, -1000.0 * tf.ones_like(y), logits)
    return tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y)

loss = getLoss(logits, y, restrictions)
trainer = tf.train.RMSPropOptimizer(learnRate).minimize(loss)
</code>```

Question

I have a working solution for Tensorflow 1.0, it is a simple muodification of the loss function. However, I want to rewrite it in Tensorflow 2.0 and Keras.

I assume I would need to pass the class restriction matrix into model.fit() along with the inputs. How would I go about doing this?

Suboptimal solution idea

One easy solution (also proposed by Frederik) is to concatenate the input and class restriction matrix, and let the neural network learn the concept of class restriction from scratch.

However, this is not reliable, and makes the neural network unnecessarily bigger. Is there a better, simpler way with Keras?

答:
How does this work at inference time though? Do you know the class restrictions of a new row as well at inference time?

If the answer is "yes":

I think you should not feed the entire class restriction matrix as input, but rather the class restriction vector using concatenation. So instead of feeding a row with shape (n,), you feed row_plus_class_restrictions with shape (n+20,).

```<code>row_feature_0
row_feature_1
...
row_feature_n
0
1
.
.
.
1
</code>```

That way you don't need to nullify any error either, the model will learn what it should output based on the classification loss.

If the answer is "no":

Then your model doesn't make much sense. The training data is a bunch of (row, class_restrictions, class_it_should_be) with dimension (nb_row_features + 20 + 20), is that correct? What are you trying to train - really the practical application - what kind of data is in your rows? I don't understand what you would want if the answer is no.

Body:
Problem background

I have a basic classification problem, classifying each row into one of 20 classes.

However, there is a twist. For every row, only some of those 20 classes are valid - and this is known upfront.

In tensorflow 1.0, I have been nullifying the logits of the impossible classes. The only modfication is the loss function:

def getLoss(logits, y, restrictions):
    logits = tf.where(restrictions, -1000.0 * tf.ones_like(y), logits)
    return tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y)

loss = getLoss(logits, y, restrictions)
trainer = tf.train.RMSPropOptimizer(learnRate).minimize(loss)

Question

I have a working solution for Tensorflow 1.0, it is a simple muodification of the loss function. However, I want to rewrite it in Tensorflow 2.0 and Keras.

I assume I would need to pass the class restriction matrix into model.fit() along with the inputs. How would I go about doing this?

Suboptimal solution idea

One easy solution (also proposed by Frederik) is to concatenate the input and class restriction matrix, and let the neural network learn the concept of class restriction from scratch.

However, this is not reliable, and makes the neural network unnecessarily bigger. Is there a better, simpler way with Keras?

Body:
How does this work at inference time though? Do you know the class restrictions of a new row as well at inference time?

If the answer is "yes":

I think you should not feed the entire class restriction matrix as input, but rather the class restriction vector using concatenation. So instead of feeding a row with shape (n,), you feed row_plus_class_restrictions with shape (n+20,).

row_feature_0
row_feature_1
...
row_feature_n
0
1
.
.
.
1

That way you don't need to nullify any error either, the model will learn what it should output based on the classification loss.

If the answer is "no":

Then your model doesn't make much sense. The training data is a bunch of (row, class_restrictions, class_it_should_be) with dimension (nb_row_features + 20 + 20), is that correct? What are you trying to train - really the practical application - what kind of data is in your rows? I don't understand what you would want if the answer is no.


问:
For which types of problems are genetic algorithms an appropriate choice?
(I've pondered some time over whether this is a good question for a Q&A site. I think it is -- the answers may be partly subjective but I'm hopefully looking for objective criteria in the answers. It may be though that SO is not the best site in the network but let's try here.)

I am asking this question because just recently I have tried to use a genetic algorithm for an optimization problem with a large parameter space, and it failed, i.e. it wasn't improving over time. I switched to simulated annealing and got much better convergence. So either my GA implementation was wrong or it was the wrong tool for the job.

One typical example for an application of a GA is the Travelling Salesman Problem, the genome being the order in which the cities are visited. This makes sense: "Breeding" or "crossover" mixes and rearranges subroutes that are potentially already optimal locally but by changing the order in which these subroutes are visited, the overall efficiency may improve. A similar example would be the knapsack problem.

Another example I have encountered was using a GA to find the maximum of a 2-D function, the genome being the coordinates. This was probably chosen as a simple pedagogical example to focus on how a GA can be implemented, but then again whether a GA is the right choice here in the first place seems less than clear: Breeding just "arbitrarily" swaps coordinates or -- in this implementation -- takes the average of the individual genomes, losing all of the optimization history. Thus to me, this is an example of a problem that is intrinsically not suited for a GA, because mixing genomes (coordinates), which is the core idea of GAs, would not seem beneficial here. And without it, i.e. when reduced to only mutations, a GA is just a random walk in phase space with restarts.

In general, GAs seem to be apt for problems with discrete solution spaces with high combinatorial complexity rather than exploration of continuous phase spaces. What are other aspects to be considered?

答:
Two situations that come to mind where genetic algorithms are useful are these (I'm not an evolutionary computation expert, so feel free to correct me):

Optimization without objectives. Some objective functions result in very irregular loss landscape, so that gradient-based methods only lead to local minima. In that case, it's interesting to explore the space based on "behavioral novelty" or "creativity". See the classical novelty search paper for example. In simple terms, you map sequences of states (of the robot, agent or whatever) to behaviors in a behavior space, and try to uniformly search that behavioral space. Sequences of states are investigated based on how novel they are (e.g. based on their distance to older solutions in behavior space). This is also useful when you are interested in having diverse solutions that perform well relative to their neighbors (e.g.evolving diverse virtual creatures with novelty search and local competition).

Note that here, it makes sense to use genetic algorithms as you have neither objectives nor gradient information. You can't use simulated annealing either as it is tied to a single objective function, and doesn't care about behavioral novelty.

When we're not interested in a single solution, but that we rather want to know which parts of space present a high probability of yielding good solutions. A way to do that is to define a probability distribution with parameters, say, theta and sample from it, then compute an expectation/average over the sampled solutions, and use it's gradient relative to the theta to optimize the distribution (note that this gradient is not relative to the initial search space, where we don't want to computer gradients).


问:
How to cythonize global __builtin__ objects?
I have a problem "cythonizing" a project written in python.

1. A python class (declared in file myclass.py) is instantiated, then "declared global" using setattr(__builtin__...) in file main.py

2. A function declared in a module (file module.py) access this class instance by its global name ("globalclass"), and set some values.

So the question is: How to cythonize a python module referring an object instance by its "global name" definned outside of the module with setattr(__builtin__...) ?

I run python 2.7.15 on windows x86, with Cython 0.29.1.

The code provided below works fine when I run pure python:

python main.py
```

<p><br/>
But cythonizing the file <b>module.py</b> gives me an error: <b>undeclared name not builtin</b> referring the global name of the class instance "globalclass".</p>

<p>Here is the file <b>myclass.pyx</b>, the definition of the class:</p>

<pre class="lang-py prettyprint-override"><code>class Myclass:
    def __init__(self):
        self.value = ''

    def setValue(self,text):
        self.value = text

    def printValue(self):
        print self.value
</code>```

Here is the file module.pyx: this is the file I want to cythonize, but cython says undeclared name not builtin "globalclass":

def setValue():
    globalclass.setValue('test from module.py')
```

<p><br/>
Here is the file <b>main.py</b> (entry point) where the class is instantiated, and "declared global" using setattr(__builtin__...):</p>

<pre class="lang-py prettyprint-override"><code>import __builtin__
from myclass import Myclass
from module import setValue

if __name__ == '__main__':
    myclass = Myclass()
    setattr(__builtin__, 'globalclass', myclass)
    setValue()
    globalclass.printValue()
</code>```

And here is the file setup.py used to cythonize the all:

from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension

cyextensions = [
    Extension(name='myclass', sources=['myclass.pyx']),
    Extension(name='module', sources=['module.pyx']),
    ]

setup(name='test',
      version = '0.0.1',
      description = 'test',
      packages = ['test'],
      ext_modules = cythonize(cyextensions)
)
```

<p>And here is the command I use to cythonize:<br/></p>

<pre class="lang-sh prettyprint-override"><code>python setup.py build_ext --inplace
</code>```

Here is the error message I get when cythonizing:

Error compiling Cython file:
------------------------------------------------------------
...
def setValue():
        globalclass.setValue('test from module.py')^
------------------------------------------------------------

module.pyx:2:1: undeclared name not builtin: globalclass
```

答:
The cython compiler gets the information about python builtins at runtime.

So modifying 'builtins' before / while compiling will solve the problem without taking further action.

  I.e. use sitecustomize, usercustomize or some 'yourname'.pth to
    'import my_builtin_patching_module' for the compile step.
  Make sure the import will take your original .py, not the compiled one,
  otherwise the imported .pyd/.so may be locked, preventing the compiler output.

Body:
I have a problem "cythonizing" a project written in python.

1. A python class (declared in file myclass.py) is instantiated, then "declared global" using setattr(__builtin__...) in file main.py

2. A function declared in a module (file module.py) access this class instance by its global name ("globalclass"), and set some values.

So the question is: How to cythonize a python module referring an object instance by its "global name" definned outside of the module with setattr(__builtin__...) ?

I run python 2.7.15 on windows x86, with Cython 0.29.1.

The code provided below works fine when I run pure python:

python main.py

But cythonizing the file module.py gives me an error: undeclared name not builtin referring the global name of the class instance "globalclass".

Here is the file myclass.pyx, the definition of the class:

class Myclass:
    def __init__(self):
        self.value = ''

    def setValue(self,text):
        self.value = text

    def printValue(self):
        print self.value

Here is the file module.pyx: this is the file I want to cythonize, but cython says undeclared name not builtin "globalclass":

def setValue():
    globalclass.setValue('test from module.py')

Here is the file main.py (entry point) where the class is instantiated, and "declared global" using setattr(__builtin__...):

import __builtin__
from myclass import Myclass
from module import setValue

if __name__ == '__main__':
    myclass = Myclass()
    setattr(__builtin__, 'globalclass', myclass)
    setValue()
    globalclass.printValue()

And here is the file setup.py used to cythonize the all:

from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension

cyextensions = [
    Extension(name='myclass', sources=['myclass.pyx']),
    Extension(name='module', sources=['module.pyx']),
    ]

setup(name='test',
      version = '0.0.1',
      description = 'test',
      packages = ['test'],
      ext_modules = cythonize(cyextensions)
)

And here is the command I use to cythonize:

python setup.py build_ext --inplace

Here is the error message I get when cythonizing:

Error compiling Cython file:
------------------------------------------------------------
...
def setValue():
        globalclass.setValue('test from module.py')^
------------------------------------------------------------

module.pyx:2:1: undeclared name not builtin: globalclass


问:
Guess the number game Python
So, im new to python and i have this challenge: I have to make the Guess the Number game, between me and computer. So this is where im at so far.

```<code>import random

the_number = random.randint(1, 4)
guess = 0

print(the_number)
while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player guess lower...\n")
    elif guess < the_number:
        print("Player guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Player wins!")
        break

    guess = random.randint(1, 100)

    if guess > the_number:
        print("Computer guess lower...\n")
    elif guess < the_number:
        print("Computer guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")
    break

print("Thank you for playing")
</code>```

I wanna know how to make this to not stop until one of us is right?

答:
To get the desired output, you just need to tweak the code a bit, the break in the if statement for the computer is out of the loop of else, so it will stop the execution no matter what.

To counter this condition, you can move the break inside the else block. By doing this, the program will only break if either CPU or you correctly guess the right number.

One more thing i wanted to point out is you are printing the selecting number in the program, if it is a guessing game, isn't it supposed to be in the back-end of the code. By entering the printed number, you can win the game in the first iteration.

And just to point out, your program is selecting the number from (1, 4) but the computer is set to guess the number from (1, 100).
Kindly tick the answer if it is correct.
The modified code is -

```<code>import random

the_number = random.randint(1, 4)
guess = 0

while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player guess lower...\n")
    elif guess < the_number:
        print("Player guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Player wins!")
        break

    guess = random.randint(1, 4)

    if guess > the_number:
        print("Computer guess lower...\n")
    elif guess < the_number:
        print("Computer guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")
        break

print("Thank you for playing")
</code>```

Title: Guess the number game Python

Body:
So, im new to python and i have this challenge: I have to make the Guess the Number game, between me and computer. So this is where im at so far.

import random

the_number = random.randint(1, 4)
guess = 0

print(the_number)
while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player guess lower...\n")
    elif guess < the_number:
        print("Player guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Player wins!")
        break

    guess = random.randint(1, 100)

    if guess > the_number:
        print("Computer guess lower...\n")
    elif guess < the_number:
        print("Computer guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")
    break

print("Thank you for playing")

I wanna know how to make this to not stop until one of us is right?

Body:
To get the desired output, you just need to tweak the code a bit, the break in the if statement for the computer is out of the loop of else, so it will stop the execution no matter what.

To counter this condition, you can move the break inside the else block. By doing this, the program will only break if either CPU or you correctly guess the right number.

One more thing i wanted to point out is you are printing the selecting number in the program, if it is a guessing game, isn't it supposed to be in the back-end of the code. By entering the printed number, you can win the game in the first iteration.

And just to point out, your program is selecting the number from (1, 4) but the computer is set to guess the number from (1, 100).
Kindly tick the answer if it is correct.
The modified code is -

import random

the_number = random.randint(1, 4)
guess = 0

while guess != the_number:
    guess = int(input("Please enter a number: "))
    if guess > the_number:
        print("Player guess lower...\n")
    elif guess < the_number:
        print("Player guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Player wins!")
        break

    guess = random.randint(1, 4)

    if guess > the_number:
        print("Computer guess lower...\n")
    elif guess < the_number:
        print("Computer guess higher...\n")
    else:
        print("Game Over! The number was", the_number,"The Computer wins!")
        break

print("Thank you for playing")


问:
How to extract repeating data separately using re
I have this piece of code with the html contents of a page:

```<code>page = """<div>
<span class="item_1" dt="2012.03.12">Item Name 1</span>
<span class="item_2" dt="2012.03.6" time="12:51">Item Name 2</span></div>"""

print(re.findall(('class="(a-z_0-9)"')('dt="(0-9.)"')('>(A-Za-z 0-9)<'),page))
</code>```

The last line is not working for me. Maybe it is wrong. What I need to do is to extract class, dt and text for each span separately.

Expected output:

```<code>[('item_1', '2012.03.12', 'Item Name 1'),
('item_2','2012.03.6','Item Name 2')]
</code>```

Please help!

答:
re.findall needs a regex pattern and a string as arguments, so you need to wrap you regex around r" and " and escape any double quotes in order to have a valid pattern:

re.findall(r"('class=\"(a-z_0-9)\"')('dt=\"(0-9.)\"')('>(A-Za-z 0-9)<')",page)
```

<p>Your regex also doesn't match the info you want. One that does is:</p>

<pre class="lang-regex prettyprint-override"><code><span.*class="([^"]*)".*dt="([^"]*)".*>(.*)<\/span>
</code>```

So putting it all together we have:

import re

page = """

Item Name 1
Item Name 2
"""

print(re.findall(r'(.*)<\/span>',page))
```

<p>Which outputs:</p>

<pre class="lang-py prettyprint-override"><code>[('item_1', '2012.03.12', 'Item Name 1'), ('item_2', '2012.03.6', 'Item Name 2')]
</code>```

Body:
I have this piece of code with the html contents of a page:

page = """

Item Name 1
Item Name 2
"""

print(re.findall(('class="(a-z_0-9)"')('dt="(0-9.)"')('>(A-Za-z 0-9)<'),page))

The last line is not working for me. Maybe it is wrong. What I need to do is to extract class, dt and text for each span separately.

Expected output:

[('item_1', '2012.03.12', 'Item Name 1'),
('item_2','2012.03.6','Item Name 2')]

Please help!

Body:
re.findall needs a regex pattern and a string as arguments, so you need to wrap you regex around r" and " and escape any double quotes in order to have a valid pattern:

re.findall(r"('class=\"(a-z_0-9)\"')('dt=\"(0-9.)\"')('>(A-Za-z 0-9)<')",page)

Your regex also doesn't match the info you want. One that does is:

<span.*class="([^"]*)".*dt="([^"]*)".*>(.*)<\/span>

So putting it all together we have:

import re

page = """<div>
<span class="item_1" dt="2012.03.12">Item Name 1</span>
<span class="item_2" dt="2012.03.6" time="12:51">Item Name 2</span></div>"""

print(re.findall(r'<span.*class="([^"]*)".*dt="([^"]*)".*>(.*)<\/span>',page))

Which outputs:

[('item_1', '2012.03.12', 'Item Name 1'), ('item_2', '2012.03.6', 'Item Name 2')]


问:
Possible DNS spoofing detected. Remote host identification has changed
I recently changed server and as a consequence, I have a new IP address. When I try to use git fetch [remote repository], I get this:

```<code>> C:\Users\[path]\app>git fetch [remote repository]
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> @ WARNING: POSSIBLE DNS SPOOFING DETECTED!                @
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> The RSA host key for example.net has changed, and the key for the
> corresponding IP address [IP address of new server] is unknown. This
> could either mean that DNS SPOOFING is happening or the IP address for
> the host and its host key have changed at the same time.
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!          @
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be
> eavesdropping on you right now (man-in-the-middle attack)! It is also
> possible that a host key has just been changed. The fingerprint for
> the RSA key sent by the remote host is
> SHA256:ep0A2t+sVMSaIEbS8wt8ptfmdHSr1kNocWsBNab0tsI. Please contact
> your system administrator. Add correct host key in
> /c/Users/[username]/.ssh/known_hosts to get rid of this message.
> Offending RSA key in /c/Users/[username]/.ssh/known_hosts:1 RSA host
> key for example.net has changed and you have requested strict
> checking. Host key verification failed. fatal: Could not read from
> remote repository. Please make sure you have the correct access rights
> and the repository exists. C:\Users\[path]\app>
</code>```

I simply need to obtain a new SSH key from the new server and put it in my local computer to fix this, correct? Thank you.

答:
The warning message gives better explanation here.
The RSA host key for example.net has changed, and the key for the corresponding IP address [IP address of new server] is unknown.

Let's compare two scenarios before you change the IP of example.net (10.0.0.0) and after you change the IP of example.net (10.0.0.1).

Before change: example.net - 10.0.0.0

10.0.0.2>> ssh user@example.net
The host fingerprint of the server 10.0.0.0 is stored in known hosts file of the server 10.0.0.2.

After change: example.net - 10.0.0.1

10.0.0.2>> ssh user@example.net
Now the example.net is pointing to 10.0.0.1 but in known hosts file example.net is still having the host fingerprint of 10.0.0.0. So you get a warning whenever you try to ssh to example.net because the host key has changed since it's a new server. As per ssh, it thought that someone else has got access to your DNS and possibly changed the endpoint of the DNS to any wrong server that's why you are facing DNS spoofing warning.

To acknowledge it, you need to say the ssh that you are the one who changed it purposely. For that just remove the old host key entry from the known_host file of server 10.0.0.2 and remove entry for 10.0.0.0.

Find the fingerprint of a server:

ssh-keygen -F example.net

Remove the fingerprint of a server:

ssh-keygen -R example.net

Body:
I recently changed server and as a consequence, I have a new IP address. When I try to use git fetch [remote repository], I get this:

> C:\Users\[path]\app>git fetch [remote repository]
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> @ WARNING: POSSIBLE DNS SPOOFING DETECTED!                @
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> The RSA host key for example.net has changed, and the key for the
> corresponding IP address [IP address of new server] is unknown. This
> could either mean that DNS SPOOFING is happening or the IP address for
> the host and its host key have changed at the same time.
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!          @
> @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
> IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY! Someone could be
> eavesdropping on you right now (man-in-the-middle attack)! It is also
> possible that a host key has just been changed. The fingerprint for
> the RSA key sent by the remote host is
> SHA256:ep0A2t+sVMSaIEbS8wt8ptfmdHSr1kNocWsBNab0tsI. Please contact
> your system administrator. Add correct host key in
> /c/Users/[username]/.ssh/known_hosts to get rid of this message.
> Offending RSA key in /c/Users/[username]/.ssh/known_hosts:1 RSA host
> key for example.net has changed and you have requested strict
> checking. Host key verification failed. fatal: Could not read from
> remote repository. Please make sure you have the correct access rights
> and the repository exists. C:\Users\[path]\app>

I simply need to obtain a new SSH key from the new server and put it in my local computer to fix this, correct? Thank you.


问:
Facebook graph photo thumbnail size
I have managed to pull out these images using PHP and JSON with Facebook's graph API. This is the URL I used.
I only want 3 pictures from the album but I want all the pictures to be displayed in a standard size of 200x175px without distorting the pictures. How can I achieve this? (like displaying pictures in thumbnails in a Facebook album). This is my testing page: </p>

答:
I am just thinking about this on the fly here, but try styling the "fbimg" class.

Like so:

```<code>.fbimg {

height: 200px;

}
</code>```

If the images are going to be different (different heights and widths)...then I don't believe that you can keep them the same height and width without distortion. But if someone learns a trick how to do that...I want to learn it too. ;)

Title: Facebook graph photo thumbnail size

Body:
I am just thinking about this on the fly here, but try styling the "fbimg" class.

Like so:

.fbimg {

height: 200px;

}

If the images are going to be different (different heights and widths)...then I don't believe that you can keep them the same height and width without distortion. But if someone learns a trick how to do that...I want to learn it too. ;)


答:
You can take fromEntries of the other array then just map it:

var array1 = ['a','b','c','d','e','f','g'];
var array2 = [[2,'u'],[3,'x'],[6,'z']];
var d=Object.fromEntries(array2);
var result = array1.map((val, i)=> d[i] || val);
console.log(result);```

Title: How to replace array element with respect to Index on another array

Body:
I have one array which contains values array1 = [a,b,c,d,e,f,g] and another array contains index of array1 and the value to be replaced array2 = [[2,u],[3,x],[6,z]].

Now I want to replace value of array1 with respect to array2 please not array2 consist of [array1_position, value_to_be_replaced]

Now my new arra1 should look like this array1 = [a,b,u,x,e,f,z].

I can do this with for loop but its again time consuming. what trick can i use to replace the value quickly. I am just learning about arrays and have a little knowledge on it.


问:
Why is Eclipse Content Assist not using static imports
I'm trying to use JUnit and Mockito with content assist for static imports.

My Content Assist favorites lists:
org.mockito.Mockito.*

When I use content assist for the mock() method, the method is availble, but the import is just get a regular non-static import.  Why is this not working?

答:
With the Eclipse of 8 years later (Eclipse 2019-12 (4.14.0)), two things are needed:

Window, Preferences, Java, Editor, Content Assist, make sure that the ckeckbox "Use static imports" is ticked.

..., Content Assist, Favorites, add (if not already there) the types (e.g. org.apache.commons.lang3.StringUtils) or members (e.g. org.apache.commons.lang3.StringUtils.EMPTY) to the Favorites list, otherwise Content Assist won't propose to static-import those.


问:
Mutable collections in akka Actor return NullPointerException
I have an actor which is calling a websocket and updating a map everytime it receives an update form the web socket. the same map is being used by the actor at another point in the command.

```<code>class MyActor(broker: InMemoryBroker) extends Actor {
val myMap: TrieMap[String, String] = new TrieMap[String, String]()

//Gets a response every 1 second
webSocket.get(onReponse= r=> myMap(r.key) = r.value)

def receive()={
 case MyCommand(key)=>
   if(myMap.get(key).isDefined){     //Null pointer exception is thrown here
       //Do stuff
   }
}
</code>```

I was expecting TrieMap to be thread safe and not have such issues. Any suggestions?

答:
You should do as much processing as possible in the receive method. So rather than updating the map directly in onResponse, send yourself a message and update the map when you receive it:

```<code>class MyActor(broker: InMemoryBroker) extends Actor {
  val myMap: TrieMap[String, String] = new TrieMap[String, String]()

  private case class UpdateMap(r: ???)

  //Gets a response every 1 second
  webSocket.get(onReponse = r => self ! UpdateMap(r))

  def receive() = {
    case UpdateMap(r) =>
      myMap(r.key) = r.value

    case MyCommand(key) =>
      if (myMap.get(key).isDefined) { //Null pointer exception is thrown here
        //Do stuff
      }
  }
}
</code>```

With the method the TrieMap is only accessed from a single thread at a time.

Also, that test is better done as:

```<code>myMap.get(key).foreach{ value =>
  ???
}
</code>```

Body:
I have an actor which is calling a websocket and updating a map everytime it receives an update form the web socket. the same map is being used by the actor at another point in the command.

class MyActor(broker: InMemoryBroker) extends Actor {
val myMap: TrieMap[String, String] = new TrieMap[String, String]()

//Gets a response every 1 second
webSocket.get(onReponse= r=> myMap(r.key) = r.value)

def receive()={
 case MyCommand(key)=>
   if(myMap.get(key).isDefined){     //Null pointer exception is thrown here
       //Do stuff
   }
}

I was expecting TrieMap to be thread safe and not have such issues. Any suggestions?

Body:
You should do as much processing as possible in the receive method. So rather than updating the map directly in onResponse, send yourself a message and update the map when you receive it:

class MyActor(broker: InMemoryBroker) extends Actor {
  val myMap: TrieMap[String, String] = new TrieMap[String, String]()

  private case class UpdateMap(r: ???)

  //Gets a response every 1 second
  webSocket.get(onReponse = r => self ! UpdateMap(r))

  def receive() = {
    case UpdateMap(r) =>
      myMap(r.key) = r.value

    case MyCommand(key) =>
      if (myMap.get(key).isDefined) { //Null pointer exception is thrown here
        //Do stuff
      }
  }
}

With the method the TrieMap is only accessed from a single thread at a time.

Also, that test is better done as:

myMap.get(key).foreach{ value =>
  ???
}


问:
Avoiding Template operator overload collisions for float and non float on the operator first argument
I have a situation where my template modulus operator does play nice between floats and integer-ish types.
As I recall there is a way to make it select the more specific one over the broader scope one, but i can't seem to find or remember how to do this.

Basically I have 2 methods which are coliding (redefinition error.)

What I am trying to do is get the specialized modulus operator overload to be used when its the type (T_COORDS) is float, the the broader one when it's not float.

The specialized one (notice it uses the math fmod function):

```<code>template <size_t N
    , enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0, bool> = false>
friend Coords operator % (const Coords<float,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<float,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] = fmod(result.coords[i], coords1[i%N]);
  return result;
}
</code>```

The broader one (notice it uses the standard float modulus):

```<code>template <std::size_t N
    , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
    , bool> = false>
friend Coords operator % (const Coords<T_COORDS,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<T_COORDS,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] %= coords1[i%N];
  return result;
}
</code>```

Those overloads are enclosed with a Template class definition:

```<code>template <class T_COORDS, size_t C_COORDS, size_t N_COORDS>
class Coords {
public:

  T_COORDS coords[C_COORDS*N_COORDS];

  // (body in here)

};
</code>```

答:
T_COORDS is a class template parameter, not a function template parameter, which means it makes no difference for partial ordering as the more general function is instantiated with T_COORDS=float anyway, and so it's exactly the same as the float one. You can, however, disable that function from overload resolution, utilizing the fact that it already has some enable_if conditions that are dependent on immediate context:

```<code>template <std::size_t N
        , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
                           && !std::is_same<T_COORDS, float>{}
                           // ~~~~~~~~~~~~^
        , bool> = false>
friend Coords operator %(const Coords<T_COORDS, C_COORDS, N_COORDS>& coords0
                       , const auto (& coords1)[N]);
</code>```

Body:
I have a situation where my template modulus operator does play nice between floats and integer-ish types.
As I recall there is a way to make it select the more specific one over the broader scope one, but i can't seem to find or remember how to do this.

Basically I have 2 methods which are coliding (redefinition error.)

What I am trying to do is get the specialized modulus operator overload to be used when its the type (T_COORDS) is float, the the broader one when it's not float.

The specialized one (notice it uses the math fmod function):

template <size_t N
    , enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0, bool> = false>
friend Coords operator % (const Coords<float,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<float,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] = fmod(result.coords[i], coords1[i%N]);
  return result;
}

The broader one (notice it uses the standard float modulus):

template <std::size_t N
    , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
    , bool> = false>
friend Coords operator % (const Coords<T_COORDS,C_COORDS,N_COORDS>& coords0, const auto (& coords1)[N])
{
  Coords<T_COORDS,C_COORDS,N_COORDS> result = coords0;
  for (int i=0; i < C_COORDS*N_COORDS; i++)
      result.coords[i] %= coords1[i%N];
  return result;
}

Those overloads are enclosed with a Template class definition:

template <class T_COORDS, size_t C_COORDS, size_t N_COORDS>
class Coords {
public:

  T_COORDS coords[C_COORDS*N_COORDS];

  // (body in here)

};

Body:
T_COORDS is a class template parameter, not a function template parameter, which means it makes no difference for partial ordering as the more general function is instantiated with T_COORDS=float anyway, and so it's exactly the same as the float one. You can, however, disable that function from overload resolution, utilizing the fact that it already has some enable_if conditions that are dependent on immediate context:

template <std::size_t N
        , std::enable_if_t<N != 0 && N <= C_COORDS*N_COORDS && N % C_COORDS == 0
                           && !std::is_same<T_COORDS, float>{}
                           // ~~~~~~~~~~~~^
        , bool> = false>
friend Coords operator %(const Coords<T_COORDS, C_COORDS, N_COORDS>& coords0
                       , const auto (& coords1)[N]);


问:
Add custom weight to iOS Font descriptor in Swift
This seems like it should be rudimentarily easy, but for whatever reason it's not working. I've read similar posts on SO and it seems like there might be an issue with the Font Traits dictionary? Is this an issue or am I just completely missing something? This is my first time messing around with fonts like this so I think it might be the latter.

I don't want to use the constants or supply a font with it's "-bold" variant. I would like to have fine grain control over the font weight.

```<code>let traits = [UIFontWeightTrait : 1.0]
imgFontDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorNameAttribute: "Helvetica"])
imgFontDescriptor = imgFontDescriptor.fontDescriptorByAddingAttributes([UIFontDescriptorTraitsAttribute:traits])
imgTextFont = UIFont(descriptor: imgFontDescriptor!, size: 24.0)
</code>```

Research:

Font Descriptor returns nil in iOS 8

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIFontDescriptor_Class/#//apple_ref/doc/constant_group/Font_Traits_Dictionary_Keys

According to the iOS docs using a number value should work (I'm running iOS 9.2):

UIFontWeightTrait

The normalized weight value as an NSNumber object. The valid value range is from -1.0 to 1.0. The value of 0.0 corresponds to the regular or medium font weight. You can also use a font weight constant to specify a particular weight; for a list of constants you can use, see Font Weights. Available in iOS 7.0 and later.

答:
Here is Apple's own extension from UIFont+Extensions.swift in their CareKit framework:

https://github.com/carekit-apple/CareKit/

```<code>extension UIFont {
    static func preferredCustomFont(forTextStyle textStyle: TextStyle, weight: Weight) -> UIFont {
        let defaultDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
        let size = defaultDescriptor.pointSize
        let fontDescriptor = UIFontDescriptor(fontAttributes: [
            UIFontDescriptor.AttributeName.size: size,
            UIFontDescriptor.AttributeName.family: UIFont.systemFont(ofSize: size).familyName
        ])

        // Add the font weight to the descriptor
        let weightedFontDescriptor = fontDescriptor.addingAttributes([
            UIFontDescriptor.AttributeName.traits: [
                UIFontDescriptor.TraitKey.weight: weight
            ]
        ])
        return UIFont(descriptor: weightedFontDescriptor, size: 0)
    }
}
</code>```

Body:
This seems like it should be rudimentarily easy, but for whatever reason it's not working. I've read similar posts on SO and it seems like there might be an issue with the Font Traits dictionary? Is this an issue or am I just completely missing something? This is my first time messing around with fonts like this so I think it might be the latter.

I don't want to use the constants or supply a font with it's "-bold" variant. I would like to have fine grain control over the font weight.

let traits = [UIFontWeightTrait : 1.0]
imgFontDescriptor = UIFontDescriptor(fontAttributes: [UIFontDescriptorNameAttribute: "Helvetica"])
imgFontDescriptor = imgFontDescriptor.fontDescriptorByAddingAttributes([UIFontDescriptorTraitsAttribute:traits])
imgTextFont = UIFont(descriptor: imgFontDescriptor!, size: 24.0)

Research:

Font Descriptor returns nil in iOS 8

https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIFontDescriptor_Class/#//apple_ref/doc/constant_group/Font_Traits_Dictionary_Keys

According to the iOS docs using a number value should work (I'm running iOS 9.2):

UIFontWeightTrait

The normalized weight value as an NSNumber object. The valid value range is from -1.0 to 1.0. The value of 0.0 corresponds to the regular or medium font weight. You can also use a font weight constant to specify a particular weight; for a list of constants you can use, see Font Weights. Available in iOS 7.0 and later.

Body:
Here is Apple's own extension from UIFont+Extensions.swift in their CareKit framework:

https://github.com/carekit-apple/CareKit/

extension UIFont {
    static func preferredCustomFont(forTextStyle textStyle: TextStyle, weight: Weight) -> UIFont {
        let defaultDescriptor = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
        let size = defaultDescriptor.pointSize
        let fontDescriptor = UIFontDescriptor(fontAttributes: [
            UIFontDescriptor.AttributeName.size: size,
            UIFontDescriptor.AttributeName.family: UIFont.systemFont(ofSize: size).familyName
        ])

        // Add the font weight to the descriptor
        let weightedFontDescriptor = fontDescriptor.addingAttributes([
            UIFontDescriptor.AttributeName.traits: [
                UIFontDescriptor.TraitKey.weight: weight
            ]
        ])
        return UIFont(descriptor: weightedFontDescriptor, size: 0)
    }
}


答:
I don't think there is any shorthand for such a verbose question.
Something on top of my mind is </p>

```<code>array2.forEach((el) => {
  array1[el[0]] = el[1];
})
</code>```

Body:
I don't think there is any shorthand for such a verbose question.
Something on top of my mind is

array2.forEach((el) => {
  array1[el[0]] = el[1];
})


问:
Cannot get ATOM to retrieve current working directory
I've been programming in Python using ATOM on my MacBookPro for a while. I have the 'Script' package installed so I just use the keyboard shortcut 'command + I' to run the Python scripts within ATOM.

My issue is that the current working directory retrieved in Python is not correct.

```<code>import os

myPath = os.getcwd()
print(myPath)
</code>```

prints: /Users/MacBookPro/python_files

Where as the current directory is actually: /Users/MacBookPro/python_files/python_programs/deep_learning/pythonprogdotnet/dl_NN_python_pytorch/

This means I have to create a variable called absPath and assign it to the above, then use this variable in my code. Effectively I'm hard-coding the absolute path, but then I have to remove it when I port the code to another machine or a VMS; FloydHub or Colab.

Can someone please inform me how to get the absolute path working in ATOM?

答:
because getcwd()(get current working directory) gives you the directory in the terminal that you are running Python.
try this:

```<code>myPath = os.path.dirname(os.path.realpath(__file__))
</code>```

Body:
I've been programming in Python using ATOM on my MacBookPro for a while. I have the 'Script' package installed so I just use the keyboard shortcut 'command + I' to run the Python scripts within ATOM.

My issue is that the current working directory retrieved in Python is not correct.

import os

myPath = os.getcwd()
print(myPath)

prints: /Users/MacBookPro/python_files

Where as the current directory is actually: /Users/MacBookPro/python_files/python_programs/deep_learning/pythonprogdotnet/dl_NN_python_pytorch/

This means I have to create a variable called absPath and assign it to the above, then use this variable in my code. Effectively I'm hard-coding the absolute path, but then I have to remove it when I port the code to another machine or a VMS; FloydHub or Colab.

Can someone please inform me how to get the absolute path working in ATOM?

Body:
because getcwd()(get current working directory) gives you the directory in the terminal that you are running Python.
try this:

myPath = os.path.dirname(os.path.realpath(__file__))


问:
Laravel Scheduler running every minute regardless of specified schedule
I have the Laravel schedule command triggered in the crontab as:

```<code>* * * * * php /home/forge/site/artisan schedule:run
</code>```

This is set via Forge.

Then, in app/Console/Kernel.php I'm triggering my job to run hourly:

```<code>$schedule->job(new GetRecentArtists())->hourly();
</code>```

But it's still running every minute.

My understanding was that the artisan command needs running every minute so that job schedules can then be checked to see if the job needs triggering as per its' specific schedule.

Update

I've tried restarting the queue as suggested in the comment by Sahidul, and have confirmed that none of the built-in schedules (hourly, daily, etc) prevent it from running every minute.

When I remove the schedule from the crontab and run it via php artisan schedule:run, I get 'No scheduled commands are ready to run' but the task runs anyway.

答:
This was a red herring. I had my log message showing the job as running in the __construct method of the job, rather than in the handle method.

The job is constructed when the scheduler runs, then added to the queue to be executed as per the schedule - so the construct method was being called immediately, but the job wasn't actually being handled until the scheduled time.

Body:
I have the Laravel schedule command triggered in the crontab as:

* * * * * php /home/forge/site/artisan schedule:run

This is set via Forge.

Then, in app/Console/Kernel.php I'm triggering my job to run hourly:

$schedule->job(new GetRecentArtists())->hourly();

But it's still running every minute.

My understanding was that the artisan command needs running every minute so that job schedules can then be checked to see if the job needs triggering as per its' specific schedule.

Update

I've tried restarting the queue as suggested in the comment by Sahidul, and have confirmed that none of the built-in schedules (hourly, daily, etc) prevent it from running every minute.

When I remove the schedule from the crontab and run it via php artisan schedule:run, I get 'No scheduled commands are ready to run' but the task runs anyway.


问:
check/uncehck checkboxlist with jquery
most examples i have seen online have a snippet where they use 2 checkboxes, one for just one checkbox (all) and the second is the checkboxlist. In myy case i have only one checkboxlist bound to datasource, example my datasource list options are(All,apple,orange,red,blue), I got most of it working except when everything is unchecked and i check the last item, example blue, it checks the ALL option. so not working properly. id is the id of the 'All' item in the list</p>

```<code><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
 $(document).ready(function () {
     var id = "#<%=cbOptions.ClientID %>_0";
     var checkboxlistid = "#<%= cbOptions.ClientID %>";
     $(id).click(function () {
         $("#<%= cbOptions.ClientID %> input:checkbox").attr('checked', this.checked);
     });
     $(checkboxlistid +  " input:checkbox").click(function () {
         if ($(checkboxlistid).attr('value') != 0) {
             if ($(id).attr('checked') == true && this.checked == false) {
                 $(id).attr('checked', false);
             }
             else {
                 if ($(id).attr('checked') == true && this.checked == true)
                     CheckSelectAll();
             }

         }
     });
     function CheckSelectAll() {
         var flag = true;
         $(checkboxlistid + " input:checkbox").each(function () {
             if ($(checkboxlistid).attr('value') != 0) {
                 if (this.checked == false) {
                     flag = false;
                 }
                 else {
                     if ($(id).attr('checked') == true && this.checked == false) {
                         flag = false;
                     }
                     else {
                         flag = true;
                     }
                 }
             }
         });

         $(id).attr('checked', flag);
     }
      });
         </script>
                <asp:CheckBoxList runat="server" ID="cbOptions" >
                </asp:CheckBoxList>
        </asp:Content>
</code>```

答:
```<code><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var id = "#<%=cbOptions.ClientID %>_0";
            var checkboxlistid = "#<%= cbOptions.ClientID %>";
            $(id).click(function () {
                $("#<%= cbOptions.ClientID %> input:checkbox").attr('checked', this.checked);
            });
            $(checkboxlistid + " input:checkbox").click(function () {
            if ($(id).attr('checked') == true && this.checked == false) {
                $(id).attr('checked', false);
            }
            else
                CheckSelectAll();
            });
            function CheckSelectAll() {
                $(checkboxlistid + " input:checkbox").each(function () {
                    var checkedcount = $(checkboxlistid + " input[type=checkbox]:checked").length;
                var checkcondition = $(checkboxlistid + " input[type=checkbox]:").length - 1
                if (checkedcount >= checkcondition)
                    $(id).attr('checked', true);
                else
                    $(id).attr('checked', false);
                });
            }
        });
         </script>
                <asp:CheckBoxList runat="server" ID="cbOptions" >
                </asp:CheckBoxList>
        </asp:Content>
</code>```

Title: check/uncehck checkboxlist with jquery

Body:
most examples i have seen online have a snippet where they use 2 checkboxes, one for just one checkbox (all) and the second is the checkboxlist. In myy case i have only one checkboxlist bound to datasource, example my datasource list options are(All,apple,orange,red,blue), I got most of it working except when everything is unchecked and i check the last item, example blue, it checks the ALL option. so not working properly. id is the id of the 'All' item in the list

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

                <asp:CheckBoxList runat="server" ID="cbOptions" >
                </asp:CheckBoxList>
        </asp:Content>


问:
Select text within terminal output using VIM
Let's say I have the following output in my terminal window now:

```<code>1. vsud@vsud:~$ pwd
2. /home/vsud
3. vsud@vsud:~$ echo "Hello, world!"
4. Hello, world!
</code>```

I want to copy to clipboard the 1st and 2nd lines.

```<code>vsud@vsud:~$ pwd
/home/vsud
</code>```

With mouse - I can do that by selecting those 2 lines and pressing Ctrl + Shift + C.
But can I enter into VIM mode somehow and work with that whole output in my terminal as with pure text - so to copy 2 lines I will need to type just "H2yy" ?
Do I need to install some specific Terminal Emulator for that?

Now I'm using terminal emulator which is built in XFCE.

答:
There are two ways to do that: (1) Using tmux, and using (2) ':term' inside vim

tmux

If you are using your terminal from within tmux, you can enter copy mode and select and copy lines from your terminal. Assuming tmux Prefix is Ctrl-b, the precise steps to do this are:

Enter copy mode: Ctrl-b [

Start selecting: Space

Extend selection: use arrow keys

Store selection in buffer: Enter

Transfer selection to system clipboard: Ctrl-b : run-shell "tmux save buffer - | xsel -i -b"

Paste the selection into a vim buffer(+ register): "+p

Additional Notes:

a. tmux offers a command called "capture-pane", with which you can copy an entire pane(terminal).

b. You need xsel to be installed for step 5 above to work. Step 5 can be shortened by using a keybinding. For that have the following command in your .tmux.conf (or, entering this command on your tmux command line Ctrl-b :)

bind C-c run-shell "tmux save-buffer - | xsel -i -b"

Now step 5 is equivalent to pressing Ctrl-c.

c. You can use vim keys for navigation in copy mode: Ctrl-b :setw -g mode-keys vi

:term

If you fire terminal from inside vim using the ex command ':term', you can enter "normal" mode using: Ctrl-W Shift-n. Then you can navigate (and copy in) the terminal with vim keys as if it were a regular vim buffer.

Body:
Let's say I have the following output in my terminal window now:

1. vsud@vsud:~$ pwd
2. /home/vsud
3. vsud@vsud:~$ echo "Hello, world!"
4. Hello, world!

I want to copy to clipboard the 1st and 2nd lines.

vsud@vsud:~$ pwd
/home/vsud

With mouse - I can do that by selecting those 2 lines and pressing Ctrl + Shift + C.
But can I enter into VIM mode somehow and work with that whole output in my terminal as with pure text - so to copy 2 lines I will need to type just "H2yy" ?
Do I need to install some specific Terminal Emulator for that?

Now I'm using terminal emulator which is built in XFCE.


问:
How do I use C++20 in vscode?
I want to use C++20 in vscode as I'd like to use .contains on an unordered_set, but when I try it I get
error C2039: 'contains': is not a member of 'std::unordered_set
and I don't understand why as I 've already went on to c_cpp_properties.json and specified the use of c++20 but it still doesn't seem to work, and I can't find anything anywhere about changing the C++ version on vscode.

Compiler version: 19.25.28614 for x86

答: You must add the msvc compiler option /std:c++latest to be able to use the unordered_map::contains() member function.

Title: How do I use C++20 in vscode?


问:
Why doesn't System.Text.Json.JsonElement have TryGetString() or TryGetBoolean()
I'm parsing some JSON data with the .NET Core System.Text.Json namespace which returns JsonElement objects.

For Int32 types, for example, JsonElement has a GetInt32() which will return the value as an integer or throw an exception if it isn't an integer, and there is also a TryGetInt32() which copies the parsed value to an out variable and returns true or false depending on whether it was able to parse correctly.

The same applies to almost all other primitive types but for some reason, GetBoolean() and GetString() have no try... equivalent even though they also will throw an exception if the value cannot be parsed correctly.

This seems such an obvious oversight, it makes me think I'm doing something wrong. Can anyone explain why they aren't needed?

答:
The answer seems to be hinted at (but not fully explained) by a note in the remarks in the documentation:

This method does not parse the contents of a JSON string value.

But I was still confused until I found some comments in a github issue describing these methods. Here is a snippet of that comment (slightly elided, ** added by me):

```<code>// InvalidOperationException if Type is not True or False
public bool GetBoolean();

// InvalidOperationException if Type is not Number
// FormatException if value does not fit
public decimal GetDecimal();
public double GetDouble();
public int GetInt32();

// InvalidOperationException if Type is not Number
// false if value **does not fit.**
public bool TryGetDecimal(out decimal value);
public bool TryGetDouble(out double value);
public bool TryGetInt32(out int value);
</code>```

So, it ultimately comes down to the difference between a FormatException and an InvalidOperationException.

The latter is used to indicate that the token's ValueKind (Number, String, True, False) does not match the expected type. The former (FormatException) is used a bit off-label from what one would normally expect; instead of being thrown for parsing errors* (ie. "1.sg" is not an int), it is thrown for out of range errors!

This is better understood if we look at the numeric overloads first. The non-Try variants either return a value or throw one of two exceptions: InvalidOperationException if the values are not numbers, FormatExceptions if they don't fit. From the documentation for GetInt32:

Exceptions

InvalidOperationException

This value's ValueKind is not Number.

FormatException

The value cannot be represented as an Int32.

Compare this to the Try variants which throw one exception-- InvalidOperationException if the type is not a number--but return false if the value does not fit. From the documentation for TryGetInt32:

Exceptions

InvalidOperationException

This value's ValueKind is not Number.

Returns

Boolean true if the number can be represented as an Int32; otherwise, false.

In this case, "doesn't fit" means that the value is too large/small for the underlying type, ie. greater than int.MaxValue when using [Try]GetInt32

Now let us get back to the case of booleans where you've rightly noticed there is only a non-Try variant. Looking at the comments in the same github issue we see this:

```<code>// InvalidOperationException if Type is not True or False
public bool GetBoolean();
</code>```

And the documentation:

Exceptions

InvalidOperationException

This value's  ValueKind is neither True nor False.

What's missing here is the FormatException and the "doesn't fit" case. As we've seen above in the case of numbers the Try variant gives us detection of "yes this is a number, but it's out of the appropriate range". Booleans only have two possible values--true and false--there's no range to detect, there's no FormatException to distinguish from. Similar with strings--its either a string token or its not.

What's important to note is that in all cases an InvalidOperationException is thrown if the ValueKind doesn't match what is expected by the method. A hypothetical TryGetBoolean wouldn't return false if it encountered a string value of "abc", it would throw an InvalidOperationException because the ValueKind wasn't True or False. But that's already what GetBoolean does! So theres no need for a seperate method.

* Note: There's no parsing error because the methods don't actually attempt to parse numbers/bools inside of a json string token, they only consider values of the correct token type. In otherwords, quoted numbers/bools are not currently supported:

```<code>{
   "number": 1234,
   "notNumber": "1234",
   "bool": true,
   "notBool": "false"
}
</code>```

There is currently (2020-05-30) a request to add support for this. At which time we may see a change to the availability/functionality of the TryGet methods.

Body:
The answer seems to be hinted at (but not fully explained) by a note in the remarks in the documentation:

This method does not parse the contents of a JSON string value.

But I was still confused until I found some comments in a github issue describing these methods. Here is a snippet of that comment (slightly elided, ** added by me):

// InvalidOperationException if Type is not True or False
public bool GetBoolean();

// InvalidOperationException if Type is not Number
// FormatException if value does not fit
public decimal GetDecimal();
public double GetDouble();
public int GetInt32();

// InvalidOperationException if Type is not Number
// false if value **does not fit.**
public bool TryGetDecimal(out decimal value);
public bool TryGetDouble(out double value);
public bool TryGetInt32(out int value);

So, it ultimately comes down to the difference between a FormatException and an InvalidOperationException.

The latter is used to indicate that the token's ValueKind (Number, String, True, False) does not match the expected type. The former (FormatException) is used a bit off-label from what one would normally expect; instead of being thrown for parsing errors* (ie. "1.sg" is not an int), it is thrown for out of range errors!

This is better understood if we look at the numeric overloads first. The non-Try variants either return a value or throw one of two exceptions: InvalidOperationException if the values are not numbers, FormatExceptions if they don't fit. From the documentation for GetInt32:

Exceptions

InvalidOperationException

This value's ValueKind is not Number.

FormatException

The value cannot be represented as an Int32.

Compare this to the Try variants which throw one exception-- InvalidOperationException if the type is not a number--but return false if the value does not fit. From the documentation for TryGetInt32:

Exceptions

InvalidOperationException

This value's ValueKind is not Number.

Returns

Boolean true if the number can be represented as an Int32; otherwise, false.

In this case, "doesn't fit" means that the value is too large/small for the underlying type, ie. greater than int.MaxValue when using [Try]GetInt32

Now let us get back to the case of booleans where you've rightly noticed there is only a non-Try variant. Looking at the comments in the same github issue we see this:

// InvalidOperationException if Type is not True or False
public bool GetBoolean();

And the documentation:

Exceptions

InvalidOperationException

This value's  ValueKind is neither True nor False.

What's missing here is the FormatException and the "doesn't fit" case. As we've seen above in the case of numbers the Try variant gives us detection of "yes this is a number, but it's out of the appropriate range". Booleans only have two possible values--true and false--there's no range to detect, there's no FormatException to distinguish from. Similar with strings--its either a string token or its not.

What's important to note is that in all cases an InvalidOperationException is thrown if the ValueKind doesn't match what is expected by the method. A hypothetical TryGetBoolean wouldn't return false if it encountered a string value of "abc", it would throw an InvalidOperationException because the ValueKind wasn't True or False. But that's already what GetBoolean does! So theres no need for a seperate method.

* Note: There's no parsing error because the methods don't actually attempt to parse numbers/bools inside of a json string token, they only consider values of the correct token type. In otherwords, quoted numbers/bools are not currently supported:

{
   "number": 1234,
   "notNumber": "1234",
   "bool": true,
   "notBool": "false"
}

There is currently (2020-05-30) a request to add support for this. At which time we may see a change to the availability/functionality of the TryGet methods.


问:
Assigning HTML content to a var in Google Spreadsheet Script
I'm trying to execute an automail through a script in Google Spreadsheet to mail all my clients at a single time. But every time I'm trying to run the script it says that I've incorrectly assigned the HTML content to a variable.

The script code for assigning the value was :

```<code>function sendMail(){

  var name = 1;
  var email = 2;
  var userEmail = 3;
  var password = 4;

  var emailTemp = HtmlService.createTemplateFromFile("MailApp");
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of OneDrive Cloud Storage");

  var data = ws.getRange("B2:E" + ws.getLastRow()).getValues();

  data.forEach(function(row){
    emailTemp.name = row[name];
    emailTemp.userEmail = row[userEmail];
    emailTemp.password = row[password];
    emailTemp.email = row[email];

    var htmlMessage = emailTemp.evaluate().getContent();

    GmailApp.sendEmail(
      row[email],
      "OneDrive 5TB Storage",
      "Your email doesn't support HTML.",
      {name: "AutoMail by Shovon", htmlBody: htmlMessage}
    );
  });
}
</code>```

An error was in the line: var htmlMessage = emailTemp.evaluate().getContent();
The error message says :

I'm also attaching the HTML code:

```<code><html>
  <head>
    <base target="_top">
  </head>
  <body>
  <p>Dear <b> <?= name ?>, </b> </p>
  <p>I received your <b>OneDrive 5TB Cloud Storage</b> request yesterday. I'm really very sorry for being so late as I had some personal things to do.</p>
  <p>But the good news is I've successfully created the following <b>OneDrive Business Account</b> for you: </p>
  <p> User email:<b> <u><? = userEmail?> </u> </b> <br>
   Password: <b> <?= password?> </b> </p>
   <p> Please login to this <b> Microsoft</b> account as soon as possible and set up 2 steps verification method by using your own email address(e.g. <b> <u> <?= email ?> </u> </b>).</p>
   <p>To login <b> <u> <a href = "https://login.live.com/login.srf?wa=wsignin1.0&rpsnv=13&ct=1590813490&rver=7.0.6738.0&wp=MBI_SSL&wreply=https:%2F%2Faccount.microsoft.com%2Fauth%2Fcomplete-signin%3Fru%3Dhttps%253A%252F%252Faccount.microsoft.com%252F%253Frefp%253Dsignedout-index%2526refd%253Dwww.bing.com&lc=1033&id=292666&lw=1&fl=easi2">click here</a></u></b>.</p>
   <p>Yours,<br>
   <b>Md. Shahariar Shovon</b></p>
  </body>
</html>

</code>```

Please help me solving this issue.

答:
You have a typo.

```<code><? = userEmail?>
</code>```

should be

```<code><?= userEmail?>
</code>```

So the app script tries to eval javascript code "= userMail" instead of simple "userMail" which is apparently invalid

Body:
I'm trying to execute an automail through a script in Google Spreadsheet to mail all my clients at a single time. But every time I'm trying to run the script it says that I've incorrectly assigned the HTML content to a variable.

The script code for assigning the value was :

function sendMail(){

  var name = 1;
  var email = 2;
  var userEmail = 3;
  var password = 4;

  var emailTemp = HtmlService.createTemplateFromFile("MailApp");
  var ws = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Copy of OneDrive Cloud Storage");

  var data = ws.getRange("B2:E" + ws.getLastRow()).getValues();

  data.forEach(function(row){
    emailTemp.name = row[name];
    emailTemp.userEmail = row[userEmail];
    emailTemp.password = row[password];
    emailTemp.email = row[email];

    var htmlMessage = emailTemp.evaluate().getContent();

    GmailApp.sendEmail(
      row[email],
      "OneDrive 5TB Storage",
      "Your email doesn't support HTML.",
      {name: "AutoMail by Shovon", htmlBody: htmlMessage}
    );
  });
}

An error was in the line: var htmlMessage = emailTemp.evaluate().getContent();
The error message says :

I'm also attaching the HTML code:

    <base target="_top">

Dear  <?= name ?>,

I received your OneDrive 5TB Cloud Storage request yesterday. I'm really very sorry for being so late as I had some personal things to do.

But the good news is I've successfully created the following OneDrive Business Account for you:

 User email: <? = userEmail?>

   Password:  <?= password?>

 Please login to this  Microsoft account as soon as possible and set up 2 steps verification method by using your own email address(e.g.   <?= email ?>  ).

To login   click here.

Yours,

   Md. Shahariar Shovon

Please help me solving this issue.

Body:
You have a typo.

<? = userEmail?>

should be

<?= userEmail?>

So the app script tries to eval javascript code "= userMail" instead of simple "userMail" which is apparently invalid