问:
can't use other port for nodejs application unless I sudo
Hi I have a fairly simple Nodejs program , I want to demonstrate on a small scale what "microservices" look like.

So I want to run a couple separate Node servers on different ports on my local machine, however when I change the port number to 3001 it stops working. After I run the command with sudo, e.g. sudo node index.js it starts working with the specified port (3001). Here is my index.js file.

(By "working" I mean that I can send a GET / POST request to the various routes, when it "doesn't work" I don't get any response back even though the server is running)

index.js

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

//import routes
const postRoute = require('./routes/posts');

const app = express();

// middleware
app.use(express.json());

//route middlewares
app.use('/api/user', postRoute);

app.listen(3001, () => console.log('Server Running...'))
</code>```

./routes/post.js

```<code>const router = require('express').Router();

router.get("/posts", (req, res) => {
    res.send("hello sir!");
});

module.exports = router;
</code>```

答: This sounds unusual. What happens if you try it without the verifytoken middleware? There may be a file permissions issue with a file that the middleware relies on - maybe a secret key?

Body:
Hi I have a fairly simple Nodejs program , I want to demonstrate on a small scale what "microservices" look like.

So I want to run a couple separate Node servers on different ports on my local machine, however when I change the port number to 3001 it stops working. After I run the command with sudo, e.g. sudo node index.js it starts working with the specified port (3001). Here is my index.js file.

(By "working" I mean that I can send a GET / POST request to the various routes, when it "doesn't work" I don't get any response back even though the server is running)

index.js

const express = require('express');

//import routes
const postRoute = require('./routes/posts');

const app = express();

// middleware
app.use(express.json());

//route middlewares
app.use('/api/user', postRoute);

app.listen(3001, () => console.log('Server Running...'))

./routes/post.js

const router = require('express').Router();

router.get("/posts", (req, res) => {
    res.send("hello sir!");
});

module.exports = router;


来源: stackexchange

问:
Gatsby: what's the difference between basepath and path prefix?
I don't understand the difference between basepath and path prefix in Gatsby, and when to use each feature

Basepath: https://www.gatsbyjs.org/tutorial/part-seven/

Path prefix: https://www.gatsbyjs.org/docs/path-prefix/

答:
TL:DR

pathPrefix has much more impact on your site — it add a prefix to the generated url of all your pages and assets. basePath is just a helper for generating slug from your filesystem — In my experience with Gatsby I rarely use it at all.

pathPrefix

It appends a prefix to url of all your pages & assets. This way, you can deploy Gatsby site as a sub directory of another site.

```<code>Without Prefix             | With 'blog' Prefix
---------------------------|--------------------------------
myblog.com/                | myblog.com/blog
myblog.com/hello/          | myblog.com/blog/hello
myblog.com/image-123.png   | myblog.com/blog/image-123.png
</code>```

basePath

It's an option of createFilePath which helps you create slug from your project structure. It doesn't affect whether you're serving your Gatsby from root or not.

If your project directory is like this:

```<code><root>
  |--content
  |     |--writing
  |     |    `--page1.md
  |     `--images
  |          `--cat.md
  |
  |--gatsby-config.js
 ...
</code>```

And you set this in your gatsby-config.js

```<code>module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/content`,
        name: 'content'
      }
    }
  ]
}

</code>```

Then createFilePath will return this slug for your file: writing/page1/, which maybe not what you want. Maybe you want it to be /page1/. In this case, setting basePath to writing will return /page1/.

ContentLicense: CC BY-SA 4.0

Body:
TL:DR

pathPrefix has much more impact on your site — it add a prefix to the generated url of all your pages and assets. basePath is just a helper for generating slug from your filesystem — In my experience with Gatsby I rarely use it at all.

pathPrefix

It appends a prefix to url of all your pages & assets. This way, you can deploy Gatsby site as a sub directory of another site.

Without Prefix             | With 'blog' Prefix
---------------------------|--------------------------------
myblog.com/                | myblog.com/blog
myblog.com/hello/          | myblog.com/blog/hello
myblog.com/image-123.png   | myblog.com/blog/image-123.png

basePath

It's an option of createFilePath which helps you create slug from your project structure. It doesn't affect whether you're serving your Gatsby from root or not.

If your project directory is like this:

<root>
  |--content
  |     |--writing
  |     |    `--page1.md
  |     `--images
  |          `--cat.md
  |
  |--gatsby-config.js
 ...

And you set this in your gatsby-config.js

module.exports = {
  plugins: [
    {
      resolve: 'gatsby-source-filesystem',
      options: {
        path: `${__dirname}/content`,
        name: 'content'
      }
    }
  ]
}

Then createFilePath will return this slug for your file: writing/page1/, which maybe not what you want. Maybe you want it to be /page1/. In this case, setting basePath to writing will return /page1/.


问:
How could I protect the users from my webpage from being tracked?
This is maybe quite a broad question and I tried to look for other stack exchanges where addressing my question would suit better – but in the end I decided that it might be still a question of a technical nature, and so I am posting it here:

I recently started to think more about privacy and security and I realized that I as a web user can only do so much about staying untracked. VPN, (slow) Tor, privacy helpers, add-blockers, Firefox are just a few tools to name, but still I realize that the information that I normally share (like installed add-ons, browser size, IP location etc.) can still very well be fingerprinted.

Normally as a web-developer I am told that we should add analytics, that we should find out more about the users to «make a better service», but I think I would like to do the opposite.

So:
Are there steps I could take, when building a website, that help the visitors to stay untracked? And I don't mean «not installing google analytics», I mean things like somehow actively messing with the statistics, so that my hosters server is incapable of tracking things correctly or similar things...
Right now I can't really think of anything, but I somehow believe that I as a person who builds bricks of the internet could and should be able to influence these kind of things directly...

For now I see the obvious things:
- not using statistic services
- use https
- not using any third party tools that might include tracking or open doors for other trackers
But still this seems to just omit the bad things, but I can't actually do active stuff...

So I would be very glad to hear your thoughts about this. (Or guide me to a place, where this discussion fits a better..)

Cheers

merc

答:
As a web developer, you can only control your website.

Assuming you aren't caching any data or using cookies, then users shouldn't be tracked while using your website by tools like 3rd party cookies.

Here is a good article about online tracking and how it works.

As far as I know, there isn't an effective way to actively mess with tracking statistics. Your best bet is to avoid installing libraries or tools that track your users.


问:
Fieldset HTML Styling using CSS
I have 5 fieldsets which I want to layout in a particular design.
All have the same width, but may have different heights.

```<code>┌-[Fieldset 1]----┐
|                 |
|                 |
└-----------------┘
┌-[Fieldset 2]----┐  ┌-[Fieldset 3]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘
┌-[Fieldset 4]----┐  ┌-[Fieldset 5]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘
</code>```

in my HTML source, I want to make the source "clean", which removes any unnecessary formatting tags which include "br" and "p". The container of the fieldsets is set to the full width of the window.

The only way where I can style in it this structure currently, is by placing "br" elements after the fieldsets I want to move to the next line:

```<code><fieldset style='width:200px;'><legend>Fieldset1</legend></fieldset><br/>
<fieldset style='width:200px;'><legend>Fieldset2</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset3</legend></fieldset><br/>
<fieldset style='width:200px;'><legend>Fieldset4</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset5</legend></fieldset>
</code>```

The container which holds the fieldsets is actually the full length of the screen, (ie:100%). If I take out the "br"s the fieldsets line-up next to each other in a haphazard way.

I have tried various ways to align and adjust the fieldsets in the order that I want them using CSS including using float, clear, padding-left but to no avail.

Is there a proper methodology using CSS that can be applied to get the desired effect wanted as shown above?

thankyou.

答:
```<code><style type="text/css">
fieldset {
    width: 200px;
    float: left;
}

.clear {
    clear: both;
}
</style>

<fieldset><legend>Fieldset1</legend></fieldset>
<fieldset class="clear"><legend>Fieldset2</legend></fieldset>
<fieldset><legend>Fieldset3</legend></fieldset>
<fieldset class="clear"><legend>Fieldset4</legend></fieldset>
<fieldset><legend>Fieldset5</legend></fieldset>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Fieldset HTML Styling using CSS

Body:
I have 5 fieldsets which I want to layout in a particular design.
All have the same width, but may have different heights.

┌-[Fieldset 1]----┐
|                 |
|                 |
└-----------------┘
┌-[Fieldset 2]----┐  ┌-[Fieldset 3]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘
┌-[Fieldset 4]----┐  ┌-[Fieldset 5]----┐
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
|                 |  |                 |
└-----------------┘  └-----------------┘

in my HTML source, I want to make the source "clean", which removes any unnecessary formatting tags which include "br" and "p". The container of the fieldsets is set to the full width of the window.

The only way where I can style in it this structure currently, is by placing "br" elements after the fieldsets I want to move to the next line:

<fieldset style='width:200px;'><legend>Fieldset1</legend></fieldset>

<fieldset style='width:200px;'><legend>Fieldset2</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset3</legend></fieldset>

<fieldset style='width:200px;'><legend>Fieldset4</legend></fieldset>
<fieldset style='width:200px;'><legend>Fieldset5</legend></fieldset>

The container which holds the fieldsets is actually the full length of the screen, (ie:100%). If I take out the "br"s the fieldsets line-up next to each other in a haphazard way.

I have tried various ways to align and adjust the fieldsets in the order that I want them using CSS including using float, clear, padding-left but to no avail.

Is there a proper methodology using CSS that can be applied to get the desired effect wanted as shown above?

thankyou.


问:
What does (_) mean when calling a function?
I’ve seen the notation used elsewhere but, just as an example, I recently read about replacing

```<code>ChangeNotifierProvider(
  create: (BuildContext context) => MyCounter()
</code>```

with

```<code> ChangeNotifierProvider(
    create: (_) => MyCounter()
</code>```

What does the latter notation mean? Is the BuildContext parameter optional and the caller chosen to not supply it?

答:
Replacing a parameter with _ simply means just ignore it.

Many functions provide parameters that are likely needed for certain operations in most cases, yet there are still some cases where you don't need it (like your case), in which it is safe to ignore it.

Body:
I’ve seen the notation used elsewhere but, just as an example, I recently read about replacing

ChangeNotifierProvider(
  create: (BuildContext context) => MyCounter()

with

 ChangeNotifierProvider(
    create: (_) => MyCounter()

What does the latter notation mean? Is the BuildContext parameter optional and the caller chosen to not supply it?


问:
Angularjs computed form field validation
We have a table generated from a generic structure with filtering allowed on the columns. The structure can include a regex value for ensuring the user enters only valid filtering values. We want to apply the regex in the normal ng-pattern way with a validation message ... something like this

                    {{column.DisplayName}}

                <input type="text" class="filter form-control"
                       name="col-{{$index}}" ng-model="column.filterVal"
                       placeholder="Search" ng-pattern="column.FilterRegex" />

                      Invalid character for {{column.DisplayName}}

```

However, the ng-messages value of columnFiltersForm.col-{{$index}}.$error doesn't work. Any idea if something like this is possible, and how to achieve it?

答:
The ng-messages directive takes an AngularJS expression:

<input type="text" class="filter form-control"
       name="col-{{$index}}" ng-model="column.filterVal"
       placeholder="Search" ng-pattern="column.FilterRegex" />
̶<̶d̶i̶v̶ ̶n̶g̶-̶m̶e̶s̶s̶a̶g̶e̶s̶=̶"̶c̶o̶l̶u̶m̶n̶F̶i̶l̶t̶e̶r̶s̶F̶o̶r̶m̶.̶c̶o̶l̶-̶{̶{̶$̶i̶n̶d̶e̶x̶}̶}̶.̶$̶e̶r̶r̶o̶r̶"̶

      Invalid character for {{column.DisplayName}}

```

For more information, see

Why mixing interpolation and expressions is bad practice

Body:
We have a table generated from a generic structure with filtering allowed on the columns. The structure can include a regex value for ensuring the user enters only valid filtering values. We want to apply the regex in the normal ng-pattern way with a validation message ... something like this

                    {{column.DisplayName}}

                <input type="text" class="filter form-control"
                       name="col-{{$index}}" ng-model="column.filterVal"
                       placeholder="Search" ng-pattern="column.FilterRegex" />

                      Invalid character for {{column.DisplayName}}

However, the ng-messages value of columnFiltersForm.col-{{$index}}.$error doesn't work. Any idea if something like this is possible, and how to achieve it?

Body:
The ng-messages directive takes an AngularJS expression:

<input type="text" class="filter form-control"
       name="col-{{$index}}" ng-model="column.filterVal"
       placeholder="Search" ng-pattern="column.FilterRegex" />
̶<̶d̶i̶v̶ ̶n̶g̶-̶m̶e̶s̶s̶a̶g̶e̶s̶=̶"̶c̶o̶l̶u̶m̶n̶F̶i̶l̶t̶e̶r̶s̶F̶o̶r̶m̶.̶c̶o̶l̶-̶{̶{̶$̶i̶n̶d̶e̶x̶}̶}̶.̶$̶e̶r̶r̶o̶r̶"̶
<div ng-messages="columnFiltersForm['col-' + $index].$error"
     class="validation" role="alert">
    <span ng-message="pattern">
      Invalid character for {{column.DisplayName}}
    </span>
</div>

For more information, see

Why mixing interpolation and expressions is bad practice


问:
create nested object from records oriented dictionary
I have the following data frame:

```<code>[{'Name': 'foo', 'Description': 'foobar', 'Value': '5'}, {'Name': 'baz', 'Description': 'foobaz', 'Value': '4'}, {'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}]
</code>```

And I'd like to create two nested categories. One category for Name, Description keys and another category for Value key. Example of output for one object:

```<code>{'details': {'Name': 'foo', 'Description': 'foobar'}, 'stats': { 'Value': '5' }}
</code>```

so far I'm only able to achieve this by joining "manually" each items. I'm pretty sure this is not the right solution.

答:
Using list comprehension:</p>

```<code>from json import dump

result = [{
    'details': {col: row[col] for col in ['Name', 'Description']},
    'stat': {col: row[col] for col in ['Value']}
} for row in df.to_dict(orient='records')]

# Write to file
with open('result.json', 'w') as f:
    dump(result, f)
</code>```

Body:
I have the following data frame:

[{'Name': 'foo', 'Description': 'foobar', 'Value': '5'}, {'Name': 'baz', 'Description': 'foobaz', 'Value': '4'}, {'Name': 'bar', 'Description': 'foofoo', 'Value': '8'}]

And I'd like to create two nested categories. One category for Name, Description keys and another category for Value key. Example of output for one object:

{'details': {'Name': 'foo', 'Description': 'foobar'}, 'stats': { 'Value': '5' }}

so far I'm only able to achieve this by joining "manually" each items. I'm pretty sure this is not the right solution.

Body:
Using list comprehension:

from json import dump

result = [{
    'details': {col: row[col] for col in ['Name', 'Description']},
    'stat': {col: row[col] for col in ['Value']}
} for row in df.to_dict(orient='records')]

# Write to file
with open('result.json', 'w') as f:
    dump(result, f)


问:
Custom Policies API Manager
I tried to create a custom policy, with a purpose a mask of service:

Original Services in API:

```<code>http://API/v1/profile
http://API/v1/account
</code>```

With mask:

```<code>http://API/v1/user-profile
http://API/v1/user-account
</code>```

And combination the answer of User Bee this a solution for this problem:

```<code><switch source="get-property('axis2', 'REST_URL_POSTFIX')">
    <case regex="/v1/kyc-profile">
        <property name="REST_URL_POSTFIX" value="/v1/profile" scope="axis2"/>
    </case>
    <case regex="/v1/kyc-account">
        <property name="REST_URL_POSTFIX" value="/v1/account" scope="axis2"/>
    </case>
</switch>
</code>```

But this solution only works where the services is static, but I have others services, similar to:

```<code>http://API/v1/user-profile/{id-user}/details
http://API/v1/user-profile/{id-user}?expand=some_information
</code>```

For the last service I have this:

```<code><switch source="get-property('axis2', 'REST_URL_POSTFIX')">
   <case regex="v1/user-profile/[\/\w\W]*">
        <property name="REST_URL_POSTFIX" value="/v2/cliente/{id-user}?expand=some_information" scope="axis2"/>
   </case>
</switch>

</code>```

[/\w\W]* This part is regular expression for {id-user}?expand=some_information and similar.

The problem is: I need put dynamic value because the property value (<property name="REST_URL_POSTFIX" value="THIS" scope="axis2"/>) takes this text, example:

Service before to policie

```<code>http://API/v1/user-profile/1?expand=some_information
</code>```

Service after to policie

```<code>http://API/v1/user-profile/{id-user}?expand=some_information
</code>```

My questions are:

How to put a dynamic value for the services similar to: http://API/v1/user-profile/{id-user}?expand=some_information?

For the other service, http://API/v1/user-profile/{id-user}/details I have the similar situacion, How a resolve?

答:
In your mediation sequence, try changing the backend URL as follows.

```<code>http://API/v1/user-profile/{uri.var.id-user}?expand=some_information
</code>```

Example:

```<code><switch source="get-property('axis2', 'REST_URL_POSTFIX')">
   <case regex="v1/user-profile/[\/\w\W]*">
        <property name="REST_URL_POSTFIX" value="/v2/cliente/{uri.var.id-user}?expand=some_information" scope="axis2"/>
   </case>
</switch>
</code>```

Title: Custom Policies API Manager

Body:
I tried to create a custom policy, with a purpose a mask of service:

Original Services in API:

http://API/v1/profile
http://API/v1/account

With mask:

http://API/v1/user-profile
http://API/v1/user-account

And combination the answer of User Bee this a solution for this problem:

<switch source="get-property('axis2', 'REST_URL_POSTFIX')">
    <case regex="/v1/kyc-profile">
        <property name="REST_URL_POSTFIX" value="/v1/profile" scope="axis2"/>
    </case>
    <case regex="/v1/kyc-account">
        <property name="REST_URL_POSTFIX" value="/v1/account" scope="axis2"/>
    </case>
</switch>

But this solution only works where the services is static, but I have others services, similar to:

http://API/v1/user-profile/{id-user}/details
http://API/v1/user-profile/{id-user}?expand=some_information

For the last service I have this:

<switch source="get-property('axis2', 'REST_URL_POSTFIX')">
   <case regex="v1/user-profile/[\/\w\W]*">
        <property name="REST_URL_POSTFIX" value="/v2/cliente/{id-user}?expand=some_information" scope="axis2"/>
   </case>
</switch>

[/\w\W]* This part is regular expression for {id-user}?expand=some_information and similar.

The problem is: I need put dynamic value because the property value (<property name="REST_URL_POSTFIX" value="THIS" scope="axis2"/>) takes this text, example:

Service before to policie

http://API/v1/user-profile/1?expand=some_information

Service after to policie

http://API/v1/user-profile/{id-user}?expand=some_information

My questions are:

How to put a dynamic value for the services similar to: http://API/v1/user-profile/{id-user}?expand=some_information?

For the other service, http://API/v1/user-profile/{id-user}/details I have the similar situacion, How a resolve?

Body:
In your mediation sequence, try changing the backend URL as follows.

http://API/v1/user-profile/{uri.var.id-user}?expand=some_information

Example:

<switch source="get-property('axis2', 'REST_URL_POSTFIX')">
   <case regex="v1/user-profile/[\/\w\W]*">
        <property name="REST_URL_POSTFIX" value="/v2/cliente/{uri.var.id-user}?expand=some_information" scope="axis2"/>
   </case>
</switch>


问:
WPF CompositeCollection grouping by each collection view
I've set up a CompositeCollection containing two or more collections as follows (simplified):

```<code><Grid.Resources>
    <CollectionViewSource x:Key="CollectionA" Source="{Binding CollectionA}" />
    <CollectionViewSource x:Key="CollectionB" Source="{Binding CollectionB}" />
    <CompositeCollection x:Key="FullCollection">
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionA}}" />
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionB}}" />
    </CompositeCollection>
</Grid.Resources>
</code>```

...

```<code><ListView ItemsSource="{StaticResource FullCollection}">
    <ListView.View>
        <GridView>
</code>```

And then some columns displayed inside the GridView. However, I can't seem to be able to add GroupDescriptions to the CompositeCollection, only the individual CollectionViewSource elements.

What I want to do is group by the collections themselves, such that the ListView has a header, then the first collection's contents, another header, then the second collection's contents, etc.

Am I barking up the wrong tree trying to group these in this way?

答:
I had the same problem but for a drop down combobox. The solution was to simply had some disabled items inbetween the collections, e.g. adapting to your problem it would be something like:</p>

```<code><Grid.Resources>
    <CollectionViewSource x:Key="CollectionA" Source="{Binding CollectionA}" />
    <CollectionViewSource x:Key="CollectionB" Source="{Binding CollectionB}" />
    <CompositeCollection x:Key="FullCollection">
        <ListViewItem IsEnabled="False">Collection A:</ListViewItem>
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionA}}" />
        <ListViewItem IsEnabled="False">Collection B:</ListViewItem>
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionB}}" />
    </CompositeCollection>
</Grid.Resources>
</code>```

Body:
I've set up a CompositeCollection containing two or more collections as follows (simplified):

<Grid.Resources>
    <CollectionViewSource x:Key="CollectionA" Source="{Binding CollectionA}" />
    <CollectionViewSource x:Key="CollectionB" Source="{Binding CollectionB}" />
    <CompositeCollection x:Key="FullCollection">
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionA}}" />
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionB}}" />
    </CompositeCollection>
</Grid.Resources>

...

<ListView ItemsSource="{StaticResource FullCollection}">
    <ListView.View>
        <GridView>

And then some columns displayed inside the GridView. However, I can't seem to be able to add GroupDescriptions to the CompositeCollection, only the individual CollectionViewSource elements.

What I want to do is group by the collections themselves, such that the ListView has a header, then the first collection's contents, another header, then the second collection's contents, etc.

Am I barking up the wrong tree trying to group these in this way?

Body:
I had the same problem but for a drop down combobox. The solution was to simply had some disabled items inbetween the collections, e.g. adapting to your problem it would be something like:

<Grid.Resources>
    <CollectionViewSource x:Key="CollectionA" Source="{Binding CollectionA}" />
    <CollectionViewSource x:Key="CollectionB" Source="{Binding CollectionB}" />
    <CompositeCollection x:Key="FullCollection">
        <ListViewItem IsEnabled="False">Collection A:</ListViewItem>
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionA}}" />
        <ListViewItem IsEnabled="False">Collection B:</ListViewItem>
        <CollectionContainer Collection="{Binding Source={StaticResource CollectionB}}" />
    </CompositeCollection>
</Grid.Resources>


问:
Angular 8 unit test directive which includes setTimeout
I have the following simple autofocus directive:

```<code>@Directive({
  selector: '[appAutoFocus]',
})
export class AutofocusDirective implements AfterContentInit {

  @Input() public appAutoFocus: boolean;

  public constructor(private el: ElementRef) { }

  public ngAfterContentInit() {
    if (this.appAutoFocus) {
      setTimeout(() => {
        this.el.nativeElement.focus();
      }, 300);
    }
  }
}
</code>```

I'm now trying to write some simple unit tests, but 2 out of the 3 tests fail.

```<code>@Component({
  template: '<input type="text" [appAutoFocus]="true" />'
})
class TestComponent {
  constructor() { }
}

fdescribe('AutoFocusDirective', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let inputEl: DebugElement;
     beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [
            TestComponent,
            AutofocusDirective
          ]
        });

        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));

        spyOn(inputEl.nativeElement, 'focus');
        fixture.detectChanges();
      });

      it('should create an instance', () => {
        expect(component).toBeTruthy();
      });

      it('should call the focus event', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        fixture.whenStable().then(() => {
         expect(inputEl.nativeElement.focus).toHaveBeenCalled();
        });
      }));

      it('should autofocus the input control', () => {
        const debugEl: DebugElement = fixture.debugElement;
        expect(debugEl.query(By.css('input:focus'))).not.toBe(null);
      });
</code>```

"Should call the focus event" fails with Spec 'AutoFocusDirective should call the focus event' has no expectations.

"Should autofocus the input control" fails with Expected null not to be null

答:
Maybe you can't couple fakeAsync with fixture.whenStable.

Try:

```<code>      it('should call the focus event', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        // You should check out `flush` method to resolve instead of specifying the time in the argument of tick
        expect(inputEl.nativeElement.focus).toHaveBeenCalled();
      }));

     it('should autofocus the input control', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        const debugEl: DebugElement = fixture.debugElement;
        expect(debugEl.query(By.css('input:focus'))).not.toBe(null);
      }));
</code>```

Both of your tests do the same thing so consider putting them both in one it block.

A good read for you: https://alligator.io/angular/testing-async-fakeasync/

Body:
I have the following simple autofocus directive:

@Directive({
  selector: '[appAutoFocus]',
})
export class AutofocusDirective implements AfterContentInit {

  @Input() public appAutoFocus: boolean;

  public constructor(private el: ElementRef) { }

  public ngAfterContentInit() {
    if (this.appAutoFocus) {
      setTimeout(() => {
        this.el.nativeElement.focus();
      }, 300);
    }
  }
}

I'm now trying to write some simple unit tests, but 2 out of the 3 tests fail.

@Component({
  template: '<input type="text" [appAutoFocus]="true" />'
})
class TestComponent {
  constructor() { }
}

fdescribe('AutoFocusDirective', () => {
  let component: TestComponent;
  let fixture: ComponentFixture<TestComponent>;
  let inputEl: DebugElement;
     beforeEach(() => {
        TestBed.configureTestingModule({
          declarations: [
            TestComponent,
            AutofocusDirective
          ]
        });

        fixture = TestBed.createComponent(TestComponent);
        component = fixture.componentInstance;
        inputEl = fixture.debugElement.query(By.css('input'));

        spyOn(inputEl.nativeElement, 'focus');
        fixture.detectChanges();
      });

      it('should create an instance', () => {
        expect(component).toBeTruthy();
      });

      it('should call the focus event', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        fixture.whenStable().then(() => {
         expect(inputEl.nativeElement.focus).toHaveBeenCalled();
        });
      }));

      it('should autofocus the input control', () => {
        const debugEl: DebugElement = fixture.debugElement;
        expect(debugEl.query(By.css('input:focus'))).not.toBe(null);
      });

"Should call the focus event" fails with Spec 'AutoFocusDirective should call the focus event' has no expectations.

"Should autofocus the input control" fails with Expected null not to be null

Body:
Maybe you can't couple fakeAsync with fixture.whenStable.

Try:

      it('should call the focus event', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        // You should check out `flush` method to resolve instead of specifying the time in the argument of tick
        expect(inputEl.nativeElement.focus).toHaveBeenCalled();
      }));

     it('should autofocus the input control', fakeAsync(() => {
        tick(400);
        fixture.detectChanges();
        const debugEl: DebugElement = fixture.debugElement;
        expect(debugEl.query(By.css('input:focus'))).not.toBe(null);
      }));

Both of your tests do the same thing so consider putting them both in one it block.

A good read for you: https://alligator.io/angular/testing-async-fakeasync/


问:
Visual Studio 2008 error
When I am trying to run a C# project on my VS 2008 the following message appears:

"Project "defining" could not be opened because Microsoft Visual C# 2008 compiler could not be created.Query Service for {        } failed."

I have uninstalled and installed VS 2008 twice. Also installed a patch for it. But the error persists. I am able to run Visual Basic projects.

Any of you have an idea how to resolve this issue?

Thanks.

答: This problem is solved Here</p>

Title: Visual Studio 2008 error

Body: This problem is solved Here


问:
updating mongo documents based in map value and remove that value
am currently working in Go and have a mongo database (connected via gopkg.in/mgo.v2) so, right now I have a data structure similar to:

```<code>{
    "_id" : "some_id_bson",
    "field1" : "value1",
    "field2" : {
      {
      "key1" : "v1",
      "key2" : "v2",
      "key3" : "v3",
      "key4" : "v4"
      }
    }
}
</code>```

So, basically what I need to do (as an example) is to update in the database all the records that contains key1 and remove that from the json, so the result would be something like:

```<code>{
        "_id" : "some_id_bson",
        "field1" : "value1",
        "field2" : {
          {
          "key2" : "v2",
          "key3" : "v3",
          "key4" : "v4"
          }
        }
    }
</code>```

What can I use to achieve this? I have been searching and cannot find something oriented to maps (field2 is a map). Thanks in advance

答:
It seems like you're asking how to remove a property from a nested object in a particular document, which appears as if to be answered here: How to remove property of nested object from MongoDB document?.
from the main answer there:

Use $unset as below :

db.collectionName.update({},{"$unset":{"values.727920":""}}) EDIT For
  updating multiple documents use update options like :

db.collectionName.update({},{"$unset":{"values.727920":""}},{"multi":true})

Body:
am currently working in Go and have a mongo database (connected via gopkg.in/mgo.v2) so, right now I have a data structure similar to:

{
    "_id" : "some_id_bson",
    "field1" : "value1",
    "field2" : {
      {
      "key1" : "v1",
      "key2" : "v2",
      "key3" : "v3",
      "key4" : "v4"
      }
    }
}

So, basically what I need to do (as an example) is to update in the database all the records that contains key1 and remove that from the json, so the result would be something like:

{
        "_id" : "some_id_bson",
        "field1" : "value1",
        "field2" : {
          {
          "key2" : "v2",
          "key3" : "v3",
          "key4" : "v4"
          }
        }
    }

What can I use to achieve this? I have been searching and cannot find something oriented to maps (field2 is a map). Thanks in advance


答:
Try using $exists and $unset:

```<code>query:= bson.M{"$exists":bson.M{"field2.key1":true}}
replace:=bson.M{"$unset":bson.M{"field2.key1":""}}
collection.UpdateAll(query,replace)
</code>```

This should find all documents containing field2.key1, and remove that.

Title: updating mongo documents based in map value and remove that value

Body:
Try using $exists and $unset:

query:= bson.M{"$exists":bson.M{"field2.key1":true}}
replace:=bson.M{"$unset":bson.M{"field2.key1":""}}
collection.UpdateAll(query,replace)

This should find all documents containing field2.key1, and remove that.


问:
Refresh data in a JLabel
I have a program which calculates an integer and then uses the value within a JLabel. On intital creation everything is fine with the initialized value, but when I change the value of the int within the label I can't seem to find a way to update the JLabel. The relevant code is as follows:

```<code>    JLabel carbLbl;
    int totCarbs = 0;

    public Main() {
        carbLbl = new JLabel("Total Carbs: " + totCarbs);
        carbLbl.setFont(new Font("KidSans", Font.PLAIN, 38));
        carbLbl.setAlignmentX(Component.RIGHT_ALIGNMENT);

    void addFoodToTable() {
        String[] s = new String[3];
        s = (String[]) foodData.get(foodChoice.getSelectedIndex());
        foodList.addRow(s);
        totCarbs += Integer.parseInt(s[2]);
        carbLbl.repaint();
    }
}
</code>```

There's obviously much more code, but it's too long to include the entire script. Is there a way I can have the label update whenever I invoke the addFoodToTable() method?

答: The JLabel is not "bound" to your integer variable. When you change the integer you need to update the JLabel using carbLbl.setText(String.valueOf(totCarbs))

Title: Refresh data in a JLabel

Body:
I have a program which calculates an integer and then uses the value within a JLabel. On intital creation everything is fine with the initialized value, but when I change the value of the int within the label I can't seem to find a way to update the JLabel. The relevant code is as follows:

    JLabel carbLbl;
    int totCarbs = 0;

    public Main() {
        carbLbl = new JLabel("Total Carbs: " + totCarbs);
        carbLbl.setFont(new Font("KidSans", Font.PLAIN, 38));
        carbLbl.setAlignmentX(Component.RIGHT_ALIGNMENT);

    void addFoodToTable() {
        String[] s = new String[3];
        s = (String[]) foodData.get(foodChoice.getSelectedIndex());
        foodList.addRow(s);
        totCarbs += Integer.parseInt(s[2]);
        carbLbl.repaint();
    }
}

There's obviously much more code, but it's too long to include the entire script. Is there a way I can have the label update whenever I invoke the addFoodToTable() method?


问:
python: How to interpret indexing of slicing
Here is the code:

```<code>a = [0, 11, 22, 33, 44, 55]
a[1:4][1] = 666
print(a)
</code>```

The output is [0, 11, 22, 33, 44, 55]

So list a is not updated, then what is the effect of that assignment?

[UPDATE]
Thanks @Amadan for explanation, it makes sense. But I am still puzzled, the following slicing directly updates the list:

```<code>a[1:4] = [111, 222, 333]
</code>```

Intuitively I expect a[1:4][1] still operates on the list, but it is not.

Is my intuition wrong?

答:
a[1:4] creates a new list, whose elements are [11, 22, 33]. Then you replace its #1 element with 666, which results in a list [11, 666, 33]. Then, because this list is not referred to by any variable, it is forgotten and garbage collected.

Note that the result is very different if you have a numpy array instead of the list, since slicing of a numpy array creates a view, not a new array, if at all possible:

```<code>import numpy as np
a = np.array([0, 11, 22, 33, 44])
a[1:4][1] = 666
a
# => array([  0,  11, 666,  33,  44])
</code>```

Here, a[1:4] is not an independent [11, 22, 33], but a view into the original list, where changing a[1:4] actually changes a.

Body:
Here is the code:

a = [0, 11, 22, 33, 44, 55]
a[1:4][1] = 666
print(a)

The output is [0, 11, 22, 33, 44, 55]

So list a is not updated, then what is the effect of that assignment?

[UPDATE]
Thanks @Amadan for explanation, it makes sense. But I am still puzzled, the following slicing directly updates the list:

a[1:4] = [111, 222, 333]

Intuitively I expect a[1:4][1] still operates on the list, but it is not.

Is my intuition wrong?

Body:
a[1:4] creates a new list, whose elements are [11, 22, 33]. Then you replace its #1 element with 666, which results in a list [11, 666, 33]. Then, because this list is not referred to by any variable, it is forgotten and garbage collected.

Note that the result is very different if you have a numpy array instead of the list, since slicing of a numpy array creates a view, not a new array, if at all possible:

import numpy as np
a = np.array([0, 11, 22, 33, 44])
a[1:4][1] = 666
a
# => array([  0,  11, 666,  33,  44])

Here, a[1:4] is not an independent [11, 22, 33], but a view into the original list, where changing a[1:4] actually changes a.


问:
How do you display content of a .JSON file using Discord.js?
Currently my code reads out as

if(message.content.startsWith(prefix + 'readback')) {

  fs.readFile('msgs.json', (err, data) => {
    if (err) throw err;
    let _msgs = JSON.parse(data);
    message.channel.send(_msgs);
    console.log(_msgs)
  });
}
```

with all appropriate constants and variables

While using prefix + 'readback, the Discord Bot displays _msgs as [object Object] - to make sure it wasn't an issue with the code, I added console.log(_msgs), and the correct JSON file content displays in the console. Is there a way to get the Bot to display the contents of the JSON file in a channel?

答:
```<code>fs.readFile('msgs.json', (err, data) => {
  if (err) throw err;
  let _msgs = JSON.stringify(JSON.parse(data), null, 2);
   message.channel.send(_msgs);
   console.log(_msgs)
});
</code>```

This will format the JSON as multi-line with 2-space indentation.

If you do:

```<code>message.channel.send(data);
</code>```

Then you'll get JSON but with no formatting.

Body:
Currently my code reads out as

if(message.content.startsWith(prefix + 'readback')) {

  fs.readFile('msgs.json', (err, data) => {
    if (err) throw err;
    let _msgs = JSON.parse(data);
    message.channel.send(_msgs);
    console.log(_msgs)
  });
}

with all appropriate constants and variables

While using prefix + 'readback, the Discord Bot displays _msgs as [object Object] - to make sure it wasn't an issue with the code, I added console.log(_msgs), and the correct JSON file content displays in the console. Is there a way to get the Bot to display the contents of the JSON file in a channel?

Body:
fs.readFile('msgs.json', (err, data) => {
  if (err) throw err;
  let _msgs = JSON.stringify(JSON.parse(data), null, 2);
   message.channel.send(_msgs);
   console.log(_msgs)
});

This will format the JSON as multi-line with 2-space indentation.

If you do:

message.channel.send(data);

Then you'll get JSON but with no formatting.


问:
How to omit null field from Swagger/OpenAPI in ResponseEntity?
I'm trying to omit null values in my ResponseEntity.

My controller looks something like this:

@RestController
public class FooController {

    //fields
    //constructor

    @PostMapping
    public ResponseEntity<CreateFooResponseV10> createFoo(@Valid @RequestBody CreateFooRequestV10 foo, HttpServletRequest request) {
        //some minor logic
        return new ResponseEntity<>(aFooResponseV10Builder()
                .withFirstName(foo.getFirstName())
                .withLastName(foo.getLastName())
                .withTestField(NULLABLE_OBJECT)
                .build(), ...);
    //I generated the builders from the output classes openapi-generator provided
    }
    // more stuff...
}
```

<p>When <code>NULLABLE_OBJECT</code> is equal to <code>null</code> I expect the field to be omitted from the response like this:</p>

```{
  "firstName": "John",
  "lastName": "Doe"
}
```

<p>But I either get these responses, depending on what I've tried so far:</p>

```{
  "firstName": "John",
  "lastName": "Doe",
  "testField": null
}
```

<p>or</p>

```{
   "firstName": "John",
   "lastName": "Doe",
   "testField": {"present":false}
}
```

<p>I generate my request/response objects (<code>CreateFooResponseV10</code> and <code>CreateFooRequestV10</code>) with the use of openapi-generator</p>

<p>Here is my redacted <code>api.json</code> file:</p>

```{
  "openapi": "3.0.1",
  "info": { ... },
  "servers": [ ... ],
  "paths": {
    "/foo": {
      "post": {
        ...
        "requestBody": {
          "description": "Foo to be created",
          "content": {
            "application/foo+json;version=1.0": {
              "schema": {
                "$ref": "#/components/schemas/CreateFooRequest_V1_0"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Foo is successfully created",
            "headers": { ... },
            "content": {
              "application/foo+json": {
                "schema": {
                  "$ref": "#/components/schemas/CreateFooResponse_V1_0"
                }
              }
            }
          },
          ...
        }
      }
    }
  },
  "components": {
    "schemas": {
      "CreateFooRequest_V1_0": {
        "required": [
          "firstName",
          "lastName"
        ],
        "type": "object",
        "properties": {
          "firstName": { ... },
          "lastName": { ... },
          "testField": {
            "description": "...",
            "type": "string",
            "nullable": true
          }
        }
      },
      "CreateFooResponse_V1_0": {
        "required": [
          "firstName",
          "lastName"
        ],
        "type": "object",
        "properties": {
          "firstName": { ... },
          "lastName": { ... },
          "testField": {
            "description": "...",
            "type": "string",
            "nullable": true
          }
        }
      }
    }
  }
}
```

As you can see in both the request and response testField is not required and can be nullable.
So when testField is null it should be hidden from the response, but when it contains some date it should be shown of course.

I've tried overriding jackson's ObjectMapper bean as explained in this answer. Didn't work.

I've tried adding spring.jackson.default-property-inclusion=non_null to the application.properties. Didn't work.

What I think should work is adding @JsonIgnore above testField of the generated classes, but I don't know if this is something needed to be done manually (for each schema component, can be a lot of manual work for something that is generated) or if this can be configured in the plugin somewhere.

Thanks in advance.

extra info

OpenAPI 3.0.1

Maven 3.6.3

Java 11.0.2

jackson-databind-nullable 0.2.1

openapi-generator-maven-plugin 4.2.2

答:
Try this code. I tested and it works.

```<code>@RestController
@RequestMapping("/testws")
public class TestWS {
    @RequestMapping(value = "test", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<TestBean> test(@Context HttpServletRequest request) {
        TestBean testBean = new TestBean("John", "Doe", null);
        return ResponseEntity.ok()
                .body(testBean);
    }
}

@JsonInclude(Include.NON_NULL)
class TestBean {
    private String firstName;
    private String lastName;
    private String testField;

    public TestBean() {

    }

    public TestBean(String firstName, String lastName, String testField) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.testField = testField;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getTestField() {
        return testField;
    }

    public void setTestField(String testField) {
        this.testField = testField;
    }

}
</code>```

Json response:

```<code>{"firstName":"John","lastName":"Doe"}
</code>```

Body:
I'm trying to omit null values in my ResponseEntity.

My controller looks something like this:

@RestController
public class FooController {

    //fields
    //constructor

    @PostMapping
    public ResponseEntity<CreateFooResponseV10> createFoo(@Valid @RequestBody CreateFooRequestV10 foo, HttpServletRequest request) {
        //some minor logic
        return new ResponseEntity<>(aFooResponseV10Builder()
                .withFirstName(foo.getFirstName())
                .withLastName(foo.getLastName())
                .withTestField(NULLABLE_OBJECT)
                .build(), ...);
    //I generated the builders from the output classes openapi-generator provided
    }
    // more stuff...
}

When NULLABLE_OBJECT is equal to null I expect the field to be omitted from the response like this:

{
  "firstName": "John",
  "lastName": "Doe"
}

But I either get these responses, depending on what I've tried so far:

{
  "firstName": "John",
  "lastName": "Doe",
  "testField": null
}

or

{
   "firstName": "John",
   "lastName": "Doe",
   "testField": {"present":false}
}

I generate my request/response objects (CreateFooResponseV10 and CreateFooRequestV10) with the use of openapi-generator

Here is my redacted api.json file:

{
  "openapi": "3.0.1",
  "info": { ... },
  "servers": [ ... ],
  "paths": {
    "/foo": {
      "post": {
        ...
        "requestBody": {
          "description": "Foo to be created",
          "content": {
            "application/foo+json;version=1.0": {
              "schema": {
                "$ref": "#/components/schemas/CreateFooRequest_V1_0"
              }
            }
          },
          "required": true
        },
        "responses": {
          "201": {
            "description": "Foo is successfully created",
            "headers": { ... },
            "content": {
              "application/foo+json": {
                "schema": {
                  "$ref": "#/components/schemas/CreateFooResponse_V1_0"
                }
              }
            }
          },
          ...
        }
      }
    }
  },
  "components": {
    "schemas": {
      "CreateFooRequest_V1_0": {
        "required": [
          "firstName",
          "lastName"
        ],
        "type": "object",
        "properties": {
          "firstName": { ... },
          "lastName": { ... },
          "testField": {
            "description": "...",
            "type": "string",
            "nullable": true
          }
        }
      },
      "CreateFooResponse_V1_0": {
        "required": [
          "firstName",
          "lastName"
        ],
        "type": "object",
        "properties": {
          "firstName": { ... },
          "lastName": { ... },
          "testField": {
            "description": "...",
            "type": "string",
            "nullable": true
          }
        }
      }
    }
  }
}

As you can see in both the request and response testField is not required and can be nullable.
So when testField is null it should be hidden from the response, but when it contains some date it should be shown of course.

I've tried overriding jackson's ObjectMapper bean as explained in this answer. Didn't work.

I've tried adding spring.jackson.default-property-inclusion=non_null to the application.properties. Didn't work.

What I think should work is adding @JsonIgnore above testField of the generated classes, but I don't know if this is something needed to be done manually (for each schema component, can be a lot of manual work for something that is generated) or if this can be configured in the plugin somewhere.

Thanks in advance.

extra info

OpenAPI 3.0.1

Maven 3.6.3

Java 11.0.2

jackson-databind-nullable 0.2.1

openapi-generator-maven-plugin 4.2.2

Body:
Try this code. I tested and it works.

@RestController
@RequestMapping("/testws")
public class TestWS {
    @RequestMapping(value = "test", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public ResponseEntity<TestBean> test(@Context HttpServletRequest request) {
        TestBean testBean = new TestBean("John", "Doe", null);
        return ResponseEntity.ok()
                .body(testBean);
    }
}

@JsonInclude(Include.NON_NULL)
class TestBean {
    private String firstName;
    private String lastName;
    private String testField;

    public TestBean() {

    }

    public TestBean(String firstName, String lastName, String testField) {
        super();
        this.firstName = firstName;
        this.lastName = lastName;
        this.testField = testField;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getTestField() {
        return testField;
    }

    public void setTestField(String testField) {
        this.testField = testField;
    }

}

Json response:

{"firstName":"John","lastName":"Doe"}


问:
TestRunConfig does not copy App.config file
Hello
I have a UnitTest project, and I added multiple App.config files (never copied to the output directory). I have created runtestconfig files for different configuration I need.

```<code><DeploymentItem filename="Config01\App.config" />
</code>```

Each time I run the project using Mstest

```<code>mstest.exe /runconfig:Config01.testrunconfig /testcontainer:MyTests.dll
</code>```

or using VS2008 active configuration, my tests fail.
In solution output directory the App.config file never gets copied.

This is a test ex:

```<code>  [TestMethod]
  public void TestAge()
  {
     string value = ConfigurationManager.AppSettings["age"];
     Assert.AreEqual(value, "21");
  }
</code>```

and this is the error:Assert.AreEqual failed. Expected:<(null)>. Actual:<21>.

What am I doing wrong?

答:
I have solved my problem using xml files instead of App.config. Now if I change the configuration and I run the tests both in VS or command line using MSTest I get the expected results.
It seems it does not work using ConfigurationManager.AppSettings to read data from App.config files.</p>

Body:
Hello
I have a UnitTest project, and I added multiple App.config files (never copied to the output directory). I have created runtestconfig files for different configuration I need.

<DeploymentItem filename="Config01\App.config" />

Each time I run the project using Mstest

mstest.exe /runconfig:Config01.testrunconfig /testcontainer:MyTests.dll

or using VS2008 active configuration, my tests fail.
In solution output directory the App.config file never gets copied.

This is a test ex:

  [TestMethod]
  public void TestAge()
  {
     string value = ConfigurationManager.AppSettings["age"];
     Assert.AreEqual(value, "21");
  }

and this is the error:Assert.AreEqual failed. Expected:<(null)>. Actual:<21>.

What am I doing wrong?


问:
how to add columns to describe() table
I have a dataframe, used describe() on the dataframe, then inverted the describe() table.

Now, I want to add a column to this new table of skewness and kurtosis values.

I want to add a "Skewness" column and "Kurtosis" column to the right of "max" column. The Skewness column will have all of the skewness values of each row. The Kurtosis column will have the Kurtosis values of each row.

What you see so far is the transposed describe() table I called "summary_transpose"

```<code>                 count   mean    std   min    25%    50%    75%    max
Unnamed: 0      1000.0  499.5  288.8   0.0  249.8  499.5  749.2  999.0
FINAL_MARGIN    1000.0   -1.2   15.3 -39.0   -8.0   -2.0    8.0   28.0
SHOT_NUMBER     1000.0    6.4    4.7   1.0    3.0    5.0    9.0   23.0
PERIOD          1000.0    2.5    1.1   1.0    2.0    2.0    4.0    6.0
SHOT_CLOCK       979.0   11.8    5.4   0.3    8.0   11.5   15.0   24.0
DRIBBLES        1000.0    1.6    2.9   0.0    0.0    1.0    2.0   23.0
TOUCH_TIME      1000.0    2.9    2.6  -4.3    0.9    2.1    4.2   20.4
SHOT_DIST       1000.0   12.3    7.8   0.1    5.6   10.4   18.5   41.6
PTS_TYPE        1000.0    2.2    0.4   2.0    2.0    2.0    2.0    3.0
CLOSE_DEF_DIST  1000.0    3.6    2.3   0.0    2.1    3.1    4.7   19.8
FGM             1000.0    0.5    0.5   0.0    0.0    0.0    1.0    1.0
PTS             1000.0    1.0    1.1   0.0    0.0    0.0    2.0    3.0
</code>```

答:
The code below adds the Skewness and Kurtosis columns next to the max column.

```<code>import scipy.stats as stats
summary = round(df.describe(), 1) # rounds each value to 0.1
summary_transpose = summary.T # transposes the original summary table

summary_transpose['Skewness'] = stats.skew(df._get_numeric_data(), nan_policy='omit')
summary_transpose['Kurtosis'] = stats.kurtosis(df._get_numeric_data(), nan_policy='omit')
</code>```

Title: how to add columns to describe() table

Body:
I have a dataframe, used describe() on the dataframe, then inverted the describe() table.

Now, I want to add a column to this new table of skewness and kurtosis values.

I want to add a "Skewness" column and "Kurtosis" column to the right of "max" column. The Skewness column will have all of the skewness values of each row. The Kurtosis column will have the Kurtosis values of each row.

What you see so far is the transposed describe() table I called "summary_transpose"

                 count   mean    std   min    25%    50%    75%    max
Unnamed: 0      1000.0  499.5  288.8   0.0  249.8  499.5  749.2  999.0
FINAL_MARGIN    1000.0   -1.2   15.3 -39.0   -8.0   -2.0    8.0   28.0
SHOT_NUMBER     1000.0    6.4    4.7   1.0    3.0    5.0    9.0   23.0
PERIOD          1000.0    2.5    1.1   1.0    2.0    2.0    4.0    6.0
SHOT_CLOCK       979.0   11.8    5.4   0.3    8.0   11.5   15.0   24.0
DRIBBLES        1000.0    1.6    2.9   0.0    0.0    1.0    2.0   23.0
TOUCH_TIME      1000.0    2.9    2.6  -4.3    0.9    2.1    4.2   20.4
SHOT_DIST       1000.0   12.3    7.8   0.1    5.6   10.4   18.5   41.6
PTS_TYPE        1000.0    2.2    0.4   2.0    2.0    2.0    2.0    3.0
CLOSE_DEF_DIST  1000.0    3.6    2.3   0.0    2.1    3.1    4.7   19.8
FGM             1000.0    0.5    0.5   0.0    0.0    0.0    1.0    1.0
PTS             1000.0    1.0    1.1   0.0    0.0    0.0    2.0    3.0

Body:
The code below adds the Skewness and Kurtosis columns next to the max column.

import scipy.stats as stats
summary = round(df.describe(), 1) # rounds each value to 0.1
summary_transpose = summary.T # transposes the original summary table

summary_transpose['Skewness'] = stats.skew(df._get_numeric_data(), nan_policy='omit')
summary_transpose['Kurtosis'] = stats.kurtosis(df._get_numeric_data(), nan_policy='omit')


问:
mvvm using dagger2 with ViewModelFactory, dont understand default injection
I'm studying mvvm with AAC examples "https://github.com/android/architecture-samples".
hard to understand, I found something not understandable.
the project has ViewModel and ViewModelFactory.
the point I wanna know is that how the ViewModel of TaskFragment is injected by DefaultTasksRepository.</p>

```<code>class TasksFragment : DaggerFragment() {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    private val viewModel by viewModels<TasksViewModel> { viewModelFactory }
}
</code>```

```<code>class TasksViewModel @Inject constructor(
    private val tasksRepository: TasksRepository
) : ViewModel() {
}
</code>```

```<code>class DefaultTasksRepository @Inject constructor(
    @TasksRemoteDataSource private val tasksRemoteDataSource: TasksDataSource,
    @TasksLocalDataSource private val tasksLocalDataSource: TasksDataSource,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
}
</code>```

```<code>interface TasksRepository {

    suspend fun getTasks(forceUpdate: Boolean = false): Result<List<Task>>

    suspend fun getTask(taskId: String, forceUpdate: Boolean = false): Result<Task>

    suspend fun saveTask(task: Task)

    suspend fun completeTask(task: Task)

    suspend fun completeTask(taskId: String)

    suspend fun activateTask(task: Task)

    suspend fun activateTask(taskId: String)

    suspend fun clearCompletedTasks()

    suspend fun deleteAllTasks()

    suspend fun deleteTask(taskId: String)
}
</code>```

答:
DefaultTasksRepository @Inject constructor(), this has been registered in dagger so that we can use its reference from anywhere.

TasksViewModel @Inject constructor(), this will create TasksViewModel reference but before that it will create instance of DefaultTasksRepository and will pass into constructor of TasksViewModel.

Then you can inject TasksViewModel and use anywhere.

Body:
I'm studying mvvm with AAC examples "https://github.com/android/architecture-samples".
hard to understand, I found something not understandable.
the project has ViewModel and ViewModelFactory.
the point I wanna know is that how the ViewModel of TaskFragment is injected by DefaultTasksRepository.

class TasksFragment : DaggerFragment() {

    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory

    private val viewModel by viewModels<TasksViewModel> { viewModelFactory }
}

class TasksViewModel @Inject constructor(
    private val tasksRepository: TasksRepository
) : ViewModel() {
}

class DefaultTasksRepository @Inject constructor(
    @TasksRemoteDataSource private val tasksRemoteDataSource: TasksDataSource,
    @TasksLocalDataSource private val tasksLocalDataSource: TasksDataSource,
    private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) : TasksRepository {
}

interface TasksRepository {

    suspend fun getTasks(forceUpdate: Boolean = false): Result<List<Task>>

    suspend fun getTask(taskId: String, forceUpdate: Boolean = false): Result<Task>

    suspend fun saveTask(task: Task)

    suspend fun completeTask(task: Task)

    suspend fun completeTask(taskId: String)

    suspend fun activateTask(task: Task)

    suspend fun activateTask(taskId: String)

    suspend fun clearCompletedTasks()

    suspend fun deleteAllTasks()

    suspend fun deleteTask(taskId: String)
}


问:
JustGage not defined after upgrading to angular 8
After upgrading my apps from angular 7.2 to 8.2. the angular2-just-gage module(link) that i used throwing error.
First, is about "eve not defined", i tried upgrading raphael from version 2.2.7 to 2.2.8. But then it throw another error

justgage.js:8 Uncaught ReferenceError: JustGage is not defined
      at Object../node_modules/justgage/justgage.js (justgage.js:8)

I have tried updating JustGage and raphael module to latest version but still throwing the same error. Is there anyone who also encouter this issue and has the fix?

答:
Hmmm, I have it working in angular 8.2.4
I'm using these versions of the libraries...

"justgage": "^1.3.5",
"raphael": "2.2.8"


问:
NULL reference exception while reading user sessions (Reflection)
I have implemented the code for reading the active sessions using the reference Reading All Users Session and Get a list of all active sessions in ASP.NET.

```<code>Private List<String> getOnlineUsers()
{
    List<String> activeSessions = new List<String>();
    object obj = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null, null);
    object[] obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
    for (int i = 0; i < obj2.Length; i++)
    {
        Hashtable c2 = (Hashtable)obj2[i].GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj2[i]);
        foreach (DictionaryEntry entry in c2)
        {
            object o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value, null);
            if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState")
            {
                SessionStateItemCollection sess = (SessionStateItemCollection)o1.GetType().GetField("_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o1);
                if (sess != null)
                {
                    if (sess["loggedInUserId"] != null)
                    {
                        activeSessions.Add(sess["loggedInUserId"].ToString());
                    }
                }
            }
        }
    }
    return activeSessions;
}
</code>```

It is working fine in local system (in windows XP and Windows 7). While I hosted the application in Windows server 2003 (IIS version 6), it gives an NULL object reference error in the line

```<code>object[] obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
</code>```

Is this anything related to the permission issue or trust level settings related to IIS? Please let know anyone came across such an issue. Any help is highly appreciable.

答:
As of Feb. 2010, testing on IIS 10.0 (Windows 10), the above solutions didn't quite work, so I hacked together the following which worked for me. It builds on awerdan's answer and incorporates Diogo Damiani's.</p>

```<code>    // attempt to get Asp.Net internal cache
    // adapted from https://stackoverflow.com/a/46554310/1086134
    private static object getAspNetInternalCacheObj ()
    {
        object aspNetCacheInternal = null;

        PropertyInfo cacheInternalPropInfo = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static);
        if (cacheInternalPropInfo != null)
        {
            aspNetCacheInternal = cacheInternalPropInfo.GetValue(null, null);
            return aspNetCacheInternal;
        }

        // At some point, after some .NET Framework's security update, that internal member disappeared.
        // https://stackoverflow.com/a/45045160
        //
        // We need to look for internal cache otherwise.
        //
        var cacheInternalFieldInfo = HttpRuntime.Cache.GetType().GetField("_internalCache", BindingFlags.NonPublic | BindingFlags.Static);
        if (cacheInternalFieldInfo == null)
            return null;

        var httpRuntimeInternalCache = cacheInternalFieldInfo.GetValue(HttpRuntime.Cache);
        var httpRuntimeInternalCacheField = httpRuntimeInternalCache.GetType().GetField("_cacheInternal", BindingFlags.NonPublic | BindingFlags.Instance);
        if (httpRuntimeInternalCacheField == null)
            return null;

        aspNetCacheInternal = httpRuntimeInternalCacheField.GetValue(httpRuntimeInternalCache);
        return aspNetCacheInternal;
    }

    // adapted from https://stackoverflow.com/a/39422431/1086134
    private static IEnumerable<System.Web.SessionState.SessionStateItemCollection> getAllUserSessions()
    {
        List<Hashtable> hTables = new List<Hashtable>();
        object obj = getAspNetInternalCacheObj();
        if (obj == null)
            yield break;

        dynamic fieldInfo = obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance);
        //If server uses "_caches" to store session info
        if (fieldInfo != null)
        {
            object[] _caches = (object[])fieldInfo.GetValue(obj);
            for (int i = 0; i <= _caches.Length - 1; i++)
            {
                Hashtable hTable = (Hashtable)_caches[i].GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(_caches[i]);
                hTables.Add(hTable);
            }
        }
        //If server uses "_cachesRefs" to store session info
        else
        {
            fieldInfo = obj.GetType().GetField("_cachesRefs", BindingFlags.NonPublic | BindingFlags.Instance);
            object[] cacheRefs = fieldInfo.GetValue(obj);
            for (int i = 0; i <= cacheRefs.Length - 1; i++)
            {
                var target = cacheRefs[i].GetType().GetProperty("Target").GetValue(cacheRefs[i], null);
                Hashtable hTable = (Hashtable)target.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target);
                hTables.Add(hTable);
            }
        }

        foreach (Hashtable hTable in hTables)
        {
            foreach (DictionaryEntry entry in hTable)
            {
                object o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value, null);
                if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState")
                {
                    System.Web.SessionState.SessionStateItemCollection sess = (System.Web.SessionState.SessionStateItemCollection)o1.GetType().GetField("_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o1);
                    if (sess != null)
                        yield return sess;
                }
            }
        }
    }
</code>```

Body:
I have implemented the code for reading the active sessions using the reference Reading All Users Session and Get a list of all active sessions in ASP.NET.

Private List<String> getOnlineUsers()
{
    List<String> activeSessions = new List<String>();
    object obj = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static).GetValue(null, null);
    object[] obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);
    for (int i = 0; i < obj2.Length; i++)
    {
        Hashtable c2 = (Hashtable)obj2[i].GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj2[i]);
        foreach (DictionaryEntry entry in c2)
        {
            object o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value, null);
            if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState")
            {
                SessionStateItemCollection sess = (SessionStateItemCollection)o1.GetType().GetField("_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o1);
                if (sess != null)
                {
                    if (sess["loggedInUserId"] != null)
                    {
                        activeSessions.Add(sess["loggedInUserId"].ToString());
                    }
                }
            }
        }
    }
    return activeSessions;
}

It is working fine in local system (in windows XP and Windows 7). While I hosted the application in Windows server 2003 (IIS version 6), it gives an NULL object reference error in the line

object[] obj2 = (object[])obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(obj);

Is this anything related to the permission issue or trust level settings related to IIS? Please let know anyone came across such an issue. Any help is highly appreciable.

Body:
As of Feb. 2010, testing on IIS 10.0 (Windows 10), the above solutions didn't quite work, so I hacked together the following which worked for me. It builds on awerdan's answer and incorporates Diogo Damiani's.

    // attempt to get Asp.Net internal cache
    // adapted from https://stackoverflow.com/a/46554310/1086134
    private static object getAspNetInternalCacheObj ()
    {
        object aspNetCacheInternal = null;

        PropertyInfo cacheInternalPropInfo = typeof(HttpRuntime).GetProperty("CacheInternal", BindingFlags.NonPublic | BindingFlags.Static);
        if (cacheInternalPropInfo != null)
        {
            aspNetCacheInternal = cacheInternalPropInfo.GetValue(null, null);
            return aspNetCacheInternal;
        }

        // At some point, after some .NET Framework's security update, that internal member disappeared.
        // https://stackoverflow.com/a/45045160
        //
        // We need to look for internal cache otherwise.
        //
        var cacheInternalFieldInfo = HttpRuntime.Cache.GetType().GetField("_internalCache", BindingFlags.NonPublic | BindingFlags.Static);
        if (cacheInternalFieldInfo == null)
            return null;

        var httpRuntimeInternalCache = cacheInternalFieldInfo.GetValue(HttpRuntime.Cache);
        var httpRuntimeInternalCacheField = httpRuntimeInternalCache.GetType().GetField("_cacheInternal", BindingFlags.NonPublic | BindingFlags.Instance);
        if (httpRuntimeInternalCacheField == null)
            return null;

        aspNetCacheInternal = httpRuntimeInternalCacheField.GetValue(httpRuntimeInternalCache);
        return aspNetCacheInternal;
    }

    // adapted from https://stackoverflow.com/a/39422431/1086134
    private static IEnumerable<System.Web.SessionState.SessionStateItemCollection> getAllUserSessions()
    {
        List<Hashtable> hTables = new List<Hashtable>();
        object obj = getAspNetInternalCacheObj();
        if (obj == null)
            yield break;

        dynamic fieldInfo = obj.GetType().GetField("_caches", BindingFlags.NonPublic | BindingFlags.Instance);
        //If server uses "_caches" to store session info
        if (fieldInfo != null)
        {
            object[] _caches = (object[])fieldInfo.GetValue(obj);
            for (int i = 0; i <= _caches.Length - 1; i++)
            {
                Hashtable hTable = (Hashtable)_caches[i].GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(_caches[i]);
                hTables.Add(hTable);
            }
        }
        //If server uses "_cachesRefs" to store session info
        else
        {
            fieldInfo = obj.GetType().GetField("_cachesRefs", BindingFlags.NonPublic | BindingFlags.Instance);
            object[] cacheRefs = fieldInfo.GetValue(obj);
            for (int i = 0; i <= cacheRefs.Length - 1; i++)
            {
                var target = cacheRefs[i].GetType().GetProperty("Target").GetValue(cacheRefs[i], null);
                Hashtable hTable = (Hashtable)target.GetType().GetField("_entries", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(target);
                hTables.Add(hTable);
            }
        }

        foreach (Hashtable hTable in hTables)
        {
            foreach (DictionaryEntry entry in hTable)
            {
                object o1 = entry.Value.GetType().GetProperty("Value", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(entry.Value, null);
                if (o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState")
                {
                    System.Web.SessionState.SessionStateItemCollection sess = (System.Web.SessionState.SessionStateItemCollection)o1.GetType().GetField("_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(o1);
                    if (sess != null)
                        yield return sess;
                }
            }
        }
    }


问:
Which part of my code is running?
I have a 5k lines software that is running, and it is running at 50% CPU usage. It's quite high, and I used some 3rd party assemblies. So can I from Visual Studio, determine which part of my code is running, without using breakpoint? Using breakpoint won't detect CPU usage, because the program is not running when it stop at that particular point.

I am using visual studio 2010, c#.

Thanks.

答: You need Visual Studio® Team System Development Edition or Visual Studio Team Suite. If you have one, run Profiler using the Performance Wizard. (list of other profliers).

Title: Which part of my code is running?


问:
Problem with changing schedule_id in table msdb.dbo.sysjobschedules
I've got a script that changes the schedule on a job, but the problem is that even if it looks right when looking in SQL Server agent it still operates like the old schedule.

This is how I change the schedule;

```<code>update msdb.dbo.sysjobschedules
set schedule_id = 25
where job_id = '1256497D-2960-469A-AE91-F4E750AD5AC7'
</code>```

I've tried using sp_update_job to disable and then enable it again but that wont help.

Is there another way to change a jobs schedule?

Running SQL2014.

/Tomas

答:
You have to use sp_detach_schedule and sp_attach_schedule to remove and add a schedule.

sp_attach_schedule

https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-attach-schedule-transact-sql

sp_detach_schedule

https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-detach-schedule-transact-sql

Body:
I've got a script that changes the schedule on a job, but the problem is that even if it looks right when looking in SQL Server agent it still operates like the old schedule.

This is how I change the schedule;

update msdb.dbo.sysjobschedules
set schedule_id = 25
where job_id = '1256497D-2960-469A-AE91-F4E750AD5AC7'

I've tried using sp_update_job to disable and then enable it again but that wont help.

Is there another way to change a jobs schedule?

Running SQL2014.

/Tomas


问:
R: how to extract full date from year week?
I have a date in the follow format (year and week number):

```<code>year_week
201804
201938
201745
201402
201510
</code>```

I need to get the full date in such format: 2018-02-26 (%Y-%m-%d).
I use the next code for this purpose:

```<code>dt[, full_date := format(ISOweek2date(sub("(\\d{4})(\\d{2})", "\\1-W\\2-1", year_week)),"%Y-%m-%d")]
</code>```

but, I have the following error:

```<code>"Error: all(is.na(weekdate) | stringr::str_detect(weekdate, kPattern)) is not TRUE"
</code>```

How can I get the full date in another way?
Why am I having this error?

Thanks a lot for any help!

P.S. Sunday or Monday can be used as the first day of week.

Body:
I have a date in the follow format (year and week number):

year_week
201804
201938
201745
201402
201510

I need to get the full date in such format: 2018-02-26 (%Y-%m-%d).
I use the next code for this purpose:

dt[, full_date := format(ISOweek2date(sub("(\\d{4})(\\d{2})", "\\1-W\\2-1", year_week)),"%Y-%m-%d")]

but, I have the following error:

"Error: all(is.na(weekdate) | stringr::str_detect(weekdate, kPattern)) is not TRUE"

How can I get the full date in another way?
Why am I having this error?

Thanks a lot for any help!

P.S. Sunday or Monday can be used as the first day of week.

Body:
You can add a weekday to the date and use

as.Date(paste0(df$year_week, 1),"%Y%U%u")
#[1] "2018-01-29" "2019-09-23" "2017-11-06" "2014-01-13" "2015-03-09"

data

df <- structure(list(year_week = c(201804L, 201938L, 201745L, 201402L,
201510L)), class = "data.frame", row.names = c(NA, -5L))


问:
How to get unique values in one column based on unique values in other column
How can I transform this

A   P   1

A   Q   2

A   P   1

B   P   1

B   Q   2

B   R   3

C   P   1

C   P   1

C   Q   2

Into this:

A   P   1

A   Q   2

B   P   1

B   Q   2

B   R   3

C   P   1

C   Q   2

More info:
The values in 1st column have common values in Column B which have a relative values in Column C. Column B has multiple of common values for Column A. I want to filter/use other tools to only show unique values in Column B along with Column C which will unique to same value of Column A.

There are also other columns which are different values per entry but I don't care about those.

答:
use simple UNIQUE:

```<code>=UNIQUE(A1:C)
</code>```

Body:
use simple UNIQUE:

=UNIQUE(A1:C)


问:
Adding parameters to URL, putting array in query string

Objective

I've built an interactive where people can choose six players to make their all-star team. When they click share to Twitter, my hope is to have a URL containing parameters of all six players something like website.com/?playerName=picked?playerName=picked so that people can share their teams

Question

What is the best way to append parameters to a URL?

How do you put an array into a query string?

答:
Cleaner:

```<code>website.com/?players=player1,player2,player3,player4
</code>```

Then split the query to get result:

```<code>var arrayResult = query.players.split(",")
</code>```

Body:
Cleaner:

website.com/?players=player1,player2,player3,player4

Then split the query to get result:

var arrayResult = query.players.split(",")


问:
How to add the Api Key as Authorization header with its key value
As in postman their is type authorization called Api Key it gives three parmaters, Key, Value and Add to.

I have set Key to SECRET_KEY and VALUE to sdsfdsfsdf3343 and Add to: Headers

This successfully working at my backend, And I am able get that value their.

How would I set this Api key to header from my app, How to add authorization header with Key value in javascript react-native application

答:
Do you mean something like this?</p>

```<code>fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Key: 'sdsfdsfsdf3343' <------------ Put your key here?
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});
</code>```

Body:
Do you mean something like this?

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    Key: 'sdsfdsfsdf3343' <------------ Put your key here?
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  }),
});


问:
How do I pass an objectId through a URL?
I am a new programmer who is trying to learn how to create a CRUD application. I am trying to pass an objectID as a parameter through a URL.

```<code><tr>
      <td>{{this.Name}}<hr></td>
      <td>{{this.Email}}<hr></td>
      <td>{{this.Phone}}<hr></td>
      <td>
           <a href="/contacts/delete/<%= this._id %>">Delete</a>
      </td>
</tr>
</code>```

After passing the parameter I am trying to display the ID on another page with this code:

```<code>app.get('/contacts/delete/:id', function(req, res){
    const ContactId = new ObjectId(req.params.id);
    res.send(ContactId);
});
</code>```

When I run my API I am getting this error:

Cannot GET /contacts/delete/%3C%25=%20this._id%20%25%253E

答:
It needs to be this:</p>

```<code><tr>
      <td>{{this.Name}}<hr></td>
      <td>{{this.Email}}<hr></td>
      <td>{{this.Phone}}<hr></td>
      <td>
           <a href="/contacts/delete/{{this._id}}>">Delete</a>
      </td>
</tr>
</code>```

Body:
I am a new programmer who is trying to learn how to create a CRUD application. I am trying to pass an objectID as a parameter through a URL.

      {{this.Name}}

      {{this.Email}}

      {{this.Phone}}

           <a href="/contacts/delete/<%= this._id %>">Delete

After passing the parameter I am trying to display the ID on another page with this code:

app.get('/contacts/delete/:id', function(req, res){
    const ContactId = new ObjectId(req.params.id);
    res.send(ContactId);
});

When I run my API I am getting this error:

Cannot GET /contacts/delete/%3C%25=%20this._id%20%25%253E

Body:
It needs to be this:

<tr>
      <td>{{this.Name}}<hr></td>
      <td>{{this.Email}}<hr></td>
      <td>{{this.Phone}}<hr></td>
      <td>
           <a href="/contacts/delete/{{this._id}}>">Delete</a>
      </td>
</tr>


问:
Rotating a 3d polygon into xy-plane while maintaining orientation
I have a polygon oriented any way and positioned anywhere in 3d space. I need to transform the polygon into the xy-plane so that I can perform various operations on it (in particular generating a grid of points across the bounding box of the polygon) in 2d rather than 3d, then transform it back.

The problem comes with the orientation of the transformed polygon. If I just wanted to rotate into the plane, I could take the angle between the polygon's normal and the xy-plane and rotate around an axis orthogonal to both (cross product). However, I require that the polygon's bounding box be oriented such that the bottom (lowest z-value) edge of the bounding box is coplanar with the xy-plane, both before and after transformation. In other words, the bounding box is resting flush on one side which is parallel to the ground. After transformation, this edge would be parallel to the x-axis. This is so that the grid of points I generate on the surface will always have rows running parallel to the ground, regardless of the polygon's orientation.

My approach is to perform two rotations; first rotate around the z-axis by the angle between the line formed by the intersection of the polygon's plane and the xy-plane, and the x-axis. This ensures that the bottom of the bounding box is not moving out of the xy-plane. Then, rotate again around the x-axis by the angle between the polygon's (new) normal and the xz-plane. Here are the steps:

Find the equation for the polygon's plane (from the normal).

Find the intersection of the polygon's plane and the xy-plane. This is a line in the xy-plane.

Find the angle between this line and the x-axis.

Rotate the polygon by this angle around the z-axis.

Determine new normal.

Find the angle between new normal and xy-plane's normal.

Rotate the polygon by this angle around the x-axis.

The polygon should now be in the xy-plane; generate bounding box using max/min x and y values, generate point grid, etc., then transform everything back to where it started.

I realize that two rotations should be combined to reduce the number of matrix multiplications, but this is the general algorithm.

I'm not a graphics expert; can anyone offer advice on this technique? Is there a better way? Does my approach sound correct? I am developing in Java and am looking at using the Transform3D class for the rotations.

Body:
You need the following matrix to change vertex coordinates from frame x0,y0,z0, to x1,y1,z1 and eventually a translation to make origins coincide.

     // F0 changes x0,y0,z0 to world X,Y,Z
     F0[0, 0] = X0.X;
     F0[0, 1] = X0.Y;
     F0[0, 2] = X0.Z;
     F0[1, 0] = Y0.X;
     F0[1, 1] = Y0.Y;
     F0[1, 2] = Y0.Z;
     F0[2, 0] = Z0.X;
     F0[2, 1] = Z0.Y;
     F0[2, 2] = Z0.Z;
     F0[3, 3] = 1.0;

     // F1 changes world X,Y,Z to x1,y1,z1
     F1[0, 0] = X1.X;
     F1[0, 1] = Y1.X;
     F1[0, 2] = Z1.X;
     F1[1, 0] = X1.Y;
     F1[1, 1] = Y1.Y;
     F1[1, 2] = Z1.Y;
     F1[2, 0] = X1.Z;
     F1[2, 1] = Y1.Z;
     F1[2, 2] = Z1.Z;
     F1[3, 3] = 1.0;

     matrix = F1*F0


问:
How to map Dart String with FFI
I've the Dart type as:

typedef dart_func = String Function(String x);
```

<p>And want to map it with Dart FFi, but their could not find neither String, nor Utf8, I tried</p>

<pre class="lang-dart prettyprint-override"><code>typedef ffi_func = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> x);
</code>```

But it failed, and gave that Utf8 isn't a type

答:
You need to include the ffi package too: https://pub.dev/packages/ffi

Simple usage is:

```<code>import 'package:ffi/ffi.dart';

  final foo = 'foo';
  final fooNative = foo.toNativeUtf8(); // a Pointer<Utf8>

  // given a Pointer<Utf8>, get a Dart string
  final fooDart = fooNative.toDartString();

  // don't forget to free the pointer created by toNativeUtf8
  malloc.free(fooNative);
</code>```

Example code is here: https://github.com/dart-lang/samples/blob/master/ffi/structs/structs.dart

Title: How to map Dart String with FFI

Body:
I've the Dart type as:

typedef dart_func = String Function(String x);

And want to map it with Dart FFi, but their could not find neither String, nor Utf8, I tried

typedef ffi_func = ffi.Pointer<Utf8> Function(ffi.Pointer<Utf8> x);

But it failed, and gave that Utf8 isn't a type

Body:
You need to include the ffi package too: https://pub.dev/packages/ffi

Simple usage is:

import 'package:ffi/ffi.dart';

  final foo = 'foo';
  final fooNative = foo.toNativeUtf8(); // a Pointer<Utf8>

  // given a Pointer<Utf8>, get a Dart string
  final fooDart = fooNative.toDartString();

  // don't forget to free the pointer created by toNativeUtf8
  malloc.free(fooNative);

Example code is here: https://github.com/dart-lang/samples/blob/master/ffi/structs/structs.dart


问:
Question about dafny to prove the Lemma in seq<int>
I just start learning with dafny. Now I have predicate:

```<code>predicate allEqual(s:seq<int>)
//{forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] }
//{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] }
//{forall i::0<i<|s| ==> s[i-1]==s[i]}
{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]}
</code>```

and then I need to prove the Lemma :

```<code>lemma equivalenceContiguous(s:seq<int>)
ensures (allEqual(s) <==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1])
</code>```

how can I do to prove this? As I know I need to write "assert" or something?

答:
This proof is especially easy, since you're trying to prove that allEqual is what it is defined to be. Just add an empty body to the lemma:

```<code>lemma equivalenceContiguous(s: seq<int>)
  ensures allEqual(s) <==> forall i :: 0 <= i < |s| - 1 ==> s[i] == s[i+1]
{
}
</code>```

Body:
I just start learning with dafny. Now I have predicate:

predicate allEqual(s:seq<int>)
//{forall i,j::0<=i<|s| && 0<=j<|s| ==> s[i]==s[j] }
//{forall i,j::0<=i<=j<|s| ==> s[i]==s[j] }
//{forall i::0<i<|s| ==> s[i-1]==s[i]}
{forall i::0<=i<|s|-1 ==> s[i]==s[i+1]}

and then I need to prove the Lemma :

lemma equivalenceContiguous(s:seq<int>)
ensures (allEqual(s) <==> forall i::0<=i<|s|-1 ==> s[i]==s[i+1])

how can I do to prove this? As I know I need to write "assert" or something?

Body:
This proof is especially easy, since you're trying to prove that allEqual is what it is defined to be. Just add an empty body to the lemma:

lemma equivalenceContiguous(s: seq<int>)
  ensures allEqual(s) <==> forall i :: 0 <= i < |s| - 1 ==> s[i] == s[i+1]
{
}


问:
Cloning a Gitlab project to a Google Colab instance using SSH or HTTPS
My issue is that I would like to connect a Google Colab instance with a Gitlab project, but neither SSH nor HTTPS seem to work. From the error messages, I suspect setting-related issues in Colab. Maybe I have to allow Colab to connect to Gitlab and put it on a whitelist somewhere?

Running the following shell commands from a Notebook in Colab while being in the '/content' directory

```<code>git config --global user.name "mr_bla"
git config --global user.email "bla@wbla.bla"
git clone https://gitlab.com/mr_bla/mr_blas_project.git
</code>```

results in the following error messages:

```<code>Cloning into 'mr_blas_project'...
fatal: could not read Username for 'https://gitlab.com': No such device or address
</code>```

I have generated SSH keys as I'm used to, but the SSH check

```<code>ssh -vvvT git@gitlab.com:mr_bla/mr_blas_project.git
</code>```

fails, leading to the following error:

```<code>OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com:mr_bla/mr_blas_project.git" port 22
ssh: Could not resolve hostname gitlab.com:mr_bla/mr_blas_project.git: Name or service not known
</code>```

Trying the SSH-way to clone a project doesn't work either:

```<code>git clone git@gitlab.com:mr_bla/mr_blas_project.git
</code>```

results in:

```<code>Cloning into 'mr_blas_project'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

The Google Colab instance is running the following OS:

```<code>cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic
</code>```

I've checked, among many others, the following questions without success:

ssh: Could not resolve hostname git: Name or service not known fatal: Could not read from remote repository

fatal: could not read Username for 'https://github.com': No such file or directory

答: Change the repo visibility to public (from private?) in gitlab. I understand it might not be always possible, but doing that solved the problem for me. </p>

Body:
My issue is that I would like to connect a Google Colab instance with a Gitlab project, but neither SSH nor HTTPS seem to work. From the error messages, I suspect setting-related issues in Colab. Maybe I have to allow Colab to connect to Gitlab and put it on a whitelist somewhere?

Running the following shell commands from a Notebook in Colab while being in the '/content' directory

git config --global user.name "mr_bla"
git config --global user.email "bla@wbla.bla"
git clone https://gitlab.com/mr_bla/mr_blas_project.git

results in the following error messages:

Cloning into 'mr_blas_project'...
fatal: could not read Username for 'https://gitlab.com': No such device or address

I have generated SSH keys as I'm used to, but the SSH check

ssh -vvvT git@gitlab.com:mr_bla/mr_blas_project.git

fails, leading to the following error:

OpenSSH_7.6p1 Ubuntu-4ubuntu0.3, OpenSSL 1.0.2n  7 Dec 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "gitlab.com:mr_bla/mr_blas_project.git" port 22
ssh: Could not resolve hostname gitlab.com:mr_bla/mr_blas_project.git: Name or service not known

Trying the SSH-way to clone a project doesn't work either:

git clone git@gitlab.com:mr_bla/mr_blas_project.git

results in:

Cloning into 'mr_blas_project'...
Host key verification failed.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The Google Colab instance is running the following OS:

cat /etc/os-release
NAME="Ubuntu"
VERSION="18.04.3 LTS (Bionic Beaver)"
ID=ubuntu
ID_LIKE=debian
PRETTY_NAME="Ubuntu 18.04.3 LTS"
VERSION_ID="18.04"
HOME_URL="https://www.ubuntu.com/"
SUPPORT_URL="https://help.ubuntu.com/"
BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"
PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"
VERSION_CODENAME=bionic
UBUNTU_CODENAME=bionic

I've checked, among many others, the following questions without success:

ssh: Could not resolve hostname git: Name or service not known fatal: Could not read from remote repository

fatal: could not read Username for 'https://github.com': No such file or directory