问:
Need help adding data from database into a reacttable using react.js
i'm new to React.js and i want to create an app that uses Microsoft SQL SERVER MANAGER +.net+ React for client side.I want to have a search filter in the react table so I can search each column from the table which is filled with data from MSSM.The app is working if i don t use a search engine but I really need to for my project.The problem is from the client side in Car.js  I guess.Thanks in advice!
I'll put the code components  and the error below

EDIT
i want to replace "data[]"(which is hardcorded) from the following link ,with my "cars" taken from the database

link: https://codesandbox.io/s/inspiring-visvesvaraya-347r5?file=/src/styles.css:0-58

Car.js

```<code>import React,{Component} from 'react';
import {Table} from'react-bootstrap';
import {Button,ButtonToolbar} from'react-bootstrap';
import {AddCarModal} from'./AddCarModal';
import {EditCarModal} from './EditCarModal';
import ReactDOM from "react-dom";
import GlobalSearchComponent from "./GlobalSearchComponent";
import "react-table-v6/react-table.css";
import "./styles.css";
import ReactTable from "react-table";

export class Car extends Component
{
   constructor(props){
       super(props);
       this.state={cars:[] ,addModalShow : false, editModalShow :false, filteredData: [],
        columns: [],
        searchInput: ""}
   }
   componentDidMount()
   {
       this.refreshList();

       this.getColumns();

   }
   refreshList()
   {

    fetch('https://localhost:44385/api/car')
       .then(response => response.json())
       .then(data=> {
           this.setState({cars:data});
       }
       );
    }
        componentDidUpdate(){
            this.refreshList();
        }

   deleteCar( carid)
   {
     if(window.confirm('Are you sure?'))
     {
         fetch('https://localhost:44385/api/car/' + carid,{
          method:'DELETE',
          headers :{'Accept' :'application/json',
            'Content-Type':'application/json'
          }
         })
     }
    }

      getColumns = () => {
        let columns = [
          {
            Header: "Model Name",
            accessor: "modelName",
            sortable: false,
            show: true,
            displayValue: " Model Name"
          },
          {
            Header: "Fuel Type",
            accessor: "fueltype",
            sortable: false,
            show: true,
            displayValue: "Fuel type "
          },
          {
            Header: "Body Type",
            accessor: "bodytype",
            sortable: false,
            show: true,
            displayValue: " Body Type "
          },
          {
            Header: "Price interval",
            accessor: "priceinterval",
            sortable: false,
            show: true,
            displayValue: " Visits "
          },
          {
            Header: "Offroad rank",
            accessor: "offroadrank",
            sortable: false,
            show: true,
            displayValue: " Offroad rank "
          },
          {
            Header: "Maximum speed interval",
            accessor: "maximumspeedinterval",
            sortable: false,
            show: true,
            displayValue: "Maximum speed interval"
          },
          {
            Header: "Luxury rank",
            accessor: "luxuryrank",
            sortable: false,
            show: true,
            displayValue: "Luxury rank"
          },
          {
            Header: "Reliability rank",
            accessor: "reliabilityrank",
            sortable: false,
            show: true,
            displayValue: "Reliability rank"
          },
          {
            Header: "Safety rank",
            accessor: "safetyrank",
            sortable: false,
            show: true,
            displayValue: "Safety rank"
          },
          {
            Header: "Practicality rank",
            accessor: "practicalityrank",
            sortable: false,
            show: true,
            displayValue: "Practicality rank"
          },
          {
            Header: "Drive rank",
            accessor: "driverank",
            sortable: false,
            show: true,
            displayValue: "Drive rank"
          },
          {
            Header: "Interior rank",
            accessor: "interiorrank",
            sortable: false,
            show: true,
            displayValue: "Interior rank"
          },
          {
            Header: "Good for city traffic?",
            accessor: "forcity",
            sortable: false,
            show: true,
            displayValue: " Yes or No? "
          },
          {
            Header: "Good for long distance?",
            accessor: "forlong",
            sortable: false,
            show: true,
            displayValue: " Yes or No? "
          },
          {
            Header: "Consumption",
            accessor: "consumption",
            sortable: false,
            show: true,
            displayValue: "Consumption"
          },
          {
            Header: "Electric consumption",
            accessor: "econsumption",
            sortable: false,
            show: true,
            displayValue: " Electric consumption"
          },
          {
            Header: "Engine type",
            accessor: "enginetype",
            sortable: false,
            show: true,
            displayValue: "Engine type"
          },
          {
            Header: "Cylinder number",
            accessor: "cylidnernumber",
            sortable: false,
            show: true,
            displayValue: "Cylinder number"
          },
          {
            Header: "Naturally Aspired or Turbo?",
            accessor: "naot",
            sortable: false,
            show: true,
            displayValue: "Naturally Aspired or Turbo?"
          },
          {
            Header: "Number of seats",
            accessor: "seatsnumber",
            sortable: false,
            show: true,
            displayValue: " Number of seats"
          },
          {
            Header: "Cargo space",
            accessor: "cargo",
            sortable: false,
            show: true,
            displayValue: " Cargo space "
          },
          {
            Header: "Options",
            accessor: "option",
            sortable: false,
            show: true,
            displayValue: " Option "
          }
        ];
        this.setState({ columns });
      };

      handleSetData = cars => {
        console.log(cars);
        this.setState({ cars });
      };

      handleSetFilteredData = filteredData => {
        this.setState({ filteredData });
      };

      handleSetSearchInput = searchInput => {
        this.setState({ searchInput });
      };
    render() {

      let{cars,carid,carname,carfuel,carbody,carprice,caroffroad,carspeed,carluxury,carreliability,carsafety,carpracticality,cardrive,carinterior,carcity,cardistance,
        carconsumption,careconsumption,carengine,carcylinder,carnaot,carseats,carcargo ,filteredData, columns, searchInput }=this.state;

      const dataToDisplay = searchInput.length ? filteredData : cars;

    let addModalClose=()=> this.setState({addModalShow:false});
        let editModalClose=()=> this.setState({editModalShow:false});
        return(
       <div>
   <GlobalSearchComponent
          cars={this.state.cars}
          columns={this.state.columns}
          handleSetFilteredData={this.handleSetFilteredData}
          handleSetSearchInput={this.handleSetSearchInput}
        />

<Table className="mt-4" striped bordered hover size="sm">
<thead>
 <tr>

 <ReactTable
          cars={dataToDisplay}
          columns={columns}
          defaultPageSize={10}
          className="-striped -highlight"
        />

 </tr>
</thead>
<tbody>
{cars.map(cr=>
    <tr key ={cr.id}>

    <td> {cr.modelName }  </td>
    <td> {cr.fueltype }  </td>
    <td> {cr.bodytype}  </td>
    <td> {cr.priceinterval }  </td>
    <td> {cr.offroadrank }  </td>
    <td> {cr.maximumspeedinterval }  </td>
    <td> {cr.luxuryrank }  </td>
    <td> {cr.reliabilityrank }  </td>
    <td> {cr.safetyrank }  </td>
    <td> {cr.practicalityrank}  </td>
    <td> {cr.driverank }  </td>
    <td> {cr.interiorrank }  </td>
    <td> {cr.forcity }  </td>
    <td> {cr.forlong }  </td>
    <td> {cr.consumption }  </td>
    <td> {cr.electricconsumption}  </td>
    <td> {cr.enginetype }  </td>
    <td> {cr.cylindernumber }  </td>
    <td> {cr.naot }  </td>
    <td> {cr.seatsnumber }  </td>
    <td> {cr.cargo }  </td>
    <td>
        <ButtonToolbar>
            <Button
                   className="mr-2" variant ="info"
                    onClick={()=> this.setState({editModalShow : true ,
                        carid:cr.id, carname:cr.modelName,
                    carfuel:cr.fueltype,carbody:cr.bodytype,
            carprice:cr.priceinterval,caroffroad:cr.offroadrank,
            carspeed:cr.maximumspeedinterval,  carluxury:cr.luxuryrank,
            carreliability:cr.reliabilityrank,carsafety:cr.safetyrank,
            carpracticality:cr.practicalityrank,cardrive:cr.driverank,
            carinterior:cr.interiorrank,carcity:cr.forcity,
            cardistance:cr.forlong,carconsumption:cr.consumption,
            careconsumption:cr.electricconsumption,carengine:cr.enginetype,
            carcylinder:cr.cylindernumber,carnaot:cr.naot,
            carseats:cr.seatsnumber,carcargo:cr.cargo})}
           >
               Edit
           </Button>

          <Button className="mr-2"
          onClick={()=> this.deleteCar(cr.id)}
          variant="danger"
          > Delete</Button>

                <EditCarModal
                       show = {this.state.editModalShow}
                       onHide={editModalClose}
                       carid={carid}
                       carname={carname}
                       carfuel={carfuel}
                       carbody={carbody}
                        carprice={carprice}
                       caroffroad={caroffroad}
                       carspeed={carspeed}
                       carluxury={carluxury}
                       carreliability={carreliability}
                        carsafety={carsafety}
                       carpracticality={carpracticality}
                       cardrive={cardrive}
                       carinterior={carinterior}
                       carcity={carcity}
                       cardistance={cardistance}
                       carconsumption={carconsumption}
                       careconsumption={careconsumption}
                        carengine={carengine}
                        carcylinder={carcylinder}
                        carnaot={carnaot}
                        carseats={carseats}
                         carcargo={carcargo}
              />
             </ButtonToolbar>
         </td>
    </tr>
)}
        </tbody>
 </Table>

 <ButtonToolbar>
     <Button
     variant='primary'
     onClick={()=> this.setState({addModalShow: true})}
     >Add Car </Button>

     <AddCarModal
         show={this.state.addModalShow}
         onHide={addModalClose}
     />
 </ButtonToolbar>

 </div>

    )

    }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Car />, rootElement);
</code>```

GlobalSearchComponent

```<code>import React from "react";
import { Input } from "semantic-ui-react";

export default class GlobalSearchComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filteredData: [],
      columnSearch: "",
      searchInput: ""
    };
  }

  handleChange = event => {
    const val = event.target.value;
    this.setState({ searchInput: val }, () => this.globalSearch());
    this.props.handleSetSearchInput(val);
  };

  globalSearch = () => {
    const { searchInput, columnSearch } = this.state;
    let filteredData = this.props.cars.filter(value => {
      if (columnSearch) {
        return value[columnSearch]
          .toString()
          .toLowerCase()
          .includes(searchInput.toLowerCase());
      }
      return (
        value.modelName.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.fueltype.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.bodytype.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.priceinterval.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.offroadrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.maximumspeedinterval.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.luxuryrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.reliabilityrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.safetyrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.practicalityrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.driverank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.interiorrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.forcity.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.forlong.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.consumption.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.econsumption.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.enginetype.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.cylindernumber.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.naot.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.seatsnumber.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.cargo.toLowerCase().includes(searchInput.toLowerCase())

          .toString()
          .toLowerCase()
          .includes(searchInput.toLowerCase())
      );
    });

    this.props.handleSetFilteredData(filteredData);
  };

  setColumnSearch = e => {
    this.setState({ columnSearch: e.target.value }, () => this.globalSearch());
  };

  render() {
    const { columns } = this.props;
    const { columnSearch } = this.state;

    return (
      <>
        <br />
        <Input
          size="large"
          name="searchInput"
          value={this.state.searchInput || ""}
          onChange={this.handleChange}
          label="Search"
        />
        <select
          onChange={e => {
            e.persist();
            this.setColumnSearch(e);
          }}
          value={columnSearch}
        >
          <option value=""> All columns</option>
          {columns.map(col => {
            return <option value={col.accessor}>{col.Header}</option>;
          })}
        </select>
        <br />
        <br />
      </>
    );
  }
}
</code>```

Error

```<code>Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Car`.
▶ 20 stack frames were collapsed.
Module../src/components/Car.js
C:/Users/Felix/source/repos/React/car-app/src/components/Car.js:384
  381 |     }
  382 | }
  383 | const rootElement = document.getElementById("root");
> 384 | ReactDOM.render(<Car />, rootElement);
  385 |
View compiled
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
Module../src/App.js
http://localhost:3000/static/js/main.chunk.js:129:73
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
Module../src/index.js
http://localhost:3000/static/js/main.chunk.js:2613:62
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:2758:18
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
checkDeferredModules
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 |
View compiled
Array.webpackJsonpCallback [as push]
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:67
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.  Click the 'X' or hit ESC to dismiss this message.
</code>```

答:
I am using react table version "^7.1.0". You can try this.

```<code>import React from 'react'
import styled from 'styled-components'
import {useTable} from 'react-table'
import namor from 'namor';

const range = len => {
    const arr = [];
    for (let i = 0; i < len; i++) {
        arr.push(i)
    }
    return arr
};

const newPerson = () => {
    const statusChance = Math.random();
    const jIncome = Math.floor(Math.random() * 30);
    const bIncome = Math.floor(Math.random() * 100);

    return {
        firstName: namor.generate({words: 1, numbers: 0}),
        lastName: namor.generate({words: 1, numbers: 0}),
        jIncome: jIncome,
        bIncome: bIncome,
        tIncome: jIncome + bIncome,
        progress: Math.floor(Math.random() * 100),
        status:
            statusChance > 0.66
                ? 'relationship'
                : statusChance > 0.33
                ? 'complicated'
                : 'single',
    }
};

function makeData(...lens) {
    const makeDataLevel = (depth = 0) => {
        const len = lens[depth];
        return range(len).map(d => {
            return {
                ...newPerson(),
                subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
            }
        })
    };

    return makeDataLevel()
}

const Styles = styled.div`
  padding: 1rem;

  table {
    border-spacing: 0;
    border: 1px solid black;

    tr {
      :last-child {
        td {
          border-bottom: 0;
        }
      }
    }

    th,
    td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;

      :last-child {
        border-right: 0;
      }
    }
  }
`;

function Table({columns, data}) {
    // Use the state and functions returned from useTable to build your UI
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = useTable({
        columns,
        data,
    });

    // Render the UI for your table
    return (
        <table {...getTableProps()}>
            <thead>
            {headerGroups.map(headerGroup => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                    {headerGroup.headers.map(column => (
                        <th {...column.getHeaderProps()}>{column.render('Header')}</th>
                    ))}
                </tr>
            ))}
            </thead>
            <tbody {...getTableBodyProps()}>
            {rows.map((row, i) => {
                prepareRow(row);
                return (
                    <tr {...row.getRowProps(
                        {
                            style: {backgroundColor: row.values.tIncome > 50? 'skyblue': 'lightgray'}
                        }
                    )}>
                        {row.cells.map(cell => {
                            return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                        })}
                    </tr>
                )
            })}
            </tbody>
        </table>
    )
}

function ReactTableRowColor() {
    const columns = React.useMemo(
        () => [
            {
                Header: 'Name',
                columns: [
                    {
                        Header: 'First Name',
                        accessor: 'firstName',
                    },
                    {
                        Header: 'Last Name',
                        accessor: 'lastName',
                    },
                ],
            },
            {
                Header: 'Info',
                columns: [
                    {
                        Header: 'Job Income',
                        accessor: 'jIncome',
                    },
                    {
                        Header: 'Business Income',
                        accessor: 'bIncome',
                    },
                    {
                        Header: 'Total Income',
                        accessor: 'tIncome',
                    },
                    {
                        Header: 'Status',
                        accessor: 'status',
                    },
                    {
                        Header: 'Profile Progress',
                        accessor: 'progress',
                    },
                ],
            },
        ],
        []
    );

    const data = React.useMemo(() => makeData(20), []);

    return (
        <Styles>
            <Table columns={columns} data={data}/>
        </Styles>
    )
}

export default ReactTableRowColor
</code>```

Body:
i'm new to React.js and i want to create an app that uses Microsoft SQL SERVER MANAGER +.net+ React for client side.I want to have a search filter in the react table so I can search each column from the table which is filled with data from MSSM.The app is working if i don t use a search engine but I really need to for my project.The problem is from the client side in Car.js  I guess.Thanks in advice!
I'll put the code components  and the error below

EDIT
i want to replace "data[]"(which is hardcorded) from the following link ,with my "cars" taken from the database

link: https://codesandbox.io/s/inspiring-visvesvaraya-347r5?file=/src/styles.css:0-58

Car.js

import React,{Component} from 'react';
import {Table} from'react-bootstrap';
import {Button,ButtonToolbar} from'react-bootstrap';
import {AddCarModal} from'./AddCarModal';
import {EditCarModal} from './EditCarModal';
import ReactDOM from "react-dom";
import GlobalSearchComponent from "./GlobalSearchComponent";
import "react-table-v6/react-table.css";
import "./styles.css";
import ReactTable from "react-table";

export class Car extends Component
{
   constructor(props){
       super(props);
       this.state={cars:[] ,addModalShow : false, editModalShow :false, filteredData: [],
        columns: [],
        searchInput: ""}
   }
   componentDidMount()
   {
       this.refreshList();

       this.getColumns();

   }
   refreshList()
   {

    fetch('https://localhost:44385/api/car')
       .then(response => response.json())
       .then(data=> {
           this.setState({cars:data});
       }
       );
    }
        componentDidUpdate(){
            this.refreshList();
        }

   deleteCar( carid)
   {
     if(window.confirm('Are you sure?'))
     {
         fetch('https://localhost:44385/api/car/' + carid,{
          method:'DELETE',
          headers :{'Accept' :'application/json',
            'Content-Type':'application/json'
          }
         })
     }
    }

      getColumns = () => {
        let columns = [
          {
            Header: "Model Name",
            accessor: "modelName",
            sortable: false,
            show: true,
            displayValue: " Model Name"
          },
          {
            Header: "Fuel Type",
            accessor: "fueltype",
            sortable: false,
            show: true,
            displayValue: "Fuel type "
          },
          {
            Header: "Body Type",
            accessor: "bodytype",
            sortable: false,
            show: true,
            displayValue: " Body Type "
          },
          {
            Header: "Price interval",
            accessor: "priceinterval",
            sortable: false,
            show: true,
            displayValue: " Visits "
          },
          {
            Header: "Offroad rank",
            accessor: "offroadrank",
            sortable: false,
            show: true,
            displayValue: " Offroad rank "
          },
          {
            Header: "Maximum speed interval",
            accessor: "maximumspeedinterval",
            sortable: false,
            show: true,
            displayValue: "Maximum speed interval"
          },
          {
            Header: "Luxury rank",
            accessor: "luxuryrank",
            sortable: false,
            show: true,
            displayValue: "Luxury rank"
          },
          {
            Header: "Reliability rank",
            accessor: "reliabilityrank",
            sortable: false,
            show: true,
            displayValue: "Reliability rank"
          },
          {
            Header: "Safety rank",
            accessor: "safetyrank",
            sortable: false,
            show: true,
            displayValue: "Safety rank"
          },
          {
            Header: "Practicality rank",
            accessor: "practicalityrank",
            sortable: false,
            show: true,
            displayValue: "Practicality rank"
          },
          {
            Header: "Drive rank",
            accessor: "driverank",
            sortable: false,
            show: true,
            displayValue: "Drive rank"
          },
          {
            Header: "Interior rank",
            accessor: "interiorrank",
            sortable: false,
            show: true,
            displayValue: "Interior rank"
          },
          {
            Header: "Good for city traffic?",
            accessor: "forcity",
            sortable: false,
            show: true,
            displayValue: " Yes or No? "
          },
          {
            Header: "Good for long distance?",
            accessor: "forlong",
            sortable: false,
            show: true,
            displayValue: " Yes or No? "
          },
          {
            Header: "Consumption",
            accessor: "consumption",
            sortable: false,
            show: true,
            displayValue: "Consumption"
          },
          {
            Header: "Electric consumption",
            accessor: "econsumption",
            sortable: false,
            show: true,
            displayValue: " Electric consumption"
          },
          {
            Header: "Engine type",
            accessor: "enginetype",
            sortable: false,
            show: true,
            displayValue: "Engine type"
          },
          {
            Header: "Cylinder number",
            accessor: "cylidnernumber",
            sortable: false,
            show: true,
            displayValue: "Cylinder number"
          },
          {
            Header: "Naturally Aspired or Turbo?",
            accessor: "naot",
            sortable: false,
            show: true,
            displayValue: "Naturally Aspired or Turbo?"
          },
          {
            Header: "Number of seats",
            accessor: "seatsnumber",
            sortable: false,
            show: true,
            displayValue: " Number of seats"
          },
          {
            Header: "Cargo space",
            accessor: "cargo",
            sortable: false,
            show: true,
            displayValue: " Cargo space "
          },
          {
            Header: "Options",
            accessor: "option",
            sortable: false,
            show: true,
            displayValue: " Option "
          }
        ];
        this.setState({ columns });
      };

      handleSetData = cars => {
        console.log(cars);
        this.setState({ cars });
      };

      handleSetFilteredData = filteredData => {
        this.setState({ filteredData });
      };

      handleSetSearchInput = searchInput => {
        this.setState({ searchInput });
      };
    render() {

      let{cars,carid,carname,carfuel,carbody,carprice,caroffroad,carspeed,carluxury,carreliability,carsafety,carpracticality,cardrive,carinterior,carcity,cardistance,
        carconsumption,careconsumption,carengine,carcylinder,carnaot,carseats,carcargo ,filteredData, columns, searchInput }=this.state;

      const dataToDisplay = searchInput.length ? filteredData : cars;

    let addModalClose=()=> this.setState({addModalShow:false});
        let editModalClose=()=> this.setState({editModalShow:false});
        return(

   <GlobalSearchComponent
          cars={this.state.cars}
          columns={this.state.columns}
          handleSetFilteredData={this.handleSetFilteredData}
          handleSetSearchInput={this.handleSetSearchInput}
        />

 <ReactTable
          cars={dataToDisplay}
          columns={columns}
          defaultPageSize={10}
          className="-striped -highlight"
        />

{cars.map(cr=>

     {cr.modelName }
     {cr.fueltype }
     {cr.bodytype}
     {cr.priceinterval }
     {cr.offroadrank }
     {cr.maximumspeedinterval }
     {cr.luxuryrank }
     {cr.reliabilityrank }
     {cr.safetyrank }
     {cr.practicalityrank}
     {cr.driverank }
     {cr.interiorrank }
     {cr.forcity }
     {cr.forlong }
     {cr.consumption }
     {cr.electricconsumption}
     {cr.enginetype }
     {cr.cylindernumber }
     {cr.naot }
     {cr.seatsnumber }
     {cr.cargo }

        <ButtonToolbar>
            <Button
                   className="mr-2" variant ="info"
                    onClick={()=> this.setState({editModalShow : true ,
                        carid:cr.id, carname:cr.modelName,
                    carfuel:cr.fueltype,carbody:cr.bodytype,
            carprice:cr.priceinterval,caroffroad:cr.offroadrank,
            carspeed:cr.maximumspeedinterval,  carluxury:cr.luxuryrank,
            carreliability:cr.reliabilityrank,carsafety:cr.safetyrank,
            carpracticality:cr.practicalityrank,cardrive:cr.driverank,
            carinterior:cr.interiorrank,carcity:cr.forcity,
            cardistance:cr.forlong,carconsumption:cr.consumption,
            careconsumption:cr.electricconsumption,carengine:cr.enginetype,
            carcylinder:cr.cylindernumber,carnaot:cr.naot,
            carseats:cr.seatsnumber,carcargo:cr.cargo})}
           >
               Edit
           </Button>

          <Button className="mr-2"
          onClick={()=> this.deleteCar(cr.id)}
          variant="danger"
          > Delete</Button>

                <EditCarModal
                       show = {this.state.editModalShow}
                       onHide={editModalClose}
                       carid={carid}
                       carname={carname}
                       carfuel={carfuel}
                       carbody={carbody}
                        carprice={carprice}
                       caroffroad={caroffroad}
                       carspeed={carspeed}
                       carluxury={carluxury}
                       carreliability={carreliability}
                        carsafety={carsafety}
                       carpracticality={carpracticality}
                       cardrive={cardrive}
                       carinterior={carinterior}
                       carcity={carcity}
                       cardistance={cardistance}
                       carconsumption={carconsumption}
                       careconsumption={careconsumption}
                        carengine={carengine}
                        carcylinder={carcylinder}
                        carnaot={carnaot}
                        carseats={carseats}
                         carcargo={carcargo}
              />
             </ButtonToolbar>

)}

 <ButtonToolbar>
     <Button
     variant='primary'
     onClick={()=> this.setState({addModalShow: true})}
     >Add Car </Button>

     <AddCarModal
         show={this.state.addModalShow}
         onHide={addModalClose}
     />
 </ButtonToolbar>

    )

    }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Car />, rootElement);

GlobalSearchComponent

import React from "react";
import { Input } from "semantic-ui-react";

export default class GlobalSearchComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      filteredData: [],
      columnSearch: "",
      searchInput: ""
    };
  }

  handleChange = event => {
    const val = event.target.value;
    this.setState({ searchInput: val }, () => this.globalSearch());
    this.props.handleSetSearchInput(val);
  };

  globalSearch = () => {
    const { searchInput, columnSearch } = this.state;
    let filteredData = this.props.cars.filter(value => {
      if (columnSearch) {
        return value[columnSearch]
          .toString()
          .toLowerCase()
          .includes(searchInput.toLowerCase());
      }
      return (
        value.modelName.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.fueltype.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.bodytype.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.priceinterval.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.offroadrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.maximumspeedinterval.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.luxuryrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.reliabilityrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.safetyrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.practicalityrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.driverank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.interiorrank.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.forcity.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.forlong.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.consumption.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.econsumption.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.enginetype.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.cylindernumber.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.naot.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.seatsnumber.toLowerCase().includes(searchInput.toLowerCase()) ||
        value.cargo.toLowerCase().includes(searchInput.toLowerCase())

          .toString()
          .toLowerCase()
          .includes(searchInput.toLowerCase())
      );
    });

    this.props.handleSetFilteredData(filteredData);
  };

  setColumnSearch = e => {
    this.setState({ columnSearch: e.target.value }, () => this.globalSearch());
  };

  render() {
    const { columns } = this.props;
    const { columnSearch } = this.state;

    return (
      <>

        <Input
          size="large"
          name="searchInput"
          value={this.state.searchInput || ""}
          onChange={this.handleChange}
          label="Search"
        />
        <select
          onChange={e => {
            e.persist();
            this.setColumnSearch(e);
          }}
          value={columnSearch}
        >
          <option value=""> All columns</option>
          {columns.map(col => {
            return <option value={col.accessor}>{col.Header}</option>;
          })}
        </select>

      </>
    );
  }
}

Error

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

Check the render method of `Car`.
▶ 20 stack frames were collapsed.
Module../src/components/Car.js
C:/Users/Felix/source/repos/React/car-app/src/components/Car.js:384
  381 |     }
  382 | }
  383 | const rootElement = document.getElementById("root");
> 384 | ReactDOM.render(<Car />, rootElement);
  385 |
View compiled
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
Module../src/App.js
http://localhost:3000/static/js/main.chunk.js:129:73
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
Module../src/index.js
http://localhost:3000/static/js/main.chunk.js:2613:62
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
fn
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:150
  147 |         );
  148 |         hotCurrentParents = [];
  149 |     }
> 150 |     return __webpack_require__(request);
      | ^  151 | };
  152 | var ObjectFactory = function ObjectFactory(name) {
  153 |     return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:2758:18
__webpack_require__
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:785
  782 | };
  783 |
  784 | // Execute the module function
> 785 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
      | ^  786 |
  787 | // Flag the module as loaded
  788 | module.l = true;
View compiled
checkDeferredModules
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:45
  42 |  }
  43 |  if(fulfilled) {
  44 |      deferredModules.splice(i--, 1);
> 45 |      result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
     | ^  46 |  }
  47 | }
  48 |
View compiled
Array.webpackJsonpCallback [as push]
C:/Users/Felix/source/repos/React/car-app/webpack/bootstrap:32
  29 |  deferredModules.push.apply(deferredModules, executeModules || []);
  30 |
  31 |  // run deferred modules when all chunks ready
> 32 |  return checkDeferredModules();
     | ^  33 | };
  34 | function checkDeferredModules() {
  35 |  var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:67
This screen is visible only in development. It will not appear if the app crashes in production.
Open your browser’s developer console to further inspect this error.  Click the 'X' or hit ESC to dismiss this message.

Body:
I am using react table version "^7.1.0". You can try this.

import React from 'react'
import styled from 'styled-components'
import {useTable} from 'react-table'
import namor from 'namor';

const range = len => {
    const arr = [];
    for (let i = 0; i < len; i++) {
        arr.push(i)
    }
    return arr
};

const newPerson = () => {
    const statusChance = Math.random();
    const jIncome = Math.floor(Math.random() * 30);
    const bIncome = Math.floor(Math.random() * 100);

    return {
        firstName: namor.generate({words: 1, numbers: 0}),
        lastName: namor.generate({words: 1, numbers: 0}),
        jIncome: jIncome,
        bIncome: bIncome,
        tIncome: jIncome + bIncome,
        progress: Math.floor(Math.random() * 100),
        status:
            statusChance > 0.66
                ? 'relationship'
                : statusChance > 0.33
                ? 'complicated'
                : 'single',
    }
};

function makeData(...lens) {
    const makeDataLevel = (depth = 0) => {
        const len = lens[depth];
        return range(len).map(d => {
            return {
                ...newPerson(),
                subRows: lens[depth + 1] ? makeDataLevel(depth + 1) : undefined,
            }
        })
    };

    return makeDataLevel()
}

const Styles = styled.div`
  padding: 1rem;

  table {
    border-spacing: 0;
    border: 1px solid black;

    tr {
      :last-child {
        td {
          border-bottom: 0;
        }
      }
    }

    th,
    td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;

      :last-child {
        border-right: 0;
      }
    }
  }
`;

function Table({columns, data}) {
    // Use the state and functions returned from useTable to build your UI
    const {
        getTableProps,
        getTableBodyProps,
        headerGroups,
        rows,
        prepareRow,
    } = useTable({
        columns,
        data,
    });

    // Render the UI for your table
    return (
        <table {...getTableProps()}>
            <thead>
            {headerGroups.map(headerGroup => (
                <tr {...headerGroup.getHeaderGroupProps()}>
                    {headerGroup.headers.map(column => (
                        <th {...column.getHeaderProps()}>{column.render('Header')}</th>
                    ))}
                </tr>
            ))}
            </thead>
            <tbody {...getTableBodyProps()}>
            {rows.map((row, i) => {
                prepareRow(row);
                return (
                    <tr {...row.getRowProps(
                        {
                            style: {backgroundColor: row.values.tIncome > 50? 'skyblue': 'lightgray'}
                        }
                    )}>
                        {row.cells.map(cell => {
                            return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
                        })}
                    </tr>
                )
            })}
            </tbody>
        </table>
    )
}

function ReactTableRowColor() {
    const columns = React.useMemo(
        () => [
            {
                Header: 'Name',
                columns: [
                    {
                        Header: 'First Name',
                        accessor: 'firstName',
                    },
                    {
                        Header: 'Last Name',
                        accessor: 'lastName',
                    },
                ],
            },
            {
                Header: 'Info',
                columns: [
                    {
                        Header: 'Job Income',
                        accessor: 'jIncome',
                    },
                    {
                        Header: 'Business Income',
                        accessor: 'bIncome',
                    },
                    {
                        Header: 'Total Income',
                        accessor: 'tIncome',
                    },
                    {
                        Header: 'Status',
                        accessor: 'status',
                    },
                    {
                        Header: 'Profile Progress',
                        accessor: 'progress',
                    },
                ],
            },
        ],
        []
    );

    const data = React.useMemo(() => makeData(20), []);

    return (
        <Styles>
            <Table columns={columns} data={data}/>
        </Styles>
    )
}

export default ReactTableRowColor


来源: stackexchange

问:
Understanding document types in MAG and MSA Data dump
I am currently using Microsoft Academic's datadump for a project and  unable to identify the total number of theses & dissertations(T&D) present. Based on their website, 38% of data is categorised to OTHERS type (one among them is T&D). But their 60+GB CSV dump doesn't explicitly indicate the T&D records. Can someone help me with the statistics for T&D or how find the same? </p>

<p>I tried their API too and unable to find using their API too. </p>

答:
The Microsoft Academic Graph does not explicitly segment publication sub-types by thesis or dissertations, which means that neither the API or website will either.

If this is something you'd like to see added, please let them know by using the "Feedback" link in the lower-right corner on the Microsoft Academic website.

ContentLicense: CC BY-SA 4.0

Body:
I am currently using Microsoft Academic's datadump for a project and  unable to identify the total number of theses & dissertations(T&D) present. Based on their website, 38% of data is categorised to OTHERS type (one among them is T&D). But their 60+GB CSV dump doesn't explicitly indicate the T&D records. Can someone help me with the statistics for T&D or how find the same?

I tried their API too and unable to find using their API too.


问:
Issue with embedded SVG images in dark mode
Embedded svg image inside  tag doesn't work with media query prefers-color-scheme and CSS variables (Chrome and Safari, Firefox works).</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--color)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
    <style>
        :root{--color:#ffffff;}
        @media(prefers-color-scheme:light){:root{--color:#ffffff;}}
        @media(prefers-color-scheme:dark){:root{--color:#000000;}}
    </style>
    <path d="M18 15l-6-6-6 6"/>
</svg>
</code>```

答:
Try this:</p>

```<code><?xml version="1.0" encoding="utf-8"?>
<svg
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 24 24"
  width="48" height="48">
  <style>
    :root { --color: #00FF00; }
    @media (prefers-color-scheme: light) { :root { --color: #0000FF; } }
    @media (prefers-color-scheme: dark) { :root { --color: #FF0000; } }
    path {
      fill: none;
      stroke: var(--color);
      stroke-width: 3;
      stroke-linecap: round;
      stroke-linejoin: round;
    }
  </style>
  <path d="M18 15l-6-6-6 6"/>
</svg>
</code>```

Body:
Embedded svg image inside  tag doesn't work with media query prefers-color-scheme and CSS variables (Chrome and Safari, Firefox works).

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="var(--color)" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">

    <path d="M18 15l-6-6-6 6"/>
</svg>

Body:
Try this:

<?xml version="1.0" encoding="utf-8"?>
<svg
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 24 24"
  width="48" height="48">
  <style>
    :root { --color: #00FF00; }
    @media (prefers-color-scheme: light) { :root { --color: #0000FF; } }
    @media (prefers-color-scheme: dark) { :root { --color: #FF0000; } }
    path {
      fill: none;
      stroke: var(--color);
      stroke-width: 3;
      stroke-linecap: round;
      stroke-linejoin: round;
    }
  </style>
  <path d="M18 15l-6-6-6 6"/>
</svg>


问:
Java ArrayList sublist giving wrong result
I am trying to find the index of an element after a particular position in ArrayList in Java as mentioned in this question. Below is my implementation:

```<code>import java.io.*;
import java.util.*;
class palindrome{
    public static void main(String[] args)throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[] array = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        int n=array[0];
        List<StringBuilder> ls=new ArrayList<StringBuilder>();
        while(n-->0){
            ls.add(new StringBuilder(br.readLine()));
        }
        StringBuilder rev=ls.get(1).reverse();
        System.out.println(rev);
        int i=1;
        System.out.println(ls.subList(i+1,ls.size()).indexOf(rev));
    }
}
</code>```

I'm giving below input to the program

```<code>4 2
oo
ox
xx
xo
</code>```

so, the logic is that I am trying to find the index of reverse of 'ox', which should return 3, but the code always returns -1. I cannot spot any error. Please tell me if you guys have spotted any error.

Thank You!

答:
StringBuilders are work-in-progress strings being built and as such they don't override equals(). A string builder will only compare equal to itself. It's never equal to any other builders, not even ones with the same contents.

That means that indexOf() won't work because it relies on equals(). If you want this to work you need to use plain Strings rather than StringBuilders. For example:

```<code>List<String> ls = new ArrayList<>();
while (n-- > 0) {
    ls.add(br.readLine());
}
String rev = new StringBuilder(ls.get(1)).reverse().toString();
</code>```

Or, if you want to stick with StringBuilders you can, you'll just have to forego the indexOf() method and look for the matching string yourself with a manual for loop.

Body:
I am trying to find the index of an element after a particular position in ArrayList in Java as mentioned in this question. Below is my implementation:

import java.io.*;
import java.util.*;
class palindrome{
    public static void main(String[] args)throws IOException {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        int[] array = Arrays.stream(br.readLine().split(" ")).mapToInt(Integer::parseInt).toArray();
        int n=array[0];
        List<StringBuilder> ls=new ArrayList<StringBuilder>();
        while(n-->0){
            ls.add(new StringBuilder(br.readLine()));
        }
        StringBuilder rev=ls.get(1).reverse();
        System.out.println(rev);
        int i=1;
        System.out.println(ls.subList(i+1,ls.size()).indexOf(rev));
    }
}

I'm giving below input to the program

4 2
oo
ox
xx
xo

so, the logic is that I am trying to find the index of reverse of 'ox', which should return 3, but the code always returns -1. I cannot spot any error. Please tell me if you guys have spotted any error.

Thank You!

Body:
StringBuilders are work-in-progress strings being built and as such they don't override equals(). A string builder will only compare equal to itself. It's never equal to any other builders, not even ones with the same contents.

That means that indexOf() won't work because it relies on equals(). If you want this to work you need to use plain Strings rather than StringBuilders. For example:

List<String> ls = new ArrayList<>();
while (n-- > 0) {
    ls.add(br.readLine());
}
String rev = new StringBuilder(ls.get(1)).reverse().toString();

Or, if you want to stick with StringBuilders you can, you'll just have to forego the indexOf() method and look for the matching string yourself with a manual for loop.


问:
STL + typedefs vs. OOP, best practices?
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like: </p>

```<code>typedef std::map<std::string, std::map<std::string, int> > CSVData;
</code>```

<p>Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this? </p>

答: I think most of us write less and less OO code as we get older. The urge to turn everything into an object and construct Byzantine inheritance hierarchies tends to fade in the experience of maintaining these things.</p>

ContentLicense: CC BY-SA 3.0

Title: STL + typedefs vs. OOP, best practices?

Body:
I "grew up" learning to set up data structures using OOP. But now as I learn more about C++, STL, and Boost, I find that many of my data structure needs can be met by combining STL classes into more complex composites like:

typedef std::map<std::string, std::map<std::string, int> > CSVData;

Obviously there are limits to this when I need to mix data types, but generally I find myself avoiding OOP when I can in favor of these STL composites for their simplicity. Is this a common progression? Are there best-practice rules-of-thumb for when it's better to define your own class? Are there common pitfalls to this?


问:
MathJax can't align \vert

The problem I'm having should be seen above.

```<code>\color{red}{x = (1-t)^3x_0 + 3t(1-t)^2x_{1} + 3t^2(1-t)x_{2} + t^3x_{3}}\\
\color{blue}{y = (1-t)^3y_0 + 3t(1-t)^2y_{1} + 3t^2(1-t)y_{2} + t^3y_{3}}
}\Bigg\vert t\in{[0,1]}
</code>```

I have tried multiple different methods. Can someone recommend how I could get the \vert and conditions to align centered to the two lines of the equations.

P.S. - I know the math looks ugly... it was actually intentional... it's kind of a cross between programming and math... for a "math for programmers" document.

答:
It's not clear exactly what you have in mind, but perhaps this does what you want:

$$
\left.
\begin{aligned}
\color{red}{x} &\color{red}{{}= (1-t)^3x_0 + 3t(1-t)^2x_{1} + 3t^2(1-t)x_{2} + t^3x_{3}}\ \\
\color{blue}{y} &\color{blue}{{}= (1-t)^3y_0 + 3t(1-t)^2y_{1} + 3t^2(1-t)y_{2} + t^3y_{3}}
\end{aligned}
\right\vert \ t\in{[0,1]}
$$```

Title: MathJax can't align \vert

Body:
The problem I'm having should be seen above.

\color{red}{x = (1-t)^3x_0 + 3t(1-t)^2x_{1} + 3t^2(1-t)x_{2} + t^3x_{3}}\\
\color{blue}{y = (1-t)^3y_0 + 3t(1-t)^2y_{1} + 3t^2(1-t)y_{2} + t^3y_{3}}
}\Bigg\vert t\in{[0,1]}

I have tried multiple different methods. Can someone recommend how I could get the \vert and conditions to align centered to the two lines of the equations.

P.S. - I know the math looks ugly... it was actually intentional... it's kind of a cross between programming and math... for a "math for programmers" document.

Body:
It's not clear exactly what you have in mind, but perhaps this does what you want:

<script src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" id="MathJax-script"></script>

$$
\left.
\begin{aligned}
\color{red}{x} &\color{red}{{}= (1-t)^3x_0 + 3t(1-t)^2x_{1} + 3t^2(1-t)x_{2} + t^3x_{3}}\ \\
\color{blue}{y} &\color{blue}{{}= (1-t)^3y_0 + 3t(1-t)^2y_{1} + 3t^2(1-t)y_{2} + t^3y_{3}}
\end{aligned}
\right\vert \ t\in{[0,1]}
$$


问:
Can't access ansible_host property of my inventory items
I have this inventory file:

```<code>[masters]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu

[workers]
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[nodes]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[fileserver]
fs-01 ansible_host=1.2.3.4.5 ansible_user=ubuntu
</code>```

I'm trying to install an SSH key from my local machine to all inventory machines.

```<code>- name: install the SSH key on all machines.
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking ubuntu@{{ item }}
    with_items:
      - "{{ hostvars['all'].ansible_host }}"
</code>```

However, it ends with this error:

```<code>fatal: [127.0.0.1]: FAILED! => {"msg": "\"hostvars['all']\" is undefined"}
</code>```

I'm trying to get the ansible_host 1.2.3.4.5 of each unique inventory name in my inventory. However, I'm not having much luck. What am I doing wrong?

答:
hostvars is a dictionary that stores the ansible hosts as keys and their variables as values. so for your inventory, the hostvars dict would look like this:

```<code>master: {...}
worker1: {...}
fs-01: {...}
</code>```

The reason all returns undefined is because you don't have a host named all.

Since you just want the hostname, instead of hostvars['all'].ansible_host, just use ansible_host which will resolve the hostname for you to ssh into.

Like so:

```<code>    with_items:
      - "{{ ansible_host }}"
</code>```

Body:
I have this inventory file:

[masters]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu

[workers]
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[nodes]
master ansible_host=1.2.3.4.5 ansible_user=ubuntu
worker1 ansible_host=1.2.3.4.5 ansible_user=ubuntu

[fileserver]
fs-01 ansible_host=1.2.3.4.5 ansible_user=ubuntu

I'm trying to install an SSH key from my local machine to all inventory machines.

- name: install the SSH key on all machines.
  hosts: 127.0.0.1
  connection: local
  tasks:
  - name: install SSH-key
    shell: sshpass -p {{ ssh_key_password }} ssh-copy-id -i /id_rsa.pub -o StrictHostKeyChecking ubuntu@{{ item }}
    with_items:
      - "{{ hostvars['all'].ansible_host }}"

However, it ends with this error:

fatal: [127.0.0.1]: FAILED! => {"msg": "\"hostvars['all']\" is undefined"}

I'm trying to get the ansible_host 1.2.3.4.5 of each unique inventory name in my inventory. However, I'm not having much luck. What am I doing wrong?

Body:
hostvars is a dictionary that stores the ansible hosts as keys and their variables as values. so for your inventory, the hostvars dict would look like this:

master: {...}
worker1: {...}
fs-01: {...}

The reason all returns undefined is because you don't have a host named all.

Since you just want the hostname, instead of hostvars['all'].ansible_host, just use ansible_host which will resolve the hostname for you to ssh into.

Like so:

    with_items:
      - "{{ ansible_host }}"


问:
maven offers itself postgreSQL driver dependency but then doesn't see it
I tried to connect PostgreSQL connector driver with maven but it doesn't find this dependency

I tried to add driver as .jar file with Project structure and it worked, but I want to add it just like dependency in maven.

答: As I understood it was IDEA problem. I used "mvn clean compile" in terminal and idea started see the dependency</p>


问:
Moving a work item between projects in TFS
Is it possible to move a work item from one project to another inside TFS?  I’ve seen a copy option, but no move.  Also, if it is possible, what’s the implication for any of the WI history?

I found this article from 2008 that seem to say it's not, but I wondered if there'd been any progress since then.

答:
Lars Wilhelmsen wrote a WorkItemMigrator -> http://larsw.codeplex.com/SourceControl/list/changesets

Good starting point for a utility you can customize for your needs.  We used it to split off a 100 or so work items to a new project.  Here's the program I ended up with.  Modify the query to subset the items to migrate.

```<code>namespace WorkItemMigrator
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

class Program
{

    #region Members
    private static readonly Dictionary<Uri, TfsTeamProjectCollection> Collections = new Dictionary<Uri, TfsTeamProjectCollection>();
    private static readonly Uri SourceCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
    private static readonly Uri TargetCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
    private const String Areas = "ProjectModelHierarchy";
    private const string Iterations = "ProjectLifecycle";
    private const string TargetProjectName = "TargetProject";
    private const string MicrosoftVstsCommonStackRankFieldName = "Microsoft.VSTS.Common.StackRank";
    private const string MicrosoftVstsCommonPriority = "Microsoft.VSTS.Common.Priority";
    private const string TargetWorkItemType = "User Story";
    private const string Wiql = "SELECT [System.Id], [System.State], [System.Title], [System.AssignedTo], [System.WorkItemType], [Microsoft.VSTS.Common.Priority], " +
                        "[System.IterationPath], [System.AreaPath], [System.History], [System.Description] " +
                        "FROM WorkItems WHERE [System.TeamProject] = 'SourceProject' AND " +
                        "[System.State] = 'Active' " +
                        "ORDER BY [System.Id]";

    private static WorkItemTypeCollection WorkItemTypes;
    private static Dictionary<int, int> WorkItemIdMap = new Dictionary<int, int>();

    #endregion
    static void Main()
    {
    var createAreasAndIterations = GetRunMode();

    var sourceWorkItemStore = GetSourceWorkItemStore();

    var sourceWorkItems = sourceWorkItemStore.Query(Wiql);

    var targetWorkItemStore = GetTargetWorkItemStore();
    var targetProject = targetWorkItemStore.Projects[TargetProjectName];

    WorkItemTypes = targetProject.WorkItemTypes;

    foreach (WorkItem sourceWorkItem in sourceWorkItems)
    {
        if (createAreasAndIterations)
        {
        Console.WriteLine();
        EnsureThatStructureExists(TargetProjectName, Areas, sourceWorkItem.AreaPath.Substring(sourceWorkItem.AreaPath.IndexOf("\\") + 1));
        EnsureThatStructureExists(TargetProjectName, Iterations, sourceWorkItem.IterationPath.Substring(sourceWorkItem.IterationPath.IndexOf("\\") + 1));
        }
        else
        {
        MigrateWorkItem(sourceWorkItem);
        }
    }

    if (!createAreasAndIterations)
    {
        var query = from WorkItem wi in sourceWorkItems where wi.Links.Count > 0 select wi;
        foreach (WorkItem sourceWorkItem in query)
        {
        LinkRelatedItems(targetWorkItemStore, sourceWorkItem);
        }
    }

    TextWriter tw = File.CreateText(@"C:\temp\TFS_MigratedItems.csv");
    tw.WriteLine("SourceId,TargetId");
    foreach (var entry in WorkItemIdMap)
    {
        tw.WriteLine(entry.Key + "," + entry.Value);
    }
    tw.Close();
    Console.WriteLine();
    Console.WriteLine("Done! Have a nice day.");
    Console.ReadLine();
    }

    private static bool GetRunMode()
    {
    bool createAreasAndIterations;
    while (true)
    {
        Console.Write("Create [A]reas/Iterations or [M]igrate (Ctrl-C to quit)?: ");
        var command = Console.ReadLine().ToUpper().Trim();
        if (command == "A")
        {
        createAreasAndIterations = true;
        break;
        }
        if (command == "M")
        {
        createAreasAndIterations = false;
        break;
        }
        Console.WriteLine("Unknown command " + command + " - try again.");
    }
    return createAreasAndIterations;
    }

    private static void MigrateWorkItem(WorkItem sourceWorkItem)
    {

    var targetWIT = WorkItemTypes[sourceWorkItem.Type.Name];
    var newWorkItem = targetWIT.NewWorkItem();
    //var newWorkItem = targetWorkItemType.NewWorkItem();

    // Description (Task) / Steps to reproduce (Bug)

    if (sourceWorkItem.Type.Name != "Bug")
    {
        newWorkItem.Description = sourceWorkItem.Description;
    }
    else
    {
        newWorkItem.Fields["Microsoft.VSTS.TCM.ReproSteps"].Value = sourceWorkItem.Description;
    }

    // History
    newWorkItem.History = sourceWorkItem.History;
    // Title
    newWorkItem.Title = sourceWorkItem.Title;
    // Assigned To
    newWorkItem.Fields[CoreField.AssignedTo].Value = sourceWorkItem.Fields[CoreField.AssignedTo].Value;
    // Stack Rank - Priority
    newWorkItem.Fields[MicrosoftVstsCommonPriority].Value = sourceWorkItem.Fields[MicrosoftVstsCommonPriority].Value;
    // Area Path
    newWorkItem.AreaPath = FormatPath(TargetProjectName, sourceWorkItem.AreaPath);
    // Iteration Path
    newWorkItem.IterationPath = FormatPath(TargetProjectName, sourceWorkItem.IterationPath);
    // Activity
    if (sourceWorkItem.Type.Name == "Task")
    {
        newWorkItem.Fields["Microsoft.VSTS.Common.Activity"].Value = sourceWorkItem.Fields["Microsoft.VSTS.Common.Discipline"].Value;
    }
    // State
    //newWorkItem.State = sourceWorkItem.State;
    // Reason
    //newWorkItem.Reason = sourceWorkItem.Reason;

    // build a usable rendition of prior revision history
    RevisionCollection revisions = sourceWorkItem.Revisions;
    var query = from Revision r in revisions orderby r.Fields["Changed Date"].Value descending select r;
    StringBuilder sb = new StringBuilder(String.Format("Migrated from work item {0}<BR />\n", sourceWorkItem.Id));
    foreach (Revision revision in query)
    {
        String history = (String)revision.Fields["History"].Value;
        if (!String.IsNullOrEmpty(history))
        {
        foreach (Field f in revision.Fields)
        {
            if (!Object.Equals(f.Value, f.OriginalValue))
            {
            if (f.Name == "History")
            {
                string notation = string.Empty;
                if (revision.Fields["State"].OriginalValue != revision.Fields["State"].Value)
                {
                notation = String.Format("({0} to {1})", revision.Fields["State"].OriginalValue, revision.Fields["State"].Value);
                }
                //Console.WriteLine("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation);
                sb.Append(String.Format("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}<BR />\n", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation));
            }
            }
        }
        //Console.WriteLine("Revision {0}: ", revision.Fields["Rev"].Value);
        //Console.WriteLine("  ChangedDate: " + revision.Fields["ChangedDate"].Value);
        //Console.WriteLine("  History: " + sb.ToString());
        }
    }
    newWorkItem.History = sb.ToString();

    // Attachments
    for (var i = 0; i < sourceWorkItem.AttachedFileCount; i++)
    {
        CopyAttachment(sourceWorkItem.Attachments[i], newWorkItem);
    }

    // Validate before save
    if (!newWorkItem.IsValid())
    {
        var reasons = newWorkItem.Validate();
        Console.WriteLine(string.Format("Could not validate new work item (old id: {0}).", sourceWorkItem.Id));
        foreach (Field reason in reasons)
        {
        Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
        }
    }
    else
    {
        Console.Write("[" + sourceWorkItem.Id + "] " + newWorkItem.Title);
        try
        {
        newWorkItem.Save(SaveFlags.None);
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine(string.Format(" [saved: {0}]", newWorkItem.Id));
        WorkItemIdMap.Add(sourceWorkItem.Id, newWorkItem.Id);
        Console.ResetColor();
        }
        catch (Exception ex)
        {
        Console.WriteLine(ex.Message);
        throw;
        }
    }
    }

    private static void CopyAttachment(Attachment attachment, WorkItem newWorkItem)
    {
    using (var client = new WebClient())
    {
        client.UseDefaultCredentials = true;
        client.DownloadFile(attachment.Uri, attachment.Name);
        var newAttachment = new Attachment(attachment.Name, attachment.Comment);
        newWorkItem.Attachments.Add(newAttachment);
    }
    }

    private static void LinkRelatedItems(WorkItemStore targetWorkItemStore, WorkItem sourceWorkItem)
    {
    int newId = WorkItemIdMap[sourceWorkItem.Id];
    WorkItem targetItem = targetWorkItemStore.GetWorkItem(newId);
    foreach (Link l in sourceWorkItem.Links)
    {
        if (l is RelatedLink)
        {
        RelatedLink sl = l as RelatedLink;
        switch (sl.ArtifactLinkType.Name)
        {
            case "Related Workitem":
            {
                if (WorkItemIdMap.ContainsKey(sl.RelatedWorkItemId))
                {
                int RelatedWorkItemId = WorkItemIdMap[sl.RelatedWorkItemId];
                RelatedLink rl = new RelatedLink(sl.LinkTypeEnd, RelatedWorkItemId);
                // !!!!
                // this does not work - need to check the existing links to see if one exists already for the linked workitem.
                // using contains expects the same object and that's not what I'm doing here!!!!!!
                //if (!targetItem.Links.Contains(rl))
                // !!!!
                var query = from RelatedLink qrl in targetItem.Links where qrl.RelatedWorkItemId == RelatedWorkItemId select qrl;
                if (query.Count() == 0)
                {
                    targetItem.Links.Add(rl); ;
                    // Validate before save
                    if (!targetItem.IsValid())
                    {
                    var reasons = targetItem.Validate();
                    Console.WriteLine(string.Format("Could not validate work item (old id: {0}) related link id {1}.", sourceWorkItem.Id, sl.RelatedWorkItemId));
                    foreach (Field reason in reasons)
                    {
                        Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
                    }
                    }
                    else
                    {
                    try
                    {
                        targetItem.Save(SaveFlags.None);
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine(string.Format(" [Updated: {0}]", targetItem.Id));
                        Console.ResetColor();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }
                    }

                }
                }
                break;
            }
            default:
            { break; }
        }

        }
    }
    }

    private static void EnsureThatStructureExists(string projectName, string structureType, string structurePath)
    {
    var parts = structurePath.Split('\\');

    var css = GetCommonStructureService();
    var projectInfo = css.GetProjectFromName(projectName);
    var parentNodeUri = GetCssStructure(GetCommonStructureService(), projectInfo.Uri, structureType).Uri;
    var currentPath = FormatPath(projectName, structureType == Areas ? "Area" : "Iteration");
    foreach (var part in parts)
    {
        currentPath = FormatPath(currentPath, part);
        Console.Write(currentPath);

        try
        {
        var currentNode = css.GetNodeFromPath(currentPath);
        parentNodeUri = currentNode.Uri;
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        Console.WriteLine(" [found]");
        }
        catch
        {
        parentNodeUri = css.CreateNode(part, parentNodeUri);
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(" [created]");
        }
        Console.ResetColor();
    }
    }

    private static string FormatPath(string currentPath, string part)
    {
    part = part.Substring(part.IndexOf("\\") + 1);
    currentPath = string.Format(@"{0}\{1}", currentPath, part);
    return currentPath;
    }

    private static TfsTeamProjectCollection GetProjectCollection(Uri uri)
    {
    TfsTeamProjectCollection collection;
    if (!Collections.TryGetValue(uri, out collection))
    {
        collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
        collection.Connect(ConnectOptions.IncludeServices);
        collection.Authenticate();
        Collections.Add(uri, collection);
    }
    return Collections[uri];
    }

    private static WorkItemStore GetSourceWorkItemStore()
    {
    var collection = GetProjectCollection(SourceCollectionUri);
    return collection.GetService<WorkItemStore>();
    }

    private static WorkItemStore GetTargetWorkItemStore()
    {
    var collection = GetProjectCollection(TargetCollectionUri);
    return collection.GetService<WorkItemStore>();
    }

    public static NodeInfo GetCssStructure(ICommonStructureService css, String projectUri, String structureType)
    {
    return css.ListStructures(projectUri).FirstOrDefault(node => node.StructureType == structureType);
    }

    private static ICommonStructureService GetCommonStructureService()
    {
    var collection = GetProjectCollection(TargetCollectionUri);
    return collection.GetService<ICommonStructureService>();
    }
}
}
</code>```

Body:
Lars Wilhelmsen wrote a WorkItemMigrator -> http://larsw.codeplex.com/SourceControl/list/changesets

Good starting point for a utility you can customize for your needs.  We used it to split off a 100 or so work items to a new project.  Here's the program I ended up with.  Modify the query to subset the items to migrate.

namespace WorkItemMigrator
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.Framework.Common;
using Microsoft.TeamFoundation.Server;
using Microsoft.TeamFoundation.WorkItemTracking.Client;

class Program
{

    #region Members
    private static readonly Dictionary<Uri, TfsTeamProjectCollection> Collections = new Dictionary<Uri, TfsTeamProjectCollection>();
    private static readonly Uri SourceCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
    private static readonly Uri TargetCollectionUri = new Uri("http://your.domain.com:8080/tfs/DefaultCollection");
    private const String Areas = "ProjectModelHierarchy";
    private const string Iterations = "ProjectLifecycle";
    private const string TargetProjectName = "TargetProject";
    private const string MicrosoftVstsCommonStackRankFieldName = "Microsoft.VSTS.Common.StackRank";
    private const string MicrosoftVstsCommonPriority = "Microsoft.VSTS.Common.Priority";
    private const string TargetWorkItemType = "User Story";
    private const string Wiql = "SELECT [System.Id], [System.State], [System.Title], [System.AssignedTo], [System.WorkItemType], [Microsoft.VSTS.Common.Priority], " +
                        "[System.IterationPath], [System.AreaPath], [System.History], [System.Description] " +
                        "FROM WorkItems WHERE [System.TeamProject] = 'SourceProject' AND " +
                        "[System.State] = 'Active' " +
                        "ORDER BY [System.Id]";

    private static WorkItemTypeCollection WorkItemTypes;
    private static Dictionary<int, int> WorkItemIdMap = new Dictionary<int, int>();

    #endregion
    static void Main()
    {
    var createAreasAndIterations = GetRunMode();

    var sourceWorkItemStore = GetSourceWorkItemStore();

    var sourceWorkItems = sourceWorkItemStore.Query(Wiql);

    var targetWorkItemStore = GetTargetWorkItemStore();
    var targetProject = targetWorkItemStore.Projects[TargetProjectName];

    WorkItemTypes = targetProject.WorkItemTypes;

    foreach (WorkItem sourceWorkItem in sourceWorkItems)
    {
        if (createAreasAndIterations)
        {
        Console.WriteLine();
        EnsureThatStructureExists(TargetProjectName, Areas, sourceWorkItem.AreaPath.Substring(sourceWorkItem.AreaPath.IndexOf("\\") + 1));
        EnsureThatStructureExists(TargetProjectName, Iterations, sourceWorkItem.IterationPath.Substring(sourceWorkItem.IterationPath.IndexOf("\\") + 1));
        }
        else
        {
        MigrateWorkItem(sourceWorkItem);
        }
    }

    if (!createAreasAndIterations)
    {
        var query = from WorkItem wi in sourceWorkItems where wi.Links.Count > 0 select wi;
        foreach (WorkItem sourceWorkItem in query)
        {
        LinkRelatedItems(targetWorkItemStore, sourceWorkItem);
        }
    }

    TextWriter tw = File.CreateText(@"C:\temp\TFS_MigratedItems.csv");
    tw.WriteLine("SourceId,TargetId");
    foreach (var entry in WorkItemIdMap)
    {
        tw.WriteLine(entry.Key + "," + entry.Value);
    }
    tw.Close();
    Console.WriteLine();
    Console.WriteLine("Done! Have a nice day.");
    Console.ReadLine();
    }

    private static bool GetRunMode()
    {
    bool createAreasAndIterations;
    while (true)
    {
        Console.Write("Create [A]reas/Iterations or [M]igrate (Ctrl-C to quit)?: ");
        var command = Console.ReadLine().ToUpper().Trim();
        if (command == "A")
        {
        createAreasAndIterations = true;
        break;
        }
        if (command == "M")
        {
        createAreasAndIterations = false;
        break;
        }
        Console.WriteLine("Unknown command " + command + " - try again.");
    }
    return createAreasAndIterations;
    }

    private static void MigrateWorkItem(WorkItem sourceWorkItem)
    {

    var targetWIT = WorkItemTypes[sourceWorkItem.Type.Name];
    var newWorkItem = targetWIT.NewWorkItem();
    //var newWorkItem = targetWorkItemType.NewWorkItem();

    // Description (Task) / Steps to reproduce (Bug)

    if (sourceWorkItem.Type.Name != "Bug")
    {
        newWorkItem.Description = sourceWorkItem.Description;
    }
    else
    {
        newWorkItem.Fields["Microsoft.VSTS.TCM.ReproSteps"].Value = sourceWorkItem.Description;
    }

    // History
    newWorkItem.History = sourceWorkItem.History;
    // Title
    newWorkItem.Title = sourceWorkItem.Title;
    // Assigned To
    newWorkItem.Fields[CoreField.AssignedTo].Value = sourceWorkItem.Fields[CoreField.AssignedTo].Value;
    // Stack Rank - Priority
    newWorkItem.Fields[MicrosoftVstsCommonPriority].Value = sourceWorkItem.Fields[MicrosoftVstsCommonPriority].Value;
    // Area Path
    newWorkItem.AreaPath = FormatPath(TargetProjectName, sourceWorkItem.AreaPath);
    // Iteration Path
    newWorkItem.IterationPath = FormatPath(TargetProjectName, sourceWorkItem.IterationPath);
    // Activity
    if (sourceWorkItem.Type.Name == "Task")
    {
        newWorkItem.Fields["Microsoft.VSTS.Common.Activity"].Value = sourceWorkItem.Fields["Microsoft.VSTS.Common.Discipline"].Value;
    }
    // State
    //newWorkItem.State = sourceWorkItem.State;
    // Reason
    //newWorkItem.Reason = sourceWorkItem.Reason;

    // build a usable rendition of prior revision history
    RevisionCollection revisions = sourceWorkItem.Revisions;
    var query = from Revision r in revisions orderby r.Fields["Changed Date"].Value descending select r;
    StringBuilder sb = new StringBuilder(String.Format("Migrated from work item {0}<BR />\n", sourceWorkItem.Id));
    foreach (Revision revision in query)
    {
        String history = (String)revision.Fields["History"].Value;
        if (!String.IsNullOrEmpty(history))
        {
        foreach (Field f in revision.Fields)
        {
            if (!Object.Equals(f.Value, f.OriginalValue))
            {
            if (f.Name == "History")
            {
                string notation = string.Empty;
                if (revision.Fields["State"].OriginalValue != revision.Fields["State"].Value)
                {
                notation = String.Format("({0} to {1})", revision.Fields["State"].OriginalValue, revision.Fields["State"].Value);
                }
                //Console.WriteLine("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation);
                sb.Append(String.Format("<STRONG>{0} Edited {3} by {1}</STRONG><BR />\n{2}<BR />\n", revision.Fields["Changed Date"].Value.ToString(), revision.Fields["Changed By"].Value.ToString(), f.Value, notation));
            }
            }
        }
        //Console.WriteLine("Revision {0}: ", revision.Fields["Rev"].Value);
        //Console.WriteLine("  ChangedDate: " + revision.Fields["ChangedDate"].Value);
        //Console.WriteLine("  History: " + sb.ToString());
        }
    }
    newWorkItem.History = sb.ToString();

    // Attachments
    for (var i = 0; i < sourceWorkItem.AttachedFileCount; i++)
    {
        CopyAttachment(sourceWorkItem.Attachments[i], newWorkItem);
    }

    // Validate before save
    if (!newWorkItem.IsValid())
    {
        var reasons = newWorkItem.Validate();
        Console.WriteLine(string.Format("Could not validate new work item (old id: {0}).", sourceWorkItem.Id));
        foreach (Field reason in reasons)
        {
        Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
        }
    }
    else
    {
        Console.Write("[" + sourceWorkItem.Id + "] " + newWorkItem.Title);
        try
        {
        newWorkItem.Save(SaveFlags.None);
        Console.ForegroundColor = ConsoleColor.Cyan;
        Console.WriteLine(string.Format(" [saved: {0}]", newWorkItem.Id));
        WorkItemIdMap.Add(sourceWorkItem.Id, newWorkItem.Id);
        Console.ResetColor();
        }
        catch (Exception ex)
        {
        Console.WriteLine(ex.Message);
        throw;
        }
    }
    }

    private static void CopyAttachment(Attachment attachment, WorkItem newWorkItem)
    {
    using (var client = new WebClient())
    {
        client.UseDefaultCredentials = true;
        client.DownloadFile(attachment.Uri, attachment.Name);
        var newAttachment = new Attachment(attachment.Name, attachment.Comment);
        newWorkItem.Attachments.Add(newAttachment);
    }
    }

    private static void LinkRelatedItems(WorkItemStore targetWorkItemStore, WorkItem sourceWorkItem)
    {
    int newId = WorkItemIdMap[sourceWorkItem.Id];
    WorkItem targetItem = targetWorkItemStore.GetWorkItem(newId);
    foreach (Link l in sourceWorkItem.Links)
    {
        if (l is RelatedLink)
        {
        RelatedLink sl = l as RelatedLink;
        switch (sl.ArtifactLinkType.Name)
        {
            case "Related Workitem":
            {
                if (WorkItemIdMap.ContainsKey(sl.RelatedWorkItemId))
                {
                int RelatedWorkItemId = WorkItemIdMap[sl.RelatedWorkItemId];
                RelatedLink rl = new RelatedLink(sl.LinkTypeEnd, RelatedWorkItemId);
                // !!!!
                // this does not work - need to check the existing links to see if one exists already for the linked workitem.
                // using contains expects the same object and that's not what I'm doing here!!!!!!
                //if (!targetItem.Links.Contains(rl))
                // !!!!
                var query = from RelatedLink qrl in targetItem.Links where qrl.RelatedWorkItemId == RelatedWorkItemId select qrl;
                if (query.Count() == 0)
                {
                    targetItem.Links.Add(rl); ;
                    // Validate before save
                    if (!targetItem.IsValid())
                    {
                    var reasons = targetItem.Validate();
                    Console.WriteLine(string.Format("Could not validate work item (old id: {0}) related link id {1}.", sourceWorkItem.Id, sl.RelatedWorkItemId));
                    foreach (Field reason in reasons)
                    {
                        Console.WriteLine("Field: " + reason.Name + ", Status: " + reason.Status + ", Value: " + reason.Value);
                    }
                    }
                    else
                    {
                    try
                    {
                        targetItem.Save(SaveFlags.None);
                        Console.ForegroundColor = ConsoleColor.Cyan;
                        Console.WriteLine(string.Format(" [Updated: {0}]", targetItem.Id));
                        Console.ResetColor();
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        throw;
                    }
                    }

                }
                }
                break;
            }
            default:
            { break; }
        }

        }
    }
    }

    private static void EnsureThatStructureExists(string projectName, string structureType, string structurePath)
    {
    var parts = structurePath.Split('\\');

    var css = GetCommonStructureService();
    var projectInfo = css.GetProjectFromName(projectName);
    var parentNodeUri = GetCssStructure(GetCommonStructureService(), projectInfo.Uri, structureType).Uri;
    var currentPath = FormatPath(projectName, structureType == Areas ? "Area" : "Iteration");
    foreach (var part in parts)
    {
        currentPath = FormatPath(currentPath, part);
        Console.Write(currentPath);

        try
        {
        var currentNode = css.GetNodeFromPath(currentPath);
        parentNodeUri = currentNode.Uri;
        Console.ForegroundColor = ConsoleColor.DarkGreen;
        Console.WriteLine(" [found]");
        }
        catch
        {
        parentNodeUri = css.CreateNode(part, parentNodeUri);
        Console.ForegroundColor = ConsoleColor.Green;
        Console.WriteLine(" [created]");
        }
        Console.ResetColor();
    }
    }

    private static string FormatPath(string currentPath, string part)
    {
    part = part.Substring(part.IndexOf("\\") + 1);
    currentPath = string.Format(@"{0}\{1}", currentPath, part);
    return currentPath;
    }

    private static TfsTeamProjectCollection GetProjectCollection(Uri uri)
    {
    TfsTeamProjectCollection collection;
    if (!Collections.TryGetValue(uri, out collection))
    {
        collection = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(uri);
        collection.Connect(ConnectOptions.IncludeServices);
        collection.Authenticate();
        Collections.Add(uri, collection);
    }
    return Collections[uri];
    }

    private static WorkItemStore GetSourceWorkItemStore()
    {
    var collection = GetProjectCollection(SourceCollectionUri);
    return collection.GetService<WorkItemStore>();
    }

    private static WorkItemStore GetTargetWorkItemStore()
    {
    var collection = GetProjectCollection(TargetCollectionUri);
    return collection.GetService<WorkItemStore>();
    }

    public static NodeInfo GetCssStructure(ICommonStructureService css, String projectUri, String structureType)
    {
    return css.ListStructures(projectUri).FirstOrDefault(node => node.StructureType == structureType);
    }

    private static ICommonStructureService GetCommonStructureService()
    {
    var collection = GetProjectCollection(TargetCollectionUri);
    return collection.GetService<ICommonStructureService>();
    }
}
}


问:
Switching between "|" and "&&" symbols in a command based on input
I'm using a bash script to concatenate the execution of a series of programs. Each of these programs produces an output and has two flags that can be set as -iInputFile.txt and -oOutputFile.txt, if no flag is set then standard input and output are automatically selected. Most of the time I simply concatenate my programs as

```<code>./Program1 | ./Program2 | ./Program3
</code>```

but if I happen to need to save the data to a file, and then also access it from the next file I need to do

```<code>./Program1 | ./Program2 -oFile.txt && ./Program3 -iFile.txt
</code>```

so my question is if there is a way to provide an input, for example 010, and only convert the symbols between script 2 and 3 from | to && while leaving everything else untouched. Hard-coding it would be impossible since I have up to 12 programs concatenated so it would have even 12! combinations. It's my first time asking so if anything is unclear from the question I'll edit to provide any information required, thank you all in advance.

答:
If you are scripting this, you can hard-code in tee between the pipeline and use bash's default value parameter expansion to essentially turn off the 'write to file feature'

```<code>./Program1 | tee ${outFile1:- /dev/null} | ./Program2 | tee ${outFile2:- /dev/null} | \
    ./Program3 | tee ${outFile3:- /dev/null}
</code>```

Note that the last call to tee might be superfluous

Proof of Concept

```<code>$ unset outFile; echo foo | tee ${outFile:- /dev/null} | cat - && cat ./tmp
foo
cat: ./tmp: No such file or directory
$ outFile=./tmp; echo foo | tee ${outFile:- /dev/null} | cat - && cat ./tmp
foo
foo
</code>```

Body:
I'm using a bash script to concatenate the execution of a series of programs. Each of these programs produces an output and has two flags that can be set as -iInputFile.txt and -oOutputFile.txt, if no flag is set then standard input and output are automatically selected. Most of the time I simply concatenate my programs as

./Program1 | ./Program2 | ./Program3

but if I happen to need to save the data to a file, and then also access it from the next file I need to do

./Program1 | ./Program2 -oFile.txt && ./Program3 -iFile.txt

so my question is if there is a way to provide an input, for example 010, and only convert the symbols between script 2 and 3 from | to && while leaving everything else untouched. Hard-coding it would be impossible since I have up to 12 programs concatenated so it would have even 12! combinations. It's my first time asking so if anything is unclear from the question I'll edit to provide any information required, thank you all in advance.

Body:
If you are scripting this, you can hard-code in tee between the pipeline and use bash's default value parameter expansion to essentially turn off the 'write to file feature'

./Program1 | tee ${outFile1:- /dev/null} | ./Program2 | tee ${outFile2:- /dev/null} | \
    ./Program3 | tee ${outFile3:- /dev/null}

Note that the last call to tee might be superfluous

Proof of Concept

$ unset outFile; echo foo | tee ${outFile:- /dev/null} | cat - && cat ./tmp
foo
cat: ./tmp: No such file or directory
$ outFile=./tmp; echo foo | tee ${outFile:- /dev/null} | cat - && cat ./tmp
foo
foo


问:
Xamarin Persistent color chooser
I make a button and Color picker to xamarin.forms app, but I want to make it when I choose one color (ex. red) and close app, when i reopen it to see this red color automatic picked. I try to use this code but Preferences not working with Color:

```<code>public Color ColorPicker
{
    get => Preferences.Get(nameof(ColorPicker), color.Red);
    set
    {
        Preferences.Set(nameof(ColorPicker), value);
        OnPropertyChanged(nameof(ColorPicker));
    }
}
</code>```

Can someone help me?

答:
I is not possible to make it like this. Because i need to use converter after to make string=>color. I am trying this:

```<code>    public class StringToColor : IValueConverter
{
    ColorTypeConverter converter = new ColorTypeConverter();
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //return value.ToString(); //not working
        //return (Color)(converter.ConvertFromInvariantString(value.ToString())); //not working
        return Color.FromHex(value.ToString()); //not working too
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}
</code>```

and add this convetor to xaml

```<code><ContentPage.Resources>
    <ResourceDictionary>
        <local:StringToColor x:Key="str" />
    </ResourceDictionary>
</ContentPage.Resources>

    <Label Text="TEST" FontSize="Title" TextColor="{Binding ColorPicker,
    Converter={StaticResource str}}"/>
</code>```

but nothing happend...

Title: Xamarin Persistent color chooser

Body:
I make a button and Color picker to xamarin.forms app, but I want to make it when I choose one color (ex. red) and close app, when i reopen it to see this red color automatic picked. I try to use this code but Preferences not working with Color:

public Color ColorPicker
{
    get => Preferences.Get(nameof(ColorPicker), color.Red);
    set
    {
        Preferences.Set(nameof(ColorPicker), value);
        OnPropertyChanged(nameof(ColorPicker));
    }
}

Can someone help me?

Body:
I is not possible to make it like this. Because i need to use converter after to make string=>color. I am trying this:

    public class StringToColor : IValueConverter
{
    ColorTypeConverter converter = new ColorTypeConverter();
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        //return value.ToString(); //not working
        //return (Color)(converter.ConvertFromInvariantString(value.ToString())); //not working
        return Color.FromHex(value.ToString()); //not working too
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value;
    }
}

and add this convetor to xaml

<ContentPage.Resources>
    <ResourceDictionary>
        <local:StringToColor x:Key="str" />
    </ResourceDictionary>
</ContentPage.Resources>

    <Label Text="TEST" FontSize="Title" TextColor="{Binding ColorPicker,
    Converter={StaticResource str}}"/>

but nothing happend...


问:
GoogleCalendarAPI accept/decline event
I am working on GoogleCalendar API and using node.js as a platform to build my application.
I am able to create events using authentication procedure and creating the calendar event using the access token generated while authenticating.

My question is that suppose if we have any attendee in the event and I want to accept/decline the event using the calendar API from the attendee's side, how can we do that?

I have tried fetching the calendar event of the attendee and matching it with the iCalUID of the event which was originally created and then modifying the event using update event on the attendee's calendar.

答:
Lets suppose that you already have the event payload with the attendees key, then you need to get the ID for the created event:

created_event = gcal_service.events().insert(
    calendarId='primary', body=event_payload
).execute()
```

<p>then copy the attendees in a new object</p>

<pre class="lang-py prettyprint-override"><code>accepted_attendees = {}
accepted_attendees['attendees'] = event_payload['attendees'].copy()
</code>```

and now what you need to do is submit a patch to the attendees calendar based on the event_id, like this:

```<code>for attendee in event_payload['attendees']:
    attendee_pos = accepted_attendees['attendees'].index(attendee)
    accepted_attendees['attendees'].pop(attendee_pos)
    accepted_attendees['attendees'].append({
        'email': attendee['email'],
        'self': True,
        'responseStatus': 'accepted',
        'additionalGuests': 0,
    })
    gcal_service.events().patch(
        calendarId='primary',
        eventId=created_event['id'],
        body=accepted_attendees
    )
</code>```

And that's all, all the other attendees, now have accepted the event, hope it helps.

Title: GoogleCalendarAPI accept/decline event

Body:
Lets suppose that you already have the event payload with the attendees key, then you need to get the ID for the created event:

created_event = gcal_service.events().insert(
    calendarId='primary', body=event_payload
).execute()

then copy the attendees in a new object

accepted_attendees = {}
accepted_attendees['attendees'] = event_payload['attendees'].copy()

and now what you need to do is submit a patch to the attendees calendar based on the event_id, like this:

for attendee in event_payload['attendees']:
    attendee_pos = accepted_attendees['attendees'].index(attendee)
    accepted_attendees['attendees'].pop(attendee_pos)
    accepted_attendees['attendees'].append({
        'email': attendee['email'],
        'self': True,
        'responseStatus': 'accepted',
        'additionalGuests': 0,
    })
    gcal_service.events().patch(
        calendarId='primary',
        eventId=created_event['id'],
        body=accepted_attendees
    )

And that's all, all the other attendees, now have accepted the event, hope it helps.