问:
How to set initial state of glimmer component based on argument?
I am struggling to figure out how to implement data down, actions up in a glimmer component hierarchy (using Ember Octane, v3.15).

I have a parent component with a list of items. When the user clicks on a button within the Parent component, I want to populate an Editor component with the data from the relevant item; when the user clicks "Save" within the Editor component, populate the changes back to the parent. Here's what happens instead:

How can I make the text box be populated with "Hello", and have changes persisted back to the list above when I click "Save"?

Code

```<code>{{!-- app/components/parent.hbs --}}
<ul>
{{#each this.models as |model|}}
    <li>{{model.text}} <button {{on 'click' (fn this.edit model)}}>Edit</button></li>
{{/each}}
</ul>

<Editor @currentModel={{this.currentModel}} @save={{this.save}} />
</code>```

// app/components/parent.js
import Component from '@glimmer/component';
export default class ParentComponent extends Component {
    @tracked models = [
        { id: 1, text: 'Hello'},
        { id: 2, text: 'World'}
    ]
    @tracked currentModel = null;

    @action
    edit(model) {
        this.currentModel = model;
    }

    @action
    save(model) {
        // persist data
        this.models = models.map( (m) => m.id == model.id ? model : m )
    }
}
```
```{{!-- app/components/editor.hbs --}}
{{#if @currentModel}}
Editing ID: {{this.id}}
{{/if}}
<Input @value={{this.text}} />
<button {{on 'click' this.save}}>Save</button>
```
<pre class="lang-js prettyprint-override"><code>// app/components/editor.hbs
import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";

export default class EditorComponent extends Component {
    @tracked text;
    @tracked id;

    constructor() {
        super(...arguments)
        if (this.args.currentModel) {
            this.text = this.args.currentModel.text;
            this.id = this.args.currentModel.id;
        }

    }

    @action
    save() {
        // persist the updated model back to the parent
        this.args.save({ id: this.id, text: this.text })
    }
}
</code>```

Rationale/Problem

I decided to implement Editor as a stateful component, because that seemed like the most idiomatic way to get form data out of the <Input /> component. I set the initial state using args. Since this.currentModel is @tracked in ParentComponent and I would expect re-assignment of that property to update the @currentModel argument passed to Editor.

Indeed that seems to be the case, since clicking "Edit" next to one of the items in ParentComponent makes Editing ID: {{this.id}} appear. However, neither the value of the <Input /> element nor the id are populated.

I understand that this.text and this.id are not being updated because the constructor of EditorComponent is not being re-run when currentModel changes in the parent... but I'm stuck on what to do instead.

What I've tried

As I was trying to figure this out, I came across this example (code), which has pretty much the same interaction between BlogAuthorComponent (hbs) and BlogAuthorEditComponent (hbs, js). Their solution, as applied to my problem, would be to write EditorComponent like this:

```<code>{{!-- app/components/editor.hbs --}}
{{#if this.isEditing}}
<small>Editing ID: {{@currentModel.id}}</small>
<Input @value={{@currentModel.text}} />
<button {{on 'click' this.save}}>Save</button>
{{/if}}
</code>```

// app/components/editor.hbs
import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";

export default class EditorComponent extends Component {
    get isEditing() {
        return !!this.args.currentModel
    }

    @action
    save() {
        // persist the updated model back to the parent
        this.args.save({ id: this.id, text: this.text })
    }
}
```

It works! But I don't like this solution, for a few reasons:

Modifying a property of something passed to the child component as an arg seems... spooky... I'm honestly not sure why it works at all (since while ParentComponent#models is @tracked, I wouldn't expect properties of POJOs  within that array to be followed...)

This updates the text in ParentComponent as you type which, while neat, isn't what I want---I want the changes to be persisted only when the user clicks "Save" (which in this case does nothing)

In my real app, when the user is not "editing" an existing item, I'd like the form to be an "Add Item" form, where clicking the "Save" button adds a new item. I'm not sure how to do this without duplicating the form and/or doing some hairly logic as to what goes in <Input @value...

I also came across this question, but it seems to refer to an old version of glimmer.

Thank you for reading this far---I would appreciate any advice!

答:
To track changes to currentModel in your editor component and set a default value, use the get accessor:

```<code>get model() {
  return this.args.currentModel || { text: '', id: null };
}
</code>```

And in your template do:

```<code>{{#if this.model.id}}
  <small>
    Editing ID:
    {{this.model.id}}
  </small>
{{/if}}
<Input @value={{this.model.text}} />
<button type="button" {{on "click" this.save}}>
  Save
</button>
</code>```

Be aware though that this will mutate currentModel in your parent component, which I guess is not what you want. To circumvent this, create a new object from the properties of the model you're editing.

Solution:

```<code>// editor/component.js
export default class EditorComponent extends Component {
  get model() {
    return this.args.currentModel;
  }

  @action
  save() {
    this.args.save(this.model);
  }
}
</code>```

In your parent component, create a new object from the passed model. Also, remember to reset currentModel in the save action. Now you can just check whether id is null or not in your parent component's save action, and if it is, just implement your save logic:

```<code>// parent/component.js
@tracked currentModel = {};

@action
edit(model) {
  // create a new object
  this.currentModel = { ...model };
}

@action
save(model) {
  if (model.id) {
    this.models = this.models.map((m) => (m.id == model.id ? model : m));
  } else {
    // save logic
  }

  this.currentModel = {};
}
</code>```

Body:
I am struggling to figure out how to implement data down, actions up in a glimmer component hierarchy (using Ember Octane, v3.15).

I have a parent component with a list of items. When the user clicks on a button within the Parent component, I want to populate an Editor component with the data from the relevant item; when the user clicks "Save" within the Editor component, populate the changes back to the parent. Here's what happens instead:

How can I make the text box be populated with "Hello", and have changes persisted back to the list above when I click "Save"?

Code

{{!-- app/components/parent.hbs --}}

{{#each this.models as |model|}}

{{model.text}} <button {{on 'click' (fn this.edit model)}}>Edit</button>

{{/each}}

<Editor @currentModel={{this.currentModel}} @save={{this.save}} />

// app/components/parent.js
import Component from '@glimmer/component';
export default class ParentComponent extends Component {
    @tracked models = [
        { id: 1, text: 'Hello'},
        { id: 2, text: 'World'}
    ]
    @tracked currentModel = null;

    @action
    edit(model) {
        this.currentModel = model;
    }

    @action
    save(model) {
        // persist data
        this.models = models.map( (m) => m.id == model.id ? model : m )
    }
}

{{!-- app/components/editor.hbs --}}
{{#if @currentModel}}
Editing ID: {{this.id}}
{{/if}}
<Input @value={{this.text}} />
<button {{on 'click' this.save}}>Save</button>

// app/components/editor.hbs
import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";

export default class EditorComponent extends Component {
    @tracked text;
    @tracked id;

    constructor() {
        super(...arguments)
        if (this.args.currentModel) {
            this.text = this.args.currentModel.text;
            this.id = this.args.currentModel.id;
        }

    }

    @action
    save() {
        // persist the updated model back to the parent
        this.args.save({ id: this.id, text: this.text })
    }
}

Rationale/Problem

I decided to implement Editor as a stateful component, because that seemed like the most idiomatic way to get form data out of the <Input /> component. I set the initial state using args. Since this.currentModel is @tracked in ParentComponent and I would expect re-assignment of that property to update the @currentModel argument passed to Editor.

Indeed that seems to be the case, since clicking "Edit" next to one of the items in ParentComponent makes Editing ID: {{this.id}} appear. However, neither the value of the <Input /> element nor the id are populated.

I understand that this.text and this.id are not being updated because the constructor of EditorComponent is not being re-run when currentModel changes in the parent... but I'm stuck on what to do instead.

What I've tried

As I was trying to figure this out, I came across this example (code), which has pretty much the same interaction between BlogAuthorComponent (hbs) and BlogAuthorEditComponent (hbs, js). Their solution, as applied to my problem, would be to write EditorComponent like this:

{{!-- app/components/editor.hbs --}}
{{#if this.isEditing}}
Editing ID: {{@currentModel.id}}
<Input @value={{@currentModel.text}} />
<button {{on 'click' this.save}}>Save</button>
{{/if}}

// app/components/editor.hbs
import Component from '@glimmer/component';
import { tracked } from "@glimmer/tracking";
import { action } from "@ember/object";

export default class EditorComponent extends Component {
    get isEditing() {
        return !!this.args.currentModel
    }

    @action
    save() {
        // persist the updated model back to the parent
        this.args.save({ id: this.id, text: this.text })
    }
}

It works! But I don't like this solution, for a few reasons:

Modifying a property of something passed to the child component as an arg seems... spooky... I'm honestly not sure why it works at all (since while ParentComponent#models is @tracked, I wouldn't expect properties of POJOs  within that array to be followed...)

This updates the text in ParentComponent as you type which, while neat, isn't what I want---I want the changes to be persisted only when the user clicks "Save" (which in this case does nothing)

In my real app, when the user is not "editing" an existing item, I'd like the form to be an "Add Item" form, where clicking the "Save" button adds a new item. I'm not sure how to do this without duplicating the form and/or doing some hairly logic as to what goes in <Input @value...

I also came across this question, but it seems to refer to an old version of glimmer.

Thank you for reading this far---I would appreciate any advice!

Body:
To track changes to currentModel in your editor component and set a default value, use the get accessor:

get model() {
  return this.args.currentModel || { text: '', id: null };
}

And in your template do:

{{#if this.model.id}}
  <small>
    Editing ID:
    {{this.model.id}}
  </small>
{{/if}}
<Input @value={{this.model.text}} />
<button type="button" {{on "click" this.save}}>
  Save
</button>

Be aware though that this will mutate currentModel in your parent component, which I guess is not what you want. To circumvent this, create a new object from the properties of the model you're editing.

Solution:

// editor/component.js
export default class EditorComponent extends Component {
  get model() {
    return this.args.currentModel;
  }

  @action
  save() {
    this.args.save(this.model);
  }
}

In your parent component, create a new object from the passed model. Also, remember to reset currentModel in the save action. Now you can just check whether id is null or not in your parent component's save action, and if it is, just implement your save logic:

// parent/component.js
@tracked currentModel = {};

@action
edit(model) {
  // create a new object
  this.currentModel = { ...model };
}

@action
save(model) {
  if (model.id) {
    this.models = this.models.map((m) => (m.id == model.id ? model : m));
  } else {
    // save logic
  }

  this.currentModel = {};
}


来源: stackexchange

问:
TypeError: resolver is not a function
I am attempting to create a basic post on click in my NextJS app to a MongoDB database. The issue i am getting is TypeError: resolver is not a function. I understand it might be a syncronicity issue but for the life of me I cannot figure out where.

Stack used: NextJS, Axios, Mongoose.

Component code snippet calling axios:

i know the states are updating so i am putting only the snippet that handles the request

```<code>  handleSubmit = async (e: any) => {
    e.preventDefault();

    await axios
      .post('/api/roomSession', {
        roomName: this.state.roomName,
        teamName: this.state.teamName
      })
      .then((response: any) => console.log('axios call reached', response))
      .catch((error: any) => console.log('---- error! ----', error));
  };

[...]
<button onClick={this.handleSubmit}>Create</button>
[...]
</code>```

NextJS API file:

```<code>import { newSession } from '../../packages/backend/mongo/connection';

const apiNewSession = async (roomName, teamName) => {
  await newSession(teamName, roomName);
};

export default apiNewSession();
</code>```

Mongoose file:

```<code>const mongoose = require('mongoose');

mongoose
  .connect(
    'mongodbconnection',
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then(() => {
    console.log('connected to mongoDB');
  })
  .catch(err => console.error('Connection failed: ', err));

  const sessionSchema = new mongoose.Schema({
    teamName: String,
    roomName: String
  });

const Session = mongoose.model.tests || mongoose.model('tests', sessionSchema);

export const newSession = async (teamName, roomName) => {
  const session = new Session({
    teamName,
    roomName
  });
  const result = await session.save();
  mongoose.connection.close();
};
</code>```

Some extra info on the strange behaviour: When first time called, the code throws the aformentioned error but manages to reach the mongoDB connection and creates an EMPTY entry inside the collection (only _id, and _v).
Upon second attempt, only the error is thrown.

答:
I was exporting the function incorrectly from the NextJS API file.

Correct method:
export default apiNewSession;

Not sure why it still happened when when i was exporting the function by default.

ContentLicense: CC BY-SA 4.0

Title: TypeError: resolver is not a function

Body:
I am attempting to create a basic post on click in my NextJS app to a MongoDB database. The issue i am getting is TypeError: resolver is not a function. I understand it might be a syncronicity issue but for the life of me I cannot figure out where.

Stack used: NextJS, Axios, Mongoose.

Component code snippet calling axios:

i know the states are updating so i am putting only the snippet that handles the request

  handleSubmit = async (e: any) => {
    e.preventDefault();

    await axios
      .post('/api/roomSession', {
        roomName: this.state.roomName,
        teamName: this.state.teamName
      })
      .then((response: any) => console.log('axios call reached', response))
      .catch((error: any) => console.log('---- error! ----', error));
  };

[...]
<button onClick={this.handleSubmit}>Create</button>
[...]

NextJS API file:

import { newSession } from '../../packages/backend/mongo/connection';

const apiNewSession = async (roomName, teamName) => {
  await newSession(teamName, roomName);
};

export default apiNewSession();

Mongoose file:

const mongoose = require('mongoose');

mongoose
  .connect(
    'mongodbconnection',
    { useNewUrlParser: true, useUnifiedTopology: true }
  )
  .then(() => {
    console.log('connected to mongoDB');
  })
  .catch(err => console.error('Connection failed: ', err));

  const sessionSchema = new mongoose.Schema({
    teamName: String,
    roomName: String
  });

const Session = mongoose.model.tests || mongoose.model('tests', sessionSchema);

export const newSession = async (teamName, roomName) => {
  const session = new Session({
    teamName,
    roomName
  });
  const result = await session.save();
  mongoose.connection.close();
};

Some extra info on the strange behaviour: When first time called, the code throws the aformentioned error but manages to reach the mongoDB connection and creates an EMPTY entry inside the collection (only _id, and _v).
Upon second attempt, only the error is thrown.


问:
Convert a single data frame into list of data frames (parsing column names into prefixes and suffixes)
I am hoping to determine an efficient way to convert a single data frame into a list of data frames. Below is my reproducible MWE:

```<code>set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)
</code>```

This results in a data frame format (dfFormat) that looks like this:

```<code>'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...
</code>```

and a list of data frames listFormat that looks like this:

```<code>List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...
</code>```

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

The column ID is always the first column in dfFormat and it is always the first column in each sublist of listFormat.

The number of sublists is equal to the number of unique column names in dfFormat before the underscore ('_'). In this case, that is three prefixes (ex. "A_B", "A_C", and "B_C"). These prefixes are also the names of the three sublists.

Within each sublist, it contains the number of columns that had the associated prefix ("A_B"). For each sublist, this was two ("Age" and "Points"). These suffixes are the names of the columns.

I asked the reverse question here (i.e. how to go from listFormat to dfFormat) and got some helpful answers that I am learning from. I need to have code to reverse both directions and it seems the reverse direction may need new types of code. I put my attempt below to show how I am stuck!

```<code>conUnd <- which(sapply(colnames(dfFormat), function(x) grepl("_", x)))
listName <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1])
uListName <- unique(sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1]))
listCol <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][2])

listFormat = list()
for (i in 1:length(uListName)){
   [Gets messy here trying to define column names based on string variables]
}
</code>```

Any advice would be greatly appreciated. I know my code is not efficient.

Body:
I am hoping to determine an efficient way to convert a single data frame into a list of data frames. Below is my reproducible MWE:

set.seed(1)
ABAge = runif(100)
ABPoints = rnorm(100)
ACAge = runif(100)
ACPoints = rnorm(100)
BCAge = runif(100)
BCPoints = rnorm(100)

A_B <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ABAge, Points = ABPoints)
A_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = ACAge, Points = ACPoints)
B_C <- data.frame(ID = as.character(paste0("ID", 1:100)), Age = BCAge, Points = BCPoints)
A_B$ID <- as.character(A_B$ID)
A_C$ID <- as.character(A_C$ID)
B_C$ID <- as.character(B_C$ID)

listFormat <- list("A_B" = A_B, "A_C" = A_C, "B_C" = B_C)

dfFormat <- data.frame(ID = as.character(paste0("ID", 1:100)), A_B.Age = ABAge, A_B.Points = ABPoints, A_C.Age = ACAge, A_C.Points = ACPoints, B_C.Age = BCAge, B_C.Points = BCPoints)
dfFormat$ID = as.character(dfFormat$ID)

This results in a data frame format (dfFormat) that looks like this:

'data.frame':   100 obs. of  7 variables:
 $ ID        : chr  "ID1" "ID2" "ID3" "ID4" ...
 $ A_B.Age   : num  0.266 0.372 0.573 0.908 0.202 ...
 $ A_B.Points: num  0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C.Age   : num  0.6737 0.0949 0.4926 0.4616 0.3752 ...
 $ A_C.Points: num  0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C.Age   : num  0.814 0.929 0.147 0.75 0.976 ...
 $ B_C.Points: num  1.474 0.677 0.38 -0.193 1.578 ...

and a list of data frames listFormat that looks like this:

List of 3
 $ A_B:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
 $ A_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
 $ B_C:'data.frame':    100 obs. of  3 variables:
  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...

I am hoping to come up with an automated way to convert the dfFormat to listFormat. As can be seen in the above objects there are two main conditions:

The column ID is always the first column in dfFormat and it is always the first column in each sublist of listFormat.

The number of sublists is equal to the number of unique column names in dfFormat before the underscore ('_'). In this case, that is three prefixes (ex. "A_B", "A_C", and "B_C"). These prefixes are also the names of the three sublists.

Within each sublist, it contains the number of columns that had the associated prefix ("A_B"). For each sublist, this was two ("Age" and "Points"). These suffixes are the names of the columns.

I asked the reverse question here (i.e. how to go from listFormat to dfFormat) and got some helpful answers that I am learning from. I need to have code to reverse both directions and it seems the reverse direction may need new types of code. I put my attempt below to show how I am stuck!

conUnd <- which(sapply(colnames(dfFormat), function(x) grepl("_", x)))
listName <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1])
uListName <- unique(sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][1]))
listCol <- sapply(colnames(dfFormat[,conUnd]), function(x) strsplit(x, "[.]")[[1]][2])

listFormat = list()
for (i in 1:length(uListName)){
   [Gets messy here trying to define column names based on string variables]
}

Any advice would be greatly appreciated. I know my code is not efficient.

Body:
You can use split.default in base R -

output <- lapply(split.default(dfFormat[-1], sub("\\..*", "",names(dfFormat[-1]))),
          function(x) cbind(dfFormat[1], setNames(x, sub(".*\\.", "", names(x)))))
str(output)

#List of 3
# $ A_B:'data.frame':   100 obs. of  3 variables:
#  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
#  ..$ Age   : num [1:100] 0.266 0.372 0.573 0.908 0.202 ...
#  ..$ Points: num [1:100] 0.398 -0.612 0.341 -1.129 1.433 ...
# $ A_C:'data.frame':   100 obs. of  3 variables:
#  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
#  ..$ Age   : num [1:100] 0.6737 0.0949 0.4926 0.4616 0.3752 ...
#  ..$ Points: num [1:100] 0.409 1.689 1.587 -0.331 -2.285 ...
# $ B_C:'data.frame':   100 obs. of  3 variables:
#  ..$ ID    : chr [1:100] "ID1" "ID2" "ID3" "ID4" ...
#  ..$ Age   : num [1:100] 0.814 0.929 0.147 0.75 0.976 ...
#  ..$ Points: num [1:100] 1.474 0.677 0.38 -0.193 1.578 ...


问:
Two classes one with reference to function to another different this value
I have problem and I don't know how to solve it:

```<code>        this.bWords.push(word);
                    ^
</code>```

TypeError: Cannot read property 'push' of undefined

here is my code:

```<code>function multiWords(words) {
    class AWords {
        constructor(words = []) {
            this.words = words;
            this.addWordFn = () => {};
        }

        setAddWordFn(fn) {
            this.addWordFn = fn;
        }

        passWords() {
            this.words.forEach(word => this.addWordFn(word));
        }
    }

    class BWords {
        constructor() {
            this.bWords = [];
        }

        addWord(word) {
            this.bWords.push(word);
        }
    }

    let x = new AWords(words);
    let y = new BWords();

    x.setAddWordFn(y.addWord);
    x.passWords();

    return y.bWords;
}

console.log(multiWords(["one", "two", "three"]));
</code>```

Do you have any ideas why there is different this value?
Many thanks
Pati

答:
It appears that the problem occurs here:

```<code>this.words.forEach(word => this.addWordFn(word));
</code>```

because the function you've set for addWordFn here:

```<code>x.setAddWordFn(y.addWord);
</code>```

Needs a different value of this than you are calling it with.  You can fix it by binding the right value of this to your callback:

```<code>x.setAddWordFn(y.addWord.bind(y));
</code>```

Remember that for regular functions, the value of this inside the function is determined by how the function is called.  When you call a function with obj.method(), the this value inside of method() will be set to obj.  So, you're calling addWord with the wrong this value because you've made it a method of some other object (that does not also have the data it needs) and are calling it off that object.

Body:
I have problem and I don't know how to solve it:

        this.bWords.push(word);
                    ^

TypeError: Cannot read property 'push' of undefined

here is my code:

function multiWords(words) {
    class AWords {
        constructor(words = []) {
            this.words = words;
            this.addWordFn = () => {};
        }

        setAddWordFn(fn) {
            this.addWordFn = fn;
        }

        passWords() {
            this.words.forEach(word => this.addWordFn(word));
        }
    }

    class BWords {
        constructor() {
            this.bWords = [];
        }

        addWord(word) {
            this.bWords.push(word);
        }
    }

    let x = new AWords(words);
    let y = new BWords();

    x.setAddWordFn(y.addWord);
    x.passWords();

    return y.bWords;
}

console.log(multiWords(["one", "two", "three"]));

Do you have any ideas why there is different this value?
Many thanks
Pati

Body:
It appears that the problem occurs here:

this.words.forEach(word => this.addWordFn(word));

because the function you've set for addWordFn here:

x.setAddWordFn(y.addWord);

Needs a different value of this than you are calling it with.  You can fix it by binding the right value of this to your callback:

x.setAddWordFn(y.addWord.bind(y));

Remember that for regular functions, the value of this inside the function is determined by how the function is called.  When you call a function with obj.method(), the this value inside of method() will be set to obj.  So, you're calling addWord with the wrong this value because you've made it a method of some other object (that does not also have the data it needs) and are calling it off that object.


问:
Wake up Azure Function
I have an existing Azure Function that is on a consumption plan

I am writing another function which will call this

Once the existing function is running, it processes files in storage account.

In order the files in my storage account to be processed, we have to manually go into the portal and "wake up" the function by navigating

Is there a way to do this via C# code?

This function is hosted on a consumption based plan

答:
In serverless computing, Azure functions get executed/spin up whenever you make an invoke, if you want to call another function inside a function you can  do via HTTP call.

Durable Functions lets you write stateful functions in a serverless environment. There's nothing built-in in Function Apps to call one HTTP function from other functions without actually making the HTTP call paticularly Function Chaining.

Title: Wake up Azure Function


问:
Does Ada have any idiomatic rules on when to use a function versus a procedure with an output parameter?
You can assign to a variable by having a function return a value to it:

My_Int : Integer := My_Math_Func [(optional params)];

Or you can do it like this with a procedure (assuming My_Int has already been declared):

My_Math_Proc ([optional params;] [in] out My_Int);

Obviously a procedure can't initialize a variable like the function does in the first example, but I'm hoping for some concrete, practical rules on when and why to pick one over the other.

答:
Brian Drummond already answered your question directly, but I wanted to add some additional info:  If your type has some sort of initializing procedure, in Ada2005/Ada2012 you can convert it to an initializing function using extended return syntax.  It will even work for limited types.

Say you have a package with a type like this:

package Example is

    type My_Type is limited private;

    procedure Initialize(Self : in out My_Type; Value : Integer);
    procedure Print(Self : My_Type);

private

    type My_Type is limited record
        Value : Integer := 0;
    end record;

end Example;

package body Example is
    procedure Initialize(Self : in out My_Type; Value : Integer) is
    begin
        Self.Value := Value;
    end Initialize;

    procedure Print(Self : My_Type) is
    begin
        Ada.Text_IO.Put_Line(Self.Value'Image);
    end Print;
end Example;
```

<p>You can then make your own initializing function out of that procedure doing something like this:</p>

<pre class="lang-ada prettyprint-override"><code>function Make_My_Type (Value : Integer) return Example.My_Type is
begin
    return Result : Example.My_Type do
        Example.Initialize(Result,Value);
    end return;
end Make_My_Type;
</code>```

and you can initialize variables easily using the procedure hidden in your function underneath:

procedure Test
   Thing : Example.My_Type := Make_My_Type(21);
begin
   Example.Print(Thing);
end Test;
```

This is different than just making a variable and returning it.  You are not able to do that with a limited type, but with extended return syntax, you can do it for any type.

Here is some additional info for extended return statements as well.

Body:
Brian Drummond already answered your question directly, but I wanted to add some additional info:  If your type has some sort of initializing procedure, in Ada2005/Ada2012 you can convert it to an initializing function using extended return syntax.  It will even work for limited types.

Say you have a package with a type like this:

package Example is

    type My_Type is limited private;

    procedure Initialize(Self : in out My_Type; Value : Integer);
    procedure Print(Self : My_Type);

private

    type My_Type is limited record
        Value : Integer := 0;
    end record;

end Example;

package body Example is
    procedure Initialize(Self : in out My_Type; Value : Integer) is
    begin
        Self.Value := Value;
    end Initialize;

    procedure Print(Self : My_Type) is
    begin
        Ada.Text_IO.Put_Line(Self.Value'Image);
    end Print;
end Example;

You can then make your own initializing function out of that procedure doing something like this:

function Make_My_Type (Value : Integer) return Example.My_Type is
begin
    return Result : Example.My_Type do
        Example.Initialize(Result,Value);
    end return;
end Make_My_Type;

and you can initialize variables easily using the procedure hidden in your function underneath:

procedure Test
   Thing : Example.My_Type := Make_My_Type(21);
begin
   Example.Print(Thing);
end Test;

This is different than just making a variable and returning it.  You are not able to do that with a limited type, but with extended return syntax, you can do it for any type.

Here is some additional info for extended return statements as well.


问:
Angular2 - Focusing a textbox on component load
I am developing a component in Angular2 (Beta 8). The component has a textbox and a dropdown. I would like to set the focus in textbox as soon as component is loaded or on change event of dropdown. How would I achieve this in angular2. Following is Html for the component.

    <form role="form" class="form-horizontal ">

                Name

                    <input id="name" type="text" [(ngModel)]="person.Name" class="form-control" />

                    <input type="button" value="Add" (click)="AddPerson()" class="btn btn-primary" />

                Person

                    <select [(ngModel)]="SelectedPerson.Id"  (change)="PersonSelected($event.target.value)" class="form-control">
                        <option *ngFor="#item of PeopleList" value="{{item.Id}}">{{item.Name}}</option>
                    </select>

    </form>

```

答:
Directive for autoFocus first field

import {
  Directive,
  ElementRef,
  AfterViewInit
} from "@angular/core";

@Directive({
  selector: "[appFocusFirstEmptyInput]"
})
export class FocusFirstEmptyInputDirective implements AfterViewInit {
  constructor(private el: ElementRef) {}
  ngAfterViewInit(): void {
    const invalidControl = this.el.nativeElement.querySelector(".ng-untouched");
    if (invalidControl) {
      invalidControl.focus();
    }
  }
}```

ContentLicense: CC BY-SA 3.0


问:
Building MLPack from C++ source using CMake: is Julia required?
I am trying to build MLPack from its C++ source using CMake, and for some reason it is complaining that it can't find Julia.

CMake Error at /usr/local/Cellar/cmake/3.14.5/share/cmake/Modules/FindPackageHandleStandardArgs.cmake:137 (message):
  Julia not found (missing: JULIA_EXECUTABLE) (Required is at least version
  "0.7.0")

Has anyone encountered a similar issue? On the MLPack build instructions, there is no mention of Julia being a required package.

Thanks,
Amine

答:
MLPack has Julia bindings that are set to build by default (see the CMake source). The CMake option is shown on the main GitHub README page. You can disable the Julia bindings build using the BUILD_JULIA_BINDINGS variable:

```<code>cmake -DBUILD_JULIA_BINDINGS=OFF ..
</code>```

Body:
MLPack has Julia bindings that are set to build by default (see the CMake source). The CMake option is shown on the main GitHub README page. You can disable the Julia bindings build using the BUILD_JULIA_BINDINGS variable:

cmake -DBUILD_JULIA_BINDINGS=OFF ..


问:
How do you load .js files with ASP.NET?
```<code><%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
  <script runat="server">

Sub Page_Load(ByVal e As System.EventArgs)
Page.ClientScript.RegisterClientScriptInclude("basicjs", "basic.js")
End Sub

</script>
    <title>RegisterClientScriptBlock Example</title>
  </head>
  <body>
<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>
  </body>
</html>
</code>```

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?

答:
JavaScript is a client-side script language. It's not something your server should execute; the client should.

ASP is a server-side language that generates some output that's presented to the user. Therefore, it cannot be ASP's responsibility to execute a JavaScript.

Instead, you should just include the JavaScript in your HTML, thus telling the client to execute it.

```<code><script type="text/javascript" src="basic.js"></script>
</code>```

Title: How do you load .js files with ASP.NET?

Body:
<%@ Page Language="VB"  %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>RegisterClientScriptBlock Example</title>

<form runat="server">
    <input type="button" id="button1" value="clickme" onclick="click()"/>
</form>

I'm using ASP.net (just learning) with VB. I can't seem to get Javascript code to work with ASP VB code. My main problem seems to be that .js files are not loading. In the example, basic.js just contains a function click() that calls an alert() message. How do I get .js files to load with ASP code?

Body:
JavaScript is a client-side script language. It's not something your server should execute; the client should.

ASP is a server-side language that generates some output that's presented to the user. Therefore, it cannot be ASP's responsibility to execute a JavaScript.

Instead, you should just include the JavaScript in your HTML, thus telling the client to execute it.

<script type="text/javascript" src="basic.js"></script>


问:
Shortest path in a complete weighted undirected graph with a known start node and visiting all nodes without returning to start node
I have a complete undirected graph of locations (nodes), where each edge represents the distance between its connected nodes, and I want to find the shortest path starting from a start node without specifying the end node so basically it can end at any node other then the first one.

I looked through TSP problem and shortest Hamiltonian path but I couldn't find the exact response to my problem .

So what this problem is exactly called or what variant of shortest path problems it is?

This is an exemple of what I am looking for. Lets have a complete weighted graph as follows:

Each edge represents the distance between two locations for exemple edge AB=5, AC=11......

My goal is to start from node A, and find the shortest path that covers all nodes (shortest possible path) and the end point can be any one other than A. For exemple this path that ends at E:

答:
This is a slight variation of a special case of The Traveling Salesman Path Problem. In The Traveling Salesman Path Problem, you're given an undirected graph, a cost function on the edges, and two vertices s and t. The problem is to find a Hamiltonian Path (that is, a path that visits each vertex exactly once) from s to t.

Your problem is the special case in which the input graph is a clique and the destination vertex t is an extra dummy vertex, connected to all other vertices by a 0-cost edge. Clearly, a solution to The Traveling Salesman Path Problem for the graph (with the extra dummy vertex t) induces a solution to your problem, obtained by simply ignoring the final extra step to the destination t.

Unfortunately, just like the famous Traveling Salesman Problem, The Traveling Salesman Path Problem is not only NP-hard, but also NP-hard to approximate to within any constant factor. However, since your costs represent distances, maybe you could assume that the cost function satisfies The Triangle Inequality?

If the cost function satisfies The Triangle Inequality, then there exists a recent 1.5-approximation algorithm. If this recent algorithm is an overkill, you can implement one of two simpler algorithms that are nicely described in lecture notes by Professor Ryan O’Donnell from CMU, and settle for either a 2-approximation or a 5/3-approximation.


问:
Cannot open Database file
I have an application that creates a database file at '/storage/emulated/0/databases/mydb.db' and there are files within this DB.
I have another application which tries to open this database. But I get error code 14. Could not open database when trying to oprn the table in this db.

```<code>public class DataBaseHelper extends SQLiteOpenHelper {

public SQLiteDatabase myDataBase;
public String TABLE_NAME;
// Database Information
static final String DB_NAME = "mydb.DB";
public static final String FILE_DIR = "databases";
private String DB_PATH = Environment.getExternalStorageDirectory()
        + File.separator + FILE_DIR + File.separator + DB_NAME;

public DataBaseHelper(Context context, String name) {
    super(context, name, null, 1);
    TABLE_NAME = name;
}

public void openDatabase() throws SQLiteException {
    String DBPath = DB_PATH + "/" +TABLE_NAME;
    myDataBase = SQLiteDatabase.openDatabase(DBPath,null,SQLiteDatabase.OPEN_READWRITE);
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}
</code>```

I get an error at myDataBase = SQLiteDatabase.openDatabase(DBPath,null,SQLiteDatabase.OPEN_READWRITE);

答:
Another thing to note is Environment.getExternalStorageDirectory() has been deprecated in API 29:

https://developer.android.com/reference/android/os/Environment#getExternalStorageDirectory()

This method was deprecated in API level 29.

To improve user privacy, direct access to shared/external storage devices is deprecated. When an app targets Build.VERSION_CODES.Q, the path returned from this method is no longer directly accessible to apps. Apps can continue to access content stored on shared/external storage by migrating to alternatives such as Context#getExternalFilesDir(String), MediaStore, or Intent#ACTION_OPEN_DOCUMENT.

Title: Cannot open Database file

Body:
I have an application that creates a database file at '/storage/emulated/0/databases/mydb.db' and there are files within this DB.
I have another application which tries to open this database. But I get error code 14. Could not open database when trying to oprn the table in this db.

public class DataBaseHelper extends SQLiteOpenHelper {

public SQLiteDatabase myDataBase;
public String TABLE_NAME;
// Database Information
static final String DB_NAME = "mydb.DB";
public static final String FILE_DIR = "databases";
private String DB_PATH = Environment.getExternalStorageDirectory()
        + File.separator + FILE_DIR + File.separator + DB_NAME;

public DataBaseHelper(Context context, String name) {
    super(context, name, null, 1);
    TABLE_NAME = name;
}

public void openDatabase() throws SQLiteException {
    String DBPath = DB_PATH + "/" +TABLE_NAME;
    myDataBase = SQLiteDatabase.openDatabase(DBPath,null,SQLiteDatabase.OPEN_READWRITE);
}

@Override
public void onCreate(SQLiteDatabase db) {

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

I get an error at myDataBase = SQLiteDatabase.openDatabase(DBPath,null,SQLiteDatabase.OPEN_READWRITE);


问:
SVG background - fixed height
I have a question to the SVG format. I created the background as you can see in the attached screenshot.

When I have a screen resolution over 920px its fine.
But when I check the responsive views, the blue svg image decreases the height value by deacreasing the windows.

My goal is, to keep the wave structure and the height, because there should be a logo on top of the background.
But when I decrease the window the logo is no longer in the blue wave.

A fixed height in the svg data is also bad, because we don't keep the complete wave structure.

How is it possible?

Do I need a parent div with background-position: cover?

Code:

```<code><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#230A59" fill-opacity="1" d="M0,288L48,272C96,256,192,224,288,192C384,160,480,128,576,133.3C672,139,768,181,864,192C960,203,1056,181,1152,165.3C1248,149,1344,139,1392,133.3L1440,128L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>'
</code>```

Title: SVG background - fixed height

Body:
I have a question to the SVG format. I created the background as you can see in the attached screenshot.

When I have a screen resolution over 920px its fine.
But when I check the responsive views, the blue svg image decreases the height value by deacreasing the windows.

My goal is, to keep the wave structure and the height, because there should be a logo on top of the background.
But when I decrease the window the logo is no longer in the blue wave.

A fixed height in the svg data is also bad, because we don't keep the complete wave structure.

How is it possible?

Do I need a parent div with background-position: cover?

Code:

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#230A59" fill-opacity="1" d="M0,288L48,272C96,256,192,224,288,192C384,160,480,128,576,133.3C672,139,768,181,864,192C960,203,1056,181,1152,165.3C1248,149,1344,139,1392,133.3L1440,128L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>'

Body:
What you are asking for is impossible.  You can't keep the aspect ratio, the complete wave structure, and the height.  The best you can do is two out of three of those things.

Aspect ratio + complete wave

svg {
  background-color: #fd490d;
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320"><path fill="#230A59" fill-opacity="1" d="M0,288L48,272C96,256,192,224,288,192C384,160,480,128,576,133.3C672,139,768,181,864,192C960,203,1056,181,1152,165.3C1248,149,1344,139,1392,133.3L1440,128L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>

Aspect ratio + height

svg {
  background-color: #fd490d;
  width: 100%;
  height: 320px;
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320" preserveAspectRatio="xMidYMid slice"><path fill="#230A59" fill-opacity="1" d="M0,288L48,272C96,256,192,224,288,192C384,160,480,128,576,133.3C672,139,768,181,864,192C960,203,1056,181,1152,165.3C1248,149,1344,139,1392,133.3L1440,128L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>

Complete wave + height

svg {
  background-color: #fd490d;
  width: 100%;
  height: 320px;
}

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 320" preserveAspectRatio="none"><path fill="#230A59" fill-opacity="1" d="M0,288L48,272C96,256,192,224,288,192C384,160,480,128,576,133.3C672,139,768,181,864,192C960,203,1056,181,1152,165.3C1248,149,1344,139,1392,133.3L1440,128L1440,0L1392,0C1344,0,1248,0,1152,0C1056,0,960,0,864,0C768,0,672,0,576,0C480,0,384,0,288,0C192,0,96,0,48,0L0,0Z"></path></svg>


问:
How to initialize the starting point of a background image in css?
I want to add a background image to my web page. The image that I want to use has around 20% transparent padding on all four sides. What attribute should I use so that the background image has an edge-to-edge fit (avoiding the transparent part)? </p>

```<code>body{
    background-image: url("bg.png");
    background-size: 90%;
    background-repeat: no-repeat;
}

</code>```

答:
For something like this, I prefer to add a container element to the page and avoid using body for background images when I need to exercise finite control over display and positioning. This would be my solution:

JSFiddle

Markup

```<code><body>
  <div class="container">
    <div class="media"></div>
  </div>
</body>
</code>```

SCSS

```<code>body {
  padding: 0;
  margin: 0;
}
.container {
  position: absolute;
  width: 100%;
  height: 100%;
  .media {
    width: 100%;
    height: 100%;
    transform: scale(1.4);
    background: {
      image: url("https://i.ytimg.com/vi/cYNlJYQI3Uw/maxresdefault.jpg");
      position: center center;
      size: cover;
      repeat: no-repeat;
    }
  }
}
</code>```

Notice that I use a CSS reset to remove automatic margin/padding on the body element, and that I allow body to fill the entire viewport.

The container class fills the body element with width and height set to 100%. I use the CSS background-size property to cover the container, then I use the transform property to scale container.

There are many ways to achieve this effect. Alternately, using a background-image property on the body tag will allow me to use background-size to scale the image to obfuscate the image's transparent padding as you described, but it is more difficult to center the image within the container.

Body:
I want to add a background image to my web page. The image that I want to use has around 20% transparent padding on all four sides. What attribute should I use so that the background image has an edge-to-edge fit (avoiding the transparent part)?

body{
    background-image: url("bg.png");
    background-size: 90%;
    background-repeat: no-repeat;
}

Body:
For something like this, I prefer to add a container element to the page and avoid using body for background images when I need to exercise finite control over display and positioning. This would be my solution:

JSFiddle

Markup

<body>
  <div class="container">
    <div class="media"></div>
  </div>
</body>

SCSS

body {
  padding: 0;
  margin: 0;
}
.container {
  position: absolute;
  width: 100%;
  height: 100%;
  .media {
    width: 100%;
    height: 100%;
    transform: scale(1.4);
    background: {
      image: url("https://i.ytimg.com/vi/cYNlJYQI3Uw/maxresdefault.jpg");
      position: center center;
      size: cover;
      repeat: no-repeat;
    }
  }
}

Notice that I use a CSS reset to remove automatic margin/padding on the body element, and that I allow body to fill the entire viewport.

The container class fills the body element with width and height set to 100%. I use the CSS background-size property to cover the container, then I use the transform property to scale container.

There are many ways to achieve this effect. Alternately, using a background-image property on the body tag will allow me to use background-size to scale the image to obfuscate the image's transparent padding as you described, but it is more difficult to center the image within the container.


问:
powershell function switch param with string array
I'm struggling to understand the outputs of the below function

```<code>function testApp
{
    param(
        [string] $appName,
        [switch] $sw = $false,
        [string[]] $test,
        [string[]] $test2
    )

    Write-Host $appName - $sw - $test - $test2
}
</code>```

testApp -appName "TestApp" -sw $true -test "one", "two" -test2 "three","four"

Output: TestApp - True - one two - three four

testApp -appName "TestApp" -sw $true -test "one", "two"

Output: TestApp - True - one two - True

The first output is as expected. But I cannot understand why the second output has "True" for the test2 array when I did not pass it. Can anyone help me in understanding the reason for the behavior? Thanks.

答:
To summarize and complement the helpful comments on the question by Lee_Dailey, Matthew and mclayton:

[switch] parameters in PowerShell (aka flags in other shells):

switch parameters are meant to imply $true vs. $false by their presence in an invocation: e.g., passing -sw by itself signals $true, whereas omitting -sw signals $false.

It is possible to pass a Boolean value explicitly, for the purpose of passing a programmatically determined value; e.g.: -sw:$var

Note the required : following the switch name, which tells PowerShell that the Boolean value belongs to the switch parameter; without it, PowerShell thinks the value is a positional argument meant for a different parameter (see below).

Caveat: Commands may interpret -sw:$false differently from omitting -sw; a prominent example is is the use of common parameter -Confirm:$false to override the effective $ConfirmPreference value.

If you need to make this distinction in your own code, use $PSBoundParameters.ContainsKey('sw') -and -not $sw to detect the -sw:$false case.

Do not assign a default value to a switch parameter variable: while technically possible, the convention is that switches default to $false (which is a [switch] instance's default value anyway); that is, a [switch] parameter should always have opt-in logic.

A [switch] parameter variable effectively behaves like a Boolean value in most contexts:

That is, you can say if ($sw) { ... }, for instance.

If you need to access the wrapped Boolean value explicitly, access the .IsPresent property (note that the property name is somewhat confusing, because in a -sw:$false invocation the switch is still present, but its value, as reflected in .IsPresent, is $false).

An example of where .IsPresent is needed is the use of a Boolean as an implicit array index, notably to emulate a ternary conditional[1]: ('falseValue', 'trueValue')[$sw.IsPresent]; without the .IsPresent, the effective Boolean value wouldn't be recognized as such and wouldn't automatically be mapped to index 0 (from $false) or 1 (from $true).

Ultimately, your problem was that you thought $true was an argument for -sw, whereas it became a positional argument implicitly bound to the -test2 parameter.

[switch] parameters never need a value, so the next argument becomes a separate, positional argument - unless you explicitly indicate that the argument belongs to the switch by following the switch name with :, as shown above.[2]

Positional vs. named argument passing in PowerShell:

Terminology note: For conceptual clarity the term argument is used to refer to a value passed to a declared parameter. This avoids the ambiguity of using parameter situationally to either refer to the language construct that receives a value vs. a given value.

Named argument passing (binding) refers to explicitly placing the target parameter name before the argument (typically separated by a space, but alternatively also and / or by :); e.g., -AppName foo.

The order in which named arguments are passed never matters.

Positional (unnamed) argument passing refers to passing an argument without preceding it by the name of its target parameter; e.g., foo.

The passing is positional in the sense that the relative position (order) among other unnamed arguments determines what target parameter is implied.

[switch] parameters are the exception in that they:

are typically passed by name only (-sw), implying value $true, and if a value is passed, require : to separate the name from the value.

never support positional binding.

You may combine named passing with positional passing, in which case the named arguments are bound first, after which the positional ones are then considered (in order) for binding to the not-yet-bound parameters.

PowerShell functions are simple functions by default. In order to exercise control over positional binding, use of the [CmdletBinding()] and / or [Parameter()] attributes is necessary (see below), which invariably turn a simple function into an advanced function.

Making a simple function an advanced one has larger behavioral implications (mostly beneficial ones), which are detailed in this answer.

By default, PowerShell functions accept positional arguments for any parameter (other than those of type [switch]), in the order in which the parameters were declared.

Additionally, simple functions accept arbitrary additional arguments for which no parameters were declared, which are collected in the automatic $args array variable.

To prevent your function from accepting any positional arguments by default, place a [CmdletBinding(PositionalBinding=$false, ...)] attribute above the param(...) block.

Since this makes your function an advanced one, this also disables passing arbitrary additional arguments ($args no longer applies and isn't populated).

As an aside: when you implement a cmdlet (a command implemented as a binary, typically via C#), this behavior is implied.

To selectively support positional arguments, decorate individual parameter declarations with a [Parameter(Position=<n>, ...)] attribute (e.g, [Parameter(Position=0)] [string] $Path)

Note: Whether you start your numbering with 0 or 1 doesn't matter, as long as the numbers used reflect the desired ordering among all positional parameters; 0 is advisable as a self-documenting convention, because it is unambiguous.

Attribute [Parameter(Position=<n>)] is an explicit opt-in that selectively overrides [CmdletBinding(PositionalBinding=$false)]: that is, the latter disables positional binding unless explicitly indicated by individual parameter declarations; in fact, the latter is implied by the former, in that once you use one [Parameter(Position=<n>)] attribute, you must use it on all other parameters you want to bind positionally as well.

[1] Note that PowerShell [Core] 7.0+ supports ternary conditionals natively: $sw ? 'trueValue' : 'falseValue'

[2] In effect, [switch] parameters are the only type for which PowerShell supports an optional argument. See this answer for more information.

Body:
I'm struggling to understand the outputs of the below function

function testApp
{
    param(
        [string] $appName,
        [switch] $sw = $false,
        [string[]] $test,
        [string[]] $test2
    )

    Write-Host $appName - $sw - $test - $test2
}

testApp -appName "TestApp" -sw $true -test "one", "two" -test2 "three","four"

Output: TestApp - True - one two - three four

testApp -appName "TestApp" -sw $true -test "one", "two"

Output: TestApp - True - one two - True

The first output is as expected. But I cannot understand why the second output has "True" for the test2 array when I did not pass it. Can anyone help me in understanding the reason for the behavior? Thanks.


答:
A solution using the tidyverse. It involves converting the data frame to long format, split the columns, spread it, ans the split the data frame based on the group name. In the last line, as.data.frame(stringsAsFactors = FALSE) is not necessary as tibble is also a data frame. I added it so that I can show you the output is the same as your expected list.

```<code>library(tidyverse)

listFormat_output <- dfFormat %>%
  pivot_longer(cols = -ID, names_to = "Type") %>%
  separate(Type, into = c("Group", "Parameter"), sep = "\\.") %>%
  pivot_wider(names_from = Parameter) %>%
  group_split(Group) %>%
  setNames(nm = map_chr(., ~unique(.x$Group))) %>%
  map(~.x %>% select(-Group) %>% as.data.frame(stringsAsFactors = FALSE))

# Check if the output is the same as the expected list
identical(listFormat, listFormat_output)
# [1] TRUE
</code>```

Title: Convert a single data frame into list of data frames (parsing column names into prefixes and suffixes)

Body:
A solution using the tidyverse. It involves converting the data frame to long format, split the columns, spread it, ans the split the data frame based on the group name. In the last line, as.data.frame(stringsAsFactors = FALSE) is not necessary as tibble is also a data frame. I added it so that I can show you the output is the same as your expected list.

library(tidyverse)

listFormat_output <- dfFormat %>%
  pivot_longer(cols = -ID, names_to = "Type") %>%
  separate(Type, into = c("Group", "Parameter"), sep = "\\.") %>%
  pivot_wider(names_from = Parameter) %>%
  group_split(Group) %>%
  setNames(nm = map_chr(., ~unique(.x$Group))) %>%
  map(~.x %>% select(-Group) %>% as.data.frame(stringsAsFactors = FALSE))

# Check if the output is the same as the expected list
identical(listFormat, listFormat_output)
# [1] TRUE


问:
pull a remote repo and pushing those files
We're working on a big project here at work with feature "bundles" (EDIT: "bundle" is just a term we use internally to refer to a specific functionality package, and isn't meant as a git term) spread out into several different git repositories. I'm getting ready to send a batch of changes upstream for review and testing, but I've run into a snag trying to get everything to play together nicely.

What I've done so far is clone from the repo containing the code bundle into my main project, which works insofar as it gets the files where they need to go. However, when I go to add/commit and push, the files from the "bundle" repo won't go with it, presumably because they are part of a different git repository than the one I'm pushing from.

It's not really a viable option to ask all the other developers on the team to pull in my "bundle" every time it changes (especially since it's still somewhat early in the dev cycle and sees a lot of revisions and refactoring), and I don't really want to copy the files by hand every time I need to send them up, either. Preferably, I'd be able to set things up so that I could pull from my "bundle" repo into my main repo, then push the changes as a whole.

Is there a way to do what I'm looking for with git?

答:
Yes, you can do it using forking.

Here is some tutorial how to fork a repository and make basic actions you need: http://help.github.com/fork-a-repo/ (GitHub help)

And here you can find something more about remotes (this feature is used to work with forks): http://help.github.com/remotes/


问:
Finding the parent of a node in a Binary tree
I am trying to write a method to find the parent of a given node. Here's my method.

I created a BinaryNode object r which initially refers to root.

```<code>    public BinaryNode r=root;
    public BinaryNode parent(BinaryNode p){
    BinaryNode findParent=p;
        if (isRoot(findParent) || r==null){
                return null;
        }
        else{
            if(r.left==findParent || r.right==findParent)
                return r;
            else{
                if (r.element<findParent.element)
                    return parent(r.right);
                else
                    return parent(r.left);
            }
        }
    }
</code>```

THis code  doesn't work properly .I think that's because r is a null object.Because when I do

```<code>if (isRoot(findParent) || r==null){
                System.out.println(r==null);
                return null;}
</code>```

r==null evaluates to true.How come that happen because I have inserted nodes as

```<code>public static void main (String args[]){
        BinaryTree t=new BinaryTree();
        t.insert(5);
        t.insert(t.root,4);
        t.insert(t.root,6);
        t.insert(t.root,60);
        t.insert(t.root,25);
        t.insert(t.root,10);
</code>```

and the root is not null.

Can some one please point out why that happens and if what I am trying to do in order to find the parent  node is logically correct.

答:
I prefer to delegate as much work as I can to lower-level components, in this case the Node class.  Re: finding a node's parent, this is how I do it ...</p>

```<code>template <typename T>
Node<T>* Node<T>::parent (const Node<T>* node)
{
    if (node)
    {
        if (*node < *this)
        {
            if (left && (*node < *left))
                return left->parent (node);
            return this;
        }
        if (*node > *this)
        {
            if (right && (*right > *node))
                return right->parent (node);
            return this;
        }
    }
    return nullptr;
}
</code>```

Body:
I am trying to write a method to find the parent of a given node. Here's my method.

I created a BinaryNode object r which initially refers to root.

    public BinaryNode r=root;
    public BinaryNode parent(BinaryNode p){
    BinaryNode findParent=p;
        if (isRoot(findParent) || r==null){
                return null;
        }
        else{
            if(r.left==findParent || r.right==findParent)
                return r;
            else{
                if (r.element<findParent.element)
                    return parent(r.right);
                else
                    return parent(r.left);
            }
        }
    }

THis code  doesn't work properly .I think that's because r is a null object.Because when I do

if (isRoot(findParent) || r==null){
                System.out.println(r==null);
                return null;}

r==null evaluates to true.How come that happen because I have inserted nodes as

public static void main (String args[]){
        BinaryTree t=new BinaryTree();
        t.insert(5);
        t.insert(t.root,4);
        t.insert(t.root,6);
        t.insert(t.root,60);
        t.insert(t.root,25);
        t.insert(t.root,10);

and the root is not null.

Can some one please point out why that happens and if what I am trying to do in order to find the parent  node is logically correct.

Body:
I prefer to delegate as much work as I can to lower-level components, in this case the Node class.  Re: finding a node's parent, this is how I do it ...

template <typename T>
Node<T>* Node<T>::parent (const Node<T>* node)
{
    if (node)
    {
        if (*node < *this)
        {
            if (left && (*node < *left))
                return left->parent (node);
            return this;
        }
        if (*node > *this)
        {
            if (right && (*right > *node))
                return right->parent (node);
            return this;
        }
    }
    return nullptr;
}


问:
AppleScript: dialog with multiple rows of buttons
A code like this display dialog "choose" buttons {"yes", "no"} creates a dialog with 2 buttons, in a single row, as expected.

I am trying to find out if it is possible to create more than one row of buttons.

For example, first row could have buttons {"red", "yellow", "blue"}, second row could be {"large", "small"}, and a third row could just be {"cancel"}.

Is it possible?

答:
Because AppleScript was designed to be a automation system, as opposed to a full-fledged programming language, it has always restricted its GUI to simple 'alert'-style panels. The idea was that a script should bother the user as little as possible, showing dialogs that ask for a single piece of information and then getting out of the way so that the script could work more or less invisibly. Its native alerts have a maximum of three buttons (on the "Yes", "No", "Cancel" model). The only native way to deal with a choice of more than three items is to use the choose from list command, e.g.:

```<code>set meal to choose from list {"Hamburger", "Pizza", "Spaghetti", "Cucumber Salad", "Pork Chops", "Green Eggs and Ham"} with title "Meal Time" with prompt "What do you want to eat?"
</code>```

which produces an alert like this:

While it's possible to create a multi-button alert with rows of buttons using AppleScriptObjC, it's a non-trivial task: a lot of effort for little reward. Basically one has to create a new alert using NSAlert, then create and attach an accessory-view in which you've added and positioned your rows of NSButtons. You'll also have to add some logic so the accessory view buttons you've created act as 'alert' buttons (meaning they dismiss the alert when clicked). Stack Overflow isn't really meant for coding services — though people do occasionally break that rule — but if you want to work through the bulk of the coding yourself, we'll happily assist you with difficulties.

Body:
Because AppleScript was designed to be a automation system, as opposed to a full-fledged programming language, it has always restricted its GUI to simple 'alert'-style panels. The idea was that a script should bother the user as little as possible, showing dialogs that ask for a single piece of information and then getting out of the way so that the script could work more or less invisibly. Its native alerts have a maximum of three buttons (on the "Yes", "No", "Cancel" model). The only native way to deal with a choice of more than three items is to use the choose from list command, e.g.:

set meal to choose from list {"Hamburger", "Pizza", "Spaghetti", "Cucumber Salad", "Pork Chops", "Green Eggs and Ham"} with title "Meal Time" with prompt "What do you want to eat?"

which produces an alert like this:

While it's possible to create a multi-button alert with rows of buttons using AppleScriptObjC, it's a non-trivial task: a lot of effort for little reward. Basically one has to create a new alert using NSAlert, then create and attach an accessory-view in which you've added and positioned your rows of NSButtons. You'll also have to add some logic so the accessory view buttons you've created act as 'alert' buttons (meaning they dismiss the alert when clicked). Stack Overflow isn't really meant for coding services — though people do occasionally break that rule — but if you want to work through the bulk of the coding yourself, we'll happily assist you with difficulties.


问:
Django - Login with email or username not working
In my project, I implement a login system where a user can login using their username or their email. I basically try to find whether a users email is inserted into the form field "usernameOrEmail" or whether it is their username entered in the "usernameOrEmail" field. I then log them in if a user is found.

Here is my code:

```<code>def login(request):
    context = {}
    if request.method == "POST":
        isFound = ""
        form = LoginForm(request.POST)
        if form.is_valid():
            try:
                user = User.objects.get(username=form.cleaned_data.get("usernameOrEmail"))
                isFound = "usernameFound"
            except User.DoesNotExist:
                try:
                    user = User.objects.get(email=form.cleaned_data.get("usernameOrEmail"))
                    isFound = "emailFound"
                except User.DoesNotExist:
                    isFound = "nothingFound"

            if isFound == "usernameFound":
                print("USERNAME FOUND!")
                user = auth.authenticate(username=form.cleaned_data.get("usernameOrEmail"), password=form.cleaned_data.get("password"))
                if user is not None:
                    auth.login(request, user)
                    return redirect('home')
                else:
                    context["error"] = "Oops, username/email or password provided is invalid"
            elif isFound == "emailFound":
                print("EMAIL FOUND")
                user = auth.authenticate(email=form.cleaned_data.get("usernameOrEmail"), password=form.cleaned_data.get("password"))
                if user is not None:
                    print("YES")
                    auth.login(request, user)
                    return redirect('home')
                else:
                    print("NO")
                    context["error"] = "Oops, username/email or password provided is invalid"
            else:
                context["error"] = "Oops, username/email or password provided is invalid"
        else:
            context["error"] = "Please enter valid form data"
    else:
        form = LoginForm()
</code>```

Weirdly, the terminal return the print statement "EMAIL FOUND" meaning that the email of a user was found, however the "NO" print statement is also printed, and the message "Oops, username/email or password provided is invalid" is returned in the template.

The other weird thing is that this system works for the users username, meaning when I enter a users username into the "usernameOrEmail" field, and I enter the correct password, the user is logged in. Anybody know the issue? thank you.

答:
The standard authentication backend only works with a username and password. Indeed, the authenticate method [GitHub] of the ModelBackend is implemented as:

```<code>    def authenticate(self, request, <b>username=None</b>, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            UserModel().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user</code>```

This is however not a problem. You can just implement this with:

```<code>def login(request):
    context = {}
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            try:
                user = User.objects.get(username=form.cleaned_data['usernameOrEmail'])
            except User.DoesNotExist:
                try:
                    user = User.objects.get(email=form.cleaned_data['usernameOrEmail'])
                except User.DoesNotExist:
                    user = None
            if user is not None:
                user = auth.authenticate(username=<b>user.username</b>, password=form.cleaned_data['password'])
            if user is not None:
                auth.login(request, user)
                return redirect('home')
            else:
                context['error'] = 'Oops, username/email or password provided is invalid'
        else:
            context['error'] = 'Please enter valid form data'
    else:
        form = LoginForm()
    # …</code>```

Body:
In my project, I implement a login system where a user can login using their username or their email. I basically try to find whether a users email is inserted into the form field "usernameOrEmail" or whether it is their username entered in the "usernameOrEmail" field. I then log them in if a user is found.

Here is my code:

def login(request):
    context = {}
    if request.method == "POST":
        isFound = ""
        form = LoginForm(request.POST)
        if form.is_valid():
            try:
                user = User.objects.get(username=form.cleaned_data.get("usernameOrEmail"))
                isFound = "usernameFound"
            except User.DoesNotExist:
                try:
                    user = User.objects.get(email=form.cleaned_data.get("usernameOrEmail"))
                    isFound = "emailFound"
                except User.DoesNotExist:
                    isFound = "nothingFound"

            if isFound == "usernameFound":
                print("USERNAME FOUND!")
                user = auth.authenticate(username=form.cleaned_data.get("usernameOrEmail"), password=form.cleaned_data.get("password"))
                if user is not None:
                    auth.login(request, user)
                    return redirect('home')
                else:
                    context["error"] = "Oops, username/email or password provided is invalid"
            elif isFound == "emailFound":
                print("EMAIL FOUND")
                user = auth.authenticate(email=form.cleaned_data.get("usernameOrEmail"), password=form.cleaned_data.get("password"))
                if user is not None:
                    print("YES")
                    auth.login(request, user)
                    return redirect('home')
                else:
                    print("NO")
                    context["error"] = "Oops, username/email or password provided is invalid"
            else:
                context["error"] = "Oops, username/email or password provided is invalid"
        else:
            context["error"] = "Please enter valid form data"
    else:
        form = LoginForm()

Weirdly, the terminal return the print statement "EMAIL FOUND" meaning that the email of a user was found, however the "NO" print statement is also printed, and the message "Oops, username/email or password provided is invalid" is returned in the template.

The other weird thing is that this system works for the users username, meaning when I enter a users username into the "usernameOrEmail" field, and I enter the correct password, the user is logged in. Anybody know the issue? thank you.

Body:
The standard authentication backend only works with a username and password. Indeed, the authenticate method [GitHub] of the ModelBackend is implemented as:

    def authenticate(self, request, username=None, password=None, **kwargs):
        if username is None:
            username = kwargs.get(UserModel.USERNAME_FIELD)
        if username is None or password is None:
            return
        try:
            user = UserModel._default_manager.get_by_natural_key(username)
        except UserModel.DoesNotExist:
            # Run the default password hasher once to reduce the timing
            # difference between an existing and a nonexistent user (#20760).
            UserModel().set_password(password)
        else:
            if user.check_password(password) and self.user_can_authenticate(user):
                return user

This is however not a problem. You can just implement this with:

def login(request):
    context = {}
    if request.method == 'POST':
        form = LoginForm(request.POST)
        if form.is_valid():
            try:
                user = User.objects.get(username=form.cleaned_data['usernameOrEmail'])
            except User.DoesNotExist:
                try:
                    user = User.objects.get(email=form.cleaned_data['usernameOrEmail'])
                except User.DoesNotExist:
                    user = None
            if user is not None:
                user = auth.authenticate(username=user.username, password=form.cleaned_data['password'])
            if user is not None:
                auth.login(request, user)
                return redirect('home')
            else:
                context['error'] = 'Oops, username/email or password provided is invalid'
        else:
            context['error'] = 'Please enter valid form data'
    else:
        form = LoginForm()
    # …


问:
PySpark DataFrame When to use/ not to use Select
Based on PySpark document:

A DataFrame is equivalent to a relational table in Spark SQL, and can be created using various functions in SQLContext

Meaning I can use Select for showing the value of a column, however, I saw sometimes these two equivalent codes are used instead:

```<code># df is a sample DataFrame with column a
df.a
# or
df['a']
</code>```

And sometimes when I use select I might get an error instead of them and vice versa sometimes I have to use Select.

For example, this is a DataFrame for finding a dog in a given picture problem:

```<code>joined_df.printSchema()
root
 |-- folder: string (nullable = true)
 |-- filename: string (nullable = true)
 |-- width: string (nullable = true)
 |-- height: string (nullable = true)
 |-- dog_list: array (nullable = true)
 |    |-- element: string (containsNull = true)
</code>```

If I want to select the dog details and show 10 rows, this code shows an error:

```<code>print(joined_df.dog_list.show(truncate=False))

Traceback (most recent call last):
 File "<stdin>", line 2, in <module>
    print(joined_df.dog_list.show(truncate=False))
TypeError: 'Column' object is not callable
</code>```

And this is not:

```<code>print(joined_df.select('dog_list').show(truncate=False))
</code>```

Question1: When I have to use Select and when I have to use df.a or df["a"]

Question2: what is the meaning of the error above? 'Column' object is not callable

答:
df.col_name return a Column object but df.select("col_name") return another dataframe

see this for documentation

The key here is Those two methods are returning two different objects, that is why your print(joined_df.dog_list.show(truncate=False)) give you the error. Meaning that the Column object does not have this .show method but the dataframe does.

So when you call a function, function takes Column as input, you should use df.col_name, if you want to operate at dataframe level, you want to use df.select("col_name")

Body:
Based on PySpark document:

A DataFrame is equivalent to a relational table in Spark SQL, and can be created using various functions in SQLContext

Meaning I can use Select for showing the value of a column, however, I saw sometimes these two equivalent codes are used instead:

# df is a sample DataFrame with column a
df.a
# or
df['a']

And sometimes when I use select I might get an error instead of them and vice versa sometimes I have to use Select.

For example, this is a DataFrame for finding a dog in a given picture problem:

joined_df.printSchema()
root
 |-- folder: string (nullable = true)
 |-- filename: string (nullable = true)
 |-- width: string (nullable = true)
 |-- height: string (nullable = true)
 |-- dog_list: array (nullable = true)
 |    |-- element: string (containsNull = true)

If I want to select the dog details and show 10 rows, this code shows an error:

print(joined_df.dog_list.show(truncate=False))

Traceback (most recent call last):
 File "<stdin>", line 2, in <module>
    print(joined_df.dog_list.show(truncate=False))
TypeError: 'Column' object is not callable

And this is not:

print(joined_df.select('dog_list').show(truncate=False))

Question1: When I have to use Select and when I have to use df.a or df["a"]

Question2: what is the meaning of the error above? 'Column' object is not callable


问:
How can I color a specific day with specific time with slotPropGetter of react-big-calendar?
I have a react-big-calendar and I want to get same informations like the day and the start and the end (as a time) for coloring the time and the day slot with slotPropGetter.

My informations from the backend is:

```<code>    {   "start": "2019-08-23T13:30:00",
        "end": "2019-08-23T18:00:00",
        "rendering": "background",
        "color": "#f740f7"
    }
</code>```

I try with slotPropGetter :

```<code>slotPropGetter={
                (date) => {
                    for(let i =0; i<this.state.eventsPlanning.length; i++) {
                      if(this.state.eventsPlanning[i].rendering === 'background') {
                        let newStyle ={
                          backgroundColor:'red'
                        }
                        return {
                          className: "rbc-day-slot rbc-time-slot",
                          style: newStyle
                        }
                      }
                    }
                  }
                }
</code>```

when I run it, it seems all the days are colored, but I want just to color according the start and the end of the informations.

How can I fix that ?

答: The slotPropGetter method is called when rendering each individual timeslot in the Day and Week views, and the date object passed is a full date/time js Date object for the starting time of the slot. How many times this method is called, per hour long block in these views, is determined by your calendar's step and timeslots properties. So, for instance, the default step is 30 and timeslots is 2, which will pass a date with HH:00 and HH:30 the two times it is called (HH being the actual 24 hour hour). If you changed this to a step of 15 and timeslots of 4 the method will be called four times every hour, incrementing fifteen minutes each time. You would have to use your own date math to then determine which slot cells are being adjusted.

Body:
I have a react-big-calendar and I want to get same informations like the day and the start and the end (as a time) for coloring the time and the day slot with slotPropGetter.

My informations from the backend is:

    {   "start": "2019-08-23T13:30:00",
        "end": "2019-08-23T18:00:00",
        "rendering": "background",
        "color": "#f740f7"
    }

I try with slotPropGetter :

slotPropGetter={
                (date) => {
                    for(let i =0; i<this.state.eventsPlanning.length; i++) {
                      if(this.state.eventsPlanning[i].rendering === 'background') {
                        let newStyle ={
                          backgroundColor:'red'
                        }
                        return {
                          className: "rbc-day-slot rbc-time-slot",
                          style: newStyle
                        }
                      }
                    }
                  }
                }

when I run it, it seems all the days are colored, but I want just to color according the start and the end of the informations.

How can I fix that ?


问:
How can I get the active screen dimensions?
What I am looking for is the equivalent of System.Windows.SystemParameters.WorkArea for the monitor that the window is currently on.

Clarification:  The window in question is WPF, not WinForm.

答:
WinForms

For multi-monitor setups you will also need account for the X and Y position:

```<code>Rectangle activeScreenDimensions = Screen.FromControl(this).Bounds;
this.Size = new Size(activeScreenDimensions.Width + activeScreenDimensions.X, activeScreenDimensions.Height + activeScreenDimensions.Y);
</code>```

OwnerDisplayName: chilltemp

LastEditorDisplayName: chilltemp

Body:
WinForms

For multi-monitor setups you will also need account for the X and Y position:

Rectangle activeScreenDimensions = Screen.FromControl(this).Bounds;
this.Size = new Size(activeScreenDimensions.Width + activeScreenDimensions.X, activeScreenDimensions.Height + activeScreenDimensions.Y);