问:
Rescale listboxes or other items? but not text (WPF)
The question is quite clear. I have listviews or listboxes in my view.
If i make my screen smaller, i want that my text (labels etc) stay the same size. But the listviews and listboxes have to become smaller, eventually with a scrollbar?

how do i do this?

Thanks

答:
The question is quite clear.

Well, not exactly.  But I think this is what you're looking for.  First, create a value converter that takes a Double and returns its reciprocal:

```<code>public class ReciprocalValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Double? d = value as Double?;
        return (d == null || d == 0)
                   ? null
                   : 1/d;
    }

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

Now you can scale any content control, using a ScaleTransform, and use the ReciprocalValueConverter to keep any individual element contained within it to the original scale.  So if the content control's scale is doubled, the content that you want to remain unchanged has its scale halved.

This example shows both scaling content controls and "unscaling" the items in a list box by assigning the LayoutTransform to each item:

```<code><Window x:Class="ScaleTransformDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ScaleTransformDemo="clr-namespace:ScaleTransformDemo" Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ScaleTransformDemo:ReciprocalValueConverter x:Key="Reciprocal" />
    </Window.Resources>
    <DockPanel>
        <Slider x:Name="ScaleSlider"
                Orientation="Vertical"
                Minimum=".2"
                Maximum="4"
                Value="1" />
    <DockPanel>
        <DockPanel.LayoutTransform>
            <ScaleTransform ScaleX="{Binding ElementName=ScaleSlider, Path=Value}"
                            ScaleY="{Binding ElementName=ScaleSlider, Path=Value}" />
        </DockPanel.LayoutTransform>
        <Label DockPanel.Dock="Top">
            The content of this label scales with the slider.
        </Label>
        <Label DockPanel.Dock="Top">
            <Label.LayoutTransform>
                <ScaleTransform ScaleX="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}"
                                ScaleY="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}" />
            </Label.LayoutTransform>
            <Label.Content>
                This label's content stays the same size.
            </Label.Content>
        </Label>
        <Label DockPanel.Dock="Top">
            The ListBox below scales with the slider, too, but the ListBoxItems don't:
        </Label>
        <ListBox Height="50"
                 DockPanel.Dock="Top">
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="LayoutTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}"
                                            ScaleY="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}" />
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBoxItem>Item 1</ListBoxItem>
            <ListBoxItem>Item 2</ListBoxItem>
            <ListBoxItem>Item 3</ListBoxItem>
            <ListBoxItem>Item 4</ListBoxItem>
            <ListBoxItem>Item 5</ListBoxItem>
            <ListBoxItem>Item 6</ListBoxItem>
        </ListBox>
        <TextBlock DockPanel.Dock="Top" />
    </DockPanel>
</DockPanel>
</Window>
</code>```

Body:
The question is quite clear.

Well, not exactly.  But I think this is what you're looking for.  First, create a value converter that takes a Double and returns its reciprocal:

public class ReciprocalValueConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Double? d = value as Double?;
        return (d == null || d == 0)
                   ? null
                   : 1/d;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

Now you can scale any content control, using a ScaleTransform, and use the ReciprocalValueConverter to keep any individual element contained within it to the original scale.  So if the content control's scale is doubled, the content that you want to remain unchanged has its scale halved.

This example shows both scaling content controls and "unscaling" the items in a list box by assigning the LayoutTransform to each item:

<Window x:Class="ScaleTransformDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ScaleTransformDemo="clr-namespace:ScaleTransformDemo" Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <ScaleTransformDemo:ReciprocalValueConverter x:Key="Reciprocal" />
    </Window.Resources>
    <DockPanel>
        <Slider x:Name="ScaleSlider"
                Orientation="Vertical"
                Minimum=".2"
                Maximum="4"
                Value="1" />
    <DockPanel>
        <DockPanel.LayoutTransform>
            <ScaleTransform ScaleX="{Binding ElementName=ScaleSlider, Path=Value}"
                            ScaleY="{Binding ElementName=ScaleSlider, Path=Value}" />
        </DockPanel.LayoutTransform>
        <Label DockPanel.Dock="Top">
            The content of this label scales with the slider.
        </Label>
        <Label DockPanel.Dock="Top">
            <Label.LayoutTransform>
                <ScaleTransform ScaleX="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}"
                                ScaleY="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}" />
            </Label.LayoutTransform>
            <Label.Content>
                This label's content stays the same size.
            </Label.Content>
        </Label>
        <Label DockPanel.Dock="Top">
            The ListBox below scales with the slider, too, but the ListBoxItems don't:
        </Label>
        <ListBox Height="50"
                 DockPanel.Dock="Top">
            <ListBox.ItemContainerStyle>
                <Style TargetType="ListBoxItem">
                    <Setter Property="LayoutTransform">
                        <Setter.Value>
                            <ScaleTransform ScaleX="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}"
                                            ScaleY="{Binding ElementName=ScaleSlider, Path=Value, Converter={StaticResource Reciprocal}}" />
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
            <ListBoxItem>Item 1</ListBoxItem>
            <ListBoxItem>Item 2</ListBoxItem>
            <ListBoxItem>Item 3</ListBoxItem>
            <ListBoxItem>Item 4</ListBoxItem>
            <ListBoxItem>Item 5</ListBoxItem>
            <ListBoxItem>Item 6</ListBoxItem>
        </ListBox>
        <TextBlock DockPanel.Dock="Top" />
    </DockPanel>
</DockPanel>
</Window>


来源: stackexchange

问:
Trying to convert a string/char to an integer yielded an unexpected result
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?</p>

```<code>using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}
</code>```

答:
Because when you're trying to convert binary[0] element, which is of char type to int type - it converts char's ASCII code that is simply a number, as it was mentioned by @QuentinUK.

If you want to store bits and convert them to numbers, you should look at std::bitset.

If you want to get any element out of std::string as a number, you should look at std::atoi.

ContentLicense: CC BY-SA 4.0

Body:
I came across something strange. It is probably trivial but I can't find the answer. Can anyone explain to me why in this action I get a result of 49?

using namespace std;

int main() {
    int number;
    string binary = "10101011";

    number = int(binary[0]);
    cout << number; // result is 49 , why is that?
}


问:
what does this.base means in preact?
Can this.base refers to current component in  Preactjs ?
I have a code which has a line

```<code>const rect = this.base.getBoundingClientRect();
</code>```

答:
this.base is to a reference to the root DOM element of your current Component.

It's the JSX element that is returned by your Component's render function.

Thus, you can use this.base once your Component has been mounted.

Here's a small example of the lifecycle from the official documentation:

```<code>class Example extends Component {
  shouldComponentUpdate() {
    // do not re-render via diff:
    return false;
  }

  componentWillReceiveProps(nextProps) {
    // you can do something with incoming props here if you need
  }

  componentDidMount() {
    // now mounted, can freely modify the DOM:
    let thing = document.createElement('maybe-a-custom-element');
    this.base.appendChild(thing);
  }

  componentWillUnmount() {
    // component is about to be removed from the DOM, perform any cleanup.
  }

  render() {
    return <div class="example" />;
  }
}
</code>```

Title: what does this.base means in preact?

Body:
Can this.base refers to current component in  Preactjs ?
I have a code which has a line

const rect = this.base.getBoundingClientRect();

Body:
this.base is to a reference to the root DOM element of your current Component.

It's the JSX element that is returned by your Component's render function.

Thus, you can use this.base once your Component has been mounted.

Here's a small example of the lifecycle from the official documentation:

class Example extends Component {
  shouldComponentUpdate() {
    // do not re-render via diff:
    return false;
  }

  componentWillReceiveProps(nextProps) {
    // you can do something with incoming props here if you need
  }

  componentDidMount() {
    // now mounted, can freely modify the DOM:
    let thing = document.createElement('maybe-a-custom-element');
    this.base.appendChild(thing);
  }

  componentWillUnmount() {
    // component is about to be removed from the DOM, perform any cleanup.
  }

  render() {
    return <div class="example" />;
  }
}


问:
Subversion: How to merge a specific commit
I have some commit on my branches. I want to merge the branches to trunk, but there have some commit that I don't merge to trunk on my branches. How do I do?</p>

答:
If one has TortoiseSVN installed, below are the steps to merge a range of revisions from a branch to the other.

Have a local checkout of the branch to which you want to merge a range of revisions from a source branch.

Right Click inside root folder --> TortoiseSVN --> Merge

By default, "Merge a range of revisions" is clicked.

Click Next

Enter the URL to merge from

Enter the specific range of revisions you want to merge

One can also click Show log and select the desired revision or range of revisions

Click Test Merge to check if it merges desired revisions/files.

Click merge

ContentLicense: CC BY-SA 3.0


问:
Javascript array search filter
I have the scenario, with provided example JSON data:

```<code>[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]
</code>```

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

```<code>filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});
</code>```

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

答:
You could take an object with all filters and another for keeping function for getting the ages of the objects.

var data = [{ name: "Joe", age: "28", hobby: ["Reading", "Chilling", "Cycling"] }, { name: "Beck", age: "25", hobby: ["Drinking", "Cycling"] }, { name: "Candace", age: "24", hobby: ["Reading", "Singing"] }],
    functions = {
        '23-26': ({ age }) => age >= 23 && age <= 26,
        '>27': ({ age }) => age > 27
    },
    filters = {
        hobby:  ["Reading", "Cycling"],
        age: ['23-26']
    },
    result = data.filter(o =>
        filters.hobby.some(v => o.hobby.includes(v)) &&
        filters.age.some(fn => functions[fn](o))
    );

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Javascript array search filter

Body:
I have the scenario, with provided example JSON data:

[{
   "name": "Joe",
   "age": "28",
   "hobby": ["Reading", "Chilling", "Cycling"]
},
{
   "name": "Beck",
   "age": "25",
   "hobby": ["Drinking", "Cycling"]
},
{
   "name": "Candace",
   "age": "24",
   "hobby": ["Reading", "Singing"]
}]

Let's say the array above are shown in some list in web page.

I have 2 (two) search dropdown with multiple selection to search name and age.

For name, let's say it shows all distinct hobbies (Reading, Chilling, Cycling, Drinking, Singing).

For age, let's say it have 2 options for age range: 23-26 and > 27.

For searching hobby, my code is (in ReactJS):

filteredPersons = this.state.personList.filter( person =>{
  return person.hobby.some(v=> filterHobby.indexOf(v) !== -1)
});

which is:

personList is list of array from JSON above;

filterHobby is list of array from multiple select, ex: if filterHobby = ["Reading","Singing"], it will show Joe and Candace.

The question is, how can I search for age with multiple selection?

Expected result:

Choose 23-26 only will show Beck and Candace

Choose >27 only will show Joe

Choose both will show Beck, Candace and Joe

Thank you for any answer.

Body:
You could take an object with all filters and another for keeping function for getting the ages of the objects.

var data = [{ name: "Joe", age: "28", hobby: ["Reading", "Chilling", "Cycling"] }, { name: "Beck", age: "25", hobby: ["Drinking", "Cycling"] }, { name: "Candace", age: "24", hobby: ["Reading", "Singing"] }],
    functions = {
        '23-26': ({ age }) => age >= 23 && age <= 26,
        '>27': ({ age }) => age > 27
    },
    filters = {
        hobby:  ["Reading", "Cycling"],
        age: ['23-26']
    },
    result = data.filter(o =>
        filters.hobby.some(v => o.hobby.includes(v)) &&
        filters.age.some(fn => functions[fn](o))
    );

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
Retrieving two columns from one table inserting into another table using mySQL and PHP
I have two tables in mySQL, notably accounts and subscriber_data.

I want to use two columns present in the accounts table (id, name), and insert it to the subscriber_data table in two columns called (sub_id, value).

I cannot seem to find a way to retrieve this information and put it into the other table without it being bunched up in the same value field in the same row like this: 0, 0, 1

Currently, my PHP looks like this:

```<code>$sql = "SELECT * FROM accounts";
$result = mysql_query($sql);

while($alt_result = mysql_fetch_array($result, MYSQL_NUM)){
$id[] = $alt_result[0];
$value1[] = $alt_result[1];
}
$idstring = implode(', ', $id);
$value1 = implode(', ', $value1);

$sql = "INSERT INTO subscriber_data (field_id, sub_id, value) VALUES('1', '$idstring', '$value1') ON DUPLICATE KEY UPDATE value='$value1'";
$result = mysql_query($sql);
</code>```

I am a novice at this, and obviously doing something wrong... I searched and couldn't find an answer.

Thanks.

答:
I didn't see at first what you were doing in PHP before calling the insert script. Maybe because I'm not used to PHP scripting, though more probably because I didn't pay enough attention at the time.

So, as far as I can understand what you are doing, you seem to be doing it wrong way.

If you need to insert values from one table into another table, you just use the INSERT...SELECT construct.

In your case it should possibly be something like this:

```<code>INSERT INTO subscriber_data (field_id, sub_id, value)
SELECT '1', id, name
FROM accounts
</code>```

Note that this is one instruction, and it replaces both SELECT... and INSERT... in your code. I think it will be enough if you leave only the last two lines of your PHP script above, where the SQL script you are storing to $sql should simply be modified according to my suggestion.

If I'm missing something, please let me know.

Body:
I have two tables in mySQL, notably accounts and subscriber_data.

I want to use two columns present in the accounts table (id, name), and insert it to the subscriber_data table in two columns called (sub_id, value).

I cannot seem to find a way to retrieve this information and put it into the other table without it being bunched up in the same value field in the same row like this: 0, 0, 1

Currently, my PHP looks like this:

$sql = "SELECT * FROM accounts";
$result = mysql_query($sql);

while($alt_result = mysql_fetch_array($result, MYSQL_NUM)){
$id[] = $alt_result[0];
$value1[] = $alt_result[1];
}
$idstring = implode(', ', $id);
$value1 = implode(', ', $value1);

$sql = "INSERT INTO subscriber_data (field_id, sub_id, value) VALUES('1', '$idstring', '$value1') ON DUPLICATE KEY UPDATE value='$value1'";
$result = mysql_query($sql);

I am a novice at this, and obviously doing something wrong... I searched and couldn't find an answer.

Thanks.

Body:
I didn't see at first what you were doing in PHP before calling the insert script. Maybe because I'm not used to PHP scripting, though more probably because I didn't pay enough attention at the time.

So, as far as I can understand what you are doing, you seem to be doing it wrong way.

If you need to insert values from one table into another table, you just use the INSERT...SELECT construct.

In your case it should possibly be something like this:

INSERT INTO subscriber_data (field_id, sub_id, value)
SELECT '1', id, name
FROM accounts

Note that this is one instruction, and it replaces both SELECT... and INSERT... in your code. I think it will be enough if you leave only the last two lines of your PHP script above, where the SQL script you are storing to $sql should simply be modified according to my suggestion.

If I'm missing something, please let me know.


问:
Angular Material (8) Error Message (from Validator) being displayed when Page reloaded
I am new to Angular Material. I am working on a Registration form using Angular Material (8). When doing so, I am seeing that the Error Message is displayed when the page is Reloaded (by hitting the "Refresh" Button on the browser). The field is never touched in any way, shape or form.

Why is this the case?

TIA

File: register.component.html

```<code>[ ... snip ...]

       <div class="flex-register-form">

            <!-- Form -->
            <form [formGroup]="registerForm" (ngSubmit)="registerForm.valid && onSubmit()" class="text-center">

                <div class="form-col">
                    <div class="col">
                        <!-- First name -->
                        <div class="md-form">
                            <input required type="text" id="materialRegisterFormFirstName" class="form-control" mdbInput
                                formControlName="firstname" />
                            <label for="materialRegisterFormFirstName">First name</label>
                            <mat-error *ngIf="registerForm.controls['firstname'].hasError('required')" >First name is required</mat-error>
                        </div>

[ ... snip ...]
</code>```

File: register.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { RegisterModel } from '../../models/register.models';
import {  FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

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

export class RegisterComponent implements OnInit {

  user: RegisterModel = new RegisterModel();
  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.registerForm = new FormGroup({
      'firstname': new FormControl(null, [Validators.required]),
      'lastname': new FormControl(null, [Validators.required, Validators.maxLength(25)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.maxLength(25)]),
      'password': new FormControl(null, [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree': new FormControl(null, [Validators.required])
    });
  }

  onSubmit() {
    console.log(" was submited ");
  }

}
</code>```

答:
It's because as per Validation it is pending. But, we haven't touched the control yet so what we can do is that we can check whether the user interacted with the control or not by checking the control status touched of the form field.

Correction

```<code><mat-error *ngIf="registerForm.controls['firstname'].hasError('required') && registerForm.controls.firstname.touched" >First name is required</mat-error>
</code>```

You can read more about it here

Body:
I am new to Angular Material. I am working on a Registration form using Angular Material (8). When doing so, I am seeing that the Error Message is displayed when the page is Reloaded (by hitting the "Refresh" Button on the browser). The field is never touched in any way, shape or form.

Why is this the case?

TIA

File: register.component.html

[ ... snip ...]

            <form [formGroup]="registerForm" (ngSubmit)="registerForm.valid && onSubmit()" class="text-center">

                            <input required type="text" id="materialRegisterFormFirstName" class="form-control" mdbInput
                                formControlName="firstname" />
                            First name
                            <mat-error *ngIf="registerForm.controls['firstname'].hasError('required')" >First name is required</mat-error>

[ ... snip ...]

File: register.component.ts

import { Component, OnInit } from '@angular/core';
import { RegisterModel } from '../../models/register.models';
import {  FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';

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

export class RegisterComponent implements OnInit {

  user: RegisterModel = new RegisterModel();
  registerForm: FormGroup;

  constructor(private formBuilder: FormBuilder) {

  }

  ngOnInit() {
    this.registerForm = new FormGroup({
      'firstname': new FormControl(null, [Validators.required]),
      'lastname': new FormControl(null, [Validators.required, Validators.maxLength(25)]),
      'email': new FormControl(null, [Validators.required, Validators.email, Validators.maxLength(25)]),
      'password': new FormControl(null, [Validators.required, Validators.minLength(8), Validators.maxLength(25)]),
      'agree': new FormControl(null, [Validators.required])
    });
  }

  onSubmit() {
    console.log(" was submited ");
  }

}

Body:
It's because as per Validation it is pending. But, we haven't touched the control yet so what we can do is that we can check whether the user interacted with the control or not by checking the control status touched of the form field.

Correction

<mat-error *ngIf="registerForm.controls['firstname'].hasError('required') && registerForm.controls.firstname.touched" >First name is required</mat-error>

You can read more about it here


问:
How to access VueJS Mixin within imported JS Library
I have a 'commonLibrary.js' which I've imported into my Vue app.

A small snippet of this library (and a good example) is:

var defaultDecimalRounding=3

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}```
</div>
</div>
</p>

<p>So whenver "formatNumber" is called, it returns a number to a decimal rounding, based on the variable "defaultDecimalRounding"</p>

<p>What I'd like to do is move this defaultDecimalRounding variable out of the commonLibrary.js and into my Vue App so it can be changed within the app.</p>

<p>I've created a Mixin, as follows:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>Vue.mixin({
    data: function () {
        return {
            get defaultDecimalRounding() { return 3 },
        }
    },
});</code>```

But I can't seem to get my formatNumber function to read this defaultDecimalRounding Mixin.

I don't mind doing a code-rewrite for the commonLibrary.js, there's only a dozen or so functions in there, but it would be nice to know how to get VueJS and an imported JS library talking to each other for future projects.

edit
commonLibrary.js is imported as:

```<code>import common from './scripts/common.js';
const commonLibrary = {
    install() {
        Vue.common = common
        Vue.prototype.$common = common
    }
}
Vue.use(commonLibrary)
</code>```

答: Most likely you need to use this because defaultDecimalRounding is now defined in the Vue instance. So something like this.defaultDecimalRounding

Body:
I have a 'commonLibrary.js' which I've imported into my Vue app.

A small snippet of this library (and a good example) is:

var defaultDecimalRounding=3

function formatNumber(number) {
    if (isNaN(number.value) == true) { return '-' }
    return numberWithCommas(parseFloat(number.value, 2).toFixed(defaultDecimalRounding));
}

So whenver "formatNumber" is called, it returns a number to a decimal rounding, based on the variable "defaultDecimalRounding"

What I'd like to do is move this defaultDecimalRounding variable out of the commonLibrary.js and into my Vue App so it can be changed within the app.

I've created a Mixin, as follows:

Vue.mixin({
    data: function () {
        return {
            get defaultDecimalRounding() { return 3 },
        }
    },
});

But I can't seem to get my formatNumber function to read this defaultDecimalRounding Mixin.

I don't mind doing a code-rewrite for the commonLibrary.js, there's only a dozen or so functions in there, but it would be nice to know how to get VueJS and an imported JS library talking to each other for future projects.

edit
commonLibrary.js is imported as:

import common from './scripts/common.js';
const commonLibrary = {
    install() {
        Vue.common = common
        Vue.prototype.$common = common
    }
}
Vue.use(commonLibrary)


问:
Why is fminunc in this for loop giving the same result each time?
I am trying to run 'fminunc' multiple times in for loop.

Part of code:

```<code>P = 0.70 ;
idx = randperm(m);
X_Training = X(idx(1:round(P*m)),:);
X_Testing = X(idx(round(P*m)+1:end),:);
y_Traning = y(idx(1:round(P*m)),:);
y_Testing = y(idx(round(P*m)+1:end),:);

s             = 100;
border_all    = zeros( 2, s );
lambda        = 1;
accuracy      = 0;
initial_theta = zeros( n + 1, 1 );
options       = optimset( 'GradObj', 'on', 'MaxIter', 400 );

for i = 1 : 1 : s
    [theta, J, exit_flag] = fminunc( @(t) costFunctionReg( t, X_Training, y_Traning, lambda ), initial_theta, options );

    for border = 0.01 : 0.01 : 1
        p          = predict( theta, X_Testing, border );
        accuracy_t = mean( double( p == y_Testing ) ) * 100;

        if accuracy_t > accuracy
            accuracy      = accuracy_t;
            border_result = border;
        endif
    endfor

    border_all(1, i) = border_result;
    border_all(2, i) = accuracy;
endfor
</code>```

I use the output values of "theta" later to check different changing variable "i" (for i=1:1:s..).
Every time I run the script "theta" is calculated, but it does not change in other "for loop" iterations. However, it should be a bit different in every iteration.

At the same time, when I rerun the script, I get new values of "theta".  So, it seems that it is calculated from scratch only at the first iteration and not at others.  Perhaps some memory issue.  Have tried 'clear' function, but the result is the same.

Has anyone faced the same problem?

答:
Converting comment thread to an answer for anyone googling with a similar problem:

This is because once you enter the for loop, the inputs to fminunc never change again, so you are effectively always calling it with the same inputs, and therefore getting the same output out.

Move the randomized initializations at the top part of your code snippet inside the for loop, and you will get different outputs each time, as you intend.

Body:
I am trying to run 'fminunc' multiple times in for loop.

Part of code:

P = 0.70 ;
idx = randperm(m);
X_Training = X(idx(1:round(P*m)),:);
X_Testing = X(idx(round(P*m)+1:end),:);
y_Traning = y(idx(1:round(P*m)),:);
y_Testing = y(idx(round(P*m)+1:end),:);

s             = 100;
border_all    = zeros( 2, s );
lambda        = 1;
accuracy      = 0;
initial_theta = zeros( n + 1, 1 );
options       = optimset( 'GradObj', 'on', 'MaxIter', 400 );

for i = 1 : 1 : s
    [theta, J, exit_flag] = fminunc( @(t) costFunctionReg( t, X_Training, y_Traning, lambda ), initial_theta, options );

    for border = 0.01 : 0.01 : 1
        p          = predict( theta, X_Testing, border );
        accuracy_t = mean( double( p == y_Testing ) ) * 100;

        if accuracy_t > accuracy
            accuracy      = accuracy_t;
            border_result = border;
        endif
    endfor

    border_all(1, i) = border_result;
    border_all(2, i) = accuracy;
endfor

I use the output values of "theta" later to check different changing variable "i" (for i=1:1:s..).
Every time I run the script "theta" is calculated, but it does not change in other "for loop" iterations. However, it should be a bit different in every iteration.

At the same time, when I rerun the script, I get new values of "theta".  So, it seems that it is calculated from scratch only at the first iteration and not at others.  Perhaps some memory issue.  Have tried 'clear' function, but the result is the same.

Has anyone faced the same problem?


问:
Function with varying number of for loops using the arguments in the loop
Firstly I would like to say that I've read this thread:

Function with varying number of For Loops (python)

And while it does certainly look similar to what I'd like to know, I'm not proficient enough (at all) with recursion to make it work.

If I have the following snippet:

I = ["i" + str(i+1) for i in range(3)]
J = ["j" + str(i+1) for i in range(4)]
K = ["k" + str(i+1) for i in range(2)]
```

<p>Then I can make a function that does something like this:</p>

<pre class="lang-py prettyprint-override"><code>def f(*Sets):
    size = len(Sets)
    if size == 1:
        for i in Sets[0]:
            print(i)
    elif size == 2:
        for i in Sets[0]:
            for j in Sets[1]:
                print(i,j)
    elif size == 3:
        for i in Sets[0]:
            for j in Sets[1]:
                for k in Sets[2]:
                    print(i,j,k)
</code>```

And when executing, it would produce something like:

>>f(I)
i1
i2
i3

>>f(I,J)
i1,j1
i1,j2
...
i3,j4

>>f(I,J,K)
i1,j1,k1
i1,j1,k2
...
i3,j4,k2

```

The print statement is just an example. I would like to actually access elements in a pandas dataframe at the same time as checking the looped variable, or a dictionary, so it would include some command like print(i,j,k, ":", dictionary[i,j,k]). I need to access each variable in the loops, that´s what I mean.

This looks to me that could be widely reduced using some kind of recursion. Because if for example I need four lists, I'd have to add another elif. But I have not a recursive type of mind, and can't see how to solve it.

Or maybe it cannot be done at all. Not sure anymore of anything :P

答:
You can use recursion to implement this, but the simplest would be just to use itertools.product:

```<code>from itertools import product

def f(*sets):
    for p in product(*sets):
        # e.g. (1, 3, 5)
        print(*p)

>>> f([1, 2], [3, 4], [5, 6])
1 3 5
1 3 6
1 4 5
1 4 6
2 3 5
2 3 6
2 4 5
2 4 6
</code>```

product returns the cartesian product of the input iterables in the form of a lazy iterator over tuples.

A simple recursive implementation of the cartesian product would  go along the following lines:

```<code>def f(*sets):
    if not sets:
        return [[]]
    result = []
    for head in sets[0]:
        for combo in f(*sets[1:]):
            result.append([head] + combo)
    return result

>>> f([1, 2], [3, 4])
[[1, 3], [1, 4], [2, 3], [2, 4]]
</code>```

Body:
Firstly I would like to say that I've read this thread:

Function with varying number of For Loops (python)

And while it does certainly look similar to what I'd like to know, I'm not proficient enough (at all) with recursion to make it work.

If I have the following snippet:

I = ["i" + str(i+1) for i in range(3)]
J = ["j" + str(i+1) for i in range(4)]
K = ["k" + str(i+1) for i in range(2)]

Then I can make a function that does something like this:

def f(*Sets):
    size = len(Sets)
    if size == 1:
        for i in Sets[0]:
            print(i)
    elif size == 2:
        for i in Sets[0]:
            for j in Sets[1]:
                print(i,j)
    elif size == 3:
        for i in Sets[0]:
            for j in Sets[1]:
                for k in Sets[2]:
                    print(i,j,k)

And when executing, it would produce something like:

>>f(I)
i1
i2
i3

>>f(I,J)
i1,j1
i1,j2
...
i3,j4

>>f(I,J,K)
i1,j1,k1
i1,j1,k2
...
i3,j4,k2

The print statement is just an example. I would like to actually access elements in a pandas dataframe at the same time as checking the looped variable, or a dictionary, so it would include some command like print(i,j,k, ":", dictionary[i,j,k]). I need to access each variable in the loops, that´s what I mean.

This looks to me that could be widely reduced using some kind of recursion. Because if for example I need four lists, I'd have to add another elif. But I have not a recursive type of mind, and can't see how to solve it.

Or maybe it cannot be done at all. Not sure anymore of anything :P

Body:
You can use recursion to implement this, but the simplest would be just to use itertools.product:

from itertools import product

def f(*sets):
    for p in product(*sets):
        # e.g. (1, 3, 5)
        print(*p)

>>> f([1, 2], [3, 4], [5, 6])
1 3 5
1 3 6
1 4 5
1 4 6
2 3 5
2 3 6
2 4 5
2 4 6

product returns the cartesian product of the input iterables in the form of a lazy iterator over tuples.

A simple recursive implementation of the cartesian product would  go along the following lines:

def f(*sets):
    if not sets:
        return [[]]
    result = []
    for head in sets[0]:
        for combo in f(*sets[1:]):
            result.append([head] + combo)
    return result

>>> f([1, 2], [3, 4])
[[1, 3], [1, 4], [2, 3], [2, 4]]


问:
How return 304 status with FileResult in ASP.NET MVC RC1
As you may know we have got a new ActionResult called FileResult in RC1 version of ASP.NET MVC.

Using that, your action methods can return image to browser dynamically. Something like this:

```<code>public ActionResult DisplayPhoto(int id)
{
   Photo photo = GetPhotoFromDatabase(id);
   return File(photo.Content, photo.ContentType);
}
</code>```

In the HTML code, we can use something like this:

```<code><img src="http://mysite.com/controller/DisplayPhoto/657">
</code>```

Since the image is returned dynamically, we need a way to cache the returned stream so that we don't need to read the image again from database. I guess we can do it with something like this, I'm not sure:

```<code>Response.StatusCode = 304;
</code>```

This tells the browser that you already have the image in your cache. I just don't know what to return in my action method after setting StatusCode to 304. Should I return null or something?

答:
Don't use 304 with FileResult. From the spec:

The 304 response MUST NOT contain a
  message-body, and thus is always
  terminated by the first empty line
  after the header fields.

It's not clear what you're trying to do from your question. The server doesn't know what the browser has in its cache. The browser decides that. If you're trying to tell the browser not to re-fetch the image when needed again if it already has a copy, set the response Cache-Control header.

If you need to return 304, use EmptyResult instead.

OwnerDisplayName: Maysam

ContentLicense: CC BY-SA 2.5

Body:
As you may know we have got a new ActionResult called FileResult in RC1 version of ASP.NET MVC.

Using that, your action methods can return image to browser dynamically. Something like this:

public ActionResult DisplayPhoto(int id)
{
   Photo photo = GetPhotoFromDatabase(id);
   return File(photo.Content, photo.ContentType);
}

In the HTML code, we can use something like this:

Since the image is returned dynamically, we need a way to cache the returned stream so that we don't need to read the image again from database. I guess we can do it with something like this, I'm not sure:

Response.StatusCode = 304;

This tells the browser that you already have the image in your cache. I just don't know what to return in my action method after setting StatusCode to 304. Should I return null or something?

OwnerDisplayName: Craig Stuntz

LastEditorDisplayName: Craig Stuntz


问:
What to use for real-time log aggregation and querying?

I'm searching for tool/database/solution that can help me with aggregating real-time logs and can query them also in real-time.

Basic requirement is ability to deliver results as soon as possible, keeping in mind, that there might be many of events to query (possibly billions), but logs would have many 'columns' and each query would set some conditions on those columns, so final result will be some kind of aggregation, or only small subset of rows would be returned.

Right now I was looking at HDFS+HBase which seems like a good solution. Are there any alternatives? Can you recommend anything?

答: You can check Flume: https://github.com/cloudera/flume/wiki .</p>


问:
Rename csv columns in a folder of multiple csv
I have about 200 CSV files in a folder and some of the columns are not named the same for instance there is 'App name' ,'App Name' and 'app name' so I want to rename the this kind of columns to a standard name like 'App Name' and concatenate all the CSV's to one CSV file, </p>

答:
That would work:</p>

```<code>import glob
import os

import pandas as pd

folder = 'the folder path'
filenames = [i for i in glob.glob(folder + os.path.sep + '*.csv')]
combined_csv = pd.concat([pd.read_csv(f, skiprows=1) for f in filenames])
combined_csv.columns = ["all the header labels"]
</code>```

Body:
That would work:

import glob
import os

import pandas as pd

folder = 'the folder path'
filenames = [i for i in glob.glob(folder + os.path.sep + '*.csv')]
combined_csv = pd.concat([pd.read_csv(f, skiprows=1) for f in filenames])
combined_csv.columns = ["all the header labels"]


问:
How to add a extra field to Solr while importing CSV file?
I'm Importing data in solr from the shell script

```<code>./bin/post -c <core name> $DOWNLOADFILE
</code>```

There are some fields in CSV file like Name, Email, Phone,Added_on,Updated_on

Now I want to add another field is_deleted = 0 into solr in every record after successful import.

so how to do that?

答:
In your schema you can add this,

```<code>  <field name="is_deleted" type="pint" default="0" indexed="true" stored="true"/>
</code>```

If the field is empty the default value will be indexed.

Body:
I'm Importing data in solr from the shell script

./bin/post -c <core name> $DOWNLOADFILE

There are some fields in CSV file like Name, Email, Phone,Added_on,Updated_on

Now I want to add another field is_deleted = 0 into solr in every record after successful import.

so how to do that?

Body:
In your schema you can add this,

  <field name="is_deleted" type="pint" default="0" indexed="true" stored="true"/>

If the field is empty the default value will be indexed.


答:
Add a field in schema.xml like below.

```<code><field name="is_deleted" type="int" indexed="true" stored="true" default="0" />
</code>```

If the data is not provided while indexing, then solr will use the default value specified in the schema.xml file. If default is not defined, solr ignores this field. If field is marked as required in schema.xml - solr will reject this document with error.

Title: How to add a extra field to Solr while importing CSV file?

Body:
Add a field in schema.xml like below.

<field name="is_deleted" type="int" indexed="true" stored="true" default="0" />

If the data is not provided while indexing, then solr will use the default value specified in the schema.xml file. If default is not defined, solr ignores this field. If field is marked as required in schema.xml - solr will reject this document with error.


问:
set gui contents from another class
I want to be able to change the content of a some JLabel objects from another class. I have a GUI class containing all GUI objects (JFrame, JPanel, etc.). Let's say I have only one JLabel:

```<code>public class GUI {
    private JLabel label;

    public GUI() {
        initialize();//initializes all objects
    }

    public void update(String s) {
        this.label.setText(s);
    }
}
</code>```

GUI has a public function update(String) that I hope to call from another class.

My main class is called App:

```<code>public class App {
    private static GUI window;

    public static void main( String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    window = new GUI();
                    App.updateTxt("some string");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
         });
    }

    public  static void updateTxt(String s) {
        window.update(s);
    }
}
</code>```

This solution does not work, however, GUI.update(String) is working perfectly when called inside the GUI class.
I checked the solution proposed by Paul in:
Access GUI components from another class but I did not understand it.
So how can I invoke a method on GUI from another class to change the UI?

答:
You should take care of threading, see: Concurrency in Swing

That said, try something like this:

```<code>public void update(final String s) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            this.label.setText(s);
        }
    });
}
</code>```

Title: set gui contents from another class

Body:
I want to be able to change the content of a some JLabel objects from another class. I have a GUI class containing all GUI objects (JFrame, JPanel, etc.). Let's say I have only one JLabel:

public class GUI {
    private JLabel label;

    public GUI() {
        initialize();//initializes all objects
    }

    public void update(String s) {
        this.label.setText(s);
    }
}

GUI has a public function update(String) that I hope to call from another class.

My main class is called App:

public class App {
    private static GUI window;

    public static void main( String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    window = new GUI();
                    App.updateTxt("some string");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
         });
    }

    public  static void updateTxt(String s) {
        window.update(s);
    }
}

This solution does not work, however, GUI.update(String) is working perfectly when called inside the GUI class.
I checked the solution proposed by Paul in:
Access GUI components from another class but I did not understand it.
So how can I invoke a method on GUI from another class to change the UI?

Body:
You should take care of threading, see: Concurrency in Swing

That said, try something like this:

public void update(final String s) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            this.label.setText(s);
        }
    });
}


问:
Aligning text to be more symmetrical after a string
Hello I want to make text align so that it looks nicer. I want to print keys and corrsponding values from a dictionary.

```<code>for word in sorted(dict.keys()):
    print(f'{word}: {dict[word]}')
</code>```

however this prints it like this

```<code>a:      4
c:  2
k:   444
</code>```

I want it like this:

```<code>a:    4
c:    2
k:    444
</code>```

答:
Try this,

```<code>for key, value in sorted(dict.keys()):
    print(f'{key}: {value:>5}')
</code>```

Reference Python: Format output string, right alignment

Body:
Hello I want to make text align so that it looks nicer. I want to print keys and corrsponding values from a dictionary.

for word in sorted(dict.keys()):
    print(f'{word}: {dict[word]}')

however this prints it like this

a:      4
c:  2
k:   444

I want it like this:

a:    4
c:    2
k:    444

Body:
Try this,

for key, value in sorted(dict.keys()):
    print(f'{key}: {value:>5}')

Reference Python: Format output string, right alignment


问:
Correct way to achieve mutex operation using lockf utility in shell script
I was looking to add a mutex to my shell script. It is possible with flock but the utility is not installed on my shell and will not be able to install this utility or any other utilities.
I tried using lockf instead to acquire lock but could not get it to work as expected. Below is the snippet of what I was trying to do.

```<code>lockf -k /tmp/lock "echo $$ > lock"
echo "locked"
sleep 10

rm -f /tmp/lock
echo "unlocked
</code>```

Ideally if we run this script on two terminals the second instance should be waiting for lock until the first instance deletes the lock file. Where am I going wrong?. Any suggestions would be of great help.

答:
For example, If you would like to have a cron every minute but want to prevent running multiple times your script, you could use something like:

```<code>* * * * * lockf -t 0 /tmp/foo.lock /path/to/foo.sh
</code>```

In this case, lockf will create the lock file /tmp/foo.lock and automatically will remove on exit.

The option -t 0 prevents creating too many lockf processes, it can be read as wait N seconds for the lock to be removed or exit, if the -t N is not specified  lockf will wait indefinitely.

From the lockf man:

```<code>-t   seconds   Specifies a timeout for waiting for the lock.  By default,
     lockf waits indefinitely to acquire the lock.  If a timeout
     is specified with this option, lockf will wait at most the
     given number of seconds before giving up.  A timeout of 0 may
     be given, in which case lockf will fail unless it can acquire
     the lock immediately.  When a lock times out, command is not
     executed.
</code>```

Once you have the lock file you could test like this:

```<code>lockf -t 0 /tmp/foo.lock uname
</code>```

And will get something like:

```<code>lockf: /tmp/foo.lock: already locked
</code>```

Body:
I was looking to add a mutex to my shell script. It is possible with flock but the utility is not installed on my shell and will not be able to install this utility or any other utilities.
I tried using lockf instead to acquire lock but could not get it to work as expected. Below is the snippet of what I was trying to do.

lockf -k /tmp/lock "echo $$ > lock"
echo "locked"
sleep 10

rm -f /tmp/lock
echo "unlocked

Ideally if we run this script on two terminals the second instance should be waiting for lock until the first instance deletes the lock file. Where am I going wrong?. Any suggestions would be of great help.

Body:
For example, If you would like to have a cron every minute but want to prevent running multiple times your script, you could use something like:

* * * * * lockf -t 0 /tmp/foo.lock /path/to/foo.sh

In this case, lockf will create the lock file /tmp/foo.lock and automatically will remove on exit.

The option -t 0 prevents creating too many lockf processes, it can be read as wait N seconds for the lock to be removed or exit, if the -t N is not specified  lockf will wait indefinitely.

From the lockf man:

-t   seconds   Specifies a timeout for waiting for the lock.  By default,
     lockf waits indefinitely to acquire the lock.  If a timeout
     is specified with this option, lockf will wait at most the
     given number of seconds before giving up.  A timeout of 0 may
     be given, in which case lockf will fail unless it can acquire
     the lock immediately.  When a lock times out, command is not
     executed.

Once you have the lock file you could test like this:

lockf -t 0 /tmp/foo.lock uname

And will get something like:

lockf: /tmp/foo.lock: already locked


问:
How To Counting in Group Php MySql
How to Counting "Active People" in Table Transaction Join to Table People,
my db :
People Table

```<code>id | Name |
===========
1  | A    |
2  | B    |
3  | C    |
4  | D    |
</code>```

Transaction Table

```<code>idtrx | trxone  | trxtwo |  idpeople |
======================================
1     | 200000  |  0     |     1
2     | 5000    |  10    |     1
3     |   0     |  200   |     4
4     |   0     |  200   |     3
</code>```

im sorry i'm not good at speaking english,
I mean how to join and count active people or make transactions from the 2 tables
and make a result :
Active People

```<code>[
  {
   trxone: "1", //people
   trxtwo: "3"  //people
  }
]
</code>```

My code before :

```<code><?php
require_once "conn.php";
$query = "SELECT
COUNT(DISTINCT tbl_trx.trxone) as mf
FROM tbl_people
INNER JOIN tbl_outlet ON tbl_people.id = tbl_trx.idpeople
WHERE trxone IS NOT NULL AND WHERE id = $_GET[id]";
$sql = mysqli_query ($link,$query);
$ray = array();
while ($row = mysqli_fetch_array($sql)) {
  array_push($ray, array(
    "totaltrxone" => $row['mf']
  ));
}
echo json_encode($ray);
mysqli_close($link);
?>
</code>```

答:
```<code>SELECT COUNT(DISTINCT CASE WHEN trxone THEN trxone END) trxone,
       COUNT(DISTINCT CASE WHEN trxtwo THEN trxtwo END) trxtwo
FROM tbl_people
</code>```

Title: How To Counting in Group Php MySql

Body:
How to Counting "Active People" in Table Transaction Join to Table People,
my db :
People Table

id | Name |
===========
1  | A    |
2  | B    |
3  | C    |
4  | D    |

Transaction Table

idtrx | trxone  | trxtwo |  idpeople |
======================================
1     | 200000  |  0     |     1
2     | 5000    |  10    |     1
3     |   0     |  200   |     4
4     |   0     |  200   |     3

im sorry i'm not good at speaking english,
I mean how to join and count active people or make transactions from the 2 tables
and make a result :
Active People

[
  {
   trxone: "1", //people
   trxtwo: "3"  //people
  }
]

My code before :

<?php
require_once "conn.php";
$query = "SELECT
COUNT(DISTINCT tbl_trx.trxone) as mf
FROM tbl_people
INNER JOIN tbl_outlet ON tbl_people.id = tbl_trx.idpeople
WHERE trxone IS NOT NULL AND WHERE id = $_GET[id]";
$sql = mysqli_query ($link,$query);
$ray = array();
while ($row = mysqli_fetch_array($sql)) {
  array_push($ray, array(
    "totaltrxone" => $row['mf']
  ));
}
echo json_encode($ray);
mysqli_close($link);
?>


问:
npm cannot find module 'encoding'
So I encounter this kind of problem in npm. I'm using VSCode, btw my laptop is newly formated my OS is Ubuntu. The error that I came across when I install something is:

```<code>npm ERR! code MODULE_NOT_FOUND
npm ERR! cannot find module 'encoding'

    // Log

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'install', '-g', 'jshint' ]
2 info using npm@5.8.0
3 info using node@v8.11.2
4 verbose npm-session 94ee8611aa9e8514
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 silly fetchPackageMetaData error for jshint@latest Cannot find module 'encoding'
8 verbose stack Error: Cannot find module 'encoding'
8 verbose stack     at Function.Module._resolveFilename (module.js:547:15)
8 verbose stack     at Function.Module._load (module.js:474:25)
8 verbose stack     at Module.require (module.js:596:17)
8 verbose stack     at require (internal/module.js:11:18)
8 verbose stack     at Object.<anonymous> (/usr/share/npm/node_modules/pacote/node_modules/make-fetch-happen/node_modules/node-fetch-npm/src/body.js:13:17)
8 verbose stack     at Module._compile (module.js:652:30)
8 verbose stack     at Object.Module._extensions..js (module.js:663:10)
8 verbose stack     at Module.load (module.js:565:32)
8 verbose stack     at tryModuleLoad (module.js:505:12)
8 verbose stack     at Function.Module._load (module.js:497:3)
8 verbose stack     at Module.require (module.js:596:17)
8 verbose stack     at require (internal/module.js:11:18)
8 verbose stack     at Object.<anonymous> (/usr/share/npm/node_modules/pacote/node_modules/make-fetch-happen/node_modules/node-fetch-npm/src/index.js:15:14)
8 verbose stack     at Module._compile (module.js:652:30)
8 verbose stack     at Object.Module._extensions..js (module.js:663:10)
8 verbose stack     at Module.load (module.js:565:32)
9 verbose cwd /opt/lampp/htdocs/My Website #1
10 verbose Linux 4.18.0-parrot8-amd64
11 verbose argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "jshint"
12 verbose node v8.11.2
13 verbose npm  v5.8.0
14 error code MODULE_NOT_FOUND
15 error Cannot find module 'encoding'
16 verbose exit [ 1, true ]
</code>```

I tried reinstalling Node.js/npm but still not working.

答:
Possible dependency missing,

try:

```<code>rm -rf node_modules && npm install
</code>```

if you are mac, linux user and you are having privileges issues

try:

```<code>rm -rf node_modules && npm install
</code>```

Title: npm cannot find module 'encoding'

Body:
So I encounter this kind of problem in npm. I'm using VSCode, btw my laptop is newly formated my OS is Ubuntu. The error that I came across when I install something is:

npm ERR! code MODULE_NOT_FOUND
npm ERR! cannot find module 'encoding'

    // Log

0 info it worked if it ends with ok
1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'install', '-g', 'jshint' ]
2 info using npm@5.8.0
3 info using node@v8.11.2
4 verbose npm-session 94ee8611aa9e8514
5 silly install loadCurrentTree
6 silly install readGlobalPackageData
7 silly fetchPackageMetaData error for jshint@latest Cannot find module 'encoding'
8 verbose stack Error: Cannot find module 'encoding'
8 verbose stack     at Function.Module._resolveFilename (module.js:547:15)
8 verbose stack     at Function.Module._load (module.js:474:25)
8 verbose stack     at Module.require (module.js:596:17)
8 verbose stack     at require (internal/module.js:11:18)
8 verbose stack     at Object.<anonymous> (/usr/share/npm/node_modules/pacote/node_modules/make-fetch-happen/node_modules/node-fetch-npm/src/body.js:13:17)
8 verbose stack     at Module._compile (module.js:652:30)
8 verbose stack     at Object.Module._extensions..js (module.js:663:10)
8 verbose stack     at Module.load (module.js:565:32)
8 verbose stack     at tryModuleLoad (module.js:505:12)
8 verbose stack     at Function.Module._load (module.js:497:3)
8 verbose stack     at Module.require (module.js:596:17)
8 verbose stack     at require (internal/module.js:11:18)
8 verbose stack     at Object.<anonymous> (/usr/share/npm/node_modules/pacote/node_modules/make-fetch-happen/node_modules/node-fetch-npm/src/index.js:15:14)
8 verbose stack     at Module._compile (module.js:652:30)
8 verbose stack     at Object.Module._extensions..js (module.js:663:10)
8 verbose stack     at Module.load (module.js:565:32)
9 verbose cwd /opt/lampp/htdocs/My Website #1
10 verbose Linux 4.18.0-parrot8-amd64
11 verbose argv "/usr/bin/node" "/usr/bin/npm" "install" "-g" "jshint"
12 verbose node v8.11.2
13 verbose npm  v5.8.0
14 error code MODULE_NOT_FOUND
15 error Cannot find module 'encoding'
16 verbose exit [ 1, true ]

I tried reinstalling Node.js/npm but still not working.

Body:
Possible dependency missing,

try:

rm -rf node_modules && npm install

if you are mac, linux user and you are having privileges issues

try:

rm -rf node_modules && npm install


问:
Unset img src if no url is provided vue.js
I'm learning vue.js
I'm testing how it works with ajax and the wp rest api, I'm creating a custom panel theme and I want to show the content on the right side of the screen in a scrollable panel and the pages on the left side of . the screen without the possibility to scroll.
I'm able to display the content of the posts and pages, I'm getting also the featured image, and I placed it inside an  tag. I need to understand how to tell vue.js that if there isn't any url data to show the featured image, the src of the image element needs to be unset. Is this possible ?

```<code><?php get_header(); ?>

<div class="container-fluid content-wrapper" style="overflow:hidden;height:100vh;">
  <div class="row" id="app" style="margin:2em 0 2em 0;">
<!-- Sidebar Top Area -->
    <div class="col-sm-12 col-md-4 col-lg-4" id="navPanel" style="padding:2em;">
<?php $links = new WP_Query( array('post_type' => 'page', 'posts_per_page' => -1) ); ?>
<?php if( $links->have_posts() ): while( $links->have_posts() ): $links->the_post(); ?>
      <h1 class="home-claim" style="font-size:2em;">
        <a class="" href="#" v-on:click.prevent="getContent(<?php echo get_the_ID(); ?>)" ><?php the_title(); ?></a>
      </h1>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
    </div>
<!-- Post/Pages Content -->
    <div class="col-sm-12 col-md-8 col-lg-8" id="contentPanel" style="padding:0 0 2em 0;overflow:auto;height:100vh;">
<!-- Image here -->
      <img class="img-fluid w-100" v-if="featuredImage" v-bind:src="featuredImage" />
      <div class="" id="" v-html="content"></div>

    </div>
<!-- Sidebar Bottom Area -->
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
(function($){
  $(document).ready(function(){

  var app = new Vue({
    el: '#app',
    data: {
      content: null,
      featuredImage: null,
    },
    mounted: function(){

    },
    methods: {
      getContent: function(id){
        console.log('method Fired!');
        var self = this;
        console.log(id);
        var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
        $.getJSON( url, function(data){
          console.log(data);
          self.content = data.content.rendered;
          self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
          //console.log(data._embedded["wp:featuredmedia"][0].source_url);
          //console.log(data.content.rendered);
        });
      }

    }
  });

  }); // doc ready
}(jQuery));
</script>

<?php get_footer(); ?>
</code>```

I've also noticed that only for a page I have, the wp api will return a 401 code for the featured image.
Any help will be appreciated.

答:
Unset the featuredImage before doing the load:

(function($){
  $(document).ready(function(){
    var app = new Vue({
      methods: {
        getContent: function(id){
          var self = this;

          // unset the image before you are loading.
          // this way it will also unset when the loading fails.
          self.featuredImage = null;

          var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
          $.getJSON( url, function(data){
            self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
          });
        }
      }
    });
  });
}(jQuery));```

Body:
I'm learning vue.js
I'm testing how it works with ajax and the wp rest api, I'm creating a custom panel theme and I want to show the content on the right side of the screen in a scrollable panel and the pages on the left side of . the screen without the possibility to scroll.
I'm able to display the content of the posts and pages, I'm getting also the featured image, and I placed it inside an  tag. I need to understand how to tell vue.js that if there isn't any url data to show the featured image, the src of the image element needs to be unset. Is this possible ?

<?php get_header(); ?>

<?php $links = new WP_Query( array('post_type' => 'page', 'posts_per_page' => -1) ); ?>
<?php if( $links->have_posts() ): while( $links->have_posts() ): $links->the_post(); ?>

        <a class="" href="#" v-on:click.prevent="getContent(<?php echo get_the_ID(); ?>)" ><?php the_title(); ?>

<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>

<?php get_footer(); ?>

I've also noticed that only for a page I have, the wp api will return a 401 code for the featured image.
Any help will be appreciated.


问:
problem to recover the value of an input [javascript, php]
The employee must not exceed 100€ of product, so I wanted him to write down the quantity of product he wants, press a button and a dialog box appears to display the total price of the order.
I managed to have the price of the item displayed for each product in the dialog box and to have the prices for each chosen product added together.

However, I cannot recover the value of the input which is the quantity chosen by the employee.

```<code>    $lenum = 0;
      foreach ($lesProduits as $leProduit){
        ?>
        <img src="<?php echo $leProduit['image'];?>">
        <br><input type="checkbox" id="<?php echo $leProduit['nproduit']?>" name="nproduits[]" value="<?php echo $leProduit['nproduit']?>">
        <?php echo $leProduit['nproduit']; ?> - <?php echo $leProduit['designation']; ?><br>
        Boitage : <?php echo $leProduit['boitage'];?><br>
        Prix Unitaire : <?php echo $leProduit['prix']; ?>€<br>
        Quantité : <?php echo $leProduit['qtestock'];  ?> <br>
        Quantité souhaité :  <input type="text" name="txtqte[]" id="<?php echo $lenum;?>"  size="3"/><br>
        <input type="button" value="Enregistrer" onclick="leprix(lep = <?php echo $leProduit['prix'];?>,<?php echo $lenum;?>)">
        <br>
        <hr><br>
        <?php
        $lenum ++;
      }
      ?>
</code>```

and the script

```<code>function leprix(lep,inputId){
    var lavaleur = document.getElementById(inputId).value;
    alert("la prix du produit est de : " + lep);
    alert("la quantité demandé est de : " + lavaleur);
}
</code>```

For the first product when $lenum = 0 it works but then it displays $lenum and not the value of the input

答:
This should work:</p>

```<code>   <input type="text" name="txtqte[]" name="<?php echo $lenum;?>" id="<?php echo $lenum;?>"  size="3"/>
   <input type="button" value="Enregistrer" onclick="leprix('<?php echo $lenum;?>')">
   <script>
       function leprix(inputId){
            var input = document.getElementById(inputId).value;
            alert(input);
       }
   </script>
</code>```

Body:
The employee must not exceed 100€ of product, so I wanted him to write down the quantity of product he wants, press a button and a dialog box appears to display the total price of the order.
I managed to have the price of the item displayed for each product in the dialog box and to have the prices for each chosen product added together.

However, I cannot recover the value of the input which is the quantity chosen by the employee.

    $lenum = 0;
      foreach ($lesProduits as $leProduit){
        ?>
        <img src="<?php echo $leProduit['image'];?>">

<input type="checkbox" id="<?php echo $leProduit['nproduit']?>" name="nproduits[]" value="<?php echo $leProduit['nproduit']?>">
        <?php echo $leProduit['nproduit']; ?> - <?php echo $leProduit['designation']; ?>

        Boitage : <?php echo $leProduit['boitage'];?>

        Prix Unitaire : <?php echo $leProduit['prix']; ?>€

        Quantité : <?php echo $leProduit['qtestock'];  ?>

        Quantité souhaité :  <input type="text" name="txtqte[]" id="<?php echo $lenum;?>"  size="3"/>

        <input type="button" value="Enregistrer" onclick="leprix(lep = <?php echo $leProduit['prix'];?>,<?php echo $lenum;?>)">

        <?php
        $lenum ++;
      }
      ?>

and the script

function leprix(lep,inputId){
    var lavaleur = document.getElementById(inputId).value;
    alert("la prix du produit est de : " + lep);
    alert("la quantité demandé est de : " + lavaleur);
}

For the first product when $lenum = 0 it works but then it displays $lenum and not the value of the input

Body:
This should work:

   <input type="text" name="txtqte[]" name="<?php echo $lenum;?>" id="<?php echo $lenum;?>"  size="3"/>
   <input type="button" value="Enregistrer" onclick="leprix('<?php echo $lenum;?>')">
   <script>
       function leprix(inputId){
            var input = document.getElementById(inputId).value;
            alert(input);
       }
   </script>


问:
Loop through array and populate matrix - JS
I want to populate matrix table dynamically. I have this part of API response:

```<code>"Characteristics": [
            {
                "Description": "Benefits - Pay Related",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Preapproved",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Age/Service Weighted Plan",
                "Years": [
                    2018,
                    2017
                ]
            },
            {
                "Description": "Benefits - Profit Sharing",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - 404c",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Participant Directed",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - 401(K)",
                "Years": [
                    2018,
                    2017
                ]
            },
            {
                "Description": "Benefits - 401(m) Arrangement",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Auto Enrollment",
                "Years": [
                    2018,
                    2017
                ]
            }
</code>```

As you can see the "Description" always exist, but not for all years. In the end I want to have something like this rendered:

The provided table is not related to the data - as you can see for "Benefits - Age/Service Weighted Plan" there is no 2016 in "Years" so I want there to be 'N'. I have function to detect unique years from other part of the data which containing all years for which any information is provided. This is in API response:

```<code>const uniqueYearsPension = data => {
  return data.map(element => {
    return element.Year;
  });
};
</code>```

I tried populating table like this:

```<code><table className="table table-striped table-bordered table-sm table-hover">
                  <thead className="thead-dark">
                    <tr>
                      <th>Description</th>
                      {DataExtract.uniqueYearsPension(
                        props.types[2][index]
                      ).map((el, ind) => {
                        return <th key={ind}>{el}</th>;
                      })}
                    </tr>
                  </thead>
                  <tbody className="table-hover">
                    {element.Characteristics &&
                      element.Characteristics.map((e, i) => {
                        return (
                          <tr key={i}>
                            <td>{e.Description}</td>
                            {e.Years.reverse().map((year, yearID) => {
                              console.log(year);
                              return DataExtract.uniqueYearsPension(
                                props.types[2][index]
                              ).map((el, ind) => {
                                console.log(year);
                                if (year == el) {
                                  return <td key={yearID}>Y</td>;
                                }
                              });
                            })}
                          </tr>
                        );
                      })}
                  </tbody>
                </table>
</code>```

But it is populating row 1 by 1 and if 2016 is missing it is putting 2017 result in this column and so 2018 is empty instead of 2016 - which is absolutely normal. If I add else statement here:

```<code>if (year == el) {
                                  return <td key={yearID}>Y</td>;
                                } else return <td key={yearID}>N</td>
</code>```

It is printing on the row many many results. Any ideas how to populate my table like a matrix?

答:
Try to save the result of uniqueYearsPension into a variable at first to avoid recalculation.
And then during the render tr just map on all years and check whether e.Years includes the value.
The code would look like:

```<code>const uniqueYears = DataExtract.uniqueYearsPension(props.types[2][index]);
...
...
<table className="table table-striped table-bordered table-sm table-hover">
    <thead className="thead-dark">
        <tr>
            <th>Description</th>
            {
                uniqueYears.map((value, key) => {
                    return <th key={key}>{value}</th>;
                })
            }
        </tr>
    </thead>
    <tbody className="table-hover">
        {element.Characteristics &&
            element.Characteristics.map((e, i) => {
                return (
                    <tr key={i}>
                        <td>{e.Description}</td>
                        {
                            uniqueYears.map((year, yearID) => {
                                if (e.Years.includes(year)) {
                                    return <td key={yearID}>Y</td>;
                                } else {
                                    return <td key={yearID}>N</td>;
                                }
                            })
                        }
                    </tr>
                );
            })}
    </tbody>
</table>
</code>```

Body:
I want to populate matrix table dynamically. I have this part of API response:

"Characteristics": [
            {
                "Description": "Benefits - Pay Related",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Preapproved",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Age/Service Weighted Plan",
                "Years": [
                    2018,
                    2017
                ]
            },
            {
                "Description": "Benefits - Profit Sharing",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - 404c",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Participant Directed",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - 401(K)",
                "Years": [
                    2018,
                    2017
                ]
            },
            {
                "Description": "Benefits - 401(m) Arrangement",
                "Years": [
                    2018,
                    2017,
                    2016
                ]
            },
            {
                "Description": "Benefits - Auto Enrollment",
                "Years": [
                    2018,
                    2017
                ]
            }

As you can see the "Description" always exist, but not for all years. In the end I want to have something like this rendered:

The provided table is not related to the data - as you can see for "Benefits - Age/Service Weighted Plan" there is no 2016 in "Years" so I want there to be 'N'. I have function to detect unique years from other part of the data which containing all years for which any information is provided. This is in API response:

const uniqueYearsPension = data => {
  return data.map(element => {
    return element.Year;
  });
};

I tried populating table like this:

                      Description
                      {DataExtract.uniqueYearsPension(
                        props.types[2][index]
                      ).map((el, ind) => {
                        return {el}	;
                      })}

                    {element.Characteristics &&
                      element.Characteristics.map((e, i) => {
                        return (

                            {e.Description}
                            {e.Years.reverse().map((year, yearID) => {
                              console.log(year);
                              return DataExtract.uniqueYearsPension(
                                props.types[2][index]
                              ).map((el, ind) => {
                                console.log(year);
                                if (year == el) {
                                  return Y	;
                                }
                              });
                            })}

                        );
                      })}

But it is populating row 1 by 1 and if 2016 is missing it is putting 2017 result in this column and so 2018 is empty instead of 2016 - which is absolutely normal. If I add else statement here:

if (year == el) {
                                  return Y	;
                                } else return N

It is printing on the row many many results. Any ideas how to populate my table like a matrix?

Body:
Try to save the result of uniqueYearsPension into a variable at first to avoid recalculation.
And then during the render tr just map on all years and check whether e.Years includes the value.
The code would look like:

const uniqueYears = DataExtract.uniqueYearsPension(props.types[2][index]);
...
...
<table className="table table-striped table-bordered table-sm table-hover">
    <thead className="thead-dark">
        <tr>
            <th>Description</th>
            {
                uniqueYears.map((value, key) => {
                    return <th key={key}>{value}</th>;
                })
            }
        </tr>
    </thead>
    <tbody className="table-hover">
        {element.Characteristics &&
            element.Characteristics.map((e, i) => {
                return (
                    <tr key={i}>
                        <td>{e.Description}</td>
                        {
                            uniqueYears.map((year, yearID) => {
                                if (e.Years.includes(year)) {
                                    return <td key={yearID}>Y</td>;
                                } else {
                                    return <td key={yearID}>N</td>;
                                }
                            })
                        }
                    </tr>
                );
            })}
    </tbody>
</table>


问:
How to iterate through the synset list generated from wordnet using python 3.4.2
I am using wordnet to find the synonyms for a particular word as shown below

```<code>synonyms = wn.synsets('good','a')
</code>```

where wn is wordnet. This returns a list of synsets like

```<code>Synset('good.a.01')
Synset('full.s.06')
Synset('good.a.03')
Synset('estimable.s.02')
Synset('beneficial.s.01')
</code>```

etc...

How to iterate through each synset and get the name and the pos tag of each synset?

答:
I am using this in my code:

```<code>from nltk.corpus import wordnet

word = input()

for syn in wordnet.synsets(word):
    for l in syn.lemmas():
        print(syn.pos())
        print(l.name())
</code>```

The syn.pos() can be called outside the inner loop as well, because each lemma contains words with same pos.

Body:
I am using wordnet to find the synonyms for a particular word as shown below

synonyms = wn.synsets('good','a')

where wn is wordnet. This returns a list of synsets like

Synset('good.a.01')
Synset('full.s.06')
Synset('good.a.03')
Synset('estimable.s.02')
Synset('beneficial.s.01')

etc...

How to iterate through each synset and get the name and the pos tag of each synset?

Body:
I am using this in my code:

from nltk.corpus import wordnet

word = input()

for syn in wordnet.synsets(word):
    for l in syn.lemmas():
        print(syn.pos())
        print(l.name())

The syn.pos() can be called outside the inner loop as well, because each lemma contains words with same pos.


问:
Numpy/Scipy : solving several least squares with the same design matrix
I face a least square problem that i solve via scipy.linalg.lstsq(M,b), where :

M has shape (n,n)

b has shape (n,)

The issue is that i have to solve it a bunch of time for different b's. How can i do something more efficient ? I guess that lstsq does a lot of things independently of the value of b.

Ideas ?

答:
Your question is unclear, but I am guessing you mean to compute the equation Mx=b through scipy.linalg.lstsq(M,b) for different arrays (b0, b1, b2..). If that is the case you could just parallelize the process with concurrent.futures.ProcessPoolExecutor. The documentation for this is fairly simple and can help python run multiple scipy solvers at once.

Hope this helps.


问:
how to read text file from POST with express-uploadfile?
I am trying to make node js server, for uploading text files there.

so I am using POST for get local user's text file, then I want to make server read the file.

I think I can make user upload he's local text file, I can get uploaded file's description.

but It is hard to make server read the file's actual string.
because I always get 'undefined' when I get try to read it by
logFile.data.toString('utf8');

Could you guide me how to read the uploaded text file's string?

Here is my tried code, Thank you.:

html:

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>

<h3>ENTER</h3>
<form action="/loadfile" method="post" enctype="multipart/form-data">
    <table>

        <tr>
            <td>file : </td>
            <td><input type="file" name="fileName"></td>
        </tr>
        <tr>
            <td><input type="submit" value="submit"></td>
        </tr>
    </table>
</form>

</body>
</html>

</code>```

logFile is a file from POST.
I think logFile.data returns the byte array of its text file contents,
so I tried to convert to String by toString('utf8') or toString().

This is node js server:

```<code>var fileupload = require("express-fileupload");
  app.use(fileupload());
  app.use(bodyParser.urlencoded({extended: false}));

           (fetching html... )

app.post('/loadfile', (req,res) =>{

      console.log("react to post action - loadFile");
      res.send("submit ok");
        var logFile = req.files;

        console.log(logFile);
        var buffer = logFile.data;
        console.log(buffer.toString('utf8'));

    });

</code>```

when I put "test.txt" files to this html, this is server's console reaction.

```<code>
2020-02-14T08:18:50.909771+00:00 app[web.1]: react to post action - loadFile
2020-02-14T08:18:50.912904+00:00 app[web.1]: {
2020-02-14T08:18:50.912905+00:00 app[web.1]: fileName: {
2020-02-14T08:18:50.912906+00:00 app[web.1]: name: 'test.txt',
2020-02-14T08:18:50.912907+00:00 app[web.1]: data: <Buffer 68 65 6c 6c 6f 20 74
68 69 73 20 69 73 20 74 65 73 74 20 74 65 78 74 20 66 69 6c 65>,
2020-02-14T08:18:50.912907+00:00 app[web.1]: size: 28,
2020-02-14T08:18:50.912908+00:00 app[web.1]: encoding: '7bit',
2020-02-14T08:18:50.912908+00:00 app[web.1]: tempFilePath: '',
2020-02-14T08:18:50.912912+00:00 app[web.1]: truncated: false,
2020-02-14T08:18:50.912912+00:00 app[web.1]: mimetype: 'text/plain',
2020-02-14T08:18:50.912913+00:00 app[web.1]: md5: 'f4e8dbc8c1fa4d01329d4f8260511
1d2',
2020-02-14T08:18:50.912913+00:00 app[web.1]: mv: [Function: mv]
2020-02-14T08:18:50.912914+00:00 app[web.1]: }

** I can see the uploaded file's information properly **

2020-02-14T08:18:50.912914+00:00 app[web.1]: }
2020-02-14T08:18:50.914538+00:00 app[web.1]: TypeError: Cannot read property 'to
String' of undefined
2020-02-14T08:18:50.914539+00:00 app[web.1]: at /app/server.js:111:28
2020-02-14T08:18:50.914540+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914540+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/route.js:137:13)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Route.dispatch (/app/node_module
s/express/lib/router/route.js:112:3)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at /app/node_modules/express/lib/ro
uter/index.js:281:22
2020-02-14T08:18:50.914542+00:00 app[web.1]: at Function.process_params (/app/no
de_modules/express/lib/router/index.js:335:12)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/index.js:275:10)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at urlencodedParser (/app/node_modu
les/body-parser/lib/types/urlencoded.js:100:7)
2020-02-14T08:18:50.914543+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)

**But read the file's actual string by 'toString()' is not possible, why??**

</code>```

答: res.send('submit ok') must be at the bottom. </p>

Body:
I am trying to make node js server, for uploading text files there.

so I am using POST for get local user's text file, then I want to make server read the file.

I think I can make user upload he's local text file, I can get uploaded file's description.

but It is hard to make server read the file's actual string.
because I always get 'undefined' when I get try to read it by
logFile.data.toString('utf8');

Could you guide me how to read the uploaded text file's string?

Here is my tried code, Thank you.:

html:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Document</title>

ENTER

<form action="/loadfile" method="post" enctype="multipart/form-data">

            file :
            <input type="file" name="fileName">

            <input type="submit" value="submit">

</form>

logFile is a file from POST.
I think logFile.data returns the byte array of its text file contents,
so I tried to convert to String by toString('utf8') or toString().

This is node js server:

var fileupload = require("express-fileupload");
  app.use(fileupload());
  app.use(bodyParser.urlencoded({extended: false}));

           (fetching html... )

app.post('/loadfile', (req,res) =>{

      console.log("react to post action - loadFile");
      res.send("submit ok");
        var logFile = req.files;

        console.log(logFile);
        var buffer = logFile.data;
        console.log(buffer.toString('utf8'));

    });

when I put "test.txt" files to this html, this is server's console reaction.

2020-02-14T08:18:50.909771+00:00 app[web.1]: react to post action - loadFile
2020-02-14T08:18:50.912904+00:00 app[web.1]: {
2020-02-14T08:18:50.912905+00:00 app[web.1]: fileName: {
2020-02-14T08:18:50.912906+00:00 app[web.1]: name: 'test.txt',
2020-02-14T08:18:50.912907+00:00 app[web.1]: data: <Buffer 68 65 6c 6c 6f 20 74
68 69 73 20 69 73 20 74 65 73 74 20 74 65 78 74 20 66 69 6c 65>,
2020-02-14T08:18:50.912907+00:00 app[web.1]: size: 28,
2020-02-14T08:18:50.912908+00:00 app[web.1]: encoding: '7bit',
2020-02-14T08:18:50.912908+00:00 app[web.1]: tempFilePath: '',
2020-02-14T08:18:50.912912+00:00 app[web.1]: truncated: false,
2020-02-14T08:18:50.912912+00:00 app[web.1]: mimetype: 'text/plain',
2020-02-14T08:18:50.912913+00:00 app[web.1]: md5: 'f4e8dbc8c1fa4d01329d4f8260511
1d2',
2020-02-14T08:18:50.912913+00:00 app[web.1]: mv: [Function: mv]
2020-02-14T08:18:50.912914+00:00 app[web.1]: }

** I can see the uploaded file's information properly **

2020-02-14T08:18:50.912914+00:00 app[web.1]: }
2020-02-14T08:18:50.914538+00:00 app[web.1]: TypeError: Cannot read property 'to
String' of undefined
2020-02-14T08:18:50.914539+00:00 app[web.1]: at /app/server.js:111:28
2020-02-14T08:18:50.914540+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914540+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/route.js:137:13)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Route.dispatch (/app/node_module
s/express/lib/router/route.js:112:3)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)
2020-02-14T08:18:50.914541+00:00 app[web.1]: at /app/node_modules/express/lib/ro
uter/index.js:281:22
2020-02-14T08:18:50.914542+00:00 app[web.1]: at Function.process_params (/app/no
de_modules/express/lib/router/index.js:335:12)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at next (/app/node_modules/express/
lib/router/index.js:275:10)
2020-02-14T08:18:50.914542+00:00 app[web.1]: at urlencodedParser (/app/node_modu
les/body-parser/lib/types/urlencoded.js:100:7)
2020-02-14T08:18:50.914543+00:00 app[web.1]: at Layer.handle [as handle_request]
 (/app/node_modules/express/lib/router/layer.js:95:5)

**But read the file's actual string by 'toString()' is not possible, why??**


问:
ClassNotFoundException when running JUnit test in Maven
I'm currently trying to set up automated testing for a Maven project, but I've run into a problem. When running my tests using mvn test, I get the following result:

```<code>-------------------------------------------------------------------------------
Test set: no.digipat.patornat.servlets.ServletTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.398 s <<< FAILURE! - in no.digipat.patornat.servlets.ServletTests
no.digipat.patornat.servlets.ServletTests  Time elapsed: 0.368 s  <<< ERROR!
java.lang.NoClassDefFoundError: com/mongodb/OperationExecutor
Caused by: java.lang.ClassNotFoundException: com.mongodb.OperationExecutor

</code>```

I get the same error when running the tests in Eclipse.

This is my pom.xml:

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>no.digipat.patornat</groupId>
  <artifactId>backend</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Pat or Nat Backend</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
  </properties>

  <repositories>
    <repository>
      <id>cytomine-uliege-Cytomine-java-client</id>
      <url>https://packagecloud.io/cytomine-uliege/Cytomine-java-client/maven2</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.lordofthejars</groupId>
      <artifactId>nosqlunit-mongodb</artifactId>
      <version>1.0.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.github.fakemongo</groupId>
      <artifactId>fongo</artifactId>
      <version>2.2.0-RC2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.github.stefanbirkner</groupId>
      <artifactId>system-rules</artifactId>
      <version>1.19.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>be.cytomine.client</groupId>
      <artifactId>cytomine-java-client</artifactId>
      <version>2.0.7-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.12.1</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M4</version>
        <configuration>
          <includes>
            <include>ServletTests.java</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

</code>```

The relevant Java files:

ServletTests.java:

```<code>package no.digipat.patornat.servlets;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import static com.lordofthejars.nosqlunit.mongodb.InMemoryMongoDb.InMemoryMongoRuleBuilder.newInMemoryMongoDbRule;

@RunWith(Suite.class)
@SuiteClasses({MyTest.class})
public class ServletTests {

    private static final EnvironmentVariables environmentVariables = new EnvironmentVariables();
    @ClassRule
    public static final TestRule chain = RuleChain
        .outerRule(newInMemoryMongoDbRule().build())
        .around(environmentVariables);

    @BeforeClass
    public static void setUpClass() {
        environmentVariables.set("MY_VARIABLE", "some value");
    }

}

</code>```

MyTest.java:

```<code>package no.digipat.patornat.servlets;
import static org.junit.Assert.*;

import org.junit.Test;

public class MyTest {

    @Test
    public void test() {
        fail("Not yet implemented");
    }

}

</code>```

Any ideas on how to solve this? I tried running mvn clean (which previously helped me fix a similar issue), but to no avail.

答:
I think you need the maven-compiler-plugin in your pom.xml

```<code><build>
  <!-- put here the path of your test source directory -->
  <testSourceDirectory>src/test</testSourceDirectory>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>${maven.compiler.source}</source>
        <target>${maven.compiler.target}</target>
      </configuration>
    </plugin>
  </plugins>
  ...
</code>```

Body:
I'm currently trying to set up automated testing for a Maven project, but I've run into a problem. When running my tests using mvn test, I get the following result:

-------------------------------------------------------------------------------
Test set: no.digipat.patornat.servlets.ServletTests
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.398 s <<< FAILURE! - in no.digipat.patornat.servlets.ServletTests
no.digipat.patornat.servlets.ServletTests  Time elapsed: 0.368 s  <<< ERROR!
java.lang.NoClassDefFoundError: com/mongodb/OperationExecutor
Caused by: java.lang.ClassNotFoundException: com.mongodb.OperationExecutor

I get the same error when running the tests in Eclipse.

This is my pom.xml:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>no.digipat.patornat</groupId>
  <artifactId>backend</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Pat or Nat Backend</name>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>11</maven.compiler.target>
    <maven.compiler.source>11</maven.compiler.source>
  </properties>

  <repositories>
    <repository>
      <id>cytomine-uliege-Cytomine-java-client</id>
      <url>https://packagecloud.io/cytomine-uliege/Cytomine-java-client/maven2</url>
      <releases>
        <enabled>true</enabled>
      </releases>
      <snapshots>
        <enabled>true</enabled>
      </snapshots>
    </repository>
  </repositories>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.lordofthejars</groupId>
      <artifactId>nosqlunit-mongodb</artifactId>
      <version>1.0.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.github.fakemongo</groupId>
      <artifactId>fongo</artifactId>
      <version>2.2.0-RC2</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>com.github.stefanbirkner</groupId>
      <artifactId>system-rules</artifactId>
      <version>1.19.0</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.0.1</version>
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>be.cytomine.client</groupId>
      <artifactId>cytomine-java-client</artifactId>
      <version>2.0.7-SNAPSHOT</version>
    </dependency>
    <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.12.1</version>
      <scope>compile</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M4</version>
        <configuration>
          <includes>
            <include>ServletTests.java</include>
          </includes>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>

The relevant Java files:

ServletTests.java:

package no.digipat.patornat.servlets;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.contrib.java.lang.system.EnvironmentVariables;
import org.junit.rules.RuleChain;
import org.junit.rules.TestRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

import static com.lordofthejars.nosqlunit.mongodb.InMemoryMongoDb.InMemoryMongoRuleBuilder.newInMemoryMongoDbRule;

@RunWith(Suite.class)
@SuiteClasses({MyTest.class})
public class ServletTests {

    private static final EnvironmentVariables environmentVariables = new EnvironmentVariables();
    @ClassRule
    public static final TestRule chain = RuleChain
        .outerRule(newInMemoryMongoDbRule().build())
        .around(environmentVariables);

    @BeforeClass
    public static void setUpClass() {
        environmentVariables.set("MY_VARIABLE", "some value");
    }

}

MyTest.java:

package no.digipat.patornat.servlets;
import static org.junit.Assert.*;

import org.junit.Test;

public class MyTest {

    @Test
    public void test() {
        fail("Not yet implemented");
    }

}

Any ideas on how to solve this? I tried running mvn clean (which previously helped me fix a similar issue), but to no avail.

Body:
I think you need the maven-compiler-plugin in your pom.xml

<build>
  <!-- put here the path of your test source directory -->
  <testSourceDirectory>src/test</testSourceDirectory>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>${maven.compiler.source}</source>
        <target>${maven.compiler.target}</target>
      </configuration>
    </plugin>
  </plugins>
  ...