问:
React and Flask-Restful - how to render Jinja template
I am building a RESTful Flask API with React at the frontend.

I want to be able to use React to get and upload data, but render my Jinja templates first at server side with Flask. This is what I have so far:

React

Seeds.jsx

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

class Seeds extends Component{
  constructor (props) {
    super(props);
    this.state = {
      restaurant:'',
      email: '',
      id: '',
      username: '',
      active: '',
      admin: ''
    };
  };
  componentDidMount() {
    if (this.props.isAuthenticated) {
      this.getSeeds();
    }
  };
  getSeeds(event) {
    const options = {
      url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds`,
      method: 'get',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
    };
    return axios(options)
    .then((res) => {
    console.log(res)
      console.log(res.data.data)
      this.setState({
        restaurant: res.data.data[0].restaurant,
        template: res.data.data[0].content
      })
    })
    .catch((error) => { console.log(error); });
  };

    render(){
        let seeds_page;
        seeds_page = this.setState.template;

        return (
           <div className="form">
            {seeds_page}
           </div>
        );
    }
}

export default Seeds;
</code>```

Flask

seeds.py

```<code>seeds_bp = Blueprint('seeds',
                     __name__,
                     template_folder='templates',
                     static_url_path='static')

@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():

    user = User.query.filter_by(id=1).first()

    response_object = {
          'status': 'success',
          'message': 'success',
          'data': [{"user": user.restaurant,
                    "content": "seeds.html"}]
    }
    return jsonify(response_object), 200
</code>```

Jinja

seeds.html

```<code>{% include 'partials/head.html' %}
<section id="woz-content" >

  <div class="container">
    <h1 class="page-title">Menu(edit)</h1>
  </div>

  <div class="container">

    <h2 class="page-title">Seeds</h2>

    <ul style="list-style:none" >
        <li><form action="{{ url_for('seeds.handle_seeds') }}"method="post">Seed1
            <input type="text" name="seed1"/>
            <label style="font-size: 11px;"></label>
            <input type="submit" value="seed" >
          </form>
        </li>
       <li><form action="{{ url_for('seeds.handle_seeds') }}" method="post">Seed2
            <input type="text" name="seed2"/>
            <label style="font-size: 11px;"></label>
            <input type="submit" value="seed" >
          </form></li>
     </ul>
   </div>
</code>```

I manage to get my data, but no rendering is carried on.

How can I tweak the code in order to render my template while getting the data?

答:
I assume that you want to render seeds.html inside react component because you have this code inside react component:

```<code>render(){
        let seeds_page;
        seeds_page = this.setState.template;

        return (
           <div className="form">
            {seeds_page}
           </div>
        );
    }
</code>```

To achieve this action, you need to assure that your seeds.html file have the same syntax of JSX. For example, this code did not work inside your react component:

```<code><h1 class='title'>Some title</h1>
</code>```

because react use className instead of class. So, you need to rewrite your seeds.html to be similar to JSX Syntax or find react module can parse html template to JSX code. It will be similar to this:

```<code>{% include 'partials/head.html' %}
<section id="woz-content" >

  <div className="container">
    <h1 className="page-title">Menu(edit)</h1>
  </div>
  ...
</section>
</code>```

Then you can render the template using render_template function:

```<code>from flask import render_template
@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():

    user = User.query.filter_by(id=1).first()
    example = "some example"
    template = render_template('seeds.html', example=example)

    response_object = {
          'status': 'success',
          'message': 'success',
          'data': [{"user": user.restaurant,
                    "content": template}]
    }
    return jsonify(response_object)
</code>```

Then, you can get the template via axios request and saved in the template state. To convert the template string to react component, you can use React HTML Parser an utility for converting HTML strings into React components.
So Seeds.jsx will be similar to this:

```<code>import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 }
from 'react-html-parser';

class Seeds extends Component{
    constructor (props) {
         super(props);
         this.state = {
            restaurant:'',
            email: '',
            id: '',
            username: '',
            active: '',
            admin: '',
            template: ''
         };
    };
    // ...
    render(){
        var seeds_page = this.state.template;

        return (
           <div className="form">
            { ReactHtmlParser(seeds_page) }
           </div>
        );
    }
}

export default Seeds;
</code>```

Body:
I am building a RESTful Flask API with React at the frontend.

I want to be able to use React to get and upload data, but render my Jinja templates first at server side with Flask. This is what I have so far:

React

Seeds.jsx

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

class Seeds extends Component{
  constructor (props) {
    super(props);
    this.state = {
      restaurant:'',
      email: '',
      id: '',
      username: '',
      active: '',
      admin: ''
    };
  };
  componentDidMount() {
    if (this.props.isAuthenticated) {
      this.getSeeds();
    }
  };
  getSeeds(event) {
    const options = {
      url: `${process.env.REACT_APP_WEB_SERVICE_URL}/seeds`,
      method: 'get',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${window.localStorage.authToken}`
      }
    };
    return axios(options)
    .then((res) => {
    console.log(res)
      console.log(res.data.data)
      this.setState({
        restaurant: res.data.data[0].restaurant,
        template: res.data.data[0].content
      })
    })
    .catch((error) => { console.log(error); });
  };

    render(){
        let seeds_page;
        seeds_page = this.setState.template;

        return (

            {seeds_page}

        );
    }
}

export default Seeds;

Flask

seeds.py

seeds_bp = Blueprint('seeds',
                     __name__,
                     template_folder='templates',
                     static_url_path='static')

@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():

    user = User.query.filter_by(id=1).first()

    response_object = {
          'status': 'success',
          'message': 'success',
          'data': [{"user": user.restaurant,
                    "content": "seeds.html"}]
    }
    return jsonify(response_object), 200

Jinja

seeds.html

{% include 'partials/head.html' %}

Menu(edit)

Seeds

<form action="{{ url_for('seeds.handle_seeds') }}"method="post">Seed1
            <input type="text" name="seed1"/>

            <input type="submit" value="seed" >
          </form>

<form action="{{ url_for('seeds.handle_seeds') }}" method="post">Seed2
            <input type="text" name="seed2"/>

            <input type="submit" value="seed" >
          </form>

I manage to get my data, but no rendering is carried on.

How can I tweak the code in order to render my template while getting the data?

Body:
I assume that you want to render seeds.html inside react component because you have this code inside react component:

render(){
        let seeds_page;
        seeds_page = this.setState.template;

        return (
           <div className="form">
            {seeds_page}
           </div>
        );
    }

To achieve this action, you need to assure that your seeds.html file have the same syntax of JSX. For example, this code did not work inside your react component:

<h1 class='title'>Some title</h1>

because react use className instead of class. So, you need to rewrite your seeds.html to be similar to JSX Syntax or find react module can parse html template to JSX code. It will be similar to this:

{% include 'partials/head.html' %}
<section id="woz-content" >

  <div className="container">
    <h1 className="page-title">Menu(edit)</h1>
  </div>
  ...
</section>

Then you can render the template using render_template function:

from flask import render_template
@seeds_bp.route('/seeds', methods=['GET', 'POST'])
def seeds():

    user = User.query.filter_by(id=1).first()
    example = "some example"
    template = render_template('seeds.html', example=example)

    response_object = {
          'status': 'success',
          'message': 'success',
          'data': [{"user": user.restaurant,
                    "content": template}]
    }
    return jsonify(response_object)

Then, you can get the template via axios request and saved in the template state. To convert the template string to react component, you can use React HTML Parser an utility for converting HTML strings into React components.
So Seeds.jsx will be similar to this:

import ReactHtmlParser, { processNodes, convertNodeToElement, htmlparser2 }
from 'react-html-parser';

class Seeds extends Component{
    constructor (props) {
         super(props);
         this.state = {
            restaurant:'',
            email: '',
            id: '',
            username: '',
            active: '',
            admin: '',
            template: ''
         };
    };
    // ...
    render(){
        var seeds_page = this.state.template;

        return (
           <div className="form">
            { ReactHtmlParser(seeds_page) }
           </div>
        );
    }
}

export default Seeds;


来源: stackexchange

问:
Macro run time error
I have a peice of code that filters a column for zero values and returns the rowcount. I tried looping over different columns.this macro works well with small input.
But I have an excel sheet with 160106 rows. I want to run my macro on this . I am getting a run 1004 error.I found the following link which kind of explains the problem
http://support.microsoft.com/kb/210684

But I am not able to resolve it. Could anyone please help me. I am pasting my macro below

my sample file is in
http://rapidshare.com/files/457005707/data1.xlsx
it is a 96mb file

```<code>Option Explicit
Sub findrcn()
Dim wsStart As Worksheet
Dim sWord As String
Dim RowCount As Integer
Dim i As Long
Dim j As Long
Dim l As Long
Dim k As String
Dim Final As Integer
Dim lastrow As Integer
Dim rng As Range
Dim oBook As Workbook

Set wsStart = ActiveSheet
'this loop is to check if a sheet exists
    For j = 1 To Worksheets.Count
    k = Worksheets(j).Name
    If UCase(k) = UCase("Analysis") Then
        lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
    Else
        lastrow = 0
    End If

    Next j
    MsgBox "finished checking the sheets"
i = 1
For Each rng In Range("A1:B1").Columns
        sWord = Replace(rng.Address(RowAbsolute:=False), "$", "")   ''Now I am trying to loop over all the columns

    If lastrow = 0 Then
            Sheets.Add After:=Sheets(Sheets.Count) 'Adding a new sheet
            Sheets(Sheets.Count).Name = "Analysis"
            wsStart.AutoFilterMode = False

                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that

                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count 'get the count of the number of rows after the filter
                        RowCount = Final - 1
                        End With

                       Sheets("Analysis").Range("A") = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B") = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False
                MsgBox "Trust in the Lord with all your heart and lean not on your own understanding; In all your ways acknowledge Him, and He will make your paths straight." & vbCrLf & "Proverbs 3:5" & vbCrLf & "                        SUCCESSFULLY     COMPLETED!!!"

    Else

        wsStart.AutoFilterMode = False

                lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that
                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count
                        RowCount = Final - 1 ' to account for column name
                        End With

                       Sheets("Analysis").Range("A" & lastrow) = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B" & lastrow) = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False

    End If
i = i + 1
Next rng
</code>```

答: Although that knowledgebase article is talking about copying sheets and you're copying cells, you could follow its advice and save and close your worksheets periodically.</p>

ContentLicense: CC BY-SA 3.0

Title: Macro run time error

Body:
I have a peice of code that filters a column for zero values and returns the rowcount. I tried looping over different columns.this macro works well with small input.
But I have an excel sheet with 160106 rows. I want to run my macro on this . I am getting a run 1004 error.I found the following link which kind of explains the problem
http://support.microsoft.com/kb/210684

But I am not able to resolve it. Could anyone please help me. I am pasting my macro below

my sample file is in
http://rapidshare.com/files/457005707/data1.xlsx
it is a 96mb file

Option Explicit
Sub findrcn()
Dim wsStart As Worksheet
Dim sWord As String
Dim RowCount As Integer
Dim i As Long
Dim j As Long
Dim l As Long
Dim k As String
Dim Final As Integer
Dim lastrow As Integer
Dim rng As Range
Dim oBook As Workbook

Set wsStart = ActiveSheet
'this loop is to check if a sheet exists
    For j = 1 To Worksheets.Count
    k = Worksheets(j).Name
    If UCase(k) = UCase("Analysis") Then
        lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
    Else
        lastrow = 0
    End If

    Next j
    MsgBox "finished checking the sheets"
i = 1
For Each rng In Range("A1:B1").Columns
        sWord = Replace(rng.Address(RowAbsolute:=False), "$", "")   ''Now I am trying to loop over all the columns

    If lastrow = 0 Then
            Sheets.Add After:=Sheets(Sheets.Count) 'Adding a new sheet
            Sheets(Sheets.Count).Name = "Analysis"
            wsStart.AutoFilterMode = False

                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that

                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count 'get the count of the number of rows after the filter
                        RowCount = Final - 1
                        End With

                       Sheets("Analysis").Range("A") = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B") = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False
                MsgBox "Trust in the Lord with all your heart and lean not on your own understanding; In all your ways acknowledge Him, and He will make your paths straight." & vbCrLf & "Proverbs 3:5" & vbCrLf & "                        SUCCESSFULLY     COMPLETED!!!"

    Else

        wsStart.AutoFilterMode = False

                lastrow = ((Sheets("Analysis").Range("A" & Rows.Count).End(xlUp).Row) + 1)
                With wsStart
                    .Range(sWord).AutoFilter Field:=i, Criteria1:="=0" 'if my column contains a 0 in it filter that
                        With .AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible)
                        Final = .Count
                        RowCount = Final - 1 ' to account for column name
                        End With

                       Sheets("Analysis").Range("A" & lastrow) = RowCount 'paste it in the analysis tab
                       Sheets("Analysis").Range("B" & lastrow) = (Range(sWord))

                End With
                wsStart.AutoFilterMode = False

    End If
i = i + 1
Next rng


问:
how to remove duplicate values from Array using reactjs?
hello im beginnger in javascript also in react. can somebody help me to solve this. i just try this project from reactjs blog but i just wanna try solve this with my way

todoList.js

```<code>const todoList = [
    {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
    {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
    {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
    {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
    {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

export default todoList
</code>```

FilterTableProdcTable.js

```<code>class FilterableProductTable extends React.Component{
    render(){
        const aw = []
        todoList.forEach(elem=>{
            if(aw.indexOf(elem.category) === -1){
                aw.push(
                    <li key={elem.name}> {elem.category}</li>
                )
            }
        })

        return(
            <div>
                {aw}
            </div>
        )
    }
}
</code>```

the result still same, all duplicate values still show on my screen. can somebody help me?

im sorry about my broken english, but thank you all

答:
```<code>const uniqueTodos = todoList.filter((todo,index) => {
  return index === todoList.findIndex(obj => {
    return JSON.stringify(obj) === JSON.stringify(todo);
  });
});
</code>```

Also change your data.  There is nothing unique in that dataset.

Also, this code will remove objects only if they are identical with all properties.  It can be adapted to only consider one property.

```<code>const uniqueTodos = todoList.filter((todo,index) => {
      return index === todoList.findIndex(obj => {
        return obj.category === todo.category;
      });
    });
</code>```

```<code>class FilterableProductTable extends React.Component{
    render(){
        const aw = []
        uniqueTodos.forEach(todo => {
             aw.push(<li key={todo.name}> {todo.category}</li>)
        })

        return(
            <div>
                {aw}
            </div>
        )
    }
}
</code>```

Also I have changed your dataset a little bit to test it.

```<code>const todoList = [
    {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
    {category: 'Sporting Goods', price: '$29.99', stocked: true, name: 'Basketball'},
    {category: 'Sporting Goods', price: '$29.99', stocked: true, name: 'Basketball'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
    {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}
];

export default todoList
</code>```

ContentLicense: CC BY-SA 4.0

Body:
hello im beginnger in javascript also in react. can somebody help me to solve this. i just try this project from reactjs blog but i just wanna try solve this with my way

todoList.js

const todoList = [
    {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
    {category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
    {category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
    {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
    {category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];

export default todoList

FilterTableProdcTable.js

class FilterableProductTable extends React.Component{
    render(){
        const aw = []
        todoList.forEach(elem=>{
            if(aw.indexOf(elem.category) === -1){
                aw.push(

 {elem.category}

                )
            }
        })

        return(

                {aw}

        )
    }
}

the result still same, all duplicate values still show on my screen. can somebody help me?

im sorry about my broken english, but thank you all

Body:
const uniqueTodos = todoList.filter((todo,index) => {
  return index === todoList.findIndex(obj => {
    return JSON.stringify(obj) === JSON.stringify(todo);
  });
});

Also change your data.  There is nothing unique in that dataset.

Also, this code will remove objects only if they are identical with all properties.  It can be adapted to only consider one property.

const uniqueTodos = todoList.filter((todo,index) => {
      return index === todoList.findIndex(obj => {
        return obj.category === todo.category;
      });
    });

class FilterableProductTable extends React.Component{
    render(){
        const aw = []
        uniqueTodos.forEach(todo => {
             aw.push(<li key={todo.name}> {todo.category}</li>)
        })

        return(
            <div>
                {aw}
            </div>
        )
    }
}

Also I have changed your dataset a little bit to test it.

const todoList = [
    {category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
    {category: 'Sporting Goods', price: '$29.99', stocked: true, name: 'Basketball'},
    {category: 'Sporting Goods', price: '$29.99', stocked: true, name: 'Basketball'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
    {category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
    {category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'}
];

export default todoList


问:
Why is Observable within Observable hanging?
I have an http.get call in my service member.service.ts and I want to wait until that call completes before proceeding in app.component, so I'm trying to wrap the http.get call into an Observable for processing in app.component.

[Note: previously, before I wrapped the service in an Observable, the service was working fine . . . the http.get call on its own works as expected and returns a JSON object.]

But when I wrapped the http.get call in an Observable, as below, the application hangs. I searched online and read about flatMap, forkjoin, etc., but I'd like to keep the current structure, where the http.get call is in the member service, and all the other code is in app.component.

Many thanks if any ideas why it's hanging and how to fix!

member.service.ts

```<code>import { Injectable } from '@angular/core';
import { Observable, from, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MemberService {
  url: string = "http://localhost:3000/sign-up";
  data: string = '';

  constructor(private http: HttpClient) { }

  getMemberForm(): Observable<any> {

   let library = this.http.get(this.url,{responseType: 'json'});

    library.subscribe((data) => {
      this.data = JSON.stringify(data);
    });
    return of(this.data);
  }

}

</code>```

app.component.ts

```<code>import { Component, OnInit, Injectable } from '@angular/core';
import { MemberService } from './member.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

@Injectable()
export class AppComponent implements OnInit {
  got_data: boolean = false;
  data: string;

  constructor(private member: MemberService) {}

  ngOnInit() {

    this.member.getMemberForm().subscribe((data)=>{
      this.data = data;
      if (this.data.length > 0) this.got_data = true;
    });
  }

}

</code>```

答:
You are not handling the asynchrous code in a proper way.

Asynchronous code is the code which runs outside the normal execution flow of code. The code inside your subscribe method is asynchronous and it will only run when the response of HTTP call is received.

Change your code like this:

```<code>getMemberForm(): Observable<any> {

   return this.http.get(this.url,{responseType: 'json'})
    .pipe(map( res => of(JSON.stringify(res))))
  }
</code>```

You application is hanging probably because your this.data is undefined and your are trying to change undefined into Observable

Body:
I have an http.get call in my service member.service.ts and I want to wait until that call completes before proceeding in app.component, so I'm trying to wrap the http.get call into an Observable for processing in app.component.

[Note: previously, before I wrapped the service in an Observable, the service was working fine . . . the http.get call on its own works as expected and returns a JSON object.]

But when I wrapped the http.get call in an Observable, as below, the application hangs. I searched online and read about flatMap, forkjoin, etc., but I'd like to keep the current structure, where the http.get call is in the member service, and all the other code is in app.component.

Many thanks if any ideas why it's hanging and how to fix!

member.service.ts

import { Injectable } from '@angular/core';
import { Observable, from, of } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class MemberService {
  url: string = "http://localhost:3000/sign-up";
  data: string = '';

  constructor(private http: HttpClient) { }

  getMemberForm(): Observable<any> {

   let library = this.http.get(this.url,{responseType: 'json'});

    library.subscribe((data) => {
      this.data = JSON.stringify(data);
    });
    return of(this.data);
  }

}

app.component.ts

import { Component, OnInit, Injectable } from '@angular/core';
import { MemberService } from './member.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

@Injectable()
export class AppComponent implements OnInit {
  got_data: boolean = false;
  data: string;

  constructor(private member: MemberService) {}

  ngOnInit() {

    this.member.getMemberForm().subscribe((data)=>{
      this.data = data;
      if (this.data.length > 0) this.got_data = true;
    });
  }

}

Body:
You are not handling the asynchrous code in a proper way.

Asynchronous code is the code which runs outside the normal execution flow of code. The code inside your subscribe method is asynchronous and it will only run when the response of HTTP call is received.

Change your code like this:

getMemberForm(): Observable<any> {

   return this.http.get(this.url,{responseType: 'json'})
    .pipe(map( res => of(JSON.stringify(res))))
  }

You application is hanging probably because your this.data is undefined and your are trying to change undefined into Observable


问:
CSV values to compare with table values
Need to compare CSV data with table rows data

Have tried map for csv and array for table query

答:
I hope it will help you:

```<code>public List<String[]> readCSV(String csvFile) throws IOException {
    List<String[]> returnVal = new ArrayList<>();
    String line;
    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
       while ((line = br.readLine()) != null)
           returnVal.add(line.split(","));
    }
    return returnVal;
}
</code>```

This function take csv file(path) and return list of rows.

You can compare the rows or do any analysis on the data.

Title: CSV values to compare with table values

Body:
I hope it will help you:

public List<String[]> readCSV(String csvFile) throws IOException {
    List<String[]> returnVal = new ArrayList<>();
    String line;
    try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
       while ((line = br.readLine()) != null)
           returnVal.add(line.split(","));
    }
    return returnVal;
}

This function take csv file(path) and return list of rows.

You can compare the rows or do any analysis on the data.


问:
How we run a .NET 32-bit application in a 64-bit Windows server?
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

```<code>System.BadImageFormatException: is not a valid Win32 application.
</code>```

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

答:
One thing that might work is making sure the .Net application is flagged as a true 32 bit application by changing the target CPU details.

In the Visual Studio 2005 you can do this by going to the project Properties and in the Build section set the Platform Target to x86 and not Any APU which is the default.

OwnerDisplayName: Geo

ContentLicense: CC BY-SA 2.5

Body:
We are installing a third party application in one of our 64-bit Windows servers.  This application apparently was build with the compiler option set to choose the platform at run time.  When we run the application it gives us an error:

System.BadImageFormatException: is not a valid Win32 application.

I have seen in MSDN forums that in order to fix this error I have to build the application set to 32-bit, and that way it will run fine on a 64-bit server.  I check on other StackOverflow links Other Posts.

How to get around this situation?  For everyone that wants to know more information:

The application is running fine in a 32-bit test server.

IIS version 6

using SQL Server Express 2005

On the Web Service Extension there are both Framework64\v2.0.50727\aspnet_isapi.dll

and Framework\v2.0.50727\aspnet_isapi.dll

LastEditorDisplayName: Joel Coehoorn

OwnerDisplayName: jussij


问:
How to Convert Tuple to Dictionary?
i'm using Python 2.5 and Win XP. i have a tuple as below:

```<code>>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>
</code>```

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq

Title: How to Convert Tuple to Dictionary?

Body:
i'm using Python 2.5 and Win XP. i have a tuple as below:

>>> a
(None, '{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}')
>>> a[1]
'{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}'
>>>

i want to convert tuple a[1] to dictionary because i want to use the key and value. pls help to advise. tq

Body:
>>> import ast
>>> ast.literal_eval(a[1])
{1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12}


问:
How to get the mouse pos relative to the background img
I need to get the mouse position on a divs background img.

This is the css:

```<code>width: 100%;
height: 100%;
background-image: url("default.png");
background-size: contain;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;
</code>```

This is the html:

Any help would really be appreciated.

-----------------Edit--------------------
The img has a fixed size so it doesn't fill up the whole browser screen.

答:
If you only want the position inside a specific element, you can use:

```<code>let x = event.clientX;
let y = event.clientY;
</code>```

If you wonder where does event come from:

```<code>document.querySelector("#div").addEventListener("click",(event)=>{
  let x = event.clientX;
  let y = event.clientY;
});
</code>```

And then you can do whatever you want with x and y.

Look at an example:

document.querySelector("#div").addEventListener("click",(event)=>{
  console.log(`x: ${event.clientX}, y:${event.clientY}`);
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body{
  margin:0;padding:0;
}

#div {
  position: absolute;
  width: 100%;
  height: 100%;
  background: red;
}</code>```

```

Body:
I need to get the mouse position on a divs background img.

This is the css:

width: 100%;
height: 100%;
background-image: url("default.png");
background-size: contain;
background-repeat: no-repeat;
background-attachment: fixed;
background-position: center;

This is the html:

Any help would really be appreciated.

-----------------Edit--------------------
The img has a fixed size so it doesn't fill up the whole browser screen.

Body:
If you only want the position inside a specific element, you can use:

let x = event.clientX;
let y = event.clientY;

If you wonder where does event come from:

document.querySelector("#div").addEventListener("click",(event)=>{
  let x = event.clientX;
  let y = event.clientY;
});

And then you can do whatever you want with x and y.

Look at an example:

document.querySelector("#div").addEventListener("click",(event)=>{
  console.log(`x: ${event.clientX}, y:${event.clientY}`);
});

body{
  margin:0;padding:0;
}

#div {
  position: absolute;
  width: 100%;
  height: 100%;
  background: red;
}

<div id="div"></div>


问:
Simpe C code physically breaks nucleo boards
Code below physically breaks nucleo boards. 2 so far.
ST links is unable to connect and boards are not detected.
first dead one was xncleo stm32f411re, another one is nucleo stm32f446re.
I'm a complete beginner and that is pretty much my first code.
and 2 boards dead;) The question is why it may happen? or can one reset the board harder that normal jumper reset

```<code>
int main()
{
    RCC->AHB1ENR = (1<<0);
    GPIOA->MODER = (1<<5);

    while(1)
    {
            GPIOA->ODR |=  (0<<5);
    }
}
</code>```

This is similar to this question ->
https://electronics.stackexchange.com/questions/204996/stm32-st-link-cannot-connect-to-mcu-after-successful-programming
, answer to which helped me to restore the board, however answers to my problem in this thread are also very helpfull.

答: Yes, your problem is with the line "RCC->AHB1ENR = (1<<0);". That enables power to GPIOA, but disables power to the other GPIOs (B,C,D,E, and H on the F411), which includes the SWD pins.</p>

Body:
Code below physically breaks nucleo boards. 2 so far.
ST links is unable to connect and boards are not detected.
first dead one was xncleo stm32f411re, another one is nucleo stm32f446re.
I'm a complete beginner and that is pretty much my first code.
and 2 boards dead;) The question is why it may happen? or can one reset the board harder that normal jumper reset

int main()
{
    RCC->AHB1ENR = (1<<0);
    GPIOA->MODER = (1<<5);

    while(1)
    {
            GPIOA->ODR |=  (0<<5);
    }
}

This is similar to this question ->
https://electronics.stackexchange.com/questions/204996/stm32-st-link-cannot-connect-to-mcu-after-successful-programming
, answer to which helped me to restore the board, however answers to my problem in this thread are also very helpfull.


问:
How to pass two value from a link to another page using php?
I need to pass two value from a php page to another. I can pass one value but dont know about two.

```<code><a href="boardInsert.php?exam=<?php echo $row['year']; ?>">Delete</a>
</code>```

I need to pass another variable called 'year' with 'exam'.

答:
PHP has a much better function to make query strings. It is safer than manually creating it. It is called http_build_query

You can build an array of values and then pass it through this function when making a html link.

```<code>$values = [
    'exam' => $row['idr'],
    'year' => $row['yid']
];
echo '<a href="boardInsert.php?'. http_build_query($values) .'">Delete</a>';
</code>```

Body:
I need to pass two value from a php page to another. I can pass one value but dont know about two.

<a href="boardInsert.php?exam=<?php echo $row['year']; ?>">Delete

I need to pass another variable called 'year' with 'exam'.

Body:
PHP has a much better function to make query strings. It is safer than manually creating it. It is called http_build_query

You can build an array of values and then pass it through this function when making a html link.

$values = [
    'exam' => $row['idr'],
    'year' => $row['yid']
];
echo '<a href="boardInsert.php?'. http_build_query($values) .'">Delete</a>';


问:
Line-chart of time-series data with monthly labels on x-axis but daily data on y-axis
I have the following data:

```<code>library(dplyr)
    set.seed(122)
    df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
date <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5)
</code>```

These are supposed to be 1260 daily prices with one year = 252 days and 1 month = 21 days.

Now, I want to draw a line-chart with the daily prices on the y-axis and months on the x-axis. The code below is adapted form this thread Graphing time-series data when date column doesn't exist:

library(tidyverse)

df %>%
    as.data.frame() %>%
    rename(price = 1) %>%
    mutate(rnames = rownames(.)) %>%
    ggplot(aes(x = as.numeric(rnames), y = price,
                group = rep(1:5, times=1, each=252))) +
      geom_line() +
      labs(title = "Stock Price Chart", y = "Price", x = "date") +
      scale_x_continuous(breaks = seq(1, 1260, by = 21), labels = date)
```

<p>However, I slightly changed my <code>df</code> by inserting a new first row with value <code>1</code>.</p>

```df <- rbind(df[0,],c(1),df[1:nrow(df),])
```

This is supposed to be the starting price at t=0. Unfortunately, the code doesn't work out now. Is there a quick fix for this?

答:
library(tidyverse)

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames)-1, y = price,
             group = c(1,rep(1:5, times=1, each=252)))) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21), labels = date)
```

<p>You can also add a new breakpoint for point <code>0</code>. by changing like <code>scale_x</code> like this:</p>

```scale_x_continuous(breaks = c(0, seq(1, 1260, by = 21)), labels = c("t=0", date))
```

If you still want the datapoint with price == 1 (your new row) be labeled as Jan then you don't need to subtract 1 from your x in the aesthetics and your breaks don't need to be manipulated. It works either way.

The most important thing to get my previous code to work with your new dataframe is changing the group in the aesthetics to be the same size as your new dataframe.

Body:
I have the following data:

library(dplyr)
    set.seed(122)
    df <- as_tibble(rlnorm(1260, meanlog = 0.06, sdlog = 0.20))
date <- rep(c("Jan", "Feb", "Mär", "Apr", "Mai", "Jun",
      "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"), 5)

These are supposed to be 1260 daily prices with one year = 252 days and 1 month = 21 days.

Now, I want to draw a line-chart with the daily prices on the y-axis and months on the x-axis. The code below is adapted form this thread Graphing time-series data when date column doesn't exist:

library(tidyverse)

df %>%
    as.data.frame() %>%
    rename(price = 1) %>%
    mutate(rnames = rownames(.)) %>%
    ggplot(aes(x = as.numeric(rnames), y = price,
                group = rep(1:5, times=1, each=252))) +
      geom_line() +
      labs(title = "Stock Price Chart", y = "Price", x = "date") +
      scale_x_continuous(breaks = seq(1, 1260, by = 21), labels = date)

However, I slightly changed my df by inserting a new first row with value 1.

df <- rbind(df[0,],c(1),df[1:nrow(df),])

This is supposed to be the starting price at t=0. Unfortunately, the code doesn't work out now. Is there a quick fix for this?

Body:
library(tidyverse)

df %>%
  as.data.frame() %>%
  rename(price = 1) %>%
  mutate(rnames = rownames(.)) %>%
  ggplot(aes(x = as.numeric(rnames)-1, y = price,
             group = c(1,rep(1:5, times=1, each=252)))) +
  geom_line() +
  labs(title = "Stock Price Chart", y = "Price", x = "date") +
  scale_x_continuous(breaks = seq(1, 1260, by = 21), labels = date)

You can also add a new breakpoint for point 0. by changing like scale_x like this:

scale_x_continuous(breaks = c(0, seq(1, 1260, by = 21)), labels = c("t=0", date))

If you still want the datapoint with price == 1 (your new row) be labeled as Jan then you don't need to subtract 1 from your x in the aesthetics and your breaks don't need to be manipulated. It works either way.

The most important thing to get my previous code to work with your new dataframe is changing the group in the aesthetics to be the same size as your new dataframe.


问:
Reverse lookup value of ForeignKey (Child to Parent)
I'm in need of accessing a value the reverse way using ForeignKey. I want to go from child model Category to parent model Post and grab the value title into my template

I've tried category.posts.title but it isn't showing any success for me.

The main purpose of this is to create a
 for each Category and list the blog posts with that category down below.

Models:

```<code>class Category(models.Model):
    name = models.CharField(max_length=30)

class Post(models.Model):
    slug = models.SlugField(max_length = 250, null = True, blank = True)
    title = models.CharField(max_length = 250, default="Blog Post")
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ForeignKey('Category', related_name='posts', default="2", unique=False, on_delete=models.CASCADE)
</code>```

View:

```<code>def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    categories = Category.objects.all()
    context = {
        "posts": posts,
        "categories": categories,
    }
    return render(request, "blog_index.html", context)
</code>```

Template

```<code><div class="row">
<div style="padding: 0px;" class="col l12">
    {% for category in categories %}

<div class="col l3">
    <div style="background-color: white; box-shadow: 0 1px 15px 1px rgba(62,57,107,.07); border-radius: .6rem;" class="card ">
        <div class="card-body text-center">
            <div class="mb-4 pb-3"><i class="ti-briefcase text-muted font-40"></i></div>

            <h5 class="mb-3"> <a href="{% url 'blog_category' category %}">{{ category.name }}</a></h5>

            <div><a class="d-inline-flex align-items-center text-danger" ><a href="{% url 'blog_detail' category.name category.posts.slug category.posts.pk %}">{{ category.posts.title }}</a><i class="material-icons">
                keyboard_arrow_right
                </i></a></div>

        </div>
    </div>
</div>
{% endfor %}
</code>```

答:
You need to loop over the posts in each category

```<code>{% for post in category.posts.all %}
    <a href="{% url 'blog_detail' category.name post.slug post.pk %}">{{ post.title }}</a>
{% endfor %}
</code>```

You should also use prefetch_related on your categories queryset to reduce the number of DB queries you make when you access category.posts.all as you no longer need your posts queryset

```<code>def blog_index(request):
    categories = Category.objects.annotate(
        post_count=Count('posts')
    ).prefetch_related('posts')
    context = {
        "categories": categories,
    }
    return render(request, "blog_index.html", context)
</code>```

Added the annotation for getting the count of posts for each category

```<code>{% category.post_count %}
</code>```

Body:
I'm in need of accessing a value the reverse way using ForeignKey. I want to go from child model Category to parent model Post and grab the value title into my template

I've tried category.posts.title but it isn't showing any success for me.

The main purpose of this is to create a
 for each Category and list the blog posts with that category down below.

Models:

class Category(models.Model):
    name = models.CharField(max_length=30)

class Post(models.Model):
    slug = models.SlugField(max_length = 250, null = True, blank = True)
    title = models.CharField(max_length = 250, default="Blog Post")
    body = models.TextField()
    created_on = models.DateTimeField(null=True)
    last_modified = models.DateTimeField(null=True)
    categories = models.ForeignKey('Category', related_name='posts', default="2", unique=False, on_delete=models.CASCADE)

View:

def blog_index(request):
    posts = Post.objects.all().order_by('-created_on')
    categories = Category.objects.all()
    context = {
        "posts": posts,
        "categories": categories,
    }
    return render(request, "blog_index.html", context)

Template

    {% for category in categories %}

 {{ category.name }}

{{ category.posts.title }}
                keyboard_arrow_right

{% endfor %}

Body:
You need to loop over the posts in each category

{% for post in category.posts.all %}
    <a href="{% url 'blog_detail' category.name post.slug post.pk %}">{{ post.title }}</a>
{% endfor %}

You should also use prefetch_related on your categories queryset to reduce the number of DB queries you make when you access category.posts.all as you no longer need your posts queryset

def blog_index(request):
    categories = Category.objects.annotate(
        post_count=Count('posts')
    ).prefetch_related('posts')
    context = {
        "categories": categories,
    }
    return render(request, "blog_index.html", context)

Added the annotation for getting the count of posts for each category

{% category.post_count %}


问:
Convert String (http json) to Object in java (automatic)
I'm a beginner in programming, and I need some help. Is it possible to convert an HTTP (that returns a Json) automatic call to object in java? For example it reads the request, and when I call System.out.println (obj) it already returns me an OBJECT of this request, instead of String. Is it possible? If so, could you help me ... I already did the method to call the url and return string, but I need to return OBJECT, so I can compare with HashCode and Equals.

My code:

enter image description here
output:
{"header":{"messageId":"02938ec7-b2c3-4131-8ecf-3ad3a8509b41"},"body":{"products"

What I wanted: output
Informacoes [header=Header [messageId=66d22c00-bddc-4ea7-afbd-7c7225fcb914], body=Body

答:
From what I can understand from your question, it looks like Gson might be useful. Gson is a library that allows you to convert between JSON and Java primitives/objects. Here's an example I just wrote:

```<code>    class BagOfPrimitives {
        private int value1 = 1;
        private String value2 = "abc";
    }

    public static void main(String[] args) {
        Gson gson = new Gson();
        String json = "{\"value1\":1,\"value2\":\"abc\"}";
        BagOfPrimitives obj = gson.fromJson(json, BagOfPrimitives.class);
    }
</code>```

This code converts the json {"value1":1,"value2":"abc"} into an object of the class BagOfPrimitives.

To add Gson to your project, go here, click "Downloads" at the top right, and click "jar". Then follow these instructions to add the jar file to your project. Then you should be able to write import com.google.gson.* at the top of your class and use Gson in your java code.

Body:
From what I can understand from your question, it looks like Gson might be useful. Gson is a library that allows you to convert between JSON and Java primitives/objects. Here's an example I just wrote:

    class BagOfPrimitives {
        private int value1 = 1;
        private String value2 = "abc";
    }

    public static void main(String[] args) {
        Gson gson = new Gson();
        String json = "{\"value1\":1,\"value2\":\"abc\"}";
        BagOfPrimitives obj = gson.fromJson(json, BagOfPrimitives.class);
    }

This code converts the json {"value1":1,"value2":"abc"} into an object of the class BagOfPrimitives.

To add Gson to your project, go here, click "Downloads" at the top right, and click "jar". Then follow these instructions to add the jar file to your project. Then you should be able to write import com.google.gson.* at the top of your class and use Gson in your java code.


问:
Custom allocators as alternatives to vector of smart pointers?
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

```<code>std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

```<code>std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};
</code>```

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

答:
[A shared pointer] seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So what?  Maybe the code is a little less self-documenting, but it will solve all your problems.
(And by the way you are muddling things by using the word "consumer", which in a traditional producer/consumer paradigm would take ownership.)

Also, returning a raw pointer in your current code is already entirely ambiguous as to ownership.  In general, I'd say it's good practice to avoid raw pointers if you can (like you don't need to call delete.)  I would return a reference if you go with unique_ptr

```<code>std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing& get_thing_for_consumer() {
    // some thing-selection logic
    return *i_am_the_owner_of_things[5]; // 5 is just an example
}
</code>```

Body:
This question is about owning pointers, consuming pointers, smart pointers, vectors, and allocators.

I am a little bit lost on my thoughts about code architecture. Furthermore, if this  question has already an answer somewhere, 1. sorry, but I haven't found a satisfying answer so far and 2. please point me to it.

My problem is the following:

I have several "things" stored in a vector and several "consumers" of those "things". So, my first try was like follows:

std::vector<thing> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return &i_am_the_owner_of_things[5]; // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

In my application, this would be safe because the "things" outlive the "consumers" in any case. However, more "things" can be added during runtime and that can become a problem because if the std::vector<thing> i_am_the_owner_of_things; gets reallocated, all the thing* m_thing pointers become invalid.

A fix to this scenario would be to store unique pointers to "things" instead of "things" directly, i.e. like follows:

std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing* get_thing_for_consumer() {
    // some thing-selection logic
    return i_am_the_owner_of_things[5].get(); // 5 is just an example
}

...

// somewhere else in the code:
class consumer {
    consumer() {
       m_thing = get_thing_for_consumer();
    }

    thing* m_thing;
};

The downside here is that memory coherency between "things" is lost. Can this memory coherency be re-established by using custom allocators somehow? I am thinking of something like an allocator which would always allocate memory for, e.g., 10 elements at a time and whenever required, adds more 10-elements-sized chunks of memory.

Example:

initially:

v = ☐☐☐☐☐☐☐☐☐☐

more elements:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

and again:

v = ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐  ☐☐☐☐☐☐☐☐☐☐

Using such an allocator, I wouldn't even have to use std::unique_ptrs of "things" because at std::vector's reallocation time, the memory addresses of the already existing elements would not change.

As alternative, I can only think of referencing the "thing" in "consumer" via a std::shared_ptr<thing> m_thing, as opposed to the current thing* m_thing but that seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So, is the allocator-approach a good one? And if so, how can it be done? Do I have to implement the allocator by myself or is there an existing one?

Body:
[A shared pointer] seems like the worst approach to me, because a "thing" shall not own a "consumer" and with shared pointers I would create shared ownership.

So what?  Maybe the code is a little less self-documenting, but it will solve all your problems.
(And by the way you are muddling things by using the word "consumer", which in a traditional producer/consumer paradigm would take ownership.)

Also, returning a raw pointer in your current code is already entirely ambiguous as to ownership.  In general, I'd say it's good practice to avoid raw pointers if you can (like you don't need to call delete.)  I would return a reference if you go with unique_ptr

std::vector<std::unique_ptr<thing>> i_am_the_owner_of_things;
thing& get_thing_for_consumer() {
    // some thing-selection logic
    return *i_am_the_owner_of_things[5]; // 5 is just an example
}


答:
As far as one Category can have multiple posts you would need to iterate over them:

```<code>category.posts.all()
</code>```

In template:

```<code>{% for category in categories %}
    {{ category.name }}
    { % for post in category.posts.all %}
        {{ post.title }}
    {% endfor %}
{% endfor%}
</code>```

Title: Reverse lookup value of ForeignKey (Child to Parent)

Body:
As far as one Category can have multiple posts you would need to iterate over them:

category.posts.all()

In template:

{% for category in categories %}
    {{ category.name }}
    { % for post in category.posts.all %}
        {{ post.title }}
    {% endfor %}
{% endfor%}


问:
Restricting domain of solution set when using SymPy solve in the multiple variables case
Say, I'm trying to solve the system of equations:

for θ, λ and ɸ , where a, b, c and d are complex numbers and the matrix on the LHS is a unitary matrix.

The SymPy code I have at hand does successfully do the job but there are a few edge cases it misses.

```<code>from sympy import *
def get_angles(a, b, c, d):
    theta, phi, lamb = symbols('\\theta \\phi \\lambda', real=True)
    a_eq = Eq(cos(theta / 2), a)
    b_eq = Eq(exp(I * phi) * sin(theta / 2), b)
    c_eq = Eq(-exp(I * lamb) * sin(theta / 2), c)
    d_eq = Eq(exp(I * (phi + lamb)) * cos(theta / 2), d)
    res = solve([a_eq, b_eq, c_eq, d_eq],
                theta,
                phi,
                lamb,
                check=False,
                set=True)
    return res
</code>```

For instance, it doesn't restrict the range of the solutions. I did notice this answer but it only works for single variable cases. So any idea how to add the domain restrictions for the solution set, when dealing with multiple variables?

答:
You can declare assumptions on the symbols and solve should check them e.g.:

```<code>In [12]: solve(x*(1-x))
Out[12]: [0, 1]

In [13]: x = Symbol('x', positive=True)

In [14]: solve(x*(1-x))
Out[14]: [1]
</code>```

That works for some restrictions but won't work for a restriction like x<y. You can however post-process the output from solve:

```<code>In [6]: sol = [{x:1, y:2, z:3}, {x:1, y:0, z:4}, {x:3, y:2, z:1}]

In [7]: sol
Out[7]: [{x: 1, y: 2, z: 3}, {x: 1, y: 0, z: 4}, {x: 3, y: 2, z: 1}]

In [8]: cond = And(0 < x, x < z, 0 < y)

In [9]: cond
Out[9]: x > 0 ∧ y > 0 ∧ x < z

In [10]: cond.subs(sol[0])
Out[10]: True

In [11]: [s for s in sol if cond.subs(s)]
Out[11]: [{x: 1, y: 2, z: 3}]
</code>```

Body:
Say, I'm trying to solve the system of equations:

for θ, λ and ɸ , where a, b, c and d are complex numbers and the matrix on the LHS is a unitary matrix.

The SymPy code I have at hand does successfully do the job but there are a few edge cases it misses.

from sympy import *
def get_angles(a, b, c, d):
    theta, phi, lamb = symbols('\\theta \\phi \\lambda', real=True)
    a_eq = Eq(cos(theta / 2), a)
    b_eq = Eq(exp(I * phi) * sin(theta / 2), b)
    c_eq = Eq(-exp(I * lamb) * sin(theta / 2), c)
    d_eq = Eq(exp(I * (phi + lamb)) * cos(theta / 2), d)
    res = solve([a_eq, b_eq, c_eq, d_eq],
                theta,
                phi,
                lamb,
                check=False,
                set=True)
    return res

For instance, it doesn't restrict the range of the solutions. I did notice this answer but it only works for single variable cases. So any idea how to add the domain restrictions for the solution set, when dealing with multiple variables?

Body:
You can declare assumptions on the symbols and solve should check them e.g.:

In [12]: solve(x*(1-x))
Out[12]: [0, 1]

In [13]: x = Symbol('x', positive=True)

In [14]: solve(x*(1-x))
Out[14]: [1]

That works for some restrictions but won't work for a restriction like x<y. You can however post-process the output from solve:

In [6]: sol = [{x:1, y:2, z:3}, {x:1, y:0, z:4}, {x:3, y:2, z:1}]

In [7]: sol
Out[7]: [{x: 1, y: 2, z: 3}, {x: 1, y: 0, z: 4}, {x: 3, y: 2, z: 1}]

In [8]: cond = And(0 < x, x < z, 0 < y)

In [9]: cond
Out[9]: x > 0 ∧ y > 0 ∧ x < z

In [10]: cond.subs(sol[0])
Out[10]: True

In [11]: [s for s in sol if cond.subs(s)]
Out[11]: [{x: 1, y: 2, z: 3}]


问:
/usr/bin/sudo must be owned by uid 0 and have the setuid bit set version .ubantu14.04 LTS
when I set the EACCESS for npm and I was ran the chown command in my terminal for change owner permission but now i stuck in this
sudo :" /usr/bin/sudo must be owned by uid 0 and have the setuid bit set" my version is : ubuntu14.04 LTS please help me guyz :)</p>

答:
/usr/bin/sudo mv /usr/local/bin/sudo{,2}
hash -r

Refer this https://unix.stackexchange.com/questions/419122/sudo-must-be-owned-by-uid-0-and-have-the-setuid-bit-set?newreg=b2490740fb214ce79c316ad76f859e0a


问:
Can Xtext be used for parsing general purpose programming languages?
I'm currently developing a general-purpose agent-based programming language (its syntaxt will be somewhat inspired by Java, and we are also using object in this language).

Since the beginning of the project we were doubtful about the fact of using ANTLR or Xtext. At that time we found out that Xtext was implementing a subset of the feature of ANTLR. So we decided to use ANLTR for our language losing the possibility to have a full-fledged Eclipse editor for free for our language (such a nice features provided by Xtext).

However, as the best of my knowledge, this summer the Xtext project has done a big step forward. Quoting from the link:

What are the limitations of Xtext?

Sven: You can implement almost any kind of programming language or DSL
  with Xtext. There is one exception, that is if you need to use so
  called  'Semantic Predicates' which is a rather complicated thing I
  don't think is worth being explained here. Very few languages really
  need this concept. However the prominent example is C/C++.  We want to
  look into that topic for the next release.

And that is also reinforced in the Xtext documentation:

What is Xtext? No matter if you want to create a small textual domain-specific language (DSL) or you want to implement a full-blown
  general purpose programming language. With Xtext you can create your
  very own languages in a snap. Also if you already have an existing
  language but it lacks decent tool support, you can use Xtext to create
  a sophisticated Eclipse-based development environment providing
  editing experience known from modern Java IDEs in a surprisingly short
  amount of time. We call Xtext a language development framework.

If Xtext has got rid of its past limitations why is it still not possible to find a complex Xtext grammar for the best known programming languages (Java, C#, etc.)?

On the ANTLR website you can find tons of such grammar examples, for what concerns Xtext instead the only sample I was able to find is the one reported in the documentation. So maybe Xtext is still not mature to be used for implementing a general purpose programming language? I'm a bit worried about this... I would not start to re-write the grammar in Xtext for then to recognize that it was not suited for that.

答:
I guess the most simple answer to your question is: Many general purpose languages can be implemented using Xtext. But since there is no general answer to which parser-capabilities a general purpose languages needs, there is no general answer to your questions.

However, I've got a few pointers:

With Xtext 2.0 (released this summer), Xtext supports syntactic predicates. This is one of the most requested features to handle ambiguous syntax without enabling antlr's backtracking.

You might want to look at the brand-new languages Xbase and Xtend, which are (judging based on their capabilities) general-purpose and which are developed using Xtext. Sven has some nice screen casts in his blog: http://blog.efftinge.de/

Regarding your question why we don't see Xtext-grammars for Java, C++, etc.:
With Xtext, a language is more than just a grammar, so just having a grammar that describes a language's syntax is a good starting point but usually not an artifact valuable enough for shipping. The reason is that with an Xtext-grammar you also define the AST's structure (Abstract Syntax Tree, and an Ecore Model in fact) including true cross references. Since this model is the main internal API of your language people usually spend a lot of thought designing it. Furthermore, to resolve cross references (aka linking) you need to implement scoping (as it is called in Xtext). Without a proper implementation of scoping you can either not have true cross references in your model or you'll get many lining errors.

A guess my point is that creating a grammar + designing the AST model + implementing scoping is just a little more effort that taking a grammar from some language-zoo and translating it to Xtext's syntax.


问:
What is the correct way to authenticate from JavaScript in an HTML file to the Microsoft Web Chat control for Bot Framework v4?
My goal is to create an HTML page with JavaScript that runs this Microsoft Bot Framework v4 Web Chat Control

https://github.com/Microsoft/BotFramework-WebChat

As described in the comments for this StackOverflow question

Microsoft Bot Framework image size in adaptive card

I tried to follow the sample code here

https://github.com/compulim/BotFramework-MockBot

specifically

BotFramework-WebChat-master\samples\01.a.getting-started-full-bundle

but could not get it working.  In the other question linked above, I was told by Microsoft support to authenticate another way:

You need to make a POST request to https://directline.botframework.com/v3/directline/tokens/generate with Authorization: Bearer  in the header. Alternatively, you can use const token =  directly, instead

However, in the sample code noted above, it says

To talk to your bot, you should use the token exchanged using your Direct Line secret.
  You should never put the Direct Line secret in the browser or client app.

If the code suggested above is JavaScript included in an HTML file, it is visible from View Source by anyone who loads the page.

Using the DirectLine secret seems to violate the rule to not expose this secret, which I've read could provide access to all conversations, not only the current one.

If the JS code in plain view uses the DirectLine secret to get a token, then uses the token to authenticate, using the token doesn't seem to accomplish anything, as the DL secret is exposed.  Why not just use DL secret?

What is the Microsoft-recommended, simplest way to authenticate to the web chat control linked to above?

Thanks!

答:
Why not just use DL secret?

As you said, this would allow access to all conversations with the bot.

If the JS code in plain view uses the DirectLine secret to get a token, then uses the token to authenticate, using the token doesn't seem to accomplish anything, as the DL secret is exposed.

Correct again. To keep your secret hidden, you'd need to set up your own token server. We don't have an official, ready-to-go sample of how how to set this up, but this sample by the Web Chat author should get you started.

If you want to write your own, the flow would basically be:

Have your WebChat client send a request for a token to your token server

Your token server can store the secret in a variable, so long as you don't make the code public. Have your token server reach out to https://directline.botframework.com/v3/directline/tokens/generate with a POST request and the header, Authorization: Bearer <YourSecret>

Return the token that results from that request back to the WebChat client

Your WebChat client will now have a token without ever needing to know the secret because it used your token server middleware

What is the Microsoft-recommended, simplest way to authenticate to the web chat control linked to above?

Unfortunately, there is no method that is both "simple" and "recommended". The simplest is to just use your secret, directly. This is fine if you don't care that user conversations can be exposed. The recommended way, though, is to implement your own token server.

Additional Reading on Exposing the Secret

From this GitHub issue

For purposes of this discussion, we're going to treat secrets and tokens to be the same thing. We can go into detail on those later if you want. I'll refer to them as "secret/token" for now.

To access a conversation, you need the secret/token and a conversation ID. These values are sometimes glued together, and are sometimes in separate variables. Sometimes they're in the URL, and sometimes they're stored in JavaScript in memory. These are similar to a user token, stored in a user's cookie.

In all cases, these values are accessible to a user sitting at their own computer. They can read their own URLs, they can read their own JavaScript variable state, and they can read their own cookies.

If they send any of this information to someone else, that person can impersonate them. If my bank emails me a password reset link, and I share that with someone else, that person can reset my account password and log in to my account.

Our iFrame uses URLs to pass these parameters, as that's an adequate level of security in many cases. (Have you ever visited a website, manually extracted the URL to an iFrame, sent it to someone else, and expected your session to remain private? Probably not.)

If you want additional security, you can skip the iFrame and send your own secret/token inside JS or a cookie. Your JS can extract that and send it to the Web Chat JS object. Once Web Chat has the secret/token, is exclusively uses HTTP Authorization headers to send those values to the Direct Line service.

So, leaving your secret exposed isn't a big deal, per se. However, it does allow a nefarious user to impersonate any other user.

This is default behavior because Directline needs some way to figure out who it is authenticated to talk to. The secret verifies that the client (Web Chat) is okay. But what verifies that the user is? A user id? But then any user could set their own user id and impersonate somebody else. The only way to really secure this is to implement something on your own end that uses the secret to get a Directline token, then passes that back to the Web Chat client.

Also, to get conversation data, somebody would need both the secret and the conversation id. The likelihood of figuring out the conversation id is pretty small.

Generally speaking though, this security is only a concern if you're trying to persist user data. If your users would start a new conversation each time they open the bot, you can just generate a unique user id and not worry if the secret is exposed.

Here's a good blog post regarding creating a Client Controller (token server) in C# and Node
as well as some additional security features/concepts..

Here's another blog post on additional security considerations and using Enhanced DirectLine Authentication Features


问:
Why isn't this code executing the stored procedure and inserting data?
I have a controller listed here which should be calling the Dapper method, however I cannot get it to execute. It's not throwing any exceptions and it is redirecting under the try catch however the procedure doesn't seem to be running as no new users are ever created.

The connection set up works with simple inline .Query methods however as soon as I attempt to do this with a stored procedure, it fails.

Model:

    public class User
    {
        public int UserID { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Boolean ActiveB { get; set; }
    }
```

<p>View:</p>

```@model ScaleBase.Models.FullUser

@{
    ViewData["Title"] = "Create";
}

Create

User

        <form asp-action="Create">

                <input asp-for="OrganisationID" class="form-control" />

                <input asp-for="ClientID" class="form-control" />

                <input asp-for="TeamID" class="form-control" />

                <input asp-for="Email" class="form-control" />

                <input asp-for="Username" class="form-control" />

                <input asp-for="Password" type="password" class="form-control" />

                <input asp-for="FirstName" class="form-control" />

                <input asp-for="LastName" class="form-control" />

                        <input asp-for="ActiveB" /> @Html.DisplayNameFor(model => model.ActiveB)

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

```

<p>Controller:</p>

```public ActionResult Create(IFormCollection collection)
{
        try
        {
            DynamicParameters parameters = new DynamicParameters();

            parameters.Add("@Organisation", collection["OrganisationID"]);
            parameters.Add("@ClientID1", collection["ClientID"]);
            parameters.Add("@Team", collection["TeamID"]);
            parameters.Add("@Email", collection["Email"]);
            parameters.Add("@UserName", collection["UserName"]);
            parameters.Add("@Password", collection["Password"]);
            parameters.Add("@FirstName", collection["FirstName"]);
            parameters.Add("@LastName", collection["LastName"]);

            var affectedRows = _dapperRepo.CreateUser(parameters);

            return RedirectToAction(nameof(Index));
        }
        catch (Exception)
        {
            throw;
        }
    }
```

<p>Dapper repo:</p>

```    public async Task<User> CreateUser(DynamicParameters parameters)
    {
        using (IDbConnection conn = Connection)
        {
            string sproc = "EXEC sproc_NewUser @Organisation, @Client1, @Team, @Email  @UserName, @Password, @FirstName, @LastName";
            conn.Open();
            var result = await conn.QueryAsync(sproc, parameters, commandType: CommandType.StoredProcedure);
            return result.FirstOrDefault();
        }
    }
```

<p>Stored procedure:</p>

```BEGIN TRY
    BEGIN TRANSACTION NewUser
        DECLARE @salt UNIQUEIDENTIFIER = NEWID()

        INSERT INTO [dbo].[User] (Username, Email, FirstName, LastName, Password, Salt, Active)
        VALUES (@UserName, @Email, @FirstName, @LastName, HASHBYTES('SHA2_512', @Password+CAST(@salt AS NVARCHAR(36))), @salt, 1)

        INSERT INTO [dbo].[UserOrganisations] (UserID, OrganisationID)
        VALUES (IDENT_CURRENT('User'), @Organisation)

        INSERT INTO [dbo].[UserClients] (UserID, ClientID)
        VALUES (IDENT_CURRENT('User'), @Client1)

        IF @Client2 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client2)
        END

        IF @Client3 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client3)
        END

        IF @Client4 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client4)
        END

        IF @Client5 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client5)
        END

        INSERT INTO [dbo].[UserTeams] (UserID, TeamID)
        VALUES (IDENT_CURRENT('User'), @Team)

        INSERT INTO [dbo].[UserPermission] (UserID, HolidayCount, HolidayUsed, TemplateID, ConfigState1, ConfigState2, ConfigState3, ConfigState4, ConfigState5)
        VALUES (IDENT_CURRENT('User'), @Holiday, 0, 1, 255, null, null, null, null)

        INSERT INTO [dbo].[UserTime] (UserID, Scale, StartTime, EndTime)
        VALUES (IDENT_CURRENT('User'), 1, @StartTime, @EndTime)

        COMMIT TRANSACTION NewUser

        PRINT 'Success'

        SELECT
            [UserID], [Username], [Email], [Firstname], [Lastname], [Active]
        FROM
            [User]
        WHERE
            [UserID] = IDENT_CURRENT('User')
END TRY
BEGIN CATCH
    IF (@@TRANCOUNT > 0)
    BEGIN
        ROLLBACK TRANSACTION NewUser
        PRINT 'Failed'
    END

    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage

        RETURN 'Error'
END CATCH
```

答:
Instead of using QueryAsync use ExecuteAsync that will return the number of rows altered by the command.

Also you are not awaiting your async call. That is no good practice. Try this:

```<code>var affectedRows = await _dapperRepo.CreateUser(parameters);
</code>```

and

```<code>var result = await conn.ExecuteAsync(sproc, parameters, commandType: CommandType.StoredProcedure);
</code>```

You can refer to this: https://dapper-tutorial.net/async#executeasync

Body:
I have a controller listed here which should be calling the Dapper method, however I cannot get it to execute. It's not throwing any exceptions and it is redirecting under the try catch however the procedure doesn't seem to be running as no new users are ever created.

The connection set up works with simple inline .Query methods however as soon as I attempt to do this with a stored procedure, it fails.

Model:

    public class User
    {
        public int UserID { get; set; }
        public string Username { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Boolean ActiveB { get; set; }
    }

View:

@model ScaleBase.Models.FullUser

@{
    ViewData["Title"] = "Create";
}

Create

User

        <form asp-action="Create">

                <input asp-for="OrganisationID" class="form-control" />

                <input asp-for="ClientID" class="form-control" />

                <input asp-for="TeamID" class="form-control" />

                <input asp-for="Email" class="form-control" />

                <input asp-for="Username" class="form-control" />

                <input asp-for="Password" type="password" class="form-control" />

                <input asp-for="FirstName" class="form-control" />

                <input asp-for="LastName" class="form-control" />

                        <input asp-for="ActiveB" /> @Html.DisplayNameFor(model => model.ActiveB)

                <input type="submit" value="Create" class="btn btn-default" />

        </form>

Controller:

public ActionResult Create(IFormCollection collection)
{
        try
        {
            DynamicParameters parameters = new DynamicParameters();

            parameters.Add("@Organisation", collection["OrganisationID"]);
            parameters.Add("@ClientID1", collection["ClientID"]);
            parameters.Add("@Team", collection["TeamID"]);
            parameters.Add("@Email", collection["Email"]);
            parameters.Add("@UserName", collection["UserName"]);
            parameters.Add("@Password", collection["Password"]);
            parameters.Add("@FirstName", collection["FirstName"]);
            parameters.Add("@LastName", collection["LastName"]);

            var affectedRows = _dapperRepo.CreateUser(parameters);

            return RedirectToAction(nameof(Index));
        }
        catch (Exception)
        {
            throw;
        }
    }

Dapper repo:

    public async Task<User> CreateUser(DynamicParameters parameters)
    {
        using (IDbConnection conn = Connection)
        {
            string sproc = "EXEC sproc_NewUser @Organisation, @Client1, @Team, @Email  @UserName, @Password, @FirstName, @LastName";
            conn.Open();
            var result = await conn.QueryAsync(sproc, parameters, commandType: CommandType.StoredProcedure);
            return result.FirstOrDefault();
        }
    }

Stored procedure:

BEGIN TRY
    BEGIN TRANSACTION NewUser
        DECLARE @salt UNIQUEIDENTIFIER = NEWID()

        INSERT INTO [dbo].[User] (Username, Email, FirstName, LastName, Password, Salt, Active)
        VALUES (@UserName, @Email, @FirstName, @LastName, HASHBYTES('SHA2_512', @Password+CAST(@salt AS NVARCHAR(36))), @salt, 1)

        INSERT INTO [dbo].[UserOrganisations] (UserID, OrganisationID)
        VALUES (IDENT_CURRENT('User'), @Organisation)

        INSERT INTO [dbo].[UserClients] (UserID, ClientID)
        VALUES (IDENT_CURRENT('User'), @Client1)

        IF @Client2 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client2)
        END

        IF @Client3 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client3)
        END

        IF @Client4 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client4)
        END

        IF @Client5 IS NOT NULL
        BEGIN
            INSERT INTO [dbo].[UserClients] (UserID, ClientID)
            VALUES (IDENT_CURRENT('User'), @Client5)
        END

        INSERT INTO [dbo].[UserTeams] (UserID, TeamID)
        VALUES (IDENT_CURRENT('User'), @Team)

        INSERT INTO [dbo].[UserPermission] (UserID, HolidayCount, HolidayUsed, TemplateID, ConfigState1, ConfigState2, ConfigState3, ConfigState4, ConfigState5)
        VALUES (IDENT_CURRENT('User'), @Holiday, 0, 1, 255, null, null, null, null)

        INSERT INTO [dbo].[UserTime] (UserID, Scale, StartTime, EndTime)
        VALUES (IDENT_CURRENT('User'), 1, @StartTime, @EndTime)

        COMMIT TRANSACTION NewUser

        PRINT 'Success'

        SELECT
            [UserID], [Username], [Email], [Firstname], [Lastname], [Active]
        FROM
            [User]
        WHERE
            [UserID] = IDENT_CURRENT('User')
END TRY
BEGIN CATCH
    IF (@@TRANCOUNT > 0)
    BEGIN
        ROLLBACK TRANSACTION NewUser
        PRINT 'Failed'
    END

    SELECT
        ERROR_NUMBER() AS ErrorNumber,
        ERROR_SEVERITY() AS ErrorSeverity,
        ERROR_STATE() AS ErrorState,
        ERROR_PROCEDURE() AS ErrorProcedure,
        ERROR_LINE() AS ErrorLine,
        ERROR_MESSAGE() AS ErrorMessage

        RETURN 'Error'
END CATCH

Body:
Instead of using QueryAsync use ExecuteAsync that will return the number of rows altered by the command.

Also you are not awaiting your async call. That is no good practice. Try this:

var affectedRows = await _dapperRepo.CreateUser(parameters);

and

var result = await conn.ExecuteAsync(sproc, parameters, commandType: CommandType.StoredProcedure);

You can refer to this: https://dapper-tutorial.net/async#executeasync


问:
How can I enable cross-origin AJAX requests between my chrome extension and my Node server?
In my background.js script, I'm making vanilla AJAX GET request using the XMLHttpRequest() object to my Node server (currently hosted on localhost). The Node server is using the npm package express to handle the GET request. However, background.js just returns the error:

Access to XMLHttpRequest at 'localhost:80' from origin 'chrome-extension://jhccmehanjenpnjalilnihdmeignbcpn' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Is it a permission I need to include in the manifest.json or something? Thanks!

答: @wOxxOm solved my problem in the comment above! I just forgot the http://


问:
Vba function evaluated by named parameters
Is it possible to invoke a function by specifying what the named parameters should be?

So for example if you have

```<code>Public function tmp(optional Byref a as integer=2, optional Byref b as integer=10)

    Tmp=a*b

End function
</code>```

I want to use the above by tmp(b=5). Hope someone can help.

答:
If I understand your question correctly, you want to pass only Argument b:

```<code>Debug.Print tmp(, 5)     ' results in 2 * 5 = 10
</code>```

or simply as mentioned in comment by @Guest

```<code>Debug.Print tmp(b:=5)
</code>```

Body:
Is it possible to invoke a function by specifying what the named parameters should be?

So for example if you have

Public function tmp(optional Byref a as integer=2, optional Byref b as integer=10)

    Tmp=a*b

End function

I want to use the above by tmp(b=5). Hope someone can help.

Body:
If I understand your question correctly, you want to pass only Argument b:

Debug.Print tmp(, 5)     ' results in 2 * 5 = 10

or simply as mentioned in comment by @Guest

Debug.Print tmp(b:=5)


问:
Flutter FirebaseDatabase run transaction crash
i'm trying run a transaction in the firebase database using Flutter and i am getting an error, can someone help me to solve this?

Code:

```<code>ref.runTransaction((MutableData transaction) async {
      transaction.value = (transaction.value ?? 0) + 1;
      return transaction;
    });
</code>```

Error:

```<code>E/RepoOperation(16416): Caught Throwable.
E/RepoOperation(16416): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: FirebaseDatabaseWorker
E/RepoOperation(16416):     at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:605)
E/RepoOperation(16416):     at io.flutter.embedding.engine.FlutterJNI.dispatchPlatformMessage(FlutterJNI.java:515)
E/RepoOperation(16416):     at io.flutter.embedding.engine.dart.DartMessenger.send(DartMessenger.java:76)
E/RepoOperation(16416):     at io.flutter.embedding.engine.dart.DartExecutor.send(DartExecutor.java:166)
E/RepoOperation(16416):     at io.flutter.view.FlutterNativeView.send(FlutterNativeView.java:155)
E/RepoOperation(16416):     at io.flutter.plugin.common.MethodChannel.invokeMethod(MethodChannel.java:98)
E/RepoOperation(16416):     at io.flutter.plugins.firebase.database.FirebaseDatabasePlugin$1.doTransaction(FirebaseDatabasePlugin.java:345)
E/RepoOperation(16416):     at com.google.firebase.database.core.Repo.startTransaction(com.google.firebase:firebase-database@@17.0.0:831)
E/RepoOperation(16416):     at com.google.firebase.database.DatabaseReference$4.run(com.google.firebase:firebase-database@@17.0.0:511)
E/RepoOperation(16416):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
E/RepoOperation(16416):     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
E/RepoOperation(16416):     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
E/RepoOperation(16416):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/RepoOperation(16416):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/RepoOperation(16416):     at java.lang.Thread.run(Thread.java:764)
</code>```

Thanks in advance.

答:
I was getting the same error while using flutter dev channel.
Going to stable channel fixed it for me. To check which channel you are do flutter channel

To switch to stable channel do:

```<code>flutter channel stable
flutter upgrade
</code>```

Body:
i'm trying run a transaction in the firebase database using Flutter and i am getting an error, can someone help me to solve this?

Code:

ref.runTransaction((MutableData transaction) async {
      transaction.value = (transaction.value ?? 0) + 1;
      return transaction;
    });

Error:

E/RepoOperation(16416): Caught Throwable.
E/RepoOperation(16416): java.lang.RuntimeException: Methods marked with @UiThread must be executed on the main thread. Current thread: FirebaseDatabaseWorker
E/RepoOperation(16416):     at io.flutter.embedding.engine.FlutterJNI.ensureRunningOnMainThread(FlutterJNI.java:605)
E/RepoOperation(16416):     at io.flutter.embedding.engine.FlutterJNI.dispatchPlatformMessage(FlutterJNI.java:515)
E/RepoOperation(16416):     at io.flutter.embedding.engine.dart.DartMessenger.send(DartMessenger.java:76)
E/RepoOperation(16416):     at io.flutter.embedding.engine.dart.DartExecutor.send(DartExecutor.java:166)
E/RepoOperation(16416):     at io.flutter.view.FlutterNativeView.send(FlutterNativeView.java:155)
E/RepoOperation(16416):     at io.flutter.plugin.common.MethodChannel.invokeMethod(MethodChannel.java:98)
E/RepoOperation(16416):     at io.flutter.plugins.firebase.database.FirebaseDatabasePlugin$1.doTransaction(FirebaseDatabasePlugin.java:345)
E/RepoOperation(16416):     at com.google.firebase.database.core.Repo.startTransaction(com.google.firebase:firebase-database@@17.0.0:831)
E/RepoOperation(16416):     at com.google.firebase.database.DatabaseReference$4.run(com.google.firebase:firebase-database@@17.0.0:511)
E/RepoOperation(16416):     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:458)
E/RepoOperation(16416):     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
E/RepoOperation(16416):     at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:301)
E/RepoOperation(16416):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
E/RepoOperation(16416):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
E/RepoOperation(16416):     at java.lang.Thread.run(Thread.java:764)

Thanks in advance.

Body:
I was getting the same error while using flutter dev channel.
Going to stable channel fixed it for me. To check which channel you are do flutter channel

To switch to stable channel do:

flutter channel stable
flutter upgrade


问:
defining function using var vs function
exported:

```<code>var MyFunction = func(){}
function MyFunction func(){}
</code>```

unexported:

```<code>var myFunction = func(){}
function myFunction func(){}
</code>```

I read the var functionName = function() {} vs function functionName() {} this is about Javascript.

The reason I am considering changing from function myFunction func(){} to var myFunction = func(){} is the later makes me easier to do my unit test.

So I am wondering if there's anything I need to pay attention to before making this change.

答:
The chief distinction between the two forms is that they differ not only in syntax but rather in their semantics:

The "normal" form which uses the func name (...) form
creates a regular named function.

What you call "create a function using var" is actually creating a so-called anonymous function and assigning its value to a variable.

The difference is that in Go, anonymous functions behave as closures, while regular functions do not.

A closure is a function which "captures" any variables from its outer lexical scope which are used in the function's body (while not being shadowed by local variables and function arguments there).

The distinction may not be apparent when either form it used at the top level of a package — that is, outside of any function's body, — since the outer scope in this case is the package's global variables, but inside other functions the distinction is apparent: the "normal" form simply cannot be used.

Other distinction is that you can replace the value in a variable containing a function value, while you cannot do the same with the normal function.

Still, if we're talking about the top-level code, the suggestion offered by Flimzy holds: in production Go code, having global variables containing function values is code smell until it can be proved to be otherwise.

Title: defining function using var vs function

Body:
exported:

var MyFunction = func(){}
function MyFunction func(){}

unexported:

var myFunction = func(){}
function myFunction func(){}

I read the var functionName = function() {} vs function functionName() {} this is about Javascript.

The reason I am considering changing from function myFunction func(){} to var myFunction = func(){} is the later makes me easier to do my unit test.

So I am wondering if there's anything I need to pay attention to before making this change.


问:
how to multicell remove border in fpdf?
I set Default value: 0.
bet border will be displayed..
how to overcome this problem?
Please tell me...</p>

```<code>  while ($row = $result->fetch_row())
  {
  for ($i = 0; $i < 11; $i++)
        {
        $pdf->SetXY($x, $y);
        $pdf->Rect($x, $y, $widths[$i], $row_height);
        $pdf->MultiCell($widths[$i], $line_height,
        iconv('UTF-8', 'windows-1252', $row[$i]), 0, 'L');
        $x += $widths[$i];
    }
   }
</code>```

答:
Put in the EDGE location the value of 0

1 : All borders -
0 : No Border -
L : Only Left boarder -
RT: Only Right and Top Border -
BTL: Only Bottom Top and Left side -
You can continue with other combinations of the borders.

Title: how to multicell remove border in fpdf?

Body:
I set Default value: 0.
bet border will be displayed..
how to overcome this problem?
Please tell me...

  while ($row = $result->fetch_row())
  {
  for ($i = 0; $i < 11; $i++)
        {
        $pdf->SetXY($x, $y);
        $pdf->Rect($x, $y, $widths[$i], $row_height);
        $pdf->MultiCell($widths[$i], $line_height,
        iconv('UTF-8', 'windows-1252', $row[$i]), 0, 'L');
        $x += $widths[$i];
    }
   }


问:
How can I make a single instance form (not application)?
In my C# application I have an option dialog that can be opened from a menu command.

I want to ensure that the option dialog have only one instance (user cannot open more than one option window at a given time) without making it modal.

Also if the user already have this window opened, and he clicks in the menu item to open it again, the app just makes the already visible form became the top most window.

Can anyone point me directions on how accomplish these tasks?

Thank you very much.

答:
This May Help!
Note: The following code was taken from the article Below:
https://www.dotnetcurry.com/ShowArticle.aspx?ID=150</p>

```<code>static class Program
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        static void Main()
        {
            bool instanceCountOne = false;

            using (Mutex mtex = new Mutex(true, "MyRunningApp", out instanceCountOne))
            {
                if (instanceCountOne)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                    mtex.ReleaseMutex();
                }
                else
                {
                    MessageBox.Show("An application instance is already running");
                }
            }
        }
    }
</code>```

Body:
This May Help!
Note: The following code was taken from the article Below:
https://www.dotnetcurry.com/ShowArticle.aspx?ID=150

static class Program
    {
        ///<summary>
        /// The main entry point for the application.
        ///</summary>
        [STAThread]
        static void Main()
        {
            bool instanceCountOne = false;

            using (Mutex mtex = new Mutex(true, "MyRunningApp", out instanceCountOne))
            {
                if (instanceCountOne)
                {
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                    mtex.ReleaseMutex();
                }
                else
                {
                    MessageBox.Show("An application instance is already running");
                }
            }
        }
    }


问:
RegEx for capturing a pattern with new lines
I have the following string

```<code>1h 30min: Title
- Description Line 1
1h 30min: Title
- Description Line 1
- Description Line 2
- Description Line 3
</code>```

And I would like to get the following results using regex.

```<code>Match 1:
  "1h 30min: Title
  - Description Line 1"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1"
</code>```

```<code>Match 2:
  "1h 30min: Title
  - Description Line 1
  - Description Line 2
  - Description Line 3"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1
               - Description Line 2
               - Description Line 3"
</code>```

I have the following regex https://regex101.com/r/dp5zKq/1

```<code>(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)+?((.*\n*)*)
</code>```

However I can't figure out how to make the any character / new line regex stop when it hits a new match for the hours & minutes. Any ideas?

答:
I'm guessing this might be an expression that would be desired or close to:

```<code>([\s\S]*?)(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)?
</code>```

DEMO

Body:
I have the following string

1h 30min: Title
- Description Line 1
1h 30min: Title
- Description Line 1
- Description Line 2
- Description Line 3

And I would like to get the following results using regex.

Match 1:
  "1h 30min: Title
  - Description Line 1"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1"

Match 2:
  "1h 30min: Title
  - Description Line 1
  - Description Line 2
  - Description Line 3"

      Group 1: "1h"
      Group 2: "30min"
      Group 3: "Title
               - Description Line 1
               - Description Line 2
               - Description Line 3"

I have the following regex https://regex101.com/r/dp5zKq/1

(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)+?((.*\n*)*)

However I can't figure out how to make the any character / new line regex stop when it hits a new match for the hours & minutes. Any ideas?

Body:
I'm guessing this might be an expression that would be desired or close to:

([\s\S]*?)(([0-9]{1,2}h)\s*([0-9]{1,2}min)*\:)?

DEMO


问:
mysql rand with condition
Could someone help me out with the correct syntax for this query please.

I have, table1:

```<code>id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)
</code>```

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

答:
This should work:

```<code>SELECT id,name FROM table1
WHERE `on`=1
ORDER BY RAND()
LIMIT 0,10
</code>```

EDITED: as pointed out, column on could cause a syntax error without backticks

Title: mysql rand with condition

Body:
Could someone help me out with the correct syntax for this query please.

I have, table1:

id,   int
on,   tinyint - this can be 0 or 1
name, varchar(2000)

From this I am trying to get 10 random id/name which have on set to 1.

What query should I use?

Body:
This should work:

SELECT id,name FROM table1
WHERE `on`=1
ORDER BY RAND()
LIMIT 0,10

EDITED: as pointed out, column on could cause a syntax error without backticks