问:
How exactly does the onClick binding work in React?
I'm learning React JS for the first time as it is the likely approach my team will be taking at work on a new project. I am trying to understand this onClick binding behavior and what exactly it is doing.

I looked at some articles that try to explain binding specific instances of components/objects to their respective functions and they sort of make sense. But using 'this.props.onClick(i)' doesn't make much sense to me.

So does that code pass squares[i] as the props and somehow onClick within the Square component this updates the value of the button? When running the program that is what it seems to do but I just can't seem to wrap my head around this logic. Especially since I am coming from a back-end background with C# and Java. Any help would be greatly appreciated!

```<code>function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}
</code>```

Update:
The whole app. To give more context...

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (
      <div>
        <div className="board-row">
          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}
        </div>
        <div className="board-row">
          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}
        </div>
        <div className="board-row">
          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}
        </div>
      </div>
    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
    };
  }

  handleClick(i) {
    const history = this.state.history;
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares
      }]),
      xIsNext: !this.state.xIsNext,
    });
  }

  render() {
    const history = this.state.history;
    const current = history[history.length - 1];
    const winner = calculateWinner(current.squares);

    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    return (
      <div className="game">
        <div className="game-board">
          <Board
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          />
        </div>
        <div className="game-info">
          <div>{status}</div>
          <ol>{/* TODO */}</ol>
        </div>
      </div>
    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] == squares[b] && squares[a] == squares[c]) {
      return squares[a];
    }
  }
  return null;
}
</code>```

答:
So the first thing would be to understand the structure of this app. From parent to child component. The Game class component is the most Parent component then the Board Class component then the Square functional component.

the "props" pattern is essentially a way to pass down properties from parent components to child components.

So the Game component is passing down 2 props to the child board component

```<code>  <Board
    squares={current.squares}
    onClick={(i) => this.handleClick(i)}
  />
</code>```

This allows the Board component to access these properties with the syntax "this.props" then the name of the property. Then the Board component is taking these props and further passing it down to its own child component RenderSquare. So this allows the deeply nested child component to access the onClick event of the parent most Game component.

This is not recommended practice tho since props are supposed to be read only. IF you would like to have a child component update and change state in a parent component, then you will need to use Context.

Body:
I'm learning React JS for the first time as it is the likely approach my team will be taking at work on a new project. I am trying to understand this onClick binding behavior and what exactly it is doing.

I looked at some articles that try to explain binding specific instances of components/objects to their respective functions and they sort of make sense. But using 'this.props.onClick(i)' doesn't make much sense to me.

So does that code pass squares[i] as the props and somehow onClick within the Square component this updates the value of the button? When running the program that is what it seems to do but I just can't seem to wrap my head around this logic. Especially since I am coming from a back-end background with C# and Java. Any help would be greatly appreciated!

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (

          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}

          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}

          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}

    );
  }
}

Update:
The whole app. To give more context...

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';

function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}

class Board extends React.Component {
  renderSquare(i) {
    return (
      <Square
        value={this.props.squares[i]}
        onClick={() => this.props.onClick(i)}
      />
    );
  }

  render() {
    return (

          {this.renderSquare(0)}
          {this.renderSquare(1)}
          {this.renderSquare(2)}

          {this.renderSquare(3)}
          {this.renderSquare(4)}
          {this.renderSquare(5)}

          {this.renderSquare(6)}
          {this.renderSquare(7)}
          {this.renderSquare(8)}

    );
  }
}

class Game extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      history: [{
        squares: Array(9).fill(null)
      }],
      xIsNext: true,
    };
  }

  handleClick(i) {
    const history = this.state.history;
    const current = history[history.length - 1];
    const squares = current.squares.slice();
    if (calculateWinner(squares) || squares[i]) {
      return;
    }
    squares[i] = this.state.xIsNext ? 'X' : 'O';
    this.setState({
      history: history.concat([{
        squares: squares
      }]),
      xIsNext: !this.state.xIsNext,
    });
  }

  render() {
    const history = this.state.history;
    const current = history[history.length - 1];
    const winner = calculateWinner(current.squares);

    let status;
    if (winner) {
      status = 'Winner: ' + winner;
    } else {
      status = 'Next player: ' + (this.state.xIsNext ? 'X' : 'O');
    }

    return (

          <Board
            squares={current.squares}
            onClick={(i) => this.handleClick(i)}
          />

{status}

{/* TODO */}

    );
  }
}

// ========================================

ReactDOM.render(
  <Game />,
  document.getElementById('root')
);

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] == squares[b] && squares[a] == squares[c]) {
      return squares[a];
    }
  }
  return null;
}

Body:
So the first thing would be to understand the structure of this app. From parent to child component. The Game class component is the most Parent component then the Board Class component then the Square functional component.

the "props" pattern is essentially a way to pass down properties from parent components to child components.

So the Game component is passing down 2 props to the child board component

  <Board
    squares={current.squares}
    onClick={(i) => this.handleClick(i)}
  />

This allows the Board component to access these properties with the syntax "this.props" then the name of the property. Then the Board component is taking these props and further passing it down to its own child component RenderSquare. So this allows the deeply nested child component to access the onClick event of the parent most Game component.

This is not recommended practice tho since props are supposed to be read only. IF you would like to have a child component update and change state in a parent component, then you will need to use Context.


来源: stackexchange

问:
Write hex bytecode java from c programm
I'm working on a project with flex, bison and c and I have to create a simple compiler for a simple language that generates Java bytecode directly in a Class file, then I would be able to execute it with java. The problem is about Java bytecode. I don't know how to write bytecode in Hexadecimal directly to a file from my C program.

I tried manually with Sublime Text to write "CAFE BABE" and save it with Hex encoding. It works. I tried different fwrite and fprintf but can't find the good way to do it.

```<code>FILE *dest = fopen("HelloWorld.class", "wb");
fwrite("CAFEBABE", sizeof(unsigned int), 4, dest);
</code>```

I also saw some fprintf with 02x...

```<code>fprintf(dest, "%02x", "0xCA");
</code>```

I really don't understand how to write directly with hex encoding...

Thanks you so much for any help.

答:
Hex is a text representation of numbers. You don't want to write hex; you want to write the actual numbers.

To produce the four bytes CA FE BA BE, you can use any of the following:

```<code>const unsigned char* bytes = (const unsigned char*)"\xCA\xFE\xBA\xBE";

unsigned char bytes[] = "\xCA\xFE\xBA\xBE";

unsigned char bytes[] = { 0xCA, 0xFE, 0xBA, 0xBE };
</code>```

As for outputting them, fprintf is not ideal. While you could use the %s format specifier if you made sure the data was NUL-terminated, you couldn't actually output a NUL using it. On the other hand, fwrite is intended to write arbitrary bytes.

ContentLicense: CC BY-SA 4.0

Title: Write hex bytecode java from c programm

Body:
I'm working on a project with flex, bison and c and I have to create a simple compiler for a simple language that generates Java bytecode directly in a Class file, then I would be able to execute it with java. The problem is about Java bytecode. I don't know how to write bytecode in Hexadecimal directly to a file from my C program.

I tried manually with Sublime Text to write "CAFE BABE" and save it with Hex encoding. It works. I tried different fwrite and fprintf but can't find the good way to do it.

FILE *dest = fopen("HelloWorld.class", "wb");
fwrite("CAFEBABE", sizeof(unsigned int), 4, dest);

I also saw some fprintf with 02x...

fprintf(dest, "%02x", "0xCA");

I really don't understand how to write directly with hex encoding...

Thanks you so much for any help.

Body:
Hex is a text representation of numbers. You don't want to write hex; you want to write the actual numbers.

To produce the four bytes CA FE BA BE, you can use any of the following:

const unsigned char* bytes = (const unsigned char*)"\xCA\xFE\xBA\xBE";

unsigned char bytes[] = "\xCA\xFE\xBA\xBE";

unsigned char bytes[] = { 0xCA, 0xFE, 0xBA, 0xBE };

As for outputting them, fprintf is not ideal. While you could use the %s format specifier if you made sure the data was NUL-terminated, you couldn't actually output a NUL using it. On the other hand, fwrite is intended to write arbitrary bytes.


问:
AutoFixture - configure fixture to limit string generation length
When using AutoFixture's Build method for some type, how can I limit the length of the strings generated to fill that object's string properties/fields?</p>

答:
Here is my solution, and notes.

First, it is clear that there is some tight coupling in AutoFixture.Create to knowledge of how a specimen is built and customized.  For strings, it's annoying because we know the default is a Guid.  Using this knowledge, I created a Func that handles this in my test cases:

private readonly Func<IFixture, int, string> _createString = (IFixture fixture, int length) => (fixture.Create<string>() + fixture.Create<string>()).Substring(0, length);
```

<p>This could be inductively defined to exploit the guid generated by Auto-Fixture by default.  It is 36 characters by default, so:</p>

<pre class="lang-cs prettyprint-override"><code>private readonly Func<IFixture, int, string> _createString = (IFixture fixture, int length) =>
        {
            if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
            var sb = new StringBuilder();
            const int autoFixtureStringLength = 36;
            var i = length;
            do
            {
                sb.Append(fixture.Create<string>());
                i -= autoFixtureStringLength;
            } while (i > autoFixtureStringLength && i % autoFixtureStringLength > 0);
            sb.Append(fixture.Create<string>());
            return (sb).ToString().Substring(0, length);
        };
</code>```

Again, the whole premise to this solution is that AutoFixture is already tightly coupled to whatever object creation policy you have.  All you are doing is dove-tailing on that.

It would probably be ideal if AutoFixture exposed a "min value" and "max value" extension point to query.  This is sort of what functional testing frameworks like QuickCheck do, and then let you 'shrink' the value.

Body:
Here is my solution, and notes.

First, it is clear that there is some tight coupling in AutoFixture.Create to knowledge of how a specimen is built and customized.  For strings, it's annoying because we know the default is a Guid.  Using this knowledge, I created a Func that handles this in my test cases:

private readonly Func<IFixture, int, string> _createString = (IFixture fixture, int length) => (fixture.Create<string>() + fixture.Create<string>()).Substring(0, length);

This could be inductively defined to exploit the guid generated by Auto-Fixture by default.  It is 36 characters by default, so:

private readonly Func<IFixture, int, string> _createString = (IFixture fixture, int length) =>
        {
            if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
            var sb = new StringBuilder();
            const int autoFixtureStringLength = 36;
            var i = length;
            do
            {
                sb.Append(fixture.Create<string>());
                i -= autoFixtureStringLength;
            } while (i > autoFixtureStringLength && i % autoFixtureStringLength > 0);
            sb.Append(fixture.Create<string>());
            return (sb).ToString().Substring(0, length);
        };

Again, the whole premise to this solution is that AutoFixture is already tightly coupled to whatever object creation policy you have.  All you are doing is dove-tailing on that.

It would probably be ideal if AutoFixture exposed a "min value" and "max value" extension point to query.  This is sort of what functional testing frameworks like QuickCheck do, and then let you 'shrink' the value.


问:
How to get an .xlsx file from a Falcon resp.stream
I'm trying to get the generated .xlsx file from the API.

I have the following code on the back-end:

```<code>from io import BytesIO
from openpyxl import Workbook

@api_resource('/get_report')
class Report:
    @auth_required()
    def on_get(self, req, resp):
        wb = Workbook()
        ws = wb.active
        ws.title = "report"
        ws['C9'] = 'hello world'
        f = BytesIO()
        wb.save(f)
        f.seek(0)
        resp.stream = f
        resp.content_type = \
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
</code>```

and the following code on the frontend:

```<code>ReportsAPI.getReport(filters).then(resp => {
 openXLS([resp.data], `report.xlsx`);
});

function openXLS(blob_data, filename) {
  let blob = new Blob(blob_data, {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  });
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement("a");
  document.body.appendChild(link);
  link.style = "display: none";
  link.href = url;
  link.download = filename;
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
}
</code>```

I'm downloading the file via API request but the file is corrupted. If I save the file in the file system on the backend (```wb.save('test.xlsx')`</p>

```), the file opens without problems.

I tried to save the file as indicated in the documentation for openpyxl, but it does not work.

...
from tempfile import NamedTemporaryFile

wb = Workbook()
with NamedTemporaryFile() as tmp:
     wb.save(tmp.name)
     tmp.seek(0)
     resp.stream = BytesIO(tmp.read())
```

<p>What am I doing wrong?</p>

<p>In terminal <code>file -bi filename.xlsx</code> on normal file returns <code>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=binary</code>
, but on corrupted file it returns <code>application/zip; charset=binary</code></p>

<p>I tried to make a request to API from the terminal</p>

```http  GET 'http://127.0.0.1:8000/api/v1/get_report' > test.xlsx
```

and the file is not broken. It seems that the problem is on the front-end.

It seems to me that the problem is with the encoding, but I can not determine it.

答:
The problem was in my request to api, I use axios and by default it always process data in JSON. Just needed to set the response type as arraybuffer</p>

```<code>class ReportsAPI {
  getReport(filters) {
    return instance.get(`/get_report`, {
      params: { ...filters },
      responseType: "arraybuffer"
    });
  }
}
</code>```

Body:
I'm trying to get the generated .xlsx file from the API.

I have the following code on the back-end:

from io import BytesIO
from openpyxl import Workbook

@api_resource('/get_report')
class Report:
    @auth_required()
    def on_get(self, req, resp):
        wb = Workbook()
        ws = wb.active
        ws.title = "report"
        ws['C9'] = 'hello world'
        f = BytesIO()
        wb.save(f)
        f.seek(0)
        resp.stream = f
        resp.content_type = \
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'

and the following code on the frontend:

ReportsAPI.getReport(filters).then(resp => {
 openXLS([resp.data], `report.xlsx`);
});

function openXLS(blob_data, filename) {
  let blob = new Blob(blob_data, {
    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  });
  let url = window.URL.createObjectURL(blob);
  let link = document.createElement("a");
  document.body.appendChild(link);
  link.style = "display: none";
  link.href = url;
  link.download = filename;
  link.click();
  document.body.removeChild(link);
  window.URL.revokeObjectURL(url);
}

I'm downloading the file via API request but the file is corrupted. If I save the file in the file system on the backend (```wb.save('test.xlsx')`

), the file opens without problems.

I tried to save the file as indicated in the documentation for openpyxl, but it does not work.

...
from tempfile import NamedTemporaryFile

wb = Workbook()
with NamedTemporaryFile() as tmp:
     wb.save(tmp.name)
     tmp.seek(0)
     resp.stream = BytesIO(tmp.read())

What am I doing wrong?

In terminal file -bi filename.xlsx on normal file returns application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=binary
, but on corrupted file it returns application/zip; charset=binary

I tried to make a request to API from the terminal

http  GET 'http://127.0.0.1:8000/api/v1/get_report' > test.xlsx

and the file is not broken. It seems that the problem is on the front-end.

It seems to me that the problem is with the encoding, but I can not determine it.

Body:
The problem was in my request to api, I use axios and by default it always process data in JSON. Just needed to set the response type as arraybuffer

class ReportsAPI {
  getReport(filters) {
    return instance.get(`/get_report`, {
      params: { ...filters },
      responseType: "arraybuffer"
    });
  }
}


问:
Reading a list of tuples from a text file with strings and numbers
I have a text file where each line represents the results from a sequence mining operation. So the first element in each tuple is a tuple of strings (letters), and the second element is the frequency (int).

How can I read these back from the text file into the original format? Format as follows, copied directly from the text file.... Can't seem to find any similar examples out there but there's got to be a way to do this easily.

```<code>(('a',), 30838057)
(('a', 'b'), 23151399)
(('a', 'b', 'c'), 13865674)
(('a', 'b', 'c', 'e'), 8979035)
(('a', 'b', 'c', 'e', 'f'), 6771982)
(('a', 'b', 'c', 'e', 'f', 'g'), 4514076)
(('a', 'b', 'c', 'e', 'f', 'g', 'h'), 2403374)
</code>```

答:
As other have commented you can use the ast.literal_eval() function since your data appears to be formatted the same a Python literals:

```<code>import ast
from pprint import pprint

filename = 'tuples_list.txt'

tuple_list = []
with open(filename) as inp:
    for line in inp:
        values = ast.literal_eval(line)
        tuple_list.append(values)

pprint(tuple_list)
</code>```

Output:

[(('a',), 30838057),
 (('a', 'b'), 23151399),
 (('a', 'b', 'c'), 13865674),
 (('a', 'b', 'c', 'e'), 8979035),
 (('a', 'b', 'c', 'e', 'f'), 6771982),
 (('a', 'b', 'c', 'e', 'f', 'g'), 4514076),
 (('a', 'b', 'c', 'e', 'f', 'g', 'h'), 2403374)]
```

Body:
I have a text file where each line represents the results from a sequence mining operation. So the first element in each tuple is a tuple of strings (letters), and the second element is the frequency (int).

How can I read these back from the text file into the original format? Format as follows, copied directly from the text file.... Can't seem to find any similar examples out there but there's got to be a way to do this easily.

(('a',), 30838057)
(('a', 'b'), 23151399)
(('a', 'b', 'c'), 13865674)
(('a', 'b', 'c', 'e'), 8979035)
(('a', 'b', 'c', 'e', 'f'), 6771982)
(('a', 'b', 'c', 'e', 'f', 'g'), 4514076)
(('a', 'b', 'c', 'e', 'f', 'g', 'h'), 2403374)

Body:
As other have commented you can use the ast.literal_eval() function since your data appears to be formatted the same a Python literals:

import ast
from pprint import pprint

filename = 'tuples_list.txt'

tuple_list = []
with open(filename) as inp:
    for line in inp:
        values = ast.literal_eval(line)
        tuple_list.append(values)

pprint(tuple_list)

Output:

[(('a',), 30838057),
 (('a', 'b'), 23151399),
 (('a', 'b', 'c'), 13865674),
 (('a', 'b', 'c', 'e'), 8979035),
 (('a', 'b', 'c', 'e', 'f'), 6771982),
 (('a', 'b', 'c', 'e', 'f', 'g'), 4514076),
 (('a', 'b', 'c', 'e', 'f', 'g', 'h'), 2403374)]


问:
Firebase how to enable save prompt for currentuser?
i am using firebase authentication. When i login to the app, it's giving this error:

W/SmartLockViewModel: Non-resolvable exception: com.google.android.gms.common.api.ApiException: 16: The save prompt is disabled for the current app. To restore, remove this app from the "Never save" list in the Smart Lock for Passwords settings for all accounts on this device.

How can solve it?

答: I solved this problem. I just had add  .setIsSmartLockEnabled(false) in my firebase authentication in android.


问:
Getting the bounds of an MKMapView
In order to setup a query to an external server I want to get the bounds of the current Map View in an iPhone app I'm building. UIView should respond to bounds but it seems MKMapView doesn't. After setting a region and zooming in the map I try to get the bounds. I'm stuck on the first step which is to try to get the CGPoints that represent the SE and NW corners of the map. After that I was going to use:

```<code>- (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view
</code>```

To transform the points into map coordinates. But I can't even get that far...

```<code>//Recenter and zoom map in on search location
MKCoordinateRegion region =  {{0.0f, 0.0f}, {0.0f, 0.0f}};
region.center = mySearchLocation.searchLocation.coordinate;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[self.mapView setRegion:region animated:YES];

//After the new search location has been added to the map, and the map zoomed, we need to update the search bounds
//First we need to calculate the corners of the map
CGPoint se = CGPointMake(self.mapView.bounds.origin.x, mapView.bounds.origin.y);
CGPoint nw = CGPointMake((self.mapView.bounds.origin.x + mapView.bounds.size.width), (mapView.bounds.origin.y + mapView.bounds.size.height));
NSLog(@"points are: se %@, nw %@", se, nw);
</code>```

The code compiles without warnings however se and nw are both null. Looking at self.mapView.bounds.origin.x the variable is 0. Trying to NSLog directly self.mapView.bounds.size.width gives me a "Program received signal:  “EXC_BAD_ACCESS”." which seems to come from NSLog.

Anyone know the proper way to get the south east corner and northwest corner (in map coordinates) from the visible area of a MKMapView?

EDIT: It seems whenever you asked something here the answer comes to you right after. I was using %@ instead of @f to print each variable in NSLog which was throwing errors there. I also discovered the annotationVisibleRect property of MKMapview. It seems though that the annotationVisibleRect is based on the parent view coordinates.

答:
Updated @onmyway133's excellent answer for my purposes, I needed the coordinates of all four corners:

```<code>struct BoundingBox {
    let topRight: CLLocationCoordinate2D
    let topLeft: CLLocationCoordinate2D
    let bottomRight: CLLocationCoordinate2D
    let bottomLeft: CLLocationCoordinate2D

    init(rect: MKMapRect) {
        topRight = MKMapPoint(x: rect.maxX, y: rect.origin.y).coordinate
        topLeft = MKMapPoint(x: rect.origin.x, y: rect.origin.y).coordinate
        bottomRight = MKMapPoint(x: rect.maxX, y: rect.maxY).coordinate
        bottomLeft = MKMapPoint(x: rect.origin.x, y: rect.maxY).coordinate
    }

    var items: [String: CLLocationCoordinate2D] {
        return [
            "topRight": topRight,
            "topLeft": topLeft,
            "bottomRight": bottomRight,
            "bottomLeft": bottomLeft,
        ]
    }

    var points: [CLLocationDegrees] {
        return [
            topRight.latitude,
            topRight.longitude,
            topLeft.latitude,
            topLeft.longitude,
            bottomRight.latitude,
            bottomRight.longitude,
            bottomLeft.latitude,
            bottomLeft.longitude,
        ]
    }
}
</code>```

And an example of how I used this data:

```<code>let boundingBox = BoundingBox(rect: mapView.visibleMapRect)
var annotations = Array<MKPointAnnotation>()

for point in boundingBox.items {
    let newPoint = MKPointAnnotation()
    newPoint.coordinate = point.value
    annotations.append(newPoint)
}

mapView.addAnnotations(annotations)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Getting the bounds of an MKMapView

Body:
In order to setup a query to an external server I want to get the bounds of the current Map View in an iPhone app I'm building. UIView should respond to bounds but it seems MKMapView doesn't. After setting a region and zooming in the map I try to get the bounds. I'm stuck on the first step which is to try to get the CGPoints that represent the SE and NW corners of the map. After that I was going to use:

- (CLLocationCoordinate2D)convertPoint:(CGPoint)point toCoordinateFromView:(UIView *)view

To transform the points into map coordinates. But I can't even get that far...

//Recenter and zoom map in on search location
MKCoordinateRegion region =  {{0.0f, 0.0f}, {0.0f, 0.0f}};
region.center = mySearchLocation.searchLocation.coordinate;
region.span.longitudeDelta = 0.01f;
region.span.latitudeDelta = 0.01f;
[self.mapView setRegion:region animated:YES];

//After the new search location has been added to the map, and the map zoomed, we need to update the search bounds
//First we need to calculate the corners of the map
CGPoint se = CGPointMake(self.mapView.bounds.origin.x, mapView.bounds.origin.y);
CGPoint nw = CGPointMake((self.mapView.bounds.origin.x + mapView.bounds.size.width), (mapView.bounds.origin.y + mapView.bounds.size.height));
NSLog(@"points are: se %@, nw %@", se, nw);

The code compiles without warnings however se and nw are both null. Looking at self.mapView.bounds.origin.x the variable is 0. Trying to NSLog directly self.mapView.bounds.size.width gives me a "Program received signal:  “EXC_BAD_ACCESS”." which seems to come from NSLog.

Anyone know the proper way to get the south east corner and northwest corner (in map coordinates) from the visible area of a MKMapView?

EDIT: It seems whenever you asked something here the answer comes to you right after. I was using %@ instead of @f to print each variable in NSLog which was throwing errors there. I also discovered the annotationVisibleRect property of MKMapview. It seems though that the annotationVisibleRect is based on the parent view coordinates.

Body:
Updated @onmyway133's excellent answer for my purposes, I needed the coordinates of all four corners:

struct BoundingBox {
    let topRight: CLLocationCoordinate2D
    let topLeft: CLLocationCoordinate2D
    let bottomRight: CLLocationCoordinate2D
    let bottomLeft: CLLocationCoordinate2D

    init(rect: MKMapRect) {
        topRight = MKMapPoint(x: rect.maxX, y: rect.origin.y).coordinate
        topLeft = MKMapPoint(x: rect.origin.x, y: rect.origin.y).coordinate
        bottomRight = MKMapPoint(x: rect.maxX, y: rect.maxY).coordinate
        bottomLeft = MKMapPoint(x: rect.origin.x, y: rect.maxY).coordinate
    }

    var items: [String: CLLocationCoordinate2D] {
        return [
            "topRight": topRight,
            "topLeft": topLeft,
            "bottomRight": bottomRight,
            "bottomLeft": bottomLeft,
        ]
    }

    var points: [CLLocationDegrees] {
        return [
            topRight.latitude,
            topRight.longitude,
            topLeft.latitude,
            topLeft.longitude,
            bottomRight.latitude,
            bottomRight.longitude,
            bottomLeft.latitude,
            bottomLeft.longitude,
        ]
    }
}

And an example of how I used this data:

let boundingBox = BoundingBox(rect: mapView.visibleMapRect)
var annotations = Array<MKPointAnnotation>()

for point in boundingBox.items {
    let newPoint = MKPointAnnotation()
    newPoint.coordinate = point.value
    annotations.append(newPoint)
}

mapView.addAnnotations(annotations)


问:
Safe navigation at v-model directive in Vue.js
For example we have the following input component:

```<code> <input type="text" v-model="example.modules.report.description.title"></input>
</code>```

Full source

I don't want to define in data following object:

```<code>example: {
  modules: {
    report: {
      description: {
         title: ""
      }
    }
  }
}
</code>```

I anticipate that Vue.js will create that structure itself (just like Angular.js), but it doesn't do it.

Is there any way to solve this problem?

答:
the data() method is a factory that initializes the model on which the component is bound.

The docs explains clearly how is supposed to make it work

You should declare the initial value on the JavaScript side, inside the data option of your component.

vuejs docs

If your model is so complex to require all these nested compositions maybe you have to be fine with it or design a different data model.......or create your model with your own factory

```<code>export default {
    data : example()
}
</code>```

Body:
For example we have the following input component:

 <input type="text" v-model="example.modules.report.description.title"></input>

Full source

I don't want to define in data following object:

example: {
  modules: {
    report: {
      description: {
         title: ""
      }
    }
  }
}

I anticipate that Vue.js will create that structure itself (just like Angular.js), but it doesn't do it.

Is there any way to solve this problem?

Body:
the data() method is a factory that initializes the model on which the component is bound.

The docs explains clearly how is supposed to make it work

You should declare the initial value on the JavaScript side, inside the data option of your component.

vuejs docs

If your model is so complex to require all these nested compositions maybe you have to be fine with it or design a different data model.......or create your model with your own factory

export default {
    data : example()
}


问:
Store heroku pg backup on own S3 bucket
Heroku offers automatic and scheduled backups of your PG database.
https://devcenter.heroku.com/articles/heroku-postgres-data-safety-and-continuous-protection

GBackups will launch a dedicated dyno to take a dump of your database
  and upload it to S3

Simple question: Is it possible to upload a scheduled PG backup to one's OWN S3 Bucket? Simply to have control over the backup files and to not be limited in Storage space. Researching this topic did not provide me with an answer if this is possible.

答: Here is a buildpack for doing this on a regular schedule. It hasn't been updated in a bit, but you could easily update / adapt it as needed.</p>

Title: Store heroku pg backup on own S3 bucket


问:
Creating Shopify cart permalink with mailto
I am trying to setup an href mailto link where the subject or body will be pre-filled with a permalink to a cart filled with products.

To create this cart permalink, here is the code:

```<code>{% capture productlist %}
  {% for item in cart.items %}
    updates[{{ item.variant.id }}]={{ item.quantity }}{% unless forloop.last %}&{% endunless %}
  {% endfor %}
{% endcapture %}

<a href="/cart/update?{{ productlist }}">Cart Page Link</a>
</code>```

This code works perfectly. So now I am trying to incorporate this link into an href mailto:

```<code><a href = "mailto:email@gmail.com?subject=shopify-store.com/cart/update? {{ productlist }}"> email@gmail.com </a>
</code>```

But unfortunately, the above href does not work properly for multiple products. It only works for one variant or one product in the cart. I'm assuming it's an issue with how mailto parses the subject or body text.

How could I get this mailto to pre-fill the subject or body with the full cart page permalink for multiple variants or products?

答: I was able to get it to work. I just needed to encode the URL.</p>

Body:
I am trying to setup an href mailto link where the subject or body will be pre-filled with a permalink to a cart filled with products.

To create this cart permalink, here is the code:

{% capture productlist %}
  {% for item in cart.items %}
    updates[{{ item.variant.id }}]={{ item.quantity }}{% unless forloop.last %}&{% endunless %}
  {% endfor %}
{% endcapture %}

Cart Page Link

This code works perfectly. So now I am trying to incorporate this link into an href mailto:

 email@gmail.com

But unfortunately, the above href does not work properly for multiple products. It only works for one variant or one product in the cart. I'm assuming it's an issue with how mailto parses the subject or body text.

How could I get this mailto to pre-fill the subject or body with the full cart page permalink for multiple variants or products?


问:
Add rewrite_by_lua module to nginx:alpine
I have a docker image nginx:stable-alpine, and i need to use nginx-extras
 in order to use rewrite_by_lua directive.
I tried to install it via apk add --cached but nothing work.

This is my dockerfile:

```<code>FROM nginx:stable-alpine
RUN apk add nginx-extras
</code>```

This is the docker build logs:

```<code>Building nginx
Step 1/2 : FROM nginx:stable-alpine
 ---> acc350649a48
Step 2/2 : RUN apk add nginx-extras
 ---> Running in 857246deaaf7
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  nginx-extras (missing):
    required by: world[nginx-extras]
</code>```

Any help would be well appreciated.

答:
You have to use the following Dockerfile:

```<code>FROM alpine
RUN apk add --no-cache nginx-mod-http-lua-upstream

CMD ["nginx", "-g", "daemon off;"]
</code>```

Body:
I have a docker image nginx:stable-alpine, and i need to use nginx-extras
 in order to use rewrite_by_lua directive.
I tried to install it via apk add --cached but nothing work.

This is my dockerfile:

FROM nginx:stable-alpine
RUN apk add nginx-extras

This is the docker build logs:

Building nginx
Step 1/2 : FROM nginx:stable-alpine
 ---> acc350649a48
Step 2/2 : RUN apk add nginx-extras
 ---> Running in 857246deaaf7
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.7/community/x86_64/APKINDEX.tar.gz
ERROR: unsatisfiable constraints:
  nginx-extras (missing):
    required by: world[nginx-extras]

Any help would be well appreciated.

Body:
You have to use the following Dockerfile:

FROM alpine
RUN apk add --no-cache nginx-mod-http-lua-upstream

CMD ["nginx", "-g", "daemon off;"]


问:
How to send a mail using Outlook template using Python?
I had created an Outlook template. Now I have to send that mail to many users. want to prepare a script that will fetch the CSV file which includes emails list and send it to them.

Outlook Template contains Coloured fonts and underlined text with multiple font sizes.

答:
Maybe take a look at the library yagmail.

From the top of the page:

```<code>import yagmail
yag = yagmail.SMTP()
contents = [
    "This is the body, and here is just text http://somedomain/image.png",
    "You can find an audio file attached.", '/local/path/to/song.mp3'
]
yag.send('to@someone.com', 'subject', contents)

# Alternatively, with a simple one-liner:
yagmail.SMTP('mygmailusername').send('to@someone.com', 'subject', contents)
</code>```

When it comes to coloring and font changes - you'll have to use HTML for that. Define a body in a separate string and pass that into contents.

Body:
Maybe take a look at the library yagmail.

From the top of the page:

import yagmail
yag = yagmail.SMTP()
contents = [
    "This is the body, and here is just text http://somedomain/image.png",
    "You can find an audio file attached.", '/local/path/to/song.mp3'
]
yag.send('to@someone.com', 'subject', contents)

# Alternatively, with a simple one-liner:
yagmail.SMTP('mygmailusername').send('to@someone.com', 'subject', contents)

When it comes to coloring and font changes - you'll have to use HTML for that. Define a body in a separate string and pass that into contents.


问:
Iterate through the list
The transaction csv looks like this and I add them to list as shown below.

```<code>Bread Milk

Bread Diapers Beer Eggs Beer

[{'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Diapers': 1, 'Beer': 6, 'Eggs': 1}, {'Milk': 1, 'Diapers': 1, 'Beer': 6, 'Cola': 1}, {'Bread': 1, 'Milk': 1, 'Diapers': 1, 'Beer': 6}, {'Bread': 1, 'Milk': 1, 'Diapers': 2, 'Cola': 1, 'Chips': 2, 'Beer': 1, '': 1}, {'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}, {'Milk': 1, 'Bread': 1, 'Beer': 4, 'Cola': 1, 'Diapers': 1, 'Chips': 1}, {'Bread': 1, 'Milk': 2, 'Diapers': 2, 'Beer': 2, 'Chips': 2}, {'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}]
</code>```

I would like to consider only the list which contains the count 3 Diapers.

I would expect the transactions to return only as shown below:

```<code>{'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}
{'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}

{'Bread', 'Beer', 'Diapers', 'Milk'}
{'Bread', 'Cola', 'Beer', 'Milk', 'Chips', 'Diapers', ''}
</code>```

The code i have is:

```<code>def M():
    li = []
    # Open the csv file
    with open('transaction.csv') as fp:
        DataCaptured = csv.reader(fp, delimiter=',')
        # Iterate through each word in csv and add it's counter to the row
        for row in DataCaptured:
            li.append(dict(Counter(row)))
            if li['Diaper']==3: ---> I am missing this logic not sure how to get it.

    # Return the list of counters
        return li

print(M())
</code>```

Title: Iterate through the list

Body:
The transaction csv looks like this and I add them to list as shown below.

Bread Milk

Bread Diapers Beer Eggs Beer

[{'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Diapers': 1, 'Beer': 6, 'Eggs': 1}, {'Milk': 1, 'Diapers': 1, 'Beer': 6, 'Cola': 1}, {'Bread': 1, 'Milk': 1, 'Diapers': 1, 'Beer': 6}, {'Bread': 1, 'Milk': 1, 'Diapers': 2, 'Cola': 1, 'Chips': 2, 'Beer': 1, '': 1}, {'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}, {'Milk': 1, 'Bread': 1, 'Beer': 4, 'Cola': 1, 'Diapers': 1, 'Chips': 1}, {'Bread': 1, 'Milk': 2, 'Diapers': 2, 'Beer': 2, 'Chips': 2}, {'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}]

I would like to consider only the list which contains the count 3 Diapers.

I would expect the transactions to return only as shown below:

{'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}
{'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}

{'Bread', 'Beer', 'Diapers', 'Milk'}
{'Bread', 'Cola', 'Beer', 'Milk', 'Chips', 'Diapers', ''}

The code i have is:

def M():
    li = []
    # Open the csv file
    with open('transaction.csv') as fp:
        DataCaptured = csv.reader(fp, delimiter=',')
        # Iterate through each word in csv and add it's counter to the row
        for row in DataCaptured:
            li.append(dict(Counter(row)))
            if li['Diaper']==3: ---> I am missing this logic not sure how to get it.

    # Return the list of counters
        return li

print(M())

Body:
li=[{'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Diapers': 1, 'Beer': 6, 'Eggs': 1}, {'Milk': 1, 'Diapers': 1, 'Beer': 6, 'Cola': 1}, {'Bread': 1, 'Milk': 1, 'Diapers': 1, 'Beer': 6}, {'Bread': 1, 'Milk': 1, 'Diapers': 2, 'Cola': 1, 'Chips': 2, 'Beer': 1, '': 1}, {'Bread': 1, 'Milk': 1, '': 7}, {'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}, {'Milk': 1, 'Bread': 1, 'Beer': 4, 'Cola': 1, 'Diapers': 1, 'Chips': 1}, {'Bread': 1, 'Milk': 2, 'Diapers': 2, 'Beer': 2, 'Chips': 2}, {'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}]
    for d in li:
        if 'Diapers' in d and d['Diapers']==3:
            print(d)

OUTPUT:

{'Bread': 1, 'Cola': 1, 'Beer': 3, 'Milk': 1, 'Chips': 1, 'Diapers': 3, '': 1}
{'Bread': 2, 'Beer': 3, 'Diapers': 3, 'Milk': 1}


问:
Finding command output with the highest number in substring
I need to parse the output of a command and find the substring after the backslash (i.e. app-v2.zip) for the file with the highest version
In the below command output, I want to find app-v2.zip because v2 is the highest. I know this takes a combination of bash commands but haven't figured it out.

Command output:

```<code>gs://artifacts/app-v1.zip
gs://artifacts/app-v2.zip
</code>```

Desired variable value:

```<code>app-v2.zip
</code>```

答:
If your output is already sorted as in your example, this is trivial:

```<code>variable=$(yourCommand |awk -F/ 'END{print $NF}')
</code>```

awk -F/: Use / as the Field Separator

END{print $NF}: Print the last Field of the last Record (line)

Body:
I need to parse the output of a command and find the substring after the backslash (i.e. app-v2.zip) for the file with the highest version
In the below command output, I want to find app-v2.zip because v2 is the highest. I know this takes a combination of bash commands but haven't figured it out.

Command output:

gs://artifacts/app-v1.zip
gs://artifacts/app-v2.zip

Desired variable value:

app-v2.zip

Body:
If your output is already sorted as in your example, this is trivial:

variable=$(yourCommand |awk -F/ 'END{print $NF}')

awk -F/: Use / as the Field Separator

END{print $NF}: Print the last Field of the last Record (line)


问:
How to detect if CSS @font-face is NOT used on a page?
For the purpose of Javascript based automated unused CSS removal we are looking for a solution to detect if a @font-face block is used on a page.

Is there an easy way to verify if a font is in use in the HTML?

The method getComputedStyle() would require to test each individual HTML element and would not be efficient.

 ...

```

答:
document.fonts.check API can be used to detect font-usage. It depends on a font-string style weight size font-family.

To match Open-Sans-Italic:

```<code>document.fonts.check('italic 14px "Open Sans"');
</code>```

Body:
document.fonts.check API can be used to detect font-usage. It depends on a font-string style weight size font-family.

To match Open-Sans-Italic:

document.fonts.check('italic 14px "Open Sans"');


问:
Replace guava Fluent Iterables with Streams
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

```<code>public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}
</code>```

I tried with this solution:

```<code>public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}
</code>```

how to do that without casting the return Stream?

答:
You should use classType::cast because here you're using Object.class::cast which basically does nothing

```<code>public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return filter.stream()
                 .filter(Objects::nonNull)
                 .map(classType::cast)
                 .collect(Collectors.toList());
}
</code>```

And to be even better, add a filter(classType::isInstance) to your method chaining

Body:
I have a method for a filter by type, it gets as input Collection<?> collection and Class<T> tClass. I want to replace FluentIterable by the Stream.

public static <T> List<T> filterByType(final Collection<?> filerCollection, final Class<T> classType)
{
    return FluentIterable.from(filerCollection).filter(classType).toList();
}

I tried with this solution:

public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return (List<T>) filter.stream()
            .filter(Objects::nonNull)
            .map(Object.class::cast)
            .collect(Collectors.toList());
}

how to do that without casting the return Stream?

Body:
You should use classType::cast because here you're using Object.class::cast which basically does nothing

public static <T> List<T> typeFilter(final Collection<?> filter, final Class<T> classType) {
    return filter.stream()
                 .filter(Objects::nonNull)
                 .map(classType::cast)
                 .collect(Collectors.toList());
}

And to be even better, add a filter(classType::isInstance) to your method chaining


问:
How to replace a parent batch file?
I've got an applicationStart.bat file that calls this update.bat, and I need the update.bat to replace the applicationStart.bat with a new one.

The code of the applicationStart.bat is something like:

```<code>@echo off

call update.bat

java -Xms128m -Xmx256m com.foo.bar
</code>```

And the code of the update.bat is like:

```<code>@echo off

..\JRE\bin\jar.exe -xvf .\updateFile.jar
</code>```

I've already tried putting the applicationStart.bat inside de updateFile.jar, and on some machines it replace without error, but on other machines it will generate an error and abort the extraction.

The applicationStart.bat just remains being used for the rest of the day, when the application is being used, and in some cases, the user can shutdown the machine from the application, making things harder because I can't create another process to wait for the application to end and replace the applicationStart.bat afterwards.

How can I get this applicationStart.bat to be replaced?

答:
I just've managed to do it without editing the applicationStart.bat!

To achieve that I've created a 3rd batch called batkill.bat:

```<code>@echo off

if exist temp\applicationStart.bat (
    title batkill
    taskkill /IM cmd.exe /FI "WINDOWTITLE ne batkill" /F
    taskkill /IM ping.exe /F
    move /Y temp\applicationStart.bat .
    start applicationStart.bat
    exit
)
</code>```

And I just've ajusted the update.bat to:

```<code>@echo off

rem Still need to do this to keep the other updates the application needs,
rem without the applicationStart.bat inside
..\JRE\bin\jar.exe -xvf .\updateFile.jar

if exist temp\applicationStart.bat (
    start batkill.bat
    rem Waiting 10 seconds while the batkill comes to kills me
    ping 127.0.0.1 -n 10 -w 1000 >nul
)

</code>```

This way the applicationStart.bat remains unchanged while in execution and I need to change only the update.bat (which is easy to change and deploy)

Title: How to replace a parent batch file?

Body:
I've got an applicationStart.bat file that calls this update.bat, and I need the update.bat to replace the applicationStart.bat with a new one.

The code of the applicationStart.bat is something like:

@echo off

call update.bat

java -Xms128m -Xmx256m com.foo.bar

And the code of the update.bat is like:

@echo off

..\JRE\bin\jar.exe -xvf .\updateFile.jar

I've already tried putting the applicationStart.bat inside de updateFile.jar, and on some machines it replace without error, but on other machines it will generate an error and abort the extraction.

The applicationStart.bat just remains being used for the rest of the day, when the application is being used, and in some cases, the user can shutdown the machine from the application, making things harder because I can't create another process to wait for the application to end and replace the applicationStart.bat afterwards.

How can I get this applicationStart.bat to be replaced?

Body:
I just've managed to do it without editing the applicationStart.bat!

To achieve that I've created a 3rd batch called batkill.bat:

@echo off

if exist temp\applicationStart.bat (
    title batkill
    taskkill /IM cmd.exe /FI "WINDOWTITLE ne batkill" /F
    taskkill /IM ping.exe /F
    move /Y temp\applicationStart.bat .
    start applicationStart.bat
    exit
)

And I just've ajusted the update.bat to:

@echo off

rem Still need to do this to keep the other updates the application needs,
rem without the applicationStart.bat inside
..\JRE\bin\jar.exe -xvf .\updateFile.jar

if exist temp\applicationStart.bat (
    start batkill.bat
    rem Waiting 10 seconds while the batkill comes to kills me
    ping 127.0.0.1 -n 10 -w 1000 >nul
)

This way the applicationStart.bat remains unchanged while in execution and I need to change only the update.bat (which is easy to change and deploy)


问:
How to overcome an error from missing data in a DataReader Iterrows loop?
I'm attempting to extract historic stock prices for 500 stocks from Yahoo Finance using pandas DataReader. I've got the code to work in limited cases but I've been problem with some stock tickers that for some reason aren't supported by Yahoo finance and therefore I can extract their data.

The "No Data" stops my code working. I'd like to create code that would have a robust universal application so it would work when data is available, and then just fill a "NaN" if there isn't. I'm sure this is straight forward but just can't get my head around it.

I tried fixing the problem with if and else conditions but whatever I tried wasn't working and just couldn't figure it out.

```<code>style.use('ggplot')

start = dt.datetime(2000,1,1)
end = dt.datetime(2019,5,26)

data = pd.DataFrame([])

for index, row in tickers.iterrows():

    #if web.DataReader(row['ticker'] , 'yahoo').any():
    df = web.DataReader(row['ticker'] , 'yahoo', start, end)
    df['ticker'] = str(row['ticker'])
    data = data.append(df)

    #else:
      #  df = 'Nan'
        #df['ticker'] = str(row['ticker'])

print(data.head())
</code>```

I'd like to create DataFrame of all the historic stock prices for a given list of tickers that I've imported tickers symbols.

答: Use .dropna(), or perhaps .fillna().

Body:
I'm attempting to extract historic stock prices for 500 stocks from Yahoo Finance using pandas DataReader. I've got the code to work in limited cases but I've been problem with some stock tickers that for some reason aren't supported by Yahoo finance and therefore I can extract their data.

The "No Data" stops my code working. I'd like to create code that would have a robust universal application so it would work when data is available, and then just fill a "NaN" if there isn't. I'm sure this is straight forward but just can't get my head around it.

I tried fixing the problem with if and else conditions but whatever I tried wasn't working and just couldn't figure it out.

style.use('ggplot')

start = dt.datetime(2000,1,1)
end = dt.datetime(2019,5,26)

data = pd.DataFrame([])

for index, row in tickers.iterrows():

    #if web.DataReader(row['ticker'] , 'yahoo').any():
    df = web.DataReader(row['ticker'] , 'yahoo', start, end)
    df['ticker'] = str(row['ticker'])
    data = data.append(df)

    #else:
      #  df = 'Nan'
        #df['ticker'] = str(row['ticker'])

print(data.head())

I'd like to create DataFrame of all the historic stock prices for a given list of tickers that I've imported tickers symbols.

Body: Use .dropna(), or perhaps .fillna().


问:
Node sass could not find bindings for current environment but binding file is present
Missing binding /Users/shiverma/Desktop/project/web/node_modules/node-sass/vendor/darwin-x64-51/binding.node
Node Sass could not find a binding for your current environment: OS X 64-bit with Node.js 7.x

Found bindings for the following environments:
  - OS X 64-bit with Node.js 7.x
  - OS X 64-bit with Unsupported runtime (72)

This usually happens because your environment has changed since running npm install.
Run npm rebuild node-sass to build the binding for your current environment.

I've tried cache cleanup, npm rebuild node-sass, npm rebuild node-sass --force but nothing worked.

答: It looks like you've upgraded from Node 7 to Node 12. Node-sass is a native module, so it needs to be rebuilt for each new node version. To support Node 12, you'll need to upgrade to node-sass 4.12</p>


问:
How do I make Vuetify checkbox accurately reflect it's value?
I am attempting to get the vuetify checkbox to accurately display the correct checked value. For example I am making a check all box with 3 states [all, some, none]. If the state is none the box should be unchecked. If the state is all then it should be checked and some means it is indeterminate. My problem is that when the input-value is calculated as false and the v-checkbox gets clicked the checkbox will display as checked even though the value being fed to the component says it should be unchecked. How do I force the checkbox to always be what the input-value says it should be?

https://codepen.io/anon/pen/QRxoqL?&editable=true&editors=101

```<code><v-checkbox :input-value="val"></v-checkbox>
...
data(){
  return {
    val: false,
  }
},
</code>```

This is a simpler version but it illustrates my issue. When I click the checkbox in an unchecked state, it should remain unchecked unless the "val" variable changes to true. This will allow me to use a method to determine what state the checkbox should be displaying as and actually have that displaying.

答:
I managed to resolve this by using the readonly attribute and wrapping the checkbox in a span which had a @click the event would propagate to.

https://codepen.io/RuttyJ/pen/MdXRXQ?editors=1010

```<code><span @click="toggleValue()">
    <v-checkbox readonly :input-value="val"></v-checkbox>
</span>
</code>```

Body:
I am attempting to get the vuetify checkbox to accurately display the correct checked value. For example I am making a check all box with 3 states [all, some, none]. If the state is none the box should be unchecked. If the state is all then it should be checked and some means it is indeterminate. My problem is that when the input-value is calculated as false and the v-checkbox gets clicked the checkbox will display as checked even though the value being fed to the component says it should be unchecked. How do I force the checkbox to always be what the input-value says it should be?

https://codepen.io/anon/pen/QRxoqL?&editable=true&editors=101

<v-checkbox :input-value="val"></v-checkbox>
...
data(){
  return {
    val: false,
  }
},

This is a simpler version but it illustrates my issue. When I click the checkbox in an unchecked state, it should remain unchecked unless the "val" variable changes to true. This will allow me to use a method to determine what state the checkbox should be displaying as and actually have that displaying.

Body:
I managed to resolve this by using the readonly attribute and wrapping the checkbox in a span which had a @click the event would propagate to.

https://codepen.io/RuttyJ/pen/MdXRXQ?editors=1010

<span @click="toggleValue()">
    <v-checkbox readonly :input-value="val"></v-checkbox>
</span>


问:
Install IDF Espressif make menuconfig fatal error
I want to install the Espressif IDF on my Raspberry PI 3.

I've followed a tutorial to clone github files and so one...

I'm at the step where I have to "make menuconfig" but I get a fatal error.
The fatal error message is :

```<code>pi@raspberrypi:~/ESP32/premier $ make menuconfig

make[1]: Entering directory '/home/pi/ESP32/esp-idf/tools/kconfig'
cc  -D_GNU_SOURCE -D_DEFAULT_SOURCE -DCURSES_LOC="<ncurses.h>" -DLOCALE -MD   -c -o mconf.o mconf.c
mconf.c:1047:1: fatal error: opening dependency file mconf.d: Permission denied
 }
 ^
compilation terminated.
<builtin>: recipe for target 'mconf.o' failed
make[1]: *** [mconf.o] Error 1
make[1]: Leaving directory '/home/pi/ESP32/esp-idf/tools/kconfig'
make: *** No rule to make target '/home/pi/ESP32/esp-idf/tools/kconfig/conf', needed by '/home/pi/ESP32/esp-idf/tools/kconfig/mconf'.  Stop.
</code>```

Would someone has encountered this issue ???

答:
Permission based problems, either:
* As mentioned in the comments, restart tutorial by not deviating, or
* Fix permissions, in your "home"-case (otherwise /opt/...)</p>

```<code>chmod -R 777 /home/pi/ESP32/esp-idf/
</code>```

Body:
I want to install the Espressif IDF on my Raspberry PI 3.

I've followed a tutorial to clone github files and so one...

I'm at the step where I have to "make menuconfig" but I get a fatal error.
The fatal error message is :

pi@raspberrypi:~/ESP32/premier $ make menuconfig

make[1]: Entering directory '/home/pi/ESP32/esp-idf/tools/kconfig'
cc  -D_GNU_SOURCE -D_DEFAULT_SOURCE -DCURSES_LOC="<ncurses.h>" -DLOCALE -MD   -c -o mconf.o mconf.c
mconf.c:1047:1: fatal error: opening dependency file mconf.d: Permission denied
 }
 ^
compilation terminated.
<builtin>: recipe for target 'mconf.o' failed
make[1]: *** [mconf.o] Error 1
make[1]: Leaving directory '/home/pi/ESP32/esp-idf/tools/kconfig'
make: *** No rule to make target '/home/pi/ESP32/esp-idf/tools/kconfig/conf', needed by '/home/pi/ESP32/esp-idf/tools/kconfig/mconf'.  Stop.

Would someone has encountered this issue ???

Body:
Permission based problems, either:
* As mentioned in the comments, restart tutorial by not deviating, or
* Fix permissions, in your "home"-case (otherwise /opt/...)

chmod -R 777 /home/pi/ESP32/esp-idf/


问:
NumPy Slicing with Multiple Tuples
Consider the following:

```<code>import numpy as np

arr = np.arange(3 * 4 * 5).reshape((3, 4, 5))
</code>```

If I slice arr using slices, I get, e.g.:

```<code>arr[:, 0:2, :].shape
# (3, 2, 5)
</code>```

If now I slice arr using a mixture of slice() and tuple(), I get:

```<code>arr[:, (0, 1), :].shape
# (3, 2, 5)

np.all(arr[:, (0, 1), :] == arr[:, :2, :])
# True
</code>```

and:

```<code>arr[:, :, (0, 1)].shape
# (3, 4, 2)

np.all(arr[:, :, (0, 1)] == arr[:, :, :2])
# True
</code>```

HOWEVER, if I do:

```<code>arr[:, (0, 1), (0, 1)].shape
# (3, 2)
</code>```

which is basically, arr[:, 0, 0] and arr[:, 1, 1] concatenated.

I was expecting to get:

```<code>arr[:, (0, 1), (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), (0, 1)] == arr[:, :2, :2])
# True
</code>```

but it is clearly not the case.

If I concatenate two separate slicing, I would be able to obtain the desired result, i.e.:

```<code>arr[:, (0, 1), :][:, :, (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), :][:, :, (0, 1)] == arr[:, :2, :2])
# True
</code>```

Is it possible to obtain the same result as arr[:, (0, 1), :][:, :, (0, 1)] but USING a single slicing?

Now, this example is not so interesting, because I could replace the tuple() with a slice(), but if that is not true, it all becomes a lot more relevant, e.g.:

```<code>arr[:, (0, 2, 3), :][:, :, (0, 2, 3, 4)]
# [[[ 0  2  3  4]
#   [10 12 13 14]
#   [15 17 18 19]]

#  [[20 22 23 24]
#   [30 32 33 34]
#   [35 37 38 39]]

#  [[40 42 43 44]
#   [50 52 53 54]
#   [55 57 58 59]]]
</code>```

for which arr[:, (0, 2, 3), (0, 2, 3, 4)] would be a much more convenient syntax.

EDIT

@Divakar @hpaulj and @MadPhysicist comments / answers pointed towards a properly broadcasted Iterable to be equivalent of multiple concatenated slicing.

However, this is not the case, e.g.:

```<code>s = np.ix_((0, 1), (0, 1, 2, 3))
arr[s[0], slice(3), s[1]]
# [[[ 0  5 10]
#   [ 1  6 11]
#   [ 2  7 12]
#   [ 3  8 13]]
#
#  [[20 25 30]
#   [21 26 31]
#   [22 27 32]
#   [23 28 33]]]
</code>```

But:

```<code>arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)]
# [[[ 0  1  2  3]
#   [ 5  6  7  8]
#   [10 11 12 13]]
#
#  [[20 21 22 23]
#   [25 26 27 28]
#   [30 31 32 33]]]
</code>```

and:

```<code>np.all(arr[:2, :3, :4] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# True

np.all(arr[s[0], slice(3), s[1]] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# False
</code>```

答:
The ix_ can be combined with a slice via tuple concatenation:

```<code>In [568]: arr[(slice(None),)+np.ix_((0,2,3),(0,2,3,4))]
Out[568]:
array([[[ 0,  2,  3,  4],
        [10, 12, 13, 14],
        [15, 17, 18, 19]],

       [[20, 22, 23, 24],
        [30, 32, 33, 34],
        [35, 37, 38, 39]],

       [[40, 42, 43, 44],
        [50, 52, 53, 54],
        [55, 57, 58, 59]]])
</code>```

The ix_ tuple:

```<code>In [569]: np.ix_((0,2,3),(0,2,3,4))
Out[569]:
(array([[0],
        [2],
        [3]]), array([[0, 2, 3, 4]]))
</code>```

tuple concatenation:

```<code>In [570]: (slice(None),)+np.ix_((0,2,3),(0,2,3,4))
Out[570]:
(slice(None, None, None), array([[0],
        [2],
        [3]]), array([[0, 2, 3, 4]]))
In [571]: arr[_]
Out[571]:
array([[[ 0,  2,  3,  4],
        [10, 12, 13, 14],
        [15, 17, 18, 19]],
        ....
</code>```

The idea of building a tuple with Python code, and then using it in an indexing expression is used in a number of numpy functions.

Another way to construct this indexing tuple is:

```<code>In [581]: arr[(slice(None), *np.ix_((0,2,3),(0,2,3,4)))]
Out[581]:
array([[[ 0,  2,  3,  4],
        [10, 12, 13, 14],
        [15, 17, 18, 19]],
       ...
</code>```

This takes advantage of the Python '*' unpacking within a tuple (but not directly within an indexing expression).

It's in effect a way of doing arr[:,*ix_[...]], which produces a syntax error.

In sum:

numpy operates within Python, so is subject to all of its syntactic rules

numpy makes the 'element' indexing easy.  The block indexing is a bit harder, though it actually follows the same broadcasting rules.

MATLAB has its own language and syntax.  It makes the block indexing easy, but element indexing, as for example getting a diagonal, is more awkward, requiring an extra sub2ind function call.

Title: NumPy Slicing with Multiple Tuples

Body:
Consider the following:

import numpy as np

arr = np.arange(3 * 4 * 5).reshape((3, 4, 5))

If I slice arr using slices, I get, e.g.:

arr[:, 0:2, :].shape
# (3, 2, 5)

If now I slice arr using a mixture of slice() and tuple(), I get:

arr[:, (0, 1), :].shape
# (3, 2, 5)

np.all(arr[:, (0, 1), :] == arr[:, :2, :])
# True

and:

arr[:, :, (0, 1)].shape
# (3, 4, 2)

np.all(arr[:, :, (0, 1)] == arr[:, :, :2])
# True

HOWEVER, if I do:

arr[:, (0, 1), (0, 1)].shape
# (3, 2)

which is basically, arr[:, 0, 0] and arr[:, 1, 1] concatenated.

I was expecting to get:

arr[:, (0, 1), (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), (0, 1)] == arr[:, :2, :2])
# True

but it is clearly not the case.

If I concatenate two separate slicing, I would be able to obtain the desired result, i.e.:

arr[:, (0, 1), :][:, :, (0, 1)].shape
# (3, 2, 2)

np.all(arr[:, (0, 1), :][:, :, (0, 1)] == arr[:, :2, :2])
# True

Is it possible to obtain the same result as arr[:, (0, 1), :][:, :, (0, 1)] but USING a single slicing?

Now, this example is not so interesting, because I could replace the tuple() with a slice(), but if that is not true, it all becomes a lot more relevant, e.g.:

arr[:, (0, 2, 3), :][:, :, (0, 2, 3, 4)]
# [[[ 0  2  3  4]
#   [10 12 13 14]
#   [15 17 18 19]]

#  [[20 22 23 24]
#   [30 32 33 34]
#   [35 37 38 39]]

#  [[40 42 43 44]
#   [50 52 53 54]
#   [55 57 58 59]]]

for which arr[:, (0, 2, 3), (0, 2, 3, 4)] would be a much more convenient syntax.

EDIT

@Divakar @hpaulj and @MadPhysicist comments / answers pointed towards a properly broadcasted Iterable to be equivalent of multiple concatenated slicing.

However, this is not the case, e.g.:

s = np.ix_((0, 1), (0, 1, 2, 3))
arr[s[0], slice(3), s[1]]
# [[[ 0  5 10]
#   [ 1  6 11]
#   [ 2  7 12]
#   [ 3  8 13]]
#
#  [[20 25 30]
#   [21 26 31]
#   [22 27 32]
#   [23 28 33]]]

But:

arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)]
# [[[ 0  1  2  3]
#   [ 5  6  7  8]
#   [10 11 12 13]]
#
#  [[20 21 22 23]
#   [25 26 27 28]
#   [30 31 32 33]]]

and:

np.all(arr[:2, :3, :4] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# True

np.all(arr[s[0], slice(3), s[1]] == arr[(0, 1), :, :][:, :3, :][:, :, (0, 1, 2, 3)])
# False

Body:
The ix_ can be combined with a slice via tuple concatenation:

In [568]: arr[(slice(None),)+np.ix_((0,2,3),(0,2,3,4))]
Out[568]:
array([[[ 0,  2,  3,  4],
        [10, 12, 13, 14],
        [15, 17, 18, 19]],

       [[20, 22, 23, 24],
        [30, 32, 33, 34],
        [35, 37, 38, 39]],

       [[40, 42, 43, 44],
        [50, 52, 53, 54],
        [55, 57, 58, 59]]])

The ix_ tuple:

In [569]: np.ix_((0,2,3),(0,2,3,4))
Out[569]:
(array([[0],
        [2],
        [3]]), array([[0, 2, 3, 4]]))

tuple concatenation:

In [570]: (slice(None),)+np.ix_((0,2,3),(0,2,3,4))
Out[570]:
(slice(None, None, None), array([[0],
        [2],
        [3]]), array([[0, 2, 3, 4]]))
In [571]: arr[_]
Out[571]:
array([[[ 0,  2,  3,  4],
        [10, 12, 13, 14],
        [15, 17, 18, 19]],
        ....

The idea of building a tuple with Python code, and then using it in an indexing expression is used in a number of numpy functions.

Another way to construct this indexing tuple is:

In [581]: arr[(slice(None), *np.ix_((0,2,3),(0,2,3,4)))]
Out[581]:
array([[[ 0,  2,  3,  4],
        [10, 12, 13, 14],
        [15, 17, 18, 19]],
       ...

This takes advantage of the Python '*' unpacking within a tuple (but not directly within an indexing expression).

It's in effect a way of doing arr[:,*ix_[...]], which produces a syntax error.

In sum:

numpy operates within Python, so is subject to all of its syntactic rules

numpy makes the 'element' indexing easy.  The block indexing is a bit harder, though it actually follows the same broadcasting rules.

MATLAB has its own language and syntax.  It makes the block indexing easy, but element indexing, as for example getting a diagonal, is more awkward, requiring an extra sub2ind function call.


问:
Copying multiple pages and clearing cells
I have 7 sheets in my excel file that I need to copy all at once. I have created a button to do this with the code shown below. However, I also want to be able to clear some of the cells when I copy the sheets. I have tried to modify the second set of code from a different workbook that was copying one page at a time and clearing cells but I can't seem to get it to work. The code does not need to search for the most recent week as the code shown below does, I just need it to copy my 7 sheets and clear cells G18:G37 on sheets 2 through 7. Thanks

'What i have right now.'

```<code>Private Sub CommandButton1_Click()

Worksheets(Array("Coding Details", "Schedule A", "Schedule B", "Schedule C", "Schedule D", "Schedule E", "Schedule F")).Copy After:=Worksheets(Worksheets.Count)

End Sub
</code>```

'What i am using in my other workbook'

```<code>Private Sub CommandButton1_Click()

Dim wrkSht As Worksheet
Dim lWkNum As Long
Dim lCurNum As Long
Dim sht_LastWeek As Worksheet
Dim sht_NewWeek As Worksheet

'Find previous week and set reference to it.
For Each wrkSht In ThisWorkbook.Worksheets
    If IsNumeric(Replace(wrkSht.Name, "Week ", "")) Then
        lCurNum = CLng(Replace(wrkSht.Name, "Week ", ""))
        If lCurNum > lWkNum Then lWkNum = lCurNum
    End If
Next wrkSht
Set sht_LastWeek = ThisWorkbook.Worksheets("Week " & lWkNum)

'Create new sheet, set reference to it and rename.
sht_LastWeek.Copy After:=Sheets(sht_LastWeek.Index)
Set sht_NewWeek = Sheets(sht_LastWeek.Index + 1)
sht_NewWeek.Name = "Week " & lCurNum + 1

'Clear the cells and relink formula to previous sheet.
With sht_NewWeek
    .Range("B40:J45,C18:I21,E26:F31").ClearContents
    .Cells.Replace What:="'Week " & lCurNum - 1 & "'!", _
                   Replacement:="'Week " & lCurNum & "'!", _
                   LookAt:=xlPart
End With

End Sub
</code>```

答:
This should work:</p>

```<code>Private Sub CommandButton1_Click()

    Dim n As Long, wb As Workbook

    Set wb = ThisWorkbook

    wb.Worksheets(Array("Coding Details", "Schedule A", "Schedule B", _
                    "Schedule C", "Schedule D", "Schedule E", "Schedule F")).Copy _
                    After:=wb.Worksheets(wb.Worksheets.Count)
    For n = 0 To 5
        wb.Worksheets(wb.Worksheet.Count - n).Range("G18:G37").ClearContents
    Next n

End Sub
</code>```

Body:
I have 7 sheets in my excel file that I need to copy all at once. I have created a button to do this with the code shown below. However, I also want to be able to clear some of the cells when I copy the sheets. I have tried to modify the second set of code from a different workbook that was copying one page at a time and clearing cells but I can't seem to get it to work. The code does not need to search for the most recent week as the code shown below does, I just need it to copy my 7 sheets and clear cells G18:G37 on sheets 2 through 7. Thanks

'What i have right now.'

Private Sub CommandButton1_Click()

Worksheets(Array("Coding Details", "Schedule A", "Schedule B", "Schedule C", "Schedule D", "Schedule E", "Schedule F")).Copy After:=Worksheets(Worksheets.Count)

End Sub

'What i am using in my other workbook'

Private Sub CommandButton1_Click()

Dim wrkSht As Worksheet
Dim lWkNum As Long
Dim lCurNum As Long
Dim sht_LastWeek As Worksheet
Dim sht_NewWeek As Worksheet

'Find previous week and set reference to it.
For Each wrkSht In ThisWorkbook.Worksheets
    If IsNumeric(Replace(wrkSht.Name, "Week ", "")) Then
        lCurNum = CLng(Replace(wrkSht.Name, "Week ", ""))
        If lCurNum > lWkNum Then lWkNum = lCurNum
    End If
Next wrkSht
Set sht_LastWeek = ThisWorkbook.Worksheets("Week " & lWkNum)

'Create new sheet, set reference to it and rename.
sht_LastWeek.Copy After:=Sheets(sht_LastWeek.Index)
Set sht_NewWeek = Sheets(sht_LastWeek.Index + 1)
sht_NewWeek.Name = "Week " & lCurNum + 1

'Clear the cells and relink formula to previous sheet.
With sht_NewWeek
    .Range("B40:J45,C18:I21,E26:F31").ClearContents
    .Cells.Replace What:="'Week " & lCurNum - 1 & "'!", _
                   Replacement:="'Week " & lCurNum & "'!", _
                   LookAt:=xlPart
End With

End Sub

Body:
This should work:

Private Sub CommandButton1_Click()

    Dim n As Long, wb As Workbook

    Set wb = ThisWorkbook

    wb.Worksheets(Array("Coding Details", "Schedule A", "Schedule B", _
                    "Schedule C", "Schedule D", "Schedule E", "Schedule F")).Copy _
                    After:=wb.Worksheets(wb.Worksheets.Count)
    For n = 0 To 5
        wb.Worksheets(wb.Worksheet.Count - n).Range("G18:G37").ClearContents
    Next n

End Sub


问:
How to fix 'ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()' in python?
I'm trying to solve a class imbalance problem by randomly selecting the majority class equal to the minority class.

This is a multi-class classification problem, i've tried to sub-sample data with imbalance class distributions but i'm getting a boolean error. I've done label encoding for the classes.

no_of_frauds = train.Suspicious.value_counts()

```

<pre class="lang-py prettyprint-override"><code>non_fraud = train[train['Suspicious'] == 2]
intermediate = train[train['Suspicious'] == 0]
fraud = train[train['Suspicious'] == 1]
</code>```

selected = non_fraud.sample(no_of_frauds) #getting the error here
selected.head()
```

I expect the out to be a dataframe containing all the non-fraud items.

答:
Check this vector:
no_of_frauds = train.Suspicious.value_counts()

This doesn't gets you a integer, in which is used as an argument at the sample function.

Try instead no_of_frauds = train.Suspicious.count()

Body:
I'm trying to solve a class imbalance problem by randomly selecting the majority class equal to the minority class.

This is a multi-class classification problem, i've tried to sub-sample data with imbalance class distributions but i'm getting a boolean error. I've done label encoding for the classes.

no_of_frauds = train.Suspicious.value_counts()

non_fraud = train[train['Suspicious'] == 2]
intermediate = train[train['Suspicious'] == 0]
fraud = train[train['Suspicious'] == 1]

selected = non_fraud.sample(no_of_frauds) #getting the error here
selected.head()

I expect the out to be a dataframe containing all the non-fraud items.


问:
Boolean Reports True When It Should Be False
This is intended to detect when the user has pressed the spacebar after typing the letter A. If the spacebar is pressed, the A should be replaced by a C. Otherwise, it should be left alone.

Additionally, if the user presses space but then presses backspace, the replaced letter (C) should become an A and should no longer be replaced.
Basically a weak autocorrect system.

My issue is that the boolean that reports whether the spacebar has been pressed is randomly reporting true when I am just typing random letters and then going back to false.

Any new eyes on this would be much appreciated! I can't seem to figure out what might be causing this to happen. Thanks in advance.

```<code>public class SpellingsClient extends Activity implements SpellCheckerSession.SpellCheckerSessionListener
{
TextWatcher tt = null;
private EditText suggestions;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate (Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    suggestions = new EditText(this);
    setContentView(suggestions);
   // fetchSuggestionsFor(suggestions.getText().toString());

    tt = new TextWatcherExtended() {
        boolean movedOn;

        public void afterTextChanged(Editable s, boolean backSpace, boolean autoCorrect){
//Checks if the backspaced was pressed, sets movedOn to false if true
            suggestions.setSelection(s.length());
            if (backSpace){
                Log.d("test2", "Backspace pressed!" + backSpace);
                boolean movedOn = false;
            }
            Log.d("movedOn", "is " + movedOn);
            movedOn = true;
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after){}

        public void onTextChanged(CharSequence s, int start, int before, int count){
//Checks if spacebar pressed and user moved on, then replaces the word
//if user pressed backspace, it sets the letters back to what they were
            suggestions.removeTextChangedListener(tt);
         if (spacePressed = true && movedOn) {
             suggestions.setText(suggestions.getText().toString().replace("A", "C"));
         } else if (!movedOn) {
             suggestions.setText(suggestions.getText().toString().replace("C", "A"));
         }
         suggestions.addTextChangedListener(tt);
        }
    };
    suggestions.addTextChangedListener(tt);
}
boolean spacePressed;

public boolean dispatchKeyEvent(KeyEvent event){
//checks if spacebar was pressed and sets spacePressed to true if so
    if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE && event.getAction() == KeyEvent.ACTION_UP){
        Log.d("test", "Space bar pressed!" + event);
        spacePressed = true;
        return true;
    }
    Log.d("Spacepressed", "it's" + spacePressed);
    spacePressed = false;
    return super.dispatchKeyEvent(event);
}
</code>```

答:
spacePressed = true is your problem. This is an assignment, not a comparison.

Use == instead; or, easier, just use spacePressed, since condition == true is the same as condition, and avoids the potential for a typo.

Body:
This is intended to detect when the user has pressed the spacebar after typing the letter A. If the spacebar is pressed, the A should be replaced by a C. Otherwise, it should be left alone.

Additionally, if the user presses space but then presses backspace, the replaced letter (C) should become an A and should no longer be replaced.
Basically a weak autocorrect system.

My issue is that the boolean that reports whether the spacebar has been pressed is randomly reporting true when I am just typing random letters and then going back to false.

Any new eyes on this would be much appreciated! I can't seem to figure out what might be causing this to happen. Thanks in advance.

public class SpellingsClient extends Activity implements SpellCheckerSession.SpellCheckerSessionListener
{
TextWatcher tt = null;
private EditText suggestions;
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
protected void onCreate (Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    suggestions = new EditText(this);
    setContentView(suggestions);
   // fetchSuggestionsFor(suggestions.getText().toString());

    tt = new TextWatcherExtended() {
        boolean movedOn;

        public void afterTextChanged(Editable s, boolean backSpace, boolean autoCorrect){
//Checks if the backspaced was pressed, sets movedOn to false if true
            suggestions.setSelection(s.length());
            if (backSpace){
                Log.d("test2", "Backspace pressed!" + backSpace);
                boolean movedOn = false;
            }
            Log.d("movedOn", "is " + movedOn);
            movedOn = true;
        }

        public void beforeTextChanged(CharSequence s, int start, int count, int after){}

        public void onTextChanged(CharSequence s, int start, int before, int count){
//Checks if spacebar pressed and user moved on, then replaces the word
//if user pressed backspace, it sets the letters back to what they were
            suggestions.removeTextChangedListener(tt);
         if (spacePressed = true && movedOn) {
             suggestions.setText(suggestions.getText().toString().replace("A", "C"));
         } else if (!movedOn) {
             suggestions.setText(suggestions.getText().toString().replace("C", "A"));
         }
         suggestions.addTextChangedListener(tt);
        }
    };
    suggestions.addTextChangedListener(tt);
}
boolean spacePressed;

public boolean dispatchKeyEvent(KeyEvent event){
//checks if spacebar was pressed and sets spacePressed to true if so
    if (event.getKeyCode() == KeyEvent.KEYCODE_SPACE && event.getAction() == KeyEvent.ACTION_UP){
        Log.d("test", "Space bar pressed!" + event);
        spacePressed = true;
        return true;
    }
    Log.d("Spacepressed", "it's" + spacePressed);
    spacePressed = false;
    return super.dispatchKeyEvent(event);
}


问:
Starting Jenkins in Docker Container
I want to run Jenkins in a Docker Container on Centos7.
I saw the official documentation of Jenkins:
First, pull the official jenkins image from Docker repository.

```<code>docker pull jenkins
</code>```

Next, run a container using this image and map data directory from the container to the host; e.g in the example below /var/jenkins_home from the container is mapped to jenkins/ directory from the current path on the host. Jenkins 8080 port is also exposed to the host as 49001.

```<code>docker run -d -p 49001:8080 -v $PWD/jenkins:/var/jenkins_home -t jenkins
</code>```

But when I try to run the docker container I get the following error:

```<code>/usr/local/bin/jenkins.sh: line 25: /var/jenkins_home/copy_reference_file.log: Permission denied
</code>```

Can someone tell me how to fix this problem?

答:
The newest Jenkins documentation says to use Docker 'volumes'.
Docker is kinda tricky on this, the difference between the two is a full path name with the -v option for bind mount and just a name for volumes.

```<code>docker run -d -p 49001:8080 -v jenkins-data:/var/jenkins_home -t jenkins
</code>```

This command will create a docker volume named "jenkins-data" and you will no longer see the error.

Link to manage volumes:
https://docs.docker.com/storage/volumes/

Title: Starting Jenkins in Docker Container

Body:
I want to run Jenkins in a Docker Container on Centos7.
I saw the official documentation of Jenkins:
First, pull the official jenkins image from Docker repository.

docker pull jenkins

Next, run a container using this image and map data directory from the container to the host; e.g in the example below /var/jenkins_home from the container is mapped to jenkins/ directory from the current path on the host. Jenkins 8080 port is also exposed to the host as 49001.

docker run -d -p 49001:8080 -v $PWD/jenkins:/var/jenkins_home -t jenkins

But when I try to run the docker container I get the following error:

/usr/local/bin/jenkins.sh: line 25: /var/jenkins_home/copy_reference_file.log: Permission denied

Can someone tell me how to fix this problem?

Body:
The newest Jenkins documentation says to use Docker 'volumes'.
Docker is kinda tricky on this, the difference between the two is a full path name with the -v option for bind mount and just a name for volumes.

docker run -d -p 49001:8080 -v jenkins-data:/var/jenkins_home -t jenkins

This command will create a docker volume named "jenkins-data" and you will no longer see the error.

Link to manage volumes:
https://docs.docker.com/storage/volumes/


问:
CSS file blocked: MIME type mismatch (X-Content-Type-Options: nosniff)
I am developing an Angular 4 app and I want to apply some global styles.  Following the tutorial at the angular site, I've created a "styles.css" file in the root directory of my app, and I'm referring to that stylesheet in the index.html of my app:

```<code><link rel="stylesheet" type="text/css" href="styles.css">
</code>```

The angular app is successfully compiled:

```<code>$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
[...]
webpack: Compiled successfully.
</code>```

But when I visit http://localhost:4200 in a Chromium browser, the console shows an error at

```<code>GET http://localhost:4200/styles.css
</code>```

In a Firefox browser, the error is a bit more explicit:

```<code>GET
http://localhost:4200/styles.css [HTTP/1.1 404 Not Found 15ms]
The resource from "http://localhost:4200/styles.css" was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).
</code>```

Both files, index.html and styles.css are located in the root directory of my angular app.
I've tried to get more info about the problem :

```<code>nosniff
    Blocks a request if the requested type is

        "style" and the MIME type is not "text/css", or
        "script" and the MIME type is not a JavaScript MIME type.
</code>```

But I don't understand why it's bloking the request, since I've specified type="text/css" when referencing the stylesheet.

答:
In running into the same kind of issue for a full stack web application (in development), I simply solved the problem by correctly linking the css file to the page rendered. Removing the rel = stylesheet, as suggested above, prevents the error to show up in the browser but it does not load the styles that should be applied to the page. In short, it isn't a solution.

If you are using express-static you can use this as an example:

Server-side:

```<code>app.use(express.static(__dirname + "/public", {
    index: false,
    immutable: true,
    cacheControl: true,
    maxAge: "30d"
}));
</code>```

Client-side:

```<code> <link type="text/css" rel="stylesheet" href="/main.css">
</code>```

Just add a forward slash in front of the file you wish to link to the html page (if you are rendering html pages without using any template engines) and express-static will do the rest automatically for you.

Body:
I am developing an Angular 4 app and I want to apply some global styles.  Following the tutorial at the angular site, I've created a "styles.css" file in the root directory of my app, and I'm referring to that stylesheet in the index.html of my app:

<link rel="stylesheet" type="text/css" href="styles.css">

The angular app is successfully compiled:

$ ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200 **
[...]
webpack: Compiled successfully.

But when I visit http://localhost:4200 in a Chromium browser, the console shows an error at

GET http://localhost:4200/styles.css

In a Firefox browser, the error is a bit more explicit:

GET
http://localhost:4200/styles.css [HTTP/1.1 404 Not Found 15ms]
The resource from "http://localhost:4200/styles.css" was blocked due to MIME type mismatch (X-Content-Type-Options: nosniff).

Both files, index.html and styles.css are located in the root directory of my angular app.
I've tried to get more info about the problem :

nosniff
    Blocks a request if the requested type is

        "style" and the MIME type is not "text/css", or
        "script" and the MIME type is not a JavaScript MIME type.

But I don't understand why it's bloking the request, since I've specified type="text/css" when referencing the stylesheet.

Body:
In running into the same kind of issue for a full stack web application (in development), I simply solved the problem by correctly linking the css file to the page rendered. Removing the rel = stylesheet, as suggested above, prevents the error to show up in the browser but it does not load the styles that should be applied to the page. In short, it isn't a solution.

If you are using express-static you can use this as an example:

Server-side:

app.use(express.static(__dirname + "/public", {
    index: false,
    immutable: true,
    cacheControl: true,
    maxAge: "30d"
}));

Client-side:

 <link type="text/css" rel="stylesheet" href="/main.css">

Just add a forward slash in front of the file you wish to link to the html page (if you are rendering html pages without using any template engines) and express-static will do the rest automatically for you.


问:
Make ColorTween forward to end immediately and reverse normally without changing the controller in flutter?
I have the following code:

Animation _colorTween = ColorTween(begin: Colors.black, end: Colors.white).animate(animation);

AnimatedBuilder(
  animation: _colorTween,
  builder: (_, _) => customBuilder(_colorTween.value),
),
```

The variable animation is from another widget, which I can not change it at all. I even can not control the animation's forward and reverse because that is controlled by another built-in widget.

So I am wondering if I can make the color becomes Colors.white immediately when the forward is called. For the reverse, I am OK with the default behavior.

答:
First off, I wouldn't name your input Animation '_colorTween'. That's just confusing since it's an animation!

But since you're already using a custom builder, you could likely do something like this in the custom build function:

switch(_colorTween.status) {
case AnimationStatus.forward:
  return <Colors.white or something like it>
default:
  return <normal calculation>
}
```

Although this could result in something slightly weird if the animation runs half way, then changes direction. You could put more logic in there to handle that though if needed.

Body:
I have the following code:

Animation _colorTween = ColorTween(begin: Colors.black, end: Colors.white).animate(animation);

AnimatedBuilder(
  animation: _colorTween,
  builder: (_, _) => customBuilder(_colorTween.value),
),

The variable animation is from another widget, which I can not change it at all. I even can not control the animation's forward and reverse because that is controlled by another built-in widget.

So I am wondering if I can make the color becomes Colors.white immediately when the forward is called. For the reverse, I am OK with the default behavior.

Body:
First off, I wouldn't name your input Animation '_colorTween'. That's just confusing since it's an animation!

But since you're already using a custom builder, you could likely do something like this in the custom build function:

switch(_colorTween.status) {
case AnimationStatus.forward:
  return <Colors.white or something like it>
default:
  return <normal calculation>
}

Although this could result in something slightly weird if the animation runs half way, then changes direction. You could put more logic in there to handle that though if needed.


问:
How to change a div's outline color when selected?
I need to change the outline color when the div is selected. I have tried by using the same technique as hover (shown below), but I need help with a selector. Is it possible via JavaScript or is CSS enough?

Here is what I tried:

div {
    background: #ccc;
    margin: 20px;
}
div:hover {
    outline: 1px solid blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>1</div>
<div>2</div>
<div>3</div></code>```

答:
/*
 Fix select next previuos selected
 Fix duplicate clicks diselect
*/
var valuesOld = new Array();
var num = 0;

function selected(pDiv) {
    num = num +1;
    valuesOld[num] = pDiv;
    console.log("Key"+num+"Value="+valuesOld[num]);

    $("#div" + pDiv).css("border-left", " 1px solid rgb(133, 189,147)");

    if(valuesOld[2] > 0 && valuesOld[1]> 0){
        $("#div" + valuesOld[num-1]).css("border-left", " 1px solid rgb(221, 84, 84)");
    }
        if(pDiv == valuesOld[num]){
        $("#div" + pDiv).css("border-left", " 5px solid rgb(133, 189, 147)");
    }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>div{
  border-left: 1px solid rgb(221, 84, 84);
  margin-top: 2px;
}</code>```

1

2

3
```

Body:
I need to change the outline color when the div is selected. I have tried by using the same technique as hover (shown below), but I need help with a selector. Is it possible via JavaScript or is CSS enough?

Here is what I tried:

div {
    background: #ccc;
    margin: 20px;
}
div:hover {
    outline: 1px solid blue;
}

1

2

3

Body:
/*
 Fix select next previuos selected
 Fix duplicate clicks diselect
*/
var valuesOld = new Array();
var num = 0;

function selected(pDiv) {
    num = num +1;
    valuesOld[num] = pDiv;
    console.log("Key"+num+"Value="+valuesOld[num]);

    $("#div" + pDiv).css("border-left", " 1px solid rgb(133, 189,147)");

    if(valuesOld[2] > 0 && valuesOld[1]> 0){
        $("#div" + valuesOld[num-1]).css("border-left", " 1px solid rgb(221, 84, 84)");
    }
        if(pDiv == valuesOld[num]){
        $("#div" + pDiv).css("border-left", " 5px solid rgb(133, 189, 147)");
    }
}

div{
  border-left: 1px solid rgb(221, 84, 84);
  margin-top: 2px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<div onclick="selected(1)" id="div1">1</div>
<div onclick="selected(2)" id="div2">2</div>
<div onclick="selected(3)" id="div3">3</div>


问:
object dynamic filtering with nested array of objects using javascript
i have this data sample,

```<code>{
    "section": [
        {
            "id": 1,
            "name" : "dogs"
        },
        {
            "id": 2,
            "name" : "cats"
        }
    ],
    "price" : [
        {

            "name" : "monthly",
            "price": {
                "amount": 10
            }
        }
    ],
    "specs": {
        "color" : {
            "name" : "green"
        }
    }
}
</code>```

i want to pick some properties from that object, like that

```<code>const obj = pick(obj,["section.id","price.price"])
</code>```

it should gives an object:

```<code>{
    "section": [
        {
            "id": 1,
        },
        {
            "id": 2,
        }
    ],
    "price" : [
        {
            "price": {
                "amount": 10
            }
        }
    ],
}
</code>```

i tried lodash.pick() and didn't understand the array of object case, it understand it if i used this syntax "section[0].name" and i want it generic, like "section.name"

答:
If you re already using lodash I do not see a reason to write your own _.pick but that is up to you. Here is how you can do this with lodash in one line or in few with chaining:

let obj = { "section": [{ "id": 1, "name": "dogs" }, { "id": 2, "name": "cats" } ], "price": [{ "name": "monthly", "price": { "amount": 10 } }], "specs": { "color": { "name": "green" } } }

let resultA = _.mapValues(_.omit(obj, ['specs']), a => _.map(a, o => _.pick(o, ['id', 'price'])))

// OR cleaner and more readable with _.chain

let resultB = _(obj)
  .omit(['specs'])
  .mapValues(a => _.map(a, o => _.pick(o, ['id', 'price'])))
  .value()

console.log(resultA)
console.log(resultB)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script></code>```

The idea is to _.mapValues through the objects and map over the arrays to pick what you need. In this case 'id' and 'price'.

Body:
i have this data sample,

{
    "section": [
        {
            "id": 1,
            "name" : "dogs"
        },
        {
            "id": 2,
            "name" : "cats"
        }
    ],
    "price" : [
        {

            "name" : "monthly",
            "price": {
                "amount": 10
            }
        }
    ],
    "specs": {
        "color" : {
            "name" : "green"
        }
    }
}

i want to pick some properties from that object, like that

const obj = pick(obj,["section.id","price.price"])

it should gives an object:

{
    "section": [
        {
            "id": 1,
        },
        {
            "id": 2,
        }
    ],
    "price" : [
        {
            "price": {
                "amount": 10
            }
        }
    ],
}

i tried lodash.pick() and didn't understand the array of object case, it understand it if i used this syntax "section[0].name" and i want it generic, like "section.name"

Body:
If you re already using lodash I do not see a reason to write your own _.pick but that is up to you. Here is how you can do this with lodash in one line or in few with chaining:

let obj = { "section": [{ "id": 1, "name": "dogs" }, { "id": 2, "name": "cats" } ], "price": [{ "name": "monthly", "price": { "amount": 10 } }], "specs": { "color": { "name": "green" } } }

let resultA = _.mapValues(_.omit(obj, ['specs']), a => _.map(a, o => _.pick(o, ['id', 'price'])))

// OR cleaner and more readable with _.chain

let resultB = _(obj)
  .omit(['specs'])
  .mapValues(a => _.map(a, o => _.pick(o, ['id', 'price'])))
  .value()

console.log(resultA)
console.log(resultB)

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

The idea is to _.mapValues through the objects and map over the arrays to pick what you need. In this case 'id' and 'price'.