问:
How to clean Docker container logs?
I read my Docker container log output using

```<code>docker logs -f <container_name>
</code>```

I log lots of data to the log in my node.js app via calls to console.log(). I need to clean the log, because it's gotten too long and the docker logs command first runs through the existing lines of the log before getting to the end. How do I clean it to make it short again? I'd like to see a command like:

```<code>docker logs clean <container_name>
</code>```

But it doesn't seem to exist.

答:
If you want to remove all log files, not only for a specific container's log, you can use:

```<code>docker system prune
</code>```

But, note that this does not clear logs for running containers.

Title: How to clean Docker container logs?

Body:
I read my Docker container log output using

docker logs -f <container_name>

I log lots of data to the log in my node.js app via calls to console.log(). I need to clean the log, because it's gotten too long and the docker logs command first runs through the existing lines of the log before getting to the end. How do I clean it to make it short again? I'd like to see a command like:

docker logs clean <container_name>

But it doesn't seem to exist.

Body:
If you want to remove all log files, not only for a specific container's log, you can use:

docker system prune

But, note that this does not clear logs for running containers.


来源: stackexchange

问:
LINQ: Comparing specific values in two datatables
I have two datatables.

datatable 1 has data with columns FirstName, LastName, DOB, Gender
datatable 2 has data with columns CustomerID, FirstName, LastName, DOB, Gender

I want to compare the firstName, LastName, DOB and gender in datatable 1 and 2, and if there is a match, load that row in datatable 2 into a new datatable.

Below is what I am using, I can compare with Firstname, but I want to add the lastname, DOB and gender. Please can you show me how I can do that?

I want to do it such that if firstname, lastname, dob and gender match then return that matching row in datatable 2. The column length between the tables are different.

```<code>DataTable dtMerged = (from a in dataTable.AsEnumerable()
                                  join b in dt.AsEnumerable()
                                  on a["Forename"].ToString() equals b["FirstName"].ToString()
                                  into g
                                  where g.Count() > 0
                                  select a).CopyToDataTable();

            dtMerged.AsDataView();
</code>```

答:
Try this</p>

```<code>DataTable dtMerged = dataTable.AsEnumerable()
    .Where(ra => dt.AsEnumerable()
    .Any(rb => rb.Field<string>("firstname") == ra.Field<string>("firstname")
      && rb.Field<string>("lastname") == ra.Field<string>("lastname")
      && rb.Field<DateTime>("dob") == ra.Field<DateTime>("dob")
      && rb.Field<string>("gender") == ra.Field<string>("gender")))
              .CopyToDataTable();
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two datatables.

datatable 1 has data with columns FirstName, LastName, DOB, Gender
datatable 2 has data with columns CustomerID, FirstName, LastName, DOB, Gender

I want to compare the firstName, LastName, DOB and gender in datatable 1 and 2, and if there is a match, load that row in datatable 2 into a new datatable.

Below is what I am using, I can compare with Firstname, but I want to add the lastname, DOB and gender. Please can you show me how I can do that?

I want to do it such that if firstname, lastname, dob and gender match then return that matching row in datatable 2. The column length between the tables are different.

DataTable dtMerged = (from a in dataTable.AsEnumerable()
                                  join b in dt.AsEnumerable()
                                  on a["Forename"].ToString() equals b["FirstName"].ToString()
                                  into g
                                  where g.Count() > 0
                                  select a).CopyToDataTable();

            dtMerged.AsDataView();

Body:
Try this

DataTable dtMerged = dataTable.AsEnumerable()
    .Where(ra => dt.AsEnumerable()
    .Any(rb => rb.Field<string>("firstname") == ra.Field<string>("firstname")
      && rb.Field<string>("lastname") == ra.Field<string>("lastname")
      && rb.Field<DateTime>("dob") == ra.Field<DateTime>("dob")
      && rb.Field<string>("gender") == ra.Field<string>("gender")))
              .CopyToDataTable();


问:
While using sed command i receive the following error : Function cannot be parsed. Any Solutions or reason for this?
I need to replace a particular character in a text file with another character. For example, replacing "E" with "A":

Apple ice → ApplA Ica

While executing sed 's/E/A' < apple.txt > app.txt I receive the error

function cannot be parsed

Please help! I need to automate this using Antscript.

答:
Since you are in Ant environment, you probably don't need to execute sed at all, but rather use Copy task with filter, or ReplaceRegExp task.

```<code><?xml version="1.0" encoding="UTF-8"?>
<project>
    <replaceregexp file="apple.txt" flags="g" match="e" replace="A"/>
</project>
</code>```

This alters the file in place:

```<code>$ cat apple.txt
Apple ice
$
$ ant
Buildfile: build.xml

BUILD SUCCESSFUL
Total time: 0 seconds
$
$ cat apple.txt
ApplA icA
</code>```

Your example is strange with case (a|A, e|E). I'll assume that's typo.

Follow up: To declare encoding...

```<code><?xml version="1.0" encoding="utf-8"?>
<project>
    <replaceregexp file="apple.txt" encoding="utf-8" flags="g" match="Á" replace=" "/>
</project>
</code>```

I tested this successfully. Before:

```<code>ApplA icA
ApplÁs icÁs
</code>```

After:

```<code>ApplA icA
Appl s ic s
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Since you are in Ant environment, you probably don't need to execute sed at all, but rather use Copy task with filter, or ReplaceRegExp task.

<?xml version="1.0" encoding="UTF-8"?>
<project>
    <replaceregexp file="apple.txt" flags="g" match="e" replace="A"/>
</project>

This alters the file in place:

$ cat apple.txt
Apple ice
$
$ ant
Buildfile: build.xml

BUILD SUCCESSFUL
Total time: 0 seconds
$
$ cat apple.txt
ApplA icA

Your example is strange with case (a|A, e|E). I'll assume that's typo.

Follow up: To declare encoding...

<?xml version="1.0" encoding="utf-8"?>
<project>
    <replaceregexp file="apple.txt" encoding="utf-8" flags="g" match="Á" replace=" "/>
</project>

I tested this successfully. Before:

ApplA icA
ApplÁs icÁs

After:

ApplA icA
Appl s ic s


问:
How to read filtered rows from excel using POI library
I am reading excel file using POI library in my java code. So far fine. But now I have one requirement. The excel file contains many records (e.g. 1000 rows). It also has column headers (1st row). Now I am doing excel filtering on it. Say I have one 'year' column and I am filtering all rows for year=2019. I get 15 rows.
Question: I want to process only these 15 rows in my java code. Is there any method in poi library or way to know if the row being read is filtered or (the other way i.e. not filtered).
Thanks.

I already have working code but right now I am looking for how to read only filtered row. Nothing new tried yet other than searching in library and forums.

The below code is inside a method. I am not used to formatting with stackoverflow so kindly ignore any formatting issue.

```<code>    // For storing data into CSV files
    StringBuffer data = new StringBuffer();
    try {
        SimpleDateFormat dtFormat = new SimpleDateFormat(CommonConstants.YYYY_MM_DD); // "yyyy-MM-dd"
        String doubleQuotes = "\"";
        FileOutputStream fos = new FileOutputStream(outputFile);
        // Get the workbook object for XLSX file
        XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
        wBook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);

        // Get first sheet from the workbook
        //XSSFSheet sheet = wBook.getSheetAt(0);
        XSSFSheet sheet = wBook.getSheet(CommonConstants.METADATA_WORKSHEET);
        //Row row;
        //Cell cell;
        // Iterate through each rows from first sheet
        int rows = sheet.getLastRowNum();
        int totalRows = 0;
        int colTitelNumber = 0;
        Row firstRowRecord = sheet.getRow(1);
        for (int cn = 0; cn < firstRowRecord.getLastCellNum(); cn++) {
            Cell cellObj = firstRowRecord.getCell(cn);
            if(cellObj != null) {
                String str = cellObj.toString();
                if(CommonConstants.COLUMN_TITEL.equalsIgnoreCase(str)) {
                    colTitelNumber = cn;
                    break;
                }
            }
        }
        // Start with row Number 1. We don't need 0th number row as it is for Humans to read but not required for processing.
        for (int rowNumber = 1; rowNumber <= rows; rowNumber++) {
            StringBuffer rowData = new StringBuffer();
            boolean skipRow = false;
            Row rowRecord = sheet.getRow(rowNumber);
            if (rowRecord == null) {
                LOG.error("Empty/Null record found");
            } else {
                for (int cn = 0; cn < rowRecord.getLastCellNum(); cn++) {
                    Cell cellObj = rowRecord.getCell(cn);
                    if(cellObj == null) {
                        if(cn == colTitelNumber) {
                            skipRow = true;
                            break; // The first column cell value is empty/null. Which means Titel column cell doesn't have value so don't add this row in csv.
                        }
                        rowData.append(CommonConstants.CSV_SEPARTOR);
                        continue;
                    }
                    switch (cellObj.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            rowData.append(cellObj.getBooleanCellValue() + CommonConstants.CSV_SEPARTOR);
                            //LOG.error("Boolean:" + cellObj.getBooleanCellValue());
                            break;

                        case Cell.CELL_TYPE_NUMERIC:
                            if (DateUtil.isCellDateFormatted(cellObj)) {
                                Date date = cellObj.getDateCellValue();
                                rowData.append(dtFormat.format(date).toString() + CommonConstants.CSV_SEPARTOR);
                                //LOG.error("Date:" + cellObj.getDateCellValue());
                            } else {
                                rowData.append(cellObj.getNumericCellValue() + CommonConstants.CSV_SEPARTOR);
                                //LOG.error("Numeric:" + cellObj.getNumericCellValue());
                            }
                            break;

                        case Cell.CELL_TYPE_STRING:
                            String cellValue = cellObj.getStringCellValue();
                            // If string contains double quotes then replace it with pair of double quotes.
                            cellValue = cellValue.replaceAll(doubleQuotes, doubleQuotes + doubleQuotes);
                            // If string contains comma then surround the string with double quotes.
                            rowData.append(doubleQuotes + cellValue + doubleQuotes + CommonConstants.CSV_SEPARTOR);
                            //LOG.error("String:" + cellObj.getStringCellValue());
                            break;

                        case Cell.CELL_TYPE_BLANK:
                            rowData.append("" + CommonConstants.CSV_SEPARTOR);
                            //LOG.error("Blank:" + cellObj.toString());
                            break;

                        default:
                            rowData.append(cellObj + CommonConstants.CSV_SEPARTOR);
                    }
                }
                if(!skipRow) {
                    rowData.append("\r\n");
                    data.append(rowData); // Appending one entire row to main data string buffer.
                    totalRows++;
                }
            }
        }
        pTransferObj.put(CommonConstants.TOTAL_ROWS, (totalRows));
        fos.write(data.toString().getBytes());
        fos.close();
        wBook.close();
    } catch (Exception ex) {
        LOG.error("Exception Caught while generating CSV file", ex);
    }
</code>```

答:
All rows which are not visible in the sheet have a zero height. So if the need is only reading the visible rows, one could check via Row.getZeroHeight.

Example

Sheet:

Code:

```<code>import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.*;

class ReadExcelOnlyVisibleRows {

 public static void main(String[] args) throws Exception {

  Workbook workbook  = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));

  DataFormatter dataFormatter = new DataFormatter();

  CreationHelper creationHelper = workbook.getCreationHelper();

  FormulaEvaluator formulaEvaluator = creationHelper.createFormulaEvaluator();

  Sheet sheet = workbook.getSheetAt(0);

  for (Row row : sheet) {
   if (!row.getZeroHeight()) { // if row.getZeroHeight() is true then this row is not visible
    for (Cell cell : row) {
     String cellContent = dataFormatter.formatCellValue(cell, formulaEvaluator);
     System.out.print(cellContent + "\t");
    }
    System.out.println();
   }
  }

  workbook.close();

 }
}
</code>```

Result:

```<code>F1    F2    F3      F4
V2    2     2-Mai   FALSE
V4    4     4-Mai   FALSE
V2    6     6-Mai   FALSE
V4    8     8-Mai   FALSE
</code>```

Body:
I am reading excel file using POI library in my java code. So far fine. But now I have one requirement. The excel file contains many records (e.g. 1000 rows). It also has column headers (1st row). Now I am doing excel filtering on it. Say I have one 'year' column and I am filtering all rows for year=2019. I get 15 rows.
Question: I want to process only these 15 rows in my java code. Is there any method in poi library or way to know if the row being read is filtered or (the other way i.e. not filtered).
Thanks.

I already have working code but right now I am looking for how to read only filtered row. Nothing new tried yet other than searching in library and forums.

The below code is inside a method. I am not used to formatting with stackoverflow so kindly ignore any formatting issue.

    // For storing data into CSV files
    StringBuffer data = new StringBuffer();
    try {
        SimpleDateFormat dtFormat = new SimpleDateFormat(CommonConstants.YYYY_MM_DD); // "yyyy-MM-dd"
        String doubleQuotes = "\"";
        FileOutputStream fos = new FileOutputStream(outputFile);
        // Get the workbook object for XLSX file
        XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(inputFile));
        wBook.setMissingCellPolicy(Row.RETURN_BLANK_AS_NULL);

        // Get first sheet from the workbook
        //XSSFSheet sheet = wBook.getSheetAt(0);
        XSSFSheet sheet = wBook.getSheet(CommonConstants.METADATA_WORKSHEET);
        //Row row;
        //Cell cell;
        // Iterate through each rows from first sheet
        int rows = sheet.getLastRowNum();
        int totalRows = 0;
        int colTitelNumber = 0;
        Row firstRowRecord = sheet.getRow(1);
        for (int cn = 0; cn < firstRowRecord.getLastCellNum(); cn++) {
            Cell cellObj = firstRowRecord.getCell(cn);
            if(cellObj != null) {
                String str = cellObj.toString();
                if(CommonConstants.COLUMN_TITEL.equalsIgnoreCase(str)) {
                    colTitelNumber = cn;
                    break;
                }
            }
        }
        // Start with row Number 1. We don't need 0th number row as it is for Humans to read but not required for processing.
        for (int rowNumber = 1; rowNumber <= rows; rowNumber++) {
            StringBuffer rowData = new StringBuffer();
            boolean skipRow = false;
            Row rowRecord = sheet.getRow(rowNumber);
            if (rowRecord == null) {
                LOG.error("Empty/Null record found");
            } else {
                for (int cn = 0; cn < rowRecord.getLastCellNum(); cn++) {
                    Cell cellObj = rowRecord.getCell(cn);
                    if(cellObj == null) {
                        if(cn == colTitelNumber) {
                            skipRow = true;
                            break; // The first column cell value is empty/null. Which means Titel column cell doesn't have value so don't add this row in csv.
                        }
                        rowData.append(CommonConstants.CSV_SEPARTOR);
                        continue;
                    }
                    switch (cellObj.getCellType()) {
                        case Cell.CELL_TYPE_BOOLEAN:
                            rowData.append(cellObj.getBooleanCellValue() + CommonConstants.CSV_SEPARTOR);
                            //LOG.error("Boolean:" + cellObj.getBooleanCellValue());
                            break;

                        case Cell.CELL_TYPE_NUMERIC:
                            if (DateUtil.isCellDateFormatted(cellObj)) {
                                Date date = cellObj.getDateCellValue();
                                rowData.append(dtFormat.format(date).toString() + CommonConstants.CSV_SEPARTOR);
                                //LOG.error("Date:" + cellObj.getDateCellValue());
                            } else {
                                rowData.append(cellObj.getNumericCellValue() + CommonConstants.CSV_SEPARTOR);
                                //LOG.error("Numeric:" + cellObj.getNumericCellValue());
                            }
                            break;

                        case Cell.CELL_TYPE_STRING:
                            String cellValue = cellObj.getStringCellValue();
                            // If string contains double quotes then replace it with pair of double quotes.
                            cellValue = cellValue.replaceAll(doubleQuotes, doubleQuotes + doubleQuotes);
                            // If string contains comma then surround the string with double quotes.
                            rowData.append(doubleQuotes + cellValue + doubleQuotes + CommonConstants.CSV_SEPARTOR);
                            //LOG.error("String:" + cellObj.getStringCellValue());
                            break;

                        case Cell.CELL_TYPE_BLANK:
                            rowData.append("" + CommonConstants.CSV_SEPARTOR);
                            //LOG.error("Blank:" + cellObj.toString());
                            break;

                        default:
                            rowData.append(cellObj + CommonConstants.CSV_SEPARTOR);
                    }
                }
                if(!skipRow) {
                    rowData.append("\r\n");
                    data.append(rowData); // Appending one entire row to main data string buffer.
                    totalRows++;
                }
            }
        }
        pTransferObj.put(CommonConstants.TOTAL_ROWS, (totalRows));
        fos.write(data.toString().getBytes());
        fos.close();
        wBook.close();
    } catch (Exception ex) {
        LOG.error("Exception Caught while generating CSV file", ex);
    }

Body:
All rows which are not visible in the sheet have a zero height. So if the need is only reading the visible rows, one could check via Row.getZeroHeight.

Example

Sheet:

Code:

import java.io.FileInputStream;

import org.apache.poi.ss.usermodel.*;

class ReadExcelOnlyVisibleRows {

 public static void main(String[] args) throws Exception {

  Workbook workbook  = WorkbookFactory.create(new FileInputStream("SAMPLE.xlsx"));

  DataFormatter dataFormatter = new DataFormatter();

  CreationHelper creationHelper = workbook.getCreationHelper();

  FormulaEvaluator formulaEvaluator = creationHelper.createFormulaEvaluator();

  Sheet sheet = workbook.getSheetAt(0);

  for (Row row : sheet) {
   if (!row.getZeroHeight()) { // if row.getZeroHeight() is true then this row is not visible
    for (Cell cell : row) {
     String cellContent = dataFormatter.formatCellValue(cell, formulaEvaluator);
     System.out.print(cellContent + "\t");
    }
    System.out.println();
   }
  }

  workbook.close();

 }
}

Result:

F1    F2    F3      F4
V2    2     2-Mai   FALSE
V4    4     4-Mai   FALSE
V2    6     6-Mai   FALSE
V4    8     8-Mai   FALSE


问:
What is a right way to work with reducer in Redux?
I am building an app, sort of dictionary app. In my app a user can add, update and delete a word. Something happened and now my update function does not work. I don't understand why. When I click an update button an error appears in the console. Your hints and suggestions are appreciated.

Word update API

```<code>// @route  Put api/words/:id
// @desc   Update a word by id
// @access Private
router.put(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id).then(word => {
        // Check for word owner
        if (word.user.toString() !== req.user.id) {
          return res.status(401).json({ notauthorized: 'User not authorized' });
        }

        const wordID = req.params.id;
        const wordInput = req.body;

        // Update
        Word.findByIdAndUpdate(
          { _id: wordID },
          { $set: wordInput },
          { returnOriginal: false },
          (err, word) => {
            if (err) {
              console.log(err);
            }
          }
        )
          .then(word => {
            res.json(word);
          })
          .catch(err =>
            res
              .status(404)
              .json({ wordcannotbeupdated: 'word cannot be updated' })
          );
      });
    });
  }
);
</code>```

Word actions

```<code>export const updateWord = (id, updatedWord, history) => dispatch => {
  axios
    .put(`/api/words/${id}`, updatedWord)
    .then(res => {
      dispatch({
        type: UPDATE_WORD,
        payload: res.data
      });
      history.push('/my-words');
    })
    .catch(err =>
      dispatch({
        type: UPDATE_WORD,
        payload: ''
      })
    );
};
</code>```

Word reducer

```<code>import {
  GET_WORDS_BY_USER,
  ADD_WORD,
  UPDATE_WORD,
  GET_WORD_BY_ID,
  DELETE_WORD,
  SEARCH_WORD
} from '../actions/types';

const initialState = {
  words: [],
  word: {},
  loading: false
};

export default function(state = initialState, action) {
  switch (action.type) {
    case ADD_WORD:
      return {
        ...state,
        words: [action.payload, ...state.words]
      };
    case GET_WORDS_BY_USER:
      return {
        ...state,
        words: action.payload
      };
    case GET_WORD_BY_ID:
      return {
        ...state,
        word: action.payload
      };
    case UPDATE_WORD:
      return {
        ...state,
        words: action.payload
      };
    case SEARCH_WORD:
      return {
        ...state,
        words: action.payload
      };
    case DELETE_WORD:
      return {
        ...state,
        words: state.words.filter(word => word._id !== action.payload)
      };
    default:
      return state;
  }
}
</code>```

Edit Word React component

```<code>import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import TextFieldGroup from '../common/TextFieldGroup';
import SelectListGroup from '../common/SelectListGroup';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getWordByID, updateWord } from '../../actions/wordActions';
import isEmpty from '../../validation/is-empty';
import {
  lexisOptions,
  grammarOptions,
  partOfSpeechOptions,
  styleOptions,
  originOptions,
  sphereOptions
} from './options';

class EditWord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ugrWordCyr: '',
      rusTranslation: '',
      example: '',
      exampleTranslation: '',
      origin: '',
      sphere: '',
      see: '',
      lexis: '',
      grammar: '',
      partOfSpeech: '',
      style: '',
      errors: {}
    };
    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.onCheck = this.onCheck.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }

    if (nextProps.words.word[0]) {
      nextProps.words.word.map(word => {
        word.ugrWordCyr = !isEmpty(word.ugrWordCyr) ? word.ugrWordCyr : '';
        word.rusTranslation = !isEmpty(word.rusTranslation)
          ? word.rusTranslation
          : '';
        word.rusTranslation = !isEmpty(word.rusTranslation)
          ? word.rusTranslation
          : '';
        word.example = !isEmpty(word.example) ? word.example : '';
        word.exampleTranslation = !isEmpty(word.exampleTranslation)
          ? word.exampleTranslation
          : '';
        word.origin = !isEmpty(word.origin) ? word.origin : '';
        word.sphere = !isEmpty(word.sphere) ? word.sphere : '';
        word.see = !isEmpty(word.see) ? word.see : {};
        word.lexis = !isEmpty(word.lexis) ? word.lexis : {};
        word.grammar = !isEmpty(word.grammar) ? word.grammar : {};
        word.see = !isEmpty(word.see) ? word.see : {};
        word.style = !isEmpty(word.style) ? word.style : {};

        this.setState({
          ugrWordCyr: word.ugrWordCyr,
          rusTranslation: word.rusTranslation,
          example: word.example,
          exampleTranslation: word.exampleTranslation,
          origin: word.origin,
          sphere: word.sphere,
          style: word.style,
          lexis: word.lexis,
          grammar: word.grammar,
          see: word.see,
          partOfSpeech: word.partOfSpeech
        });
      });
    }
  }

  componentDidMount() {
    this.props.getWordByID(this.props.match.params.id);
  }

  onSubmit(e) {
    e.preventDefault();
    const wordData = {
      ugrWordCyr: this.state.ugrWordCyr,
      rusTranslation: this.state.rusTranslation,
      example: this.state.example,
      exampleTranslation: this.state.exampleTranslation,
      origin: this.state.origin,
      sphere: this.state.sphere,
      see: this.state.see,
      lexis: this.state.lexis,
      grammar: this.state.grammar,
      partOfSpeech: this.state.partOfSpeech,
      style: this.state.style
    };
    let id = this.props.match.params.id;
    // Change a function to update
    this.props.updateWord(id, wordData, this.props.history);
  }

  onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }

  onCheck(e) {
    this.setState({
      current: !this.state.current
    });
  }
  render() {
    const { errors } = this.state;

    return (
      <div className="add-word">
        <div className="container">
          <div className="row">
            <div className="col-md-8 m-auto">
              <Link to="/my-words" className="btn btn-light">
                Go Back
              </Link>
              <h1 className="display-4 text-center">Edit Word</h1>
              <form onSubmit={this.onSubmit}>
                <TextFieldGroup
                  placeholder="Бала"
                  info="Введите слово на уйгурском"
                  name="ugrWordCyr"
                  value={this.state.ugrWordCyr}
                  onChange={this.onChange}
                  error={errors.ugrWordCyr}
                />
                <TextFieldGroup
                  placeholder="Ребенок"
                  info="Введите слово на русском"
                  name="rusTranslation"
                  value={this.state.rusTranslation}
                  onChange={this.onChange}
                  error={errors.rusTranslation}
                />
                <div className="form-check mb-form">
                  <input
                    type="checkbox"
                    className="form-check-input"
                    name="see"
                    value={this.state.see}
                    onChange={this.onCheck}
                    id="see"
                  />
                  <label htmlFor="see">Смотри</label>
                </div>
                <TextFieldGroup
                  placeholder=""
                  info="Введите пример предложения на уйгурском"
                  name="example"
                  value={this.state.example}
                  onChange={this.onChange}
                  error={errors.example}
                />
                <TextFieldGroup
                  placeholder=""
                  info="Введите перевод примерного предложения на русском"
                  name="exampleTranslation"
                  value={this.state.exampleTranslation}
                  onChange={this.onChange}
                  error={errors.exampleTranslation}
                />
                <h6>Происхождение слова</h6>
                <SelectListGroup
                  placeholder="Арабское"
                  name="origin"
                  value={this.state.origin}
                  onChange={this.onChange}
                  error={errors.origin}
                  options={originOptions}
                />
                <h6>Сфера употребления слова</h6>
                <SelectListGroup
                  placeholder="Физика"
                  name="sphere"
                  value={this.state.sphere}
                  onChange={this.onChange}
                  error={errors.sphere}
                  options={sphereOptions}
                />
                <h6>Лексика слова</h6>
                <SelectListGroup
                  placeholder="лексика"
                  name="lexis"
                  value={this.state.lexis}
                  onChange={this.onChange}
                  error={errors.lexis}
                  options={lexisOptions}
                />
                <h6>Стиль слова</h6>
                <SelectListGroup
                  placeholder="стиль"
                  name="style"
                  value={this.state.style}
                  onChange={this.onChange}
                  error={errors.style}
                  options={styleOptions}
                />
                <h6>Часть речи</h6>
                <SelectListGroup
                  placeholder=""
                  name="partOfSpeech"
                  value={this.state.partOfSpeech}
                  onChange={this.onChange}
                  error={errors.partOfSpeech}
                  options={partOfSpeechOptions}
                />
                <h6>Грамматика слова</h6>
                <SelectListGroup
                  placeholder="грамматика"
                  name="grammar"
                  value={this.state.grammar}
                  onChange={this.onChange}
                  error={errors.grammar}
                  options={grammarOptions}
                />
                <input
                  type="submit"
                  value="submit"
                  className="btn btn-info btn-block mt-4"
                />
              </form>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

EditWord.propTypes = {
  getWordByID: PropTypes.func.isRequired,
  errors: PropTypes.object.isRequired,
  updateWord: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  errors: state.errors,
  words: state.words
});

export default connect(
  mapStateToProps,
  { getWordByID, updateWord }
)(withRouter(EditWord));
</code>```

答:
axios
      .put(/api/words/${id}, updatedWord)

if you are using relative api endpoint then it will be going to request to

```<code><react-server-host:port(which is 3000 in your case)>/api/words/${id}
</code>```

and i am assuming you are running your backend service on another port than 3000 . Thats why it is giving error 404 not found
So when you are requesting api, write absolute endpoint

```<code><backend-server-host:port>/api/words/${id}
</code>```

Body:
I am building an app, sort of dictionary app. In my app a user can add, update and delete a word. Something happened and now my update function does not work. I don't understand why. When I click an update button an error appears in the console. Your hints and suggestions are appreciated.

Word update API

// @route  Put api/words/:id
// @desc   Update a word by id
// @access Private
router.put(
  '/:id',
  passport.authenticate('jwt', { session: false }),
  (req, res) => {
    const { errors, isValid } = validateWordInput(req.body);

    // Check validation
    if (!isValid) {
      // Return any errors
      return res.status(400).json(errors);
    }

    Profile.findOne({ user: req.user.id }).then(profile => {
      Word.findById(req.params.id).then(word => {
        // Check for word owner
        if (word.user.toString() !== req.user.id) {
          return res.status(401).json({ notauthorized: 'User not authorized' });
        }

        const wordID = req.params.id;
        const wordInput = req.body;

        // Update
        Word.findByIdAndUpdate(
          { _id: wordID },
          { $set: wordInput },
          { returnOriginal: false },
          (err, word) => {
            if (err) {
              console.log(err);
            }
          }
        )
          .then(word => {
            res.json(word);
          })
          .catch(err =>
            res
              .status(404)
              .json({ wordcannotbeupdated: 'word cannot be updated' })
          );
      });
    });
  }
);

Word actions

export const updateWord = (id, updatedWord, history) => dispatch => {
  axios
    .put(`/api/words/${id}`, updatedWord)
    .then(res => {
      dispatch({
        type: UPDATE_WORD,
        payload: res.data
      });
      history.push('/my-words');
    })
    .catch(err =>
      dispatch({
        type: UPDATE_WORD,
        payload: ''
      })
    );
};

Word reducer

import {
  GET_WORDS_BY_USER,
  ADD_WORD,
  UPDATE_WORD,
  GET_WORD_BY_ID,
  DELETE_WORD,
  SEARCH_WORD
} from '../actions/types';

const initialState = {
  words: [],
  word: {},
  loading: false
};

export default function(state = initialState, action) {
  switch (action.type) {
    case ADD_WORD:
      return {
        ...state,
        words: [action.payload, ...state.words]
      };
    case GET_WORDS_BY_USER:
      return {
        ...state,
        words: action.payload
      };
    case GET_WORD_BY_ID:
      return {
        ...state,
        word: action.payload
      };
    case UPDATE_WORD:
      return {
        ...state,
        words: action.payload
      };
    case SEARCH_WORD:
      return {
        ...state,
        words: action.payload
      };
    case DELETE_WORD:
      return {
        ...state,
        words: state.words.filter(word => word._id !== action.payload)
      };
    default:
      return state;
  }
}

Edit Word React component

import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import TextFieldGroup from '../common/TextFieldGroup';
import SelectListGroup from '../common/SelectListGroup';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { getWordByID, updateWord } from '../../actions/wordActions';
import isEmpty from '../../validation/is-empty';
import {
  lexisOptions,
  grammarOptions,
  partOfSpeechOptions,
  styleOptions,
  originOptions,
  sphereOptions
} from './options';

class EditWord extends Component {
  constructor(props) {
    super(props);
    this.state = {
      ugrWordCyr: '',
      rusTranslation: '',
      example: '',
      exampleTranslation: '',
      origin: '',
      sphere: '',
      see: '',
      lexis: '',
      grammar: '',
      partOfSpeech: '',
      style: '',
      errors: {}
    };
    this.onChange = this.onChange.bind(this);
    this.onSubmit = this.onSubmit.bind(this);
    this.onCheck = this.onCheck.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.errors) {
      this.setState({ errors: nextProps.errors });
    }

    if (nextProps.words.word[0]) {
      nextProps.words.word.map(word => {
        word.ugrWordCyr = !isEmpty(word.ugrWordCyr) ? word.ugrWordCyr : '';
        word.rusTranslation = !isEmpty(word.rusTranslation)
          ? word.rusTranslation
          : '';
        word.rusTranslation = !isEmpty(word.rusTranslation)
          ? word.rusTranslation
          : '';
        word.example = !isEmpty(word.example) ? word.example : '';
        word.exampleTranslation = !isEmpty(word.exampleTranslation)
          ? word.exampleTranslation
          : '';
        word.origin = !isEmpty(word.origin) ? word.origin : '';
        word.sphere = !isEmpty(word.sphere) ? word.sphere : '';
        word.see = !isEmpty(word.see) ? word.see : {};
        word.lexis = !isEmpty(word.lexis) ? word.lexis : {};
        word.grammar = !isEmpty(word.grammar) ? word.grammar : {};
        word.see = !isEmpty(word.see) ? word.see : {};
        word.style = !isEmpty(word.style) ? word.style : {};

        this.setState({
          ugrWordCyr: word.ugrWordCyr,
          rusTranslation: word.rusTranslation,
          example: word.example,
          exampleTranslation: word.exampleTranslation,
          origin: word.origin,
          sphere: word.sphere,
          style: word.style,
          lexis: word.lexis,
          grammar: word.grammar,
          see: word.see,
          partOfSpeech: word.partOfSpeech
        });
      });
    }
  }

  componentDidMount() {
    this.props.getWordByID(this.props.match.params.id);
  }

  onSubmit(e) {
    e.preventDefault();
    const wordData = {
      ugrWordCyr: this.state.ugrWordCyr,
      rusTranslation: this.state.rusTranslation,
      example: this.state.example,
      exampleTranslation: this.state.exampleTranslation,
      origin: this.state.origin,
      sphere: this.state.sphere,
      see: this.state.see,
      lexis: this.state.lexis,
      grammar: this.state.grammar,
      partOfSpeech: this.state.partOfSpeech,
      style: this.state.style
    };
    let id = this.props.match.params.id;
    // Change a function to update
    this.props.updateWord(id, wordData, this.props.history);
  }

  onChange(e) {
    this.setState({ [e.target.name]: e.target.value });
  }

  onCheck(e) {
    this.setState({
      current: !this.state.current
    });
  }
  render() {
    const { errors } = this.state;

    return (

              <Link to="/my-words" className="btn btn-light">
                Go Back
              </Link>

Edit Word

              <form onSubmit={this.onSubmit}>
                <TextFieldGroup
                  placeholder="Бала"
                  info="Введите слово на уйгурском"
                  name="ugrWordCyr"
                  value={this.state.ugrWordCyr}
                  onChange={this.onChange}
                  error={errors.ugrWordCyr}
                />
                <TextFieldGroup
                  placeholder="Ребенок"
                  info="Введите слово на русском"
                  name="rusTranslation"
                  value={this.state.rusTranslation}
                  onChange={this.onChange}
                  error={errors.rusTranslation}
                />

                  <input
                    type="checkbox"
                    className="form-check-input"
                    name="see"
                    value={this.state.see}
                    onChange={this.onCheck}
                    id="see"
                  />
                  Смотри

                <TextFieldGroup
                  placeholder=""
                  info="Введите пример предложения на уйгурском"
                  name="example"
                  value={this.state.example}
                  onChange={this.onChange}
                  error={errors.example}
                />
                <TextFieldGroup
                  placeholder=""
                  info="Введите перевод примерного предложения на русском"
                  name="exampleTranslation"
                  value={this.state.exampleTranslation}
                  onChange={this.onChange}
                  error={errors.exampleTranslation}
                />

Происхождение слова

                <SelectListGroup
                  placeholder="Арабское"
                  name="origin"
                  value={this.state.origin}
                  onChange={this.onChange}
                  error={errors.origin}
                  options={originOptions}
                />

Сфера употребления слова

                <SelectListGroup
                  placeholder="Физика"
                  name="sphere"
                  value={this.state.sphere}
                  onChange={this.onChange}
                  error={errors.sphere}
                  options={sphereOptions}
                />

Лексика слова

                <SelectListGroup
                  placeholder="лексика"
                  name="lexis"
                  value={this.state.lexis}
                  onChange={this.onChange}
                  error={errors.lexis}
                  options={lexisOptions}
                />

Стиль слова

                <SelectListGroup
                  placeholder="стиль"
                  name="style"
                  value={this.state.style}
                  onChange={this.onChange}
                  error={errors.style}
                  options={styleOptions}
                />

Часть речи

                <SelectListGroup
                  placeholder=""
                  name="partOfSpeech"
                  value={this.state.partOfSpeech}
                  onChange={this.onChange}
                  error={errors.partOfSpeech}
                  options={partOfSpeechOptions}
                />

Грамматика слова

                <SelectListGroup
                  placeholder="грамматика"
                  name="grammar"
                  value={this.state.grammar}
                  onChange={this.onChange}
                  error={errors.grammar}
                  options={grammarOptions}
                />
                <input
                  type="submit"
                  value="submit"
                  className="btn btn-info btn-block mt-4"
                />
              </form>

    );
  }
}

EditWord.propTypes = {
  getWordByID: PropTypes.func.isRequired,
  errors: PropTypes.object.isRequired,
  updateWord: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  errors: state.errors,
  words: state.words
});

export default connect(
  mapStateToProps,
  { getWordByID, updateWord }
)(withRouter(EditWord));

Body:
axios
      .put(/api/words/${id}, updatedWord)

if you are using relative api endpoint then it will be going to request to

<react-server-host:port(which is 3000 in your case)>/api/words/${id}

and i am assuming you are running your backend service on another port than 3000 . Thats why it is giving error 404 not found
So when you are requesting api, write absolute endpoint

<backend-server-host:port>/api/words/${id}


问:
Giving priority to prefix match in elasticsearch in php
Is there a way in elasticsearch to give more priority for the prefix match than to the string that contains that word?

For ex.- priorities of words if I search for ram should be like this:

```<code>Ram Reddy
Joy Ram Das
Kiran Ram Goel
Swati Ram Goel
Ramesh Singh
</code>```

I have tried mapping as given in here.
I have done like this:

```<code>$params = [
        "index" => $myIndex,
            "body" => [
            "settings"=> [
            "analysis"=> [
                "analyzer"=> [
                "start_with_analyzer"=> [
                    "tokenizer"=> "my_edge_ngram",
                    "filter"=> [
                    "lowercase"
                    ]
                ]
                ],
                "tokenizer"=> [
                "my_edge_ngram"=> [
                    "type"=> "edge_ngram",
                    "min_gram"=> 3,
                    "max_gram"=> 15
                ]
                ]
            ]
            ],
            "mappings"=> [
            "doc"=> [
                "properties"=> [
                "label"=> [
                    "type"=> "text",
                    "fields"=> [
                    "keyword"=> [
                        "type"=> "keyword"
                    ],
                    "ngramed"=> [
                        "type"=> "text",
                        "analyzer"=> "start_with_analyzer"
                    ]
                    ]
                ]
                ]
            ]
            ]
    ]
    ];
    $response = $client->indices()->create($params);    // create an index
</code>```

and searching like this:

```<code>$body = [
        "size" => 100,

        '_source' => $select,
        "query"=> [
            "bool"=> [
              "should"=> [
                [
                  "query_string"=> [
                    "query"=> "ram*",
                    "fields"=> [
                      "value"
                    ],
                    "boost"=> 5
                  ]
                ],
                [
                  "query_string"=> [
                    "query"=> "ram*",
                    "fields"=> [
                      "value.ngramed"
                    ],
                    "analyzer"=> "start_with_analyzer",
                    "boost"=> 2
                  ]
                ]
              ],
              "minimum_should_match"=> 1
            ]
          ]
    ];

$params = [
    'index' => $myIndex,
    'type' => $myType,
    'body' => []
];
$params['body'] = $body;
$response = $client->search($params);
</code>```

The json of query is as follows:

```<code>    {
  "size": 100,
  "_source": [
    "label",
    "value",
    "type",
    "sr"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "query_string": {
            "query": "ram*",
            "fields": [
              "value"
            ],
            "boost": 5
          }
        },
        {
          "query_string": {
            "query": "ram*",
            "fields": [
              "value.ngramed"
            ],
            "analyzer": "start_with_analyzer",
            "boost": 2
          }
        }
      ],
      "minimum_should_match": 1,
      "must_not": {
        "match_phrase": {
          "type": "propertyValue"
        }
      }
    }
  }
}
</code>```

I am using elasticsearch 5.3.2
Is there any other way to sort the results for the search in the relational database using the search method in php?

答:
You should not enable fielddata unless really required. To overcome this you can use sub field.
Make the following changes to your code:

```<code>                       "label"=>[
                            "type"=>"text",
                            //"fielddata"=> true, ---->remove/comment this line
                            "analyzer"=>"whitespace",
                            "fields"=>[
                                "keyword"=>[
                                    "type"=>"keyword"
                                ]
                            ]
                        ]
</code>```

To sort on type field use type.keyword instead. This change apply to any field of text type and has a sub-field of type keyword available (assuming the name of this field is keyword). So change as below:

```<code>'sort' => [
    ["type.keyword"=>["order"=>"asc"]],
    ["sr"=>["order"=>"asc"]],
    ["propLabels"=>["order"=>"asc"]],
    ["value"=>["order"=>"asc"]]
]
</code>```

Update : Index creation and query to get desired output

Create the index as below:

```<code>{
  "settings": {
    "analysis": {
      "analyzer": {
        "start_with_analyzer": {
          "tokenizer": "my_edge_ngram",
          "filter": [
            "lowercase"
          ]
        }
      },
      "tokenizer": {
        "my_edge_ngram": {
          "type": "edge_ngram",
          "min_gram": 3,
          "max_gram": 15
        }
      }
    }
  },
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword"
            },
            "ngramed": {
              "type": "text"
            }
          }
        }
      }
    }
  }
}
</code>```

Use the query below to get the desired result:

```<code>{
  "query": {
    "bool": {
      "should": [
        {
          "query_string": {
            "query": "Ram",
            "fields": [
              "name"
            ],
            "boost": 5
          }
        },
        {
          "query_string": {
            "query": "Ram",
            "fields": [
              "name.ngramed"
            ],
            "analyzer": "start_with_analyzer",
            "boost": 2
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}
</code>```

In the above the query with boost value 5 increases the score for those documents where Ram is present in name. The other query with boost 2 further increases the score for the documents where name starts with Ram.

Sample O/P:

```<code>"hits": [
  {
    "_index": "test",
    "_type": "_doc",
    "_id": "2",
    "_score": 2.0137746,
    "_source": {
      "name": "Ram Reddy"
    }
  },
  {
    "_index": "test",
    "_type": "_doc",
    "_id": "1",
    "_score": 1.4384104,
    "_source": {
      "name": "Joy Ram Das"
    }
  },
  {
    "_index": "test",
    "_type": "_doc",
    "_id": "3",
    "_score": 0.5753642,
    "_source": {
      "name": "Ramesh Singh"
    }
  }
]
</code>```

Body:
Is there a way in elasticsearch to give more priority for the prefix match than to the string that contains that word?

For ex.- priorities of words if I search for ram should be like this:

Ram Reddy
Joy Ram Das
Kiran Ram Goel
Swati Ram Goel
Ramesh Singh

I have tried mapping as given in here.
I have done like this:

$params = [
        "index" => $myIndex,
            "body" => [
            "settings"=> [
            "analysis"=> [
                "analyzer"=> [
                "start_with_analyzer"=> [
                    "tokenizer"=> "my_edge_ngram",
                    "filter"=> [
                    "lowercase"
                    ]
                ]
                ],
                "tokenizer"=> [
                "my_edge_ngram"=> [
                    "type"=> "edge_ngram",
                    "min_gram"=> 3,
                    "max_gram"=> 15
                ]
                ]
            ]
            ],
            "mappings"=> [
            "doc"=> [
                "properties"=> [
                "label"=> [
                    "type"=> "text",
                    "fields"=> [
                    "keyword"=> [
                        "type"=> "keyword"
                    ],
                    "ngramed"=> [
                        "type"=> "text",
                        "analyzer"=> "start_with_analyzer"
                    ]
                    ]
                ]
                ]
            ]
            ]
    ]
    ];
    $response = $client->indices()->create($params);    // create an index

and searching like this:

$body = [
        "size" => 100,

        '_source' => $select,
        "query"=> [
            "bool"=> [
              "should"=> [
                [
                  "query_string"=> [
                    "query"=> "ram*",
                    "fields"=> [
                      "value"
                    ],
                    "boost"=> 5
                  ]
                ],
                [
                  "query_string"=> [
                    "query"=> "ram*",
                    "fields"=> [
                      "value.ngramed"
                    ],
                    "analyzer"=> "start_with_analyzer",
                    "boost"=> 2
                  ]
                ]
              ],
              "minimum_should_match"=> 1
            ]
          ]
    ];

$params = [
    'index' => $myIndex,
    'type' => $myType,
    'body' => []
];
$params['body'] = $body;
$response = $client->search($params);

The json of query is as follows:

    {
  "size": 100,
  "_source": [
    "label",
    "value",
    "type",
    "sr"
  ],
  "query": {
    "bool": {
      "should": [
        {
          "query_string": {
            "query": "ram*",
            "fields": [
              "value"
            ],
            "boost": 5
          }
        },
        {
          "query_string": {
            "query": "ram*",
            "fields": [
              "value.ngramed"
            ],
            "analyzer": "start_with_analyzer",
            "boost": 2
          }
        }
      ],
      "minimum_should_match": 1,
      "must_not": {
        "match_phrase": {
          "type": "propertyValue"
        }
      }
    }
  }
}

I am using elasticsearch 5.3.2
Is there any other way to sort the results for the search in the relational database using the search method in php?

Body:
You should not enable fielddata unless really required. To overcome this you can use sub field.
Make the following changes to your code:

                       "label"=>[
                            "type"=>"text",
                            //"fielddata"=> true, ---->remove/comment this line
                            "analyzer"=>"whitespace",
                            "fields"=>[
                                "keyword"=>[
                                    "type"=>"keyword"
                                ]
                            ]
                        ]

To sort on type field use type.keyword instead. This change apply to any field of text type and has a sub-field of type keyword available (assuming the name of this field is keyword). So change as below:

'sort' => [
    ["type.keyword"=>["order"=>"asc"]],
    ["sr"=>["order"=>"asc"]],
    ["propLabels"=>["order"=>"asc"]],
    ["value"=>["order"=>"asc"]]
]

Update : Index creation and query to get desired output

Create the index as below:

{
  "settings": {
    "analysis": {
      "analyzer": {
        "start_with_analyzer": {
          "tokenizer": "my_edge_ngram",
          "filter": [
            "lowercase"
          ]
        }
      },
      "tokenizer": {
        "my_edge_ngram": {
          "type": "edge_ngram",
          "min_gram": 3,
          "max_gram": 15
        }
      }
    }
  },
  "mappings": {
    "_doc": {
      "properties": {
        "name": {
          "type": "text",
          "fields": {
            "keyword": {
              "type": "keyword"
            },
            "ngramed": {
              "type": "text"
            }
          }
        }
      }
    }
  }
}

Use the query below to get the desired result:

{
  "query": {
    "bool": {
      "should": [
        {
          "query_string": {
            "query": "Ram",
            "fields": [
              "name"
            ],
            "boost": 5
          }
        },
        {
          "query_string": {
            "query": "Ram",
            "fields": [
              "name.ngramed"
            ],
            "analyzer": "start_with_analyzer",
            "boost": 2
          }
        }
      ],
      "minimum_should_match": 1
    }
  }
}

In the above the query with boost value 5 increases the score for those documents where Ram is present in name. The other query with boost 2 further increases the score for the documents where name starts with Ram.

Sample O/P:

"hits": [
  {
    "_index": "test",
    "_type": "_doc",
    "_id": "2",
    "_score": 2.0137746,
    "_source": {
      "name": "Ram Reddy"
    }
  },
  {
    "_index": "test",
    "_type": "_doc",
    "_id": "1",
    "_score": 1.4384104,
    "_source": {
      "name": "Joy Ram Das"
    }
  },
  {
    "_index": "test",
    "_type": "_doc",
    "_id": "3",
    "_score": 0.5753642,
    "_source": {
      "name": "Ramesh Singh"
    }
  }
]


问:
Why isn't textarea an input[type="textarea"]?
Why is there an element <textarea> instead of <input type="textarea">?

答:
So that its value can easily contain quotes and <> characters and respect whitespace and newlines.

The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.

```<code><!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Yes I can</title>
</head>
<body>
    <textarea name="test">
        I can put < and > and & signs in
        my textarea without any problems.
    </textarea>
</body>
</html>
</code>```

Body:
So that its value can easily contain quotes and <> characters and respect whitespace and newlines.

The following HTML code successfully pass the w3c validator and displays <,> and & without the need to encode them. It also respects the white spaces.

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>Yes I can</title>
</head>
<body>
    <textarea name="test">
        I can put < and > and & signs in
        my textarea without any problems.
    </textarea>
</body>
</html>


问:
check if process is UWP from python
I'd like to monitor processes which are UWP apps.
currently I'm checking it from C++ using the following code :

```<code>LONG PkgId = GetCurrentPackageId(&sz, buf);
return (PkgId != APPMODEL_ERROR_NO_PACKAGE);
</code>```

Is there any way to automatically check this attribution from python or shell command-line ?

答: After some research, it turns out that I can use this API from C# code running on top of Powershell script. </p>

Title: check if process is UWP from python

Body:
I'd like to monitor processes which are UWP apps.
currently I'm checking it from C++ using the following code :

LONG PkgId = GetCurrentPackageId(&sz, buf);
return (PkgId != APPMODEL_ERROR_NO_PACKAGE);

Is there any way to automatically check this attribution from python or shell command-line ?


问:
How to expire a particular row when a date is reached?
I have a table for students, where each student has to get an ID card and this ID card is valid for one year

I want the student record to be expired when it reaches to the expiration date and the expiration date also needs to be updated

For example, if the expiration date is 01/01/2020 it should be turned to 01/01/2021.

答:
```<code>update tablestudent set expired=yes where expirationdate < getdate()
</code>```

you need to schedule this as job that runs daily.

Body:
update tablestudent set expired=yes where expirationdate < getdate()

you need to schedule this as job that runs daily.


问:
How to find specific link in a page via Similar string in bs4 python
Is there any way for found link that contains this example string Top 100 Club Tracks Vol.1 2019.rar

but maybe the link contains this type of string

Top_100_Club_Tracks_Vol.1_2019.rar (uppercase and _)

top 100 club tracks vol.1 2019.rar (lowercase and white space)

top.100.club.tracks.vol1.2019.rar ( lowercase and dote)

i just try this code and it cant just find links contains specific string :

```<code>mystr = Top 100 Club Tracks Vol.1 2019.rar

 links = soup_music.find('a', text=Title).findNext("div",{"class":"postContent"}).findAll('a', attrs={'href':re.compile(mystr)})
</code>```

答:
Assuming it is in an a tag you can use * contains operator and pass a list of Or strings to select

```<code>soup.select('[href*="Top 100 Club Tracks Vol.1 2019.rar"],[href*="top 100 club tracks vol.1 2019.rar"]')
</code>```

keep adding comma separated variations to select as shown above.

Body:
Is there any way for found link that contains this example string Top 100 Club Tracks Vol.1 2019.rar

but maybe the link contains this type of string

Top_100_Club_Tracks_Vol.1_2019.rar (uppercase and _)

top 100 club tracks vol.1 2019.rar (lowercase and white space)

top.100.club.tracks.vol1.2019.rar ( lowercase and dote)

i just try this code and it cant just find links contains specific string :

mystr = Top 100 Club Tracks Vol.1 2019.rar

 links = soup_music.find('a', text=Title).findNext("div",{"class":"postContent"}).findAll('a', attrs={'href':re.compile(mystr)})

Body:
Assuming it is in an a tag you can use * contains operator and pass a list of Or strings to select

soup.select('[href*="Top 100 Club Tracks Vol.1 2019.rar"],[href*="top 100 club tracks vol.1 2019.rar"]')

keep adding comma separated variations to select as shown above.


问:
Group BY Statement error to get unique records
I am new to SQL Server, used to work with MYSQL and trying to get the records from a table using Group By.

The table structure is given below:

```<code>SELECT S1.ID,S1.Template_ID,S1.Assigned_By,S1.Assignees,S1.Active FROM "Schedule" AS S1;
</code>```

Output:

```<code>ID Template_ID  Assigned_By Assignees Active
2   25          1           3         1
3   25          5           6         1
6   26          5           6         1
</code>```

I need to get the values of all columns using the Group By statement below

```<code>SELECT Template_ID FROM "Schedule" WHERE "Assignees" IN(6, 3) GROUP BY "Template_ID";
</code>```

Output:

```<code>Template_ID

25
26
</code>```

I tried the following code to fetch the table using Group By, but it's fetching all the rows.

```<code>SELECT S1.ID,S1.Template_ID,S1.Assigned_By,S1.Assignees,S1.Active FROM "Schedule" AS S1 INNER JOIN(SELECT Template_ID FROM "Schedule" WHERE "Assignees" IN(6, 3) GROUP BY "Template_ID") AS S2 ON S2.Template_ID=S1.Template_ID
</code>```

My Output Should be like,

```<code>   ID Template_ID  Assigned_By Assignees Active
    2   25          1           3         1
    6   26          5           6         1
</code>```

I was wondering whether I can get ID of the column as well? I use the ID for editing the records in the web.

答:
The query doesn't work as expected in MySQL either, except by accident.

Nonaggregated columns in MySQL aren't part of the SQL standard and not even allowed in MySQL 5.7 and later unless the default value of the ONLY_FULL_GROUP_BY mode is changed.

In earlier versions the result is non-deterministic.

The server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause.

This means there's was no way to know what rows will be returned this query :

```<code>SELECT S1.ID,S1.Template_ID,S1.Assigned_By,S1.Assignees,S1.Active
FROM "Schedule" AS S1
GROUP BY Template_ID;
</code>```

To get deterministic results you'd need a way to rank rows with the ranking functions introduced in MySQL 8, like ROW_NUMBER(). These are already available in SQL Server since SQL Server 2012 at least. The syntax is the same for both databases :

```<code>WITH ranked as AS
(
    SELECT
        ID,Template_ID,Assigned_By,Assignees Active,
        ROW_NUMBER(PARTITION BY Template_ID Order BY ID)
    FROM Scheduled
    WHERE Assignees IN(6, 3)
)
SELECT ID,Template_ID,Assigned_By,Assignees Active
FROM ranked
Where RN=1
</code>```

PARTITION BY Template_ID splits the result rows based on their Template_ID value into separate partitions. Within that partition, the rows are ordered based on the ORDER BY clause. Finally, ROW_NUMBER calculates a row number for each ordered partition row.

Body:
I am new to SQL Server, used to work with MYSQL and trying to get the records from a table using Group By.

The table structure is given below:

SELECT S1.ID,S1.Template_ID,S1.Assigned_By,S1.Assignees,S1.Active FROM "Schedule" AS S1;

Output:

ID Template_ID  Assigned_By Assignees Active
2   25          1           3         1
3   25          5           6         1
6   26          5           6         1

I need to get the values of all columns using the Group By statement below

SELECT Template_ID FROM "Schedule" WHERE "Assignees" IN(6, 3) GROUP BY "Template_ID";

Output:

Template_ID

25
26

I tried the following code to fetch the table using Group By, but it's fetching all the rows.

SELECT S1.ID,S1.Template_ID,S1.Assigned_By,S1.Assignees,S1.Active FROM "Schedule" AS S1 INNER JOIN(SELECT Template_ID FROM "Schedule" WHERE "Assignees" IN(6, 3) GROUP BY "Template_ID") AS S2 ON S2.Template_ID=S1.Template_ID

My Output Should be like,

   ID Template_ID  Assigned_By Assignees Active
    2   25          1           3         1
    6   26          5           6         1

I was wondering whether I can get ID of the column as well? I use the ID for editing the records in the web.

Body:
The query doesn't work as expected in MySQL either, except by accident.

Nonaggregated columns in MySQL aren't part of the SQL standard and not even allowed in MySQL 5.7 and later unless the default value of the ONLY_FULL_GROUP_BY mode is changed.

In earlier versions the result is non-deterministic.

The server is free to choose any value from each group, so unless they are the same, the values chosen are nondeterministic. Furthermore, the selection of values from each group cannot be influenced by adding an ORDER BY clause.

This means there's was no way to know what rows will be returned this query :

SELECT S1.ID,S1.Template_ID,S1.Assigned_By,S1.Assignees,S1.Active
FROM "Schedule" AS S1
GROUP BY Template_ID;

To get deterministic results you'd need a way to rank rows with the ranking functions introduced in MySQL 8, like ROW_NUMBER(). These are already available in SQL Server since SQL Server 2012 at least. The syntax is the same for both databases :

WITH ranked as AS
(
    SELECT
        ID,Template_ID,Assigned_By,Assignees Active,
        ROW_NUMBER(PARTITION BY Template_ID Order BY ID)
    FROM Scheduled
    WHERE Assignees IN(6, 3)
)
SELECT ID,Template_ID,Assigned_By,Assignees Active
FROM ranked
Where RN=1

PARTITION BY Template_ID splits the result rows based on their Template_ID value into separate partitions. Within that partition, the rows are ordered based on the ORDER BY clause. Finally, ROW_NUMBER calculates a row number for each ordered partition row.


问:
Datatable refreshes to first page
I have been doing a particular operation on a datatable. While completing a Ajax is being called, on the success of which fnDraw() is being called and it refreshes the datatable going directly to the starting page of the Datatable. It makes a bad user experience as the user has to again go to the particular page where he/she has performed the operation. I have tried various ways but it seems the only way may be to alter the default datatables.js.

Please help on how to solve the issue.

答:
Use this, it worked for me.</p>

```<code>var table = $("#dataTable").DataTable({
  stateSave : true,
  ...
});
</code>```

Title: Datatable refreshes to first page

Body:
Use this, it worked for me.

var table = $("#dataTable").DataTable({
  stateSave : true,
  ...
});


问:
How to retrieve field from custom master object?
I am trying to write a custom object and have to retrieve one custom related field from custom object Course Master(master) to detail object Training deals. This code is showing error</p>

```<code> List<List<String>> strList = new List<List<String>>();
    List<Training_deal__c> td = [select name,   Course_master__r.course__c from Training_deal__c];

    for(Training_deal__c t : td){
        List<String> tempList = new List<String>();
        tempList.add('Training Deals');
        tempList.add(t.name);
        tempList.add(t.course__c);
        strList.add(tempList);
    }
</code>```

答:
Try This</p>

```<code>tempList.add(t.Course_master__r.course__c);
</code>```

Body:
I am trying to write a custom object and have to retrieve one custom related field from custom object Course Master(master) to detail object Training deals. This code is showing error

 List<List<String>> strList = new List<List<String>>();
    List<Training_deal__c> td = [select name,   Course_master__r.course__c from Training_deal__c];

    for(Training_deal__c t : td){
        List<String> tempList = new List<String>();
        tempList.add('Training Deals');
        tempList.add(t.name);
        tempList.add(t.course__c);
        strList.add(tempList);
    }

Body:
Try This

tempList.add(t.Course_master__r.course__c);


问:
RSA encrypt with PKCS1-V1_5 (JavaScript)
I would like to encrypt my password using Public Key in RSA format with PKCS1-1.5 padding. Currently I try to use forge library from https://github.com/digitalbazaar/forge. Part of the solution uses Tom Wu's BigInteger().

```<code>modulus = new forge.jsbn.BigInteger(modulus,16);
exponent =  new forge.jsbn.BigInteger(exponent, 16);
var text = "Password";
var rsa = forge.pki.rsa;
var publicKey = rsa.setPublicKey(modulus, exponent);
var encryptedData = publicKey.encrypt(text, 'RSAES-PKCS1-V1_5');
</code>```

provided exponent - 10001 seems to be parsed properly in BigInteger() as it returns single item array - 65537.

However when I push modulus 9bedc7ad20bdacf930f1471d0c2a9f7f1895e24d73957b145b621e7800589ec14a3122df556fae94cc45df7b1f5003062df5681a18d8165377a6dece1a8c36e0af6ce13e89890b6813eb94135bd8c4b2b743ef6d24cfc09cbd59a8105c3f31d56a0224b1db14c2e6396493571ef83d664c5b6169a1b42f988cfc3f7d39d50aa9

I get something strange as BigInteger() results:
modulus screenshot

Therefore RSA keypair created later in the code is wrong. Could anyone point me to the right direction? What is even more frustrating is that I have working .py script and cannot convert it to JS.. I cannot use any server side programming here.
(I am aware of the issues / risks with JS password encryption btw).

Update

Here's the working python Script:

```<code>import binascii
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
def assymmetric_encrypt(val, public_key):

     modulusDecoded = long(public_key["n"], 16)
     exponentDecoded = long(public_key["e"], 16)
     keyPub = RSA.construct((modulusDecoded, exponentDecoded))
     print(keyPub)
     # Generate a cypher using the PKCS1.5 standard
     cipher = PKCS1_v1_5.new(keyPub)
     return cipher.encrypt(val)

# Encrypt the password used to login
encryptedPassword = assymmetric_encrypt(password_input,public_key)
</code>```

It looks that JS should be doing the same but when providing the same modulus exponent in both scripts, the encrypted password is different (looks similar but is not equal)

Update:
Funny thing is that if I run JS script with hardcoded n, e and password I get the same encrypted data every time. When I do the same with Python script I alway get different result.. So there might be something more in the Crypto library..

Update 2:
problem was located in completely different place. Thanks to Maarten Bodewes comment, it turned out that padding library was broken (didn't generate new string each time). I changed forger lib to JSencrypt for this part and it works great. Going through pem file but this will be probably altered in the future for better performance:

```<code>var encrypt = new JSEncrypt();
encrypt.setPublicKey(pem);
var encrypted_jeencrypt= encrypt.encrypt(password);
var encrypted_jeencrypt_hex = base64toHEX(encrypted_jeencrypt);
</code>```

答:
I needed to convert python encryption method for javascript.

```<code>import base64
import binascii
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

def get_hex_rsa_encrypted_data(mod, exp, id, pw):
    mod = int(mod, 16)
    exp = int(exp, 16)

    rsa_key = RSA.construct((mod, exp))
    rsa = PKCS1_v1_5.new(rsa_key)

    raw_encrypted_user_id = rsa.encrypt(str.encode(id))
    raw_encrypted_password = rsa.encrypt(str.encode(pw))

    hex_encrypted_user_id = binascii.hexlify(raw_encrypted_user_id).decode()
    hex_encrypted_password = binascii.hexlify(raw_encrypted_password).decode()

    # print(hex_encrypted_user_id)
    # print(hex_encrypted_password)

    return {'enc_user_id': hex_encrypted_user_id, 'enc_user_pw': hex_encrypted_password}
</code>```

My Question for this one

your question helped me a lot, hope mine helps yours too. :)

Body:
I would like to encrypt my password using Public Key in RSA format with PKCS1-1.5 padding. Currently I try to use forge library from https://github.com/digitalbazaar/forge. Part of the solution uses Tom Wu's BigInteger().

modulus = new forge.jsbn.BigInteger(modulus,16);
exponent =  new forge.jsbn.BigInteger(exponent, 16);
var text = "Password";
var rsa = forge.pki.rsa;
var publicKey = rsa.setPublicKey(modulus, exponent);
var encryptedData = publicKey.encrypt(text, 'RSAES-PKCS1-V1_5');

provided exponent - 10001 seems to be parsed properly in BigInteger() as it returns single item array - 65537.

However when I push modulus 9bedc7ad20bdacf930f1471d0c2a9f7f1895e24d73957b145b621e7800589ec14a3122df556fae94cc45df7b1f5003062df5681a18d8165377a6dece1a8c36e0af6ce13e89890b6813eb94135bd8c4b2b743ef6d24cfc09cbd59a8105c3f31d56a0224b1db14c2e6396493571ef83d664c5b6169a1b42f988cfc3f7d39d50aa9

I get something strange as BigInteger() results:
modulus screenshot

Therefore RSA keypair created later in the code is wrong. Could anyone point me to the right direction? What is even more frustrating is that I have working .py script and cannot convert it to JS.. I cannot use any server side programming here.
(I am aware of the issues / risks with JS password encryption btw).

Update

Here's the working python Script:

import binascii
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
def assymmetric_encrypt(val, public_key):

     modulusDecoded = long(public_key["n"], 16)
     exponentDecoded = long(public_key["e"], 16)
     keyPub = RSA.construct((modulusDecoded, exponentDecoded))
     print(keyPub)
     # Generate a cypher using the PKCS1.5 standard
     cipher = PKCS1_v1_5.new(keyPub)
     return cipher.encrypt(val)

# Encrypt the password used to login
encryptedPassword = assymmetric_encrypt(password_input,public_key)

It looks that JS should be doing the same but when providing the same modulus exponent in both scripts, the encrypted password is different (looks similar but is not equal)

Update:
Funny thing is that if I run JS script with hardcoded n, e and password I get the same encrypted data every time. When I do the same with Python script I alway get different result.. So there might be something more in the Crypto library..

Update 2:
problem was located in completely different place. Thanks to Maarten Bodewes comment, it turned out that padding library was broken (didn't generate new string each time). I changed forger lib to JSencrypt for this part and it works great. Going through pem file but this will be probably altered in the future for better performance:

var encrypt = new JSEncrypt();
encrypt.setPublicKey(pem);
var encrypted_jeencrypt= encrypt.encrypt(password);
var encrypted_jeencrypt_hex = base64toHEX(encrypted_jeencrypt);

Body:
I needed to convert python encryption method for javascript.

import base64
import binascii
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5

def get_hex_rsa_encrypted_data(mod, exp, id, pw):
    mod = int(mod, 16)
    exp = int(exp, 16)

    rsa_key = RSA.construct((mod, exp))
    rsa = PKCS1_v1_5.new(rsa_key)

    raw_encrypted_user_id = rsa.encrypt(str.encode(id))
    raw_encrypted_password = rsa.encrypt(str.encode(pw))

    hex_encrypted_user_id = binascii.hexlify(raw_encrypted_user_id).decode()
    hex_encrypted_password = binascii.hexlify(raw_encrypted_password).decode()

    # print(hex_encrypted_user_id)
    # print(hex_encrypted_password)

    return {'enc_user_id': hex_encrypted_user_id, 'enc_user_pw': hex_encrypted_password}

My Question for this one

your question helped me a lot, hope mine helps yours too. :)


问:
Hide nested properties in loopback model
I am creating a loopback model (model1) which refers to another model and want to hide some properties of the nested model (model2). Also, I just want them to be hidden in this model1. How can I solve this issue ?

I have tried the property hidden, which works fine with the current model1 properties but not with the nested model2 properties.

```<code>{
  "name": "Model1",
  "base": "PersistedModel",
  "idInjection": true,
 ...
  "properties": {
    "pet": {
      "type": "Model2",
    }
 ...
}

{
  "name": "Model2",
 ...
  "properties": {
    "name": {
      "type": "string",
    }
 ...
}
</code>```

I want here to hide the property "name" from Model2 in the Model1 explorer

Thanks !

答:
Did you check include-with-filter documentation. I hope this should solve your problem or else share some more descriptive code that you have tried so far.

Here's another example that uses the predefined model relations to include selective fields from the related models.

```<code>{"include": [
  {"relation":"relationName",
   "scope":{"fields": ["Field1","Field2"]}
  },
  {"relation":"relation2Name",
   "scope":{"fields": ["Field3","Field4"]}
  },
]}
</code>```

Note: you won't be able to hide Ids

Body:
I am creating a loopback model (model1) which refers to another model and want to hide some properties of the nested model (model2). Also, I just want them to be hidden in this model1. How can I solve this issue ?

I have tried the property hidden, which works fine with the current model1 properties but not with the nested model2 properties.

{
  "name": "Model1",
  "base": "PersistedModel",
  "idInjection": true,
 ...
  "properties": {
    "pet": {
      "type": "Model2",
    }
 ...
}

{
  "name": "Model2",
 ...
  "properties": {
    "name": {
      "type": "string",
    }
 ...
}

I want here to hide the property "name" from Model2 in the Model1 explorer

Thanks !

Body:
Did you check include-with-filter documentation. I hope this should solve your problem or else share some more descriptive code that you have tried so far.

Here's another example that uses the predefined model relations to include selective fields from the related models.

{"include": [
  {"relation":"relationName",
   "scope":{"fields": ["Field1","Field2"]}
  },
  {"relation":"relation2Name",
   "scope":{"fields": ["Field3","Field4"]}
  },
]}

Note: you won't be able to hide Ids


问:
RecyclerView's heighet set on wrap content, yet in studio it is as tall as two screens
It works just fine when I run the app, but when working in studio the height of the recycler view is as tall as 1.5-2 screens which really slows down the work flow because I need to either scroll a lot or set it to match constraint and just change it back to wrap content before everytime I run the app. Has anyone experienced this before? First time for me.

This is my recycler, can't see anything here that should make this happen:

```<code><androidx.recyclerview.widget.RecyclerView
android:id="@+id/itinerary_sample_photos_recycler"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@+id/itinerary_youtube_player_card"
app:layout_constraintEnd_toEndOf="@+id/itinerary_youtube_player_card"
app:layout_constraintStart_toStartOf="@+id/itinerary_youtube_player_card"/>
</code>```

And this is how it looks. Notice, the area at the bottom where it says "buy 6.99" is a floating container fixed at the bottom of the screen. The recycler view stretches inside the scroll layout. It is selected so you can see the outline.

答:
When you are using Constraint layout then it is worth using MATCH_CONSTRAINT that means 0dp for both width and height.</p>

```<code>android:layout_width="0dp"
android:layout_height="0dp"
</code>```

Body:
It works just fine when I run the app, but when working in studio the height of the recycler view is as tall as 1.5-2 screens which really slows down the work flow because I need to either scroll a lot or set it to match constraint and just change it back to wrap content before everytime I run the app. Has anyone experienced this before? First time for me.

This is my recycler, can't see anything here that should make this happen:

<androidx.recyclerview.widget.RecyclerView
android:id="@+id/itinerary_sample_photos_recycler"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
app:layout_constraintTop_toBottomOf="@+id/itinerary_youtube_player_card"
app:layout_constraintEnd_toEndOf="@+id/itinerary_youtube_player_card"
app:layout_constraintStart_toStartOf="@+id/itinerary_youtube_player_card"/>

And this is how it looks. Notice, the area at the bottom where it says "buy 6.99" is a floating container fixed at the bottom of the screen. The recycler view stretches inside the scroll layout. It is selected so you can see the outline.

Body:
When you are using Constraint layout then it is worth using MATCH_CONSTRAINT that means 0dp for both width and height.

android:layout_width="0dp"
android:layout_height="0dp"


问:
How do I move an issue on github to another repo?
It happens every now and then. Some library depends on another and a user opens an issue that belongs to the wrong repo. Can I move the issue to the other repo?

You could argue that the issue could be seen as being both repos' issue because one depends on the other and as long as one doesn't work properly both don't. But I'd rather talk about solutions to the issue in the repo it belongs in.

答:
This is now (May 2019) easier.

See "Improvements to issue transfer permissions "

Users with write access to two repositories can now use issue transfer to move issues between them.

  Previously, only users with admin permissions on both repositories had the ability to transfer issues.

In addition, we will no longer allow issues to be transferred from private to public repositories.

See more at "Transferring an issue to another repository".


问:
How to test a java class using FitNesse
I have been trying to test my java class using FitNesse tool, but I get some errors:

This is my Addition.java

```<code>public class Addition{
    private double firstnum, secondnum;

    public void setFirstnum(double firstnum){
         this.firstnum = firstnum;
    }

    public void setSecondnum(double secondnum){
            this.secondnum = secondnum;
    }

    public double result(){
        return firstnum + secondnum;
    }
}
</code>```

And I have compiled this program and made its class.

And this is how my FitNesse table looks like

```<code>!***< Hidden

!define TEST_SYSTEM {slim}
!path C:\Users\Jananath Banuka\Desktop\FitNesse\classes

|eg.Addition|
|firstnum |secondnum  |result?  |
|10       |2          |12       |
|12.6     |3          |15.6     |

</code>```

But I get this error, which I don't know. Below is my error

Can someone please tell me what is wrong?

答:
Assuming your compilation did generate C:\Users\Jananath Banuka\Desktop\FitNesse\classes\eg\Addition.class I believe the problem might be with the space in your username.

Can you try copying your code to another directory without spaces in its path, update the wiki accordingly and try again?
(E.g. move the compile output to C:\temp\FitNesse\classes\eg\Addition.class, and change the !path to !path C:\temp\FitNesse\classes)

Title: How to test a java class using FitNesse

Body:
I have been trying to test my java class using FitNesse tool, but I get some errors:

This is my Addition.java

public class Addition{
    private double firstnum, secondnum;

    public void setFirstnum(double firstnum){
         this.firstnum = firstnum;
    }

    public void setSecondnum(double secondnum){
            this.secondnum = secondnum;
    }

    public double result(){
        return firstnum + secondnum;
    }
}

And I have compiled this program and made its class.

And this is how my FitNesse table looks like

!***< Hidden

!define TEST_SYSTEM {slim}
!path C:\Users\Jananath Banuka\Desktop\FitNesse\classes

|eg.Addition|
|firstnum |secondnum  |result?  |
|10       |2          |12       |
|12.6     |3          |15.6     |

But I get this error, which I don't know. Below is my error

Can someone please tell me what is wrong?


问:
Overlay transparent scrollbar over content
I have a transparent scrollbar, and want to overlay it on the content, instead of pushing the content over to the left.

答:
If you use this:

body {
    overflow: overlay;
}
```

<p>The scrollbar will then also take transparent backgrounds across the page.
This will also put the scrollbar inside the page instead of removing some of the width to put in the scrollbar.</p>

<p>Here is a demo code. I wasn't able to put it inside any of the codepen or jsfiddle, apperantly it took me a while until I figured out, but they don't show the transparency, and I don't know why.</p>

<p>But putting this in a html file should go fine.</p>

<pre class="lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<style>
html, body {
  margin: 0;
  padding: 0;
}

body {
  overflow: overlay;
}

.div1 {
  background: grey;
  margin-top: 200px;
  margin-bottom: 20px;
  height: 20px;
}

::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-thumb {
  background: rgba(90, 90, 90);
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.2);
}
</style>

<body>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

</body>
</html>
</code>```

You can also apply that on other elements, such as any scrolling box. While using inspector mode, it could be that you have to put the overflow to hidden and then back to anything else. It probably needed to refresh. After that it should be possible working on scrollbar without having to refresh it again. Just note that was for the inspector mode.

&nsbp;

Just note this won't work in internet explorer. But the internet explorer has it's own stuff.

```<code>
 <STYLE>
 <!--
 HTML,BODY
 { color:black;
   background-color:#a0a0a0;
   scrollbar-face-color:#903030;
   scrollbar-arrow-color:#FFFFFF;
   scrollbar-track-color:#C0B0B0;
   scrollbar-shadow-color:rgb(0,0,0);
   scrollbar-highlight-color:rgb(0,0,0);
   scrollbar-3dlight-color:#808080;
   scrollbar-darkshadow-Color:#202020;
 }
 -->
 </STYLE>
</code>```

more information about the IE scrollbar can be found here.

Body:
If you use this:

body {
    overflow: overlay;
}

The scrollbar will then also take transparent backgrounds across the page.
This will also put the scrollbar inside the page instead of removing some of the width to put in the scrollbar.

Here is a demo code. I wasn't able to put it inside any of the codepen or jsfiddle, apperantly it took me a while until I figured out, but they don't show the transparency, and I don't know why.

But putting this in a html file should go fine.

<!DOCTYPE html>
<html>
<style>
html, body {
  margin: 0;
  padding: 0;
}

body {
  overflow: overlay;
}

.div1 {
  background: grey;
  margin-top: 200px;
  margin-bottom: 20px;
  height: 20px;
}

::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}

::-webkit-scrollbar-thumb {
  background: rgba(90, 90, 90);
}

::-webkit-scrollbar-track {
  background: rgba(0, 0, 0, 0.2);
}
</style>

<body>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

<div class="div1"></div>

</body>
</html>

You can also apply that on other elements, such as any scrolling box. While using inspector mode, it could be that you have to put the overflow to hidden and then back to anything else. It probably needed to refresh. After that it should be possible working on scrollbar without having to refresh it again. Just note that was for the inspector mode.

&nsbp;

Just note this won't work in internet explorer. But the internet explorer has it's own stuff.

 <STYLE>
 <!--
 HTML,BODY
 { color:black;
   background-color:#a0a0a0;
   scrollbar-face-color:#903030;
   scrollbar-arrow-color:#FFFFFF;
   scrollbar-track-color:#C0B0B0;
   scrollbar-shadow-color:rgb(0,0,0);
   scrollbar-highlight-color:rgb(0,0,0);
   scrollbar-3dlight-color:#808080;
   scrollbar-darkshadow-Color:#202020;
 }
 -->
 </STYLE>

more information about the IE scrollbar can be found here.


问:
Strange difference between Integer variable and Array variable
```<code>a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]
</code>```

but Array

```<code>def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value
</code>```

Could Anybody tell me why it is?

答:
This is because calling the << method will edit the value at the reference to the array.

If you didn't want this to happen, you could do:

```<code>def bla x
  x + [1]
end
</code>```

This works by concatenating the array, x with the array [1], returning a new array from this operation.

or:

```<code>ruby-1.9.2-p136 :007 > bla a.dup
 => [1, 1]
ruby-1.9.2-p136 :008 > a
 => [1]
</code>```

This will use Object#dup, which will do a shallow copy.

If you wanted a deep copy, you can use Object#clone.

Body:
a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]

but Array

def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value

Could Anybody tell me why it is?

Body:
This is because calling the << method will edit the value at the reference to the array.

If you didn't want this to happen, you could do:

def bla x
  x + [1]
end

This works by concatenating the array, x with the array [1], returning a new array from this operation.

or:

ruby-1.9.2-p136 :007 > bla a.dup
 => [1, 1]
ruby-1.9.2-p136 :008 > a
 => [1]

This will use Object#dup, which will do a shallow copy.

If you wanted a deep copy, you can use Object#clone.


问:
Stop navigation WKWebview
This is my situation:

I have a view controller within a WKWebView. This webview starts with a page "A". In this page there are some links (href) and I want that for some of these links must open in the external browser.

For this reason I set the WKWebView delegate:

```<code>func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        if let url = webView.url?.absoluteString
        {

                if(self.isExternalURL(url))
                {
                    let urlT = URL(string: url)!
                    decisionHandler(.cancel)
                    UIApplication.shared.open(urlT, options: [:], completionHandler: nil)
                }
                else
                {
                    decisionHandler(.allow)
                }
         }
         else
         {
                decisionHandler(.allow)
         }
}

private func isExternalURL(url:String) -> Bool
{
    //......check link
}
</code>```

My problem is that if I select an external link the external browser opens, but the webview does not remain on page A, but it also loads the external link while I would like it to remain on page A.

I dont know why

答:
You can try to use  webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)

```<code>func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {

        if let url = navigationAction.request.url?.absoluteString
        {
            if self.isExternalURL(url)
            {
               webView.stopLoading()
                UIApplication.shared.open(navigationAction.request.url, options: [:], completionHandler: nil)
            }

        }

    }
</code>```

Title: Stop navigation WKWebview

Body:
This is my situation:

I have a view controller within a WKWebView. This webview starts with a page "A". In this page there are some links (href) and I want that for some of these links must open in the external browser.

For this reason I set the WKWebView delegate:

func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {

        if let url = webView.url?.absoluteString
        {

                if(self.isExternalURL(url))
                {
                    let urlT = URL(string: url)!
                    decisionHandler(.cancel)
                    UIApplication.shared.open(urlT, options: [:], completionHandler: nil)
                }
                else
                {
                    decisionHandler(.allow)
                }
         }
         else
         {
                decisionHandler(.allow)
         }
}

private func isExternalURL(url:String) -> Bool
{
    //......check link
}

My problem is that if I select an external link the external browser opens, but the webview does not remain on page A, but it also loads the external link while I would like it to remain on page A.

I dont know why

Body:
You can try to use  webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!)

func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {

        if let url = navigationAction.request.url?.absoluteString
        {
            if self.isExternalURL(url)
            {
               webView.stopLoading()
                UIApplication.shared.open(navigationAction.request.url, options: [:], completionHandler: nil)
            }

        }

    }


问:
Is there a way to add ports to tomcat at runtime?
I'm trying to add a port to tomcat at runtime. Is there a way to do this? Or is there a way to listen on all ports? I'm using spring and I want the user to be able to add call an API endpoint to add a new port to listen on.

I know that you can add additional ports in the config file, but I don't know what ports I will need to add.

```<code>@RequestMapping("/port/{port}")
void setPort(@PathVariable("port") int port){
    //add new tomcat port to listen on
}
</code>```

答:
```@Component
public class CustomizationBean implements
  WebServerFactoryCustomizer {

    @Override
    public void customize(ConfigurableServletWebServerFactory container) {
        container.setPort(8083);
    }
}
```

Body:
I'm trying to add a port to tomcat at runtime. Is there a way to do this? Or is there a way to listen on all ports? I'm using spring and I want the user to be able to add call an API endpoint to add a new port to listen on.

I know that you can add additional ports in the config file, but I don't know what ports I will need to add.

@RequestMapping("/port/{port}")
void setPort(@PathVariable("port") int port){
    //add new tomcat port to listen on
}


问:
Navigation Component with Login / Register / Home flow
I would like to use the new Navigation Component for my next application but I can't quite wrap my head around the overall flow of navigation.
The Android team recommends a single activity as an entry point. They also suggest that conditional elements like a login / register should not be the entry point.
But then how do you display the login and register buttons if the entry screen is supposed to be the home screen?

Another idea is to use a Splash screen, have the logic there to determine if the user is already logged in, if so go to the home screen, if not show the login / register screen(s).

My other issue is with the single activity. My home screen would need to be a screen with a Bottom Navigation.

How do you tie all of this the "right way"? Do I need to have a separate navigation graph for the Home view, with the Bottom Navigation and the many screens that will flow from there?

All the examples I have found have been very straightforward, and the few I have seen with a Splash screen splitting into Home and Login have a very simple Home fragment, which in my case would be . more complex with the Bottom Nav.

Thanks.

答:
One way to do this, you hide the bottom navigation in the login and popup the homepage when you navigate to the login page so the user would not be able to go back to the splash screen

1-you can hide the bottom naviagtion bar in the login fragment like this

```<code>val toolbar = activity!!.findViewById<Toolbar>(R.id.toolbar)
val bottombar = activity!!.findViewById<BottomNavigationView>(R.id.bottomNavigationView)
        toolbar.visibility = View.GONE
        bottombar.visibility = View.GONE
</code>```

2- popup the splash fragment when you navigate to the login page

```<code><action
            android:id="@+id/action_splashFragment_to_loginFragment"
            app:destination="@id/loginFragment"
            app:popUpTo="@+id/splashFragment"
            app:popUpToInclusive="true"/>
</code>```

Hopefully it will work for you

Body:
One way to do this, you hide the bottom navigation in the login and popup the homepage when you navigate to the login page so the user would not be able to go back to the splash screen

1-you can hide the bottom naviagtion bar in the login fragment like this

val toolbar = activity!!.findViewById<Toolbar>(R.id.toolbar)
val bottombar = activity!!.findViewById<BottomNavigationView>(R.id.bottomNavigationView)
        toolbar.visibility = View.GONE
        bottombar.visibility = View.GONE

2- popup the splash fragment when you navigate to the login page

<action
            android:id="@+id/action_splashFragment_to_loginFragment"
            app:destination="@id/loginFragment"
            app:popUpTo="@+id/splashFragment"
            app:popUpToInclusive="true"/>

Hopefully it will work for you