问:
Perform a lookup between C# Lists and return matched where value is minimum
I have two lists:

```<code>var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}
</code>```

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

```<code>    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }
</code>```

Example data:

qtys

```<code>WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0
</code>```

times

```<code>WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5
</code>```

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

答:
It seems to me that the cleanest and simplest query is this:

```<code>var query =
    from q in qtys
    where q.QuantityInWarehouse > 0
    join t in times on q.WarehouseId equals t.WarehouseId
    orderby t.TransitDays
    select q.WarehouseId;

var warehouseId = query.FirstOrDefault();
</code>```

This gives me 3.

Body:
I have two lists:

var qtys = new List<InventoryQuantity>()
{
    new InventoryQuantity() { WarehouseId = 1, QuantityInWarehouse = 0 },
    new InventoryQuantity() { WarehouseId = 2, QuantityInWarehouse = 452 },
    new InventoryQuantity() { WarehouseId = 3, QuantityInWarehouse = 184 },
    new InventoryQuantity() { WarehouseId = 4, QuantityInWarehouse = 328 },
    new InventoryQuantity() { WarehouseId = 5, QuantityInWarehouse = 0 },
};

var times = new List<WarehouseTransitTime>()
{
    new WarehouseTransitTime() { WarehouseId = 1, TransitDays = 1 },
    new WarehouseTransitTime() { WarehouseId = 2, TransitDays = 4 },
    new WarehouseTransitTime() { WarehouseId = 3, TransitDays = 2 },
    new WarehouseTransitTime() { WarehouseId = 4, TransitDays = 3 },
    new WarehouseTransitTime() { WarehouseId = 5, TransitDays = 5 },
};

class InventoryQuantity
{
    public int WarehouseId { get; set; }
    public int QuantityInWarehouse { get; set; }
}

class WarehouseTransitTime
{
    public int WarehouseId { get; set; }
    public int TransitDays { get; set; }
}

I need to return the WarehouseId from qtys where the Quantity > 0 and the WarehouseId equals the minimum transit days WarehouseId in times.

I know I can do something like below but seems clunky and there must be an elegant solution.

    public int NearestWarehouse()
    {
        var withQty = qtys.Where(i => i.QuantityInWarehouse > 0);
        var orderedTransit = times.OrderBy(tt => tt.TransitDays).ToList();
        //loop and compare
    }

Example data:

qtys

WarehouseId | Quantity
1           | 0
2           | 452
3           | 184
4           | 328
5           | 0

times

WarehouseId | TransitTime
1           | 1
2           | 4
3           | 2
4           | 3
5           | 5

Expected output would be 3, because warehouse 3 has inventory and the shortest transit time (2)

Body:
It seems to me that the cleanest and simplest query is this:

var query =
    from q in qtys
    where q.QuantityInWarehouse > 0
    join t in times on q.WarehouseId equals t.WarehouseId
    orderby t.TransitDays
    select q.WarehouseId;

var warehouseId = query.FirstOrDefault();

This gives me 3.


来源: stackexchange

问:
Javascript code hiding a div doesn't work (CSS @media rule doesn't work either)- 'cannot read property style of null'
So, I've got a button that display toggles a div on a click event. It works properly. However, I can't hide the same div using nearly the same code (however, I want to toggle this div after my screen becomes too big, not after clicking), because I get the problem like in the title- 'cannot read property style of null'

The part that doesn't work (hiding a div after screen becomes too big:

```<code>if (screen.width > 900) {
  document.getElementById('klik').style.display = 'none';
}
</code>```

And the part that works (button toggles a div using a click event):

```<code>function showDiv() {
  if (document.getElementById('klik').style.display == 'block'){
    document.getElementById('klik').style.display = 'none';
  }
  else{
    document.getElementById('klik').style.display = 'block';
  }
}
</code>```

I wrote this code because I want to do a scalable menu, displaying a div with list items inside after clicking on it. The menu button is visible only  when screen-width <= 900px, if screen-width > 900px I've got a normal navigation bar and the button disappears.

Am I forgetting something? I'm new to Javascript. Also one more thing- it also doesn't work using @media rule, however I can change the background-color with @media. I hope it might help. Also thanks in advance.

答:
Hmmm, actually this is exactly what media queries are made for. Did you try

```<code>@media (min-width: 900px) {
  #klik {
    display:  none;
  }
}
</code>```

If that doesn't work: Are there any other css styles that may overwrite that particular style? Something like #klik { display: block !important; } ...?

ContentLicense: CC BY-SA 4.0

Body:
So, I've got a button that display toggles a div on a click event. It works properly. However, I can't hide the same div using nearly the same code (however, I want to toggle this div after my screen becomes too big, not after clicking), because I get the problem like in the title- 'cannot read property style of null'

The part that doesn't work (hiding a div after screen becomes too big:

if (screen.width > 900) {
  document.getElementById('klik').style.display = 'none';
}

And the part that works (button toggles a div using a click event):

function showDiv() {
  if (document.getElementById('klik').style.display == 'block'){
    document.getElementById('klik').style.display = 'none';
  }
  else{
    document.getElementById('klik').style.display = 'block';
  }
}

I wrote this code because I want to do a scalable menu, displaying a div with list items inside after clicking on it. The menu button is visible only  when screen-width <= 900px, if screen-width > 900px I've got a normal navigation bar and the button disappears.

Am I forgetting something? I'm new to Javascript. Also one more thing- it also doesn't work using @media rule, however I can change the background-color with @media. I hope it might help. Also thanks in advance.

Body:
Hmmm, actually this is exactly what media queries are made for. Did you try

@media (min-width: 900px) {
  #klik {
    display:  none;
  }
}

If that doesn't work: Are there any other css styles that may overwrite that particular style? Something like #klik { display: block !important; } ...?


问:
How to know on which physical processor and on which physical core my code is running
How can I know in a C program, on which physical processor and core my code is running?
I'm using Linux and gcc 4.4.3.</p>

答: By and large it's hard to find this out in a meaningful way. Your thread will often run on many different processors during its life. You could call a function to ask which processor you are on and get a context switch whilst the function is executing. What should the function return?</p>

ContentLicense: CC BY-SA 3.0


问:
I am trying to return a class datatype using Hashmap get() but gives me error saying "must return value of type". Please advise
My return value for method getVal complains with the error:

must return value of type test1.

I am not sure why would it complain about return type as I assume get would give you the value for the corresponding key. Please help me understand this logic.

```<code>public class test1 {
    //There is some class named test1
    public test1() { //Default Constructor
    }

    public test1 getVal(String name) {
        return sample.get(name);
    }
}

public class test {
    public test() {
        HashMap<String, test1> sample = new Hashmap<>();
        sample.put("Name", new test1());
    }
}
</code>```

答: Your HashMap named sample is not visible in getVal method.  You can add it as parameter to that method or make the HashMap sample visible to the getVal method.

Body:
My return value for method getVal complains with the error:

must return value of type test1.

I am not sure why would it complain about return type as I assume get would give you the value for the corresponding key. Please help me understand this logic.

public class test1 {
    //There is some class named test1
    public test1() { //Default Constructor
    }

    public test1 getVal(String name) {
        return sample.get(name);
    }
}

public class test {
    public test() {
        HashMap<String, test1> sample = new Hashmap<>();
        sample.put("Name", new test1());
    }
}


问:
Populate input field when button is clicked
I have an *ngFor looping through a bunch of listings. I'm trying to have it so that when a user clicks the buy it now price, it autofills the input field with the buy it now price so that the user only has to hit submit. The challenge I'm facing is I'm trying to use let i = index to figure out which listing has been clicked, but it throws an error when adding let i = index to ngFor like so

*ngFor="let auction of posts | let i = index|  paginate: { itemsPerPage: 10, currentPage: p, totalItems: this.posts.count }">

It's fine like this though

*ngFor="let auction of posts |  paginate: { itemsPerPage: 10, currentPage: p, totalItems: this.posts.count }">

but let index = i doesn't play nice with paginate code. My question is how to get the index working with paginate code and how I can use it to populate the input field for that specific row?

```<code><!DOCTYPE html>
<html>
  <head> </head>

  <body [ngClass]="[(this.isOpen && this.mobile) || (this.isOpen && this.tablet) ? 'hideContent' : 'showContent']">
    <div class="loading">
      <!-- <mat-spinner class="loader" *ngIf="isLoading"></mat-spinner> -->

      <ngx-spinner id="loadingIcon" *ngIf="isLoading" type="cog" size="medium" color="#3071a9">
        <br /><br /><br /><br /><br />
        <p class="loadingTitle">Loading...</p>
      </ngx-spinner>
    </div>
    <div class="spacing"></div>
    <div class="container">
      <div class="row">
        <div id="paginator"></div>
        <ngb-pagination
          (pageChange)="onPageChange($event)"
          [collectionSize]="this.totalPosts"
          *ngIf="!this.mobile && this.totalPosts"
          [(page)]="this.currentPage"
          [boundaryLinks]="true"
        ></ngb-pagination>

        <ngb-pagination
          (pageChange)="onPageChange($event)"
          [collectionSize]="120"
          [(page)]="this.currentPage || this.totalPosts"
          *ngIf="this.mobile && this.totalPosts"
          [maxSize]="5"
          [rotate]="true"
          [ellipses]="false"
          [boundaryLinks]="true"
        ></ngb-pagination>
      </div>
    </div>
    <div
      class="row no-gutters"
      *ngIf="(!this.isOpen && this.mobile) || (this.isOpen && !this.mobile) || (!this.isOpen && !this.mobile)"
    ></div>
    <!--; let i = index-->
    <div
      class="row"
      *ngFor="let listing of posts | paginate: { itemsPerPage: 10, currentPage: p, totalItems: this.posts.count }"
    >
      <div class="col-md-12 col-centered">
        <div class="listingCard" [@simpleFadeAnimation]="'in'">
          <li>
            Buy it Now: <span id="buyItNowStatus" (click)="buyItNow(listing, i)">{{ listing.buyItNow }}</span>
          </li>

          <div class="row"></div>

          <div class="row">
            <div class="col-md-3"></div>
            <div class="col-md-6">
              <div id="title">{{ listing.Title }}</div>
            </div>
          </div>

          <div class="row">
            <div class="col-md-2 col-sm-1">
              <img
                class="image"
                src="https://cdn.shopify.com/s/files/1/dfd/7290/products/IMPERIAL_NEW1.jpg?v=1565307462"
                (click)="openImageGallery()"
              />
            </div>

            <div class="col-md-6 col-sm-5">
              <br />
              <ul class="info">
                <li>
                  <div id="bidding">
                    <!--Starting Bid-->

                    <mat-form-field appearance="outline" class="formFields">
                      <mat-label id="placeholder">Enter Bid</mat-label>

                      <input
                        matInput
                        name="bidInput"
                        type="text"
                        ngModel
                        required
                        [value]="this.buyItNow"
                        #bidInput="ngModel"
                        pattern="^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{2}$"
                      />
                      <mat-error>Dollar Format 00:00 or 0:00</mat-error>
                    </mat-form-field>

                    <button id="auctionButton" mat-raised-button (click)="confirmPurchase(bidInput.value)">
                      Submit Bid
                    </button>
                  </div>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>
</code>```

```<code>  buyItNow(listing: []) {
    this.buyItNowPrice = listing["buyItNow"];
  }
</code>```

答:
You're trying to declare the 'index' property into the pipe chain. This will fix it:

```<code>*ngFor="let listing of posts | paginate: { itemsPerPage: 10, currentPage: p, totalItems: this.posts.count }, index as i"
</code>```

Also to update only the input for the current post, i would recommend another 'Approach'. Because already have a reference to the original 'listing' object inside the 'for' loop, you may try to set the buyItNowPrice as another property in this object and link it as the ngModel from the input node.

As this way, only the (now called) CurrentBidPrice prop included in the current 'Listing' will be used to update the value on the input.

```<code>buyItNow(listing: any) {
    listing.currentBid = listing.buyItNow;
}

<input
    matInput
    name="bidInput"
    type="text"
    [(ngModel)]="listing.currentBid"
    required
    #bidInput="ngModel"
    pattern="^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{2}$" />
</code>```

I attach a Stackblitz with an example of the concept.

https://stackblitz.com/edit/angular-nccdtw

Body:
I have an *ngFor looping through a bunch of listings. I'm trying to have it so that when a user clicks the buy it now price, it autofills the input field with the buy it now price so that the user only has to hit submit. The challenge I'm facing is I'm trying to use let i = index to figure out which listing has been clicked, but it throws an error when adding let i = index to ngFor like so

*ngFor="let auction of posts | let i = index|  paginate: { itemsPerPage: 10, currentPage: p, totalItems: this.posts.count }">

It's fine like this though

*ngFor="let auction of posts |  paginate: { itemsPerPage: 10, currentPage: p, totalItems: this.posts.count }">

but let index = i doesn't play nice with paginate code. My question is how to get the index working with paginate code and how I can use it to populate the input field for that specific row?

<!DOCTYPE html>

      <ngx-spinner id="loadingIcon" *ngIf="isLoading" type="cog" size="medium" color="#3071a9">

Loading...

      </ngx-spinner>

        <ngb-pagination
          (pageChange)="onPageChange($event)"
          [collectionSize]="this.totalPosts"
          *ngIf="!this.mobile && this.totalPosts"
          [(page)]="this.currentPage"
          [boundaryLinks]="true"
        ></ngb-pagination>

        <ngb-pagination
          (pageChange)="onPageChange($event)"
          [collectionSize]="120"
          [(page)]="this.currentPage || this.totalPosts"
          *ngIf="this.mobile && this.totalPosts"
          [maxSize]="5"
          [rotate]="true"
          [ellipses]="false"
          [boundaryLinks]="true"
        ></ngb-pagination>

            Buy it Now: {{ listing.buyItNow }}

{{ listing.Title }}

                    <mat-form-field appearance="outline" class="formFields">
                      <mat-label id="placeholder">Enter Bid</mat-label>

                      <input
                        matInput
                        name="bidInput"
                        type="text"
                        ngModel
                        required
                        [value]="this.buyItNow"
                        #bidInput="ngModel"
                        pattern="^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{2}$"
                      />
                      <mat-error>Dollar Format 00:00 or 0:00</mat-error>
                    </mat-form-field>

                    <button id="auctionButton" mat-raised-button (click)="confirmPurchase(bidInput.value)">
                      Submit Bid
                    </button>

  buyItNow(listing: []) {
    this.buyItNowPrice = listing["buyItNow"];
  }

Body:
You're trying to declare the 'index' property into the pipe chain. This will fix it:

*ngFor="let listing of posts | paginate: { itemsPerPage: 10, currentPage: p, totalItems: this.posts.count }, index as i"

Also to update only the input for the current post, i would recommend another 'Approach'. Because already have a reference to the original 'listing' object inside the 'for' loop, you may try to set the buyItNowPrice as another property in this object and link it as the ngModel from the input node.

As this way, only the (now called) CurrentBidPrice prop included in the current 'Listing' will be used to update the value on the input.

buyItNow(listing: any) {
    listing.currentBid = listing.buyItNow;
}

<input
    matInput
    name="bidInput"
    type="text"
    [(ngModel)]="listing.currentBid"
    required
    #bidInput="ngModel"
    pattern="^\$?(([1-9]\d{0,2}(,\d{3})*)|0)?\.\d{2}$" />

I attach a Stackblitz with an example of the concept.

https://stackblitz.com/edit/angular-nccdtw


问:
How to make a function with events and pipe in nodejs
I'm writing a nodejs library in typescript, the main scope of this library is gonna be downloading stuff from a given url, what I'd like it to do is to be used like this

import library from 'library'

library('https://www.example.com')
    .on('progress', (progress: progress) => {
        //do something with the progress
    })
    .on('end', () => {
        //do something when done
    })
    .pipe(fs.createWriteStream('./test/file.mp4'))
```

I've never worked with node events and stream in such a way so I have no idea how to even go about this I'm using typescript and webpack also please forgive bad English

答:
You're going to need to implement a Readable stream. Node streams are instances of EventEmitter, so you automatically have access to the event API.

At the very minimum, you need to implement a _read() method which is called internally whenever the consumer is ready to receive more data from the queue. Since you want the library to report the progress, you also need to keep track of how much data has been processed and emit events accordingly.

The code below ignores several important things like backpressuring, but it's a start. I'm using node-fetch as a request library as it exposes an underlying response stream and is fairly easy to use.

```<code>// fileLoader.js
const {Readable} = require('stream')
const fetch = require('node-fetch')

class FileLoader extends Readable {
  constructor(url) {
    super()
    this._url = url
    this._fetchStarted = false
    this._totalLength = 0
    this._currentLength = 0
  }

  _processData(stream) {
    stream
      .on('end', () => {
        this.push(null)
      })
      .on('error', (err) => {
        this.destroy(err)
      })
      .on('data', (chunk) => {
        this._currentLength += chunk.length
        if (this._totalLength) {
          this.emit('progress', Math.round(this._currentLength / this._totalLength * 100))
        }
        this.push(chunk)
      })
  }

  _startFetch() {
    fetch(this._url)
      .then((res) => {
        if (!res.ok) {
          return this.destroy(new Error(`fetch resulted in ${res.status}`))
        }
        this._totalLength = res.headers.get('content-length')
        this._processData(res.body)
      })
      .catch((err) => {
        return this.destroy(new Error(err))
      })
  }

  _read() {
    if (!this._fetchStarted) {
      this._fetchStarted = true
      this._startFetch()
    }
  }
}

module.exports.loadFile = (url) => new FileLoader(url)
</code>```

And the consumer code:

```<code>// consumer.js
const fs = require('fs')
const {loadFile} = require('./fileLoader')

loadFile('http://example.com/video.mp4')
  .on('progress', (progress) => {
    console.log(`${progress}%`)
  })
  .on('end', () => {
    console.log('done')
  })
  .on('error', (err) => {
    console.log(err)
  })
  .pipe(fs.createWriteStream('./tempy.mp4'))
</code>```

Body:
I'm writing a nodejs library in typescript, the main scope of this library is gonna be downloading stuff from a given url, what I'd like it to do is to be used like this

import library from 'library'

library('https://www.example.com')
    .on('progress', (progress: progress) => {
        //do something with the progress
    })
    .on('end', () => {
        //do something when done
    })
    .pipe(fs.createWriteStream('./test/file.mp4'))

I've never worked with node events and stream in such a way so I have no idea how to even go about this I'm using typescript and webpack also please forgive bad English

Body:
You're going to need to implement a Readable stream. Node streams are instances of EventEmitter, so you automatically have access to the event API.

At the very minimum, you need to implement a _read() method which is called internally whenever the consumer is ready to receive more data from the queue. Since you want the library to report the progress, you also need to keep track of how much data has been processed and emit events accordingly.

The code below ignores several important things like backpressuring, but it's a start. I'm using node-fetch as a request library as it exposes an underlying response stream and is fairly easy to use.

// fileLoader.js
const {Readable} = require('stream')
const fetch = require('node-fetch')

class FileLoader extends Readable {
  constructor(url) {
    super()
    this._url = url
    this._fetchStarted = false
    this._totalLength = 0
    this._currentLength = 0
  }

  _processData(stream) {
    stream
      .on('end', () => {
        this.push(null)
      })
      .on('error', (err) => {
        this.destroy(err)
      })
      .on('data', (chunk) => {
        this._currentLength += chunk.length
        if (this._totalLength) {
          this.emit('progress', Math.round(this._currentLength / this._totalLength * 100))
        }
        this.push(chunk)
      })
  }

  _startFetch() {
    fetch(this._url)
      .then((res) => {
        if (!res.ok) {
          return this.destroy(new Error(`fetch resulted in ${res.status}`))
        }
        this._totalLength = res.headers.get('content-length')
        this._processData(res.body)
      })
      .catch((err) => {
        return this.destroy(new Error(err))
      })
  }

  _read() {
    if (!this._fetchStarted) {
      this._fetchStarted = true
      this._startFetch()
    }
  }
}

module.exports.loadFile = (url) => new FileLoader(url)

And the consumer code:

// consumer.js
const fs = require('fs')
const {loadFile} = require('./fileLoader')

loadFile('http://example.com/video.mp4')
  .on('progress', (progress) => {
    console.log(`${progress}%`)
  })
  .on('end', () => {
    console.log('done')
  })
  .on('error', (err) => {
    console.log(err)
  })
  .pipe(fs.createWriteStream('./tempy.mp4'))


问:
How to implement drag & Drop on an image, changing its position
I developed a slider that presents me with several images.

At the top (large image and where the slider is located) I have the initial image as the main image.

At the bottom I have the secondary images (see image below).

Is there a way to drag an image to the div that contains the slider in order to change the order? Basically I intend to exchange an image that is in the small box with the first image in the large box.

Can I change the order of the small images horizontally, too?

Thank you.

DEMO - Stackblitz

code

```<code> <div class="col-md-6" style="overflow-y: auto;"  (cdkDropListDropped)="drop($event)">
        <div class="drop" [style.border-width.px]="imagens.length > 0 ? 0: 3">
          <div class="abc">
              <ngb-carousel style="outline: none;" id="carousel" #carousel *ngIf="imagens" (slide)="change($event)">
                <ng-template *ngFor="let imgIdx of imagens; let i = index" [id]="i" ngbSlide>
                  <div class="picsum-img-wrapper">
                    <img [src]="imgIdx.Imagem" style="border-radius: 8px;" class="img-responsive Images">
                      </div>
                </ng-template>
              </ngb-carousel>
          </div>
        </div>
        <div class="row">
          <div class="Upcard" *ngFor="let imgIdx of imagens | slice:1" >
            <img class="img-responsive" [src]="imgIdx.Imagem" style="width: 100%; height: 100%">
          </div>
        </div>
      </div>
</code>```

I tried to use this, adding in the html cdkdrag, but no, it didn't work.

```<code>   drop(event: CdkDragDrop<string[]>) {
     moveItemInArray(this.imagens, event.previousIndex, event.currentIndex);
   }

   dropBig(event: CdkDragDrop<string[]>) {
     moveItemInArray(this.imagens, event.previousIndex, 0);
   }
</code>```

答:
the cdk drag and drop it's usefull to drag between two cdkDropList. Normally it's used to interchange values of two arrays (the cdkDropListData of the cdkDropList). So you need defined first the cdkDropList and the elements dragables (cdkDrag)

So, first change the angular.json to use the cdk 8.2.3, -you're using Angular 8, not mixed versions-

```<code>"@angular/cdk": "^8.2.3",
</code>```

Then create two arrays, imagens and imagens2(*) and change your .html as -see where there are the cdkDropList and the cdkDrag-

```<code><div class="col-md-6" style="overflow-y: auto;">
    <div class="drop" [style.border-width.px]="imagens.length > 0 ? 0: 3">
        <div class="abc" cdkDropList #dropList="cdkDropList" cdkDropListOrientation="horizontal"
            [cdkDropListData]="imagens"
            [cdkDropListConnectedTo]="[dragList]"
            (cdkDropListDropped)="drop($event)">
            <ngb-carousel data-interval="false" style="outline: none;" id="carousel" #carousel *ngIf="imagens"
                (slide)="change($event)">
                <ng-template *ngFor="let imgIdx of imagens; let i = index" [id]="i" ngbSlide>
                    <div class="picsum-img-wrapper" cdkDrag [cdkDragDisabled]="true">
                        <img [src]="imgIdx.Imagem" style="border-radius: 8px;" class="img-responsive Images">
                      </div>
                </ng-template>
            </ngb-carousel>
        </div>
    </div>

    <div class="row" cdkDropList #dragList="cdkDropList" cdkDropListOrientation="horizontal"
        [cdkDropListData]="imagens2"
        [cdkDropListConnectedTo]="[dropList]"
        (cdkDropListDropped)="drop($event)">
        <div class="Upcard" *ngFor="let imgIdx of imagens2" cdkDrag>
            <img class="img-responsive" [src]="imgIdx.Imagem" style="width: 100%; height: 100%">
          </div>
        </div>
    </div>
</code>```

well, in general the function drop is like

```<code>  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);
    }
  }
</code>```

But this make that when you drop an image fron imagens2 to imagens, the dragged imagen is added to the array imagens and remove from the array imagens2 -you move the images-

If you want to exchange the two images you simple use splice. Remember it's only change two arrays

```<code>  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      const imagen = { ...(event.container.data[event.currentIndex] as any) };
      const previousImagen = {
        ...(event.previousContainer.data[event.previousIndex] as any)
      };
      event.container.data.splice(event.currentIndex, 1, previousImagen);
      event.previousContainer.data.splice(event.previousIndex, 1, imagen);
    }
  }
</code>```

Well if you want not "interchange" the two images else remove from the slider the image dragged, change the function drop. Remember event.container.data is the array where you drop the imagen (in the event.currentIndex) and event.previousContainer.data is the array from you drag the imagen (the event.previousIndex give you the imagen dragged)

see your forked stackblitz

(*) I think in two differents arrays, I "clone" your array using

```<code>  imagens2 = this.imagens.map(x => ({ ...x }));
</code>```

Body:
I developed a slider that presents me with several images.

At the top (large image and where the slider is located) I have the initial image as the main image.

At the bottom I have the secondary images (see image below).

Is there a way to drag an image to the div that contains the slider in order to change the order? Basically I intend to exchange an image that is in the small box with the first image in the large box.

Can I change the order of the small images horizontally, too?

Thank you.

DEMO - Stackblitz

code

 0 ? 0: 3">

              <ngb-carousel style="outline: none;" id="carousel" #carousel *ngIf="imagens" (slide)="change($event)">
                <ng-template *ngFor="let imgIdx of imagens; let i = index" [id]="i" ngbSlide>

                </ng-template>
              </ngb-carousel>

I tried to use this, adding in the html cdkdrag, but no, it didn't work.

   drop(event: CdkDragDrop<string[]>) {
     moveItemInArray(this.imagens, event.previousIndex, event.currentIndex);
   }

   dropBig(event: CdkDragDrop<string[]>) {
     moveItemInArray(this.imagens, event.previousIndex, 0);
   }

Body:
the cdk drag and drop it's usefull to drag between two cdkDropList. Normally it's used to interchange values of two arrays (the cdkDropListData of the cdkDropList). So you need defined first the cdkDropList and the elements dragables (cdkDrag)

So, first change the angular.json to use the cdk 8.2.3, -you're using Angular 8, not mixed versions-

"@angular/cdk": "^8.2.3",

Then create two arrays, imagens and imagens2(*) and change your .html as -see where there are the cdkDropList and the cdkDrag-

<div class="col-md-6" style="overflow-y: auto;">
    <div class="drop" [style.border-width.px]="imagens.length > 0 ? 0: 3">
        <div class="abc" cdkDropList #dropList="cdkDropList" cdkDropListOrientation="horizontal"
            [cdkDropListData]="imagens"
            [cdkDropListConnectedTo]="[dragList]"
            (cdkDropListDropped)="drop($event)">
            <ngb-carousel data-interval="false" style="outline: none;" id="carousel" #carousel *ngIf="imagens"
                (slide)="change($event)">
                <ng-template *ngFor="let imgIdx of imagens; let i = index" [id]="i" ngbSlide>
                    <div class="picsum-img-wrapper" cdkDrag [cdkDragDisabled]="true">
                        <img [src]="imgIdx.Imagem" style="border-radius: 8px;" class="img-responsive Images">
                      </div>
                </ng-template>
            </ngb-carousel>
        </div>
    </div>

    <div class="row" cdkDropList #dragList="cdkDropList" cdkDropListOrientation="horizontal"
        [cdkDropListData]="imagens2"
        [cdkDropListConnectedTo]="[dropList]"
        (cdkDropListDropped)="drop($event)">
        <div class="Upcard" *ngFor="let imgIdx of imagens2" cdkDrag>
            <img class="img-responsive" [src]="imgIdx.Imagem" style="width: 100%; height: 100%">
          </div>
        </div>
    </div>

well, in general the function drop is like

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
                        event.container.data,
                        event.previousIndex,
                        event.currentIndex);
    }
  }

But this make that when you drop an image fron imagens2 to imagens, the dragged imagen is added to the array imagens and remove from the array imagens2 -you move the images-

If you want to exchange the two images you simple use splice. Remember it's only change two arrays

  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(
        event.container.data,
        event.previousIndex,
        event.currentIndex
      );
    } else {
      const imagen = { ...(event.container.data[event.currentIndex] as any) };
      const previousImagen = {
        ...(event.previousContainer.data[event.previousIndex] as any)
      };
      event.container.data.splice(event.currentIndex, 1, previousImagen);
      event.previousContainer.data.splice(event.previousIndex, 1, imagen);
    }
  }

Well if you want not "interchange" the two images else remove from the slider the image dragged, change the function drop. Remember event.container.data is the array where you drop the imagen (in the event.currentIndex) and event.previousContainer.data is the array from you drag the imagen (the event.previousIndex give you the imagen dragged)

see your forked stackblitz

(*) I think in two differents arrays, I "clone" your array using

  imagens2 = this.imagens.map(x => ({ ...x }));


问:
Checkout shopping cart UICollectionViewCell
I have a shopping cart check out flow using a UICollectionView with full page UICollectionViewCells. When the add button is pressed, the remove button is then visible and vice versa. For some reason when add and remove are repeatedly pressed it disrupts the other cells. It will show remove button on another cell when the add button on that cell was never even pressed. I am not sure what's wrong with my logic.</p>

```<code>   protocol PostCellDelegate {
func removeButtonTapped(cell: PostCell)
func addTapped(cell: PostCell)
   }

    class PostCell: UICollectionViewCell {
  var currentPrice: Float = 0
  var delegate: PostCellDelegate?

   func set(name: String, brand: String, price: String, image: String){
       nameLabel.text = name
       brandLabel.text = brand
       priceLabel.text = "$\(price)"
    photoImageView.loadImage(urlString: image)

   }

 override init(frame: CGRect) {
     super.init(frame: frame)
    self.myButton.addTarget(self, action: #selector(addButtonTapped(sender:)), for: .touchUpInside)
    self.removeButton.addTarget(self, action: #selector(subButtonTapped(sender:)), for: .touchUpInside)
   self.contentView.addSubview(containerView)
    setupCellConstraints()

    }
@objc func addButtonTapped(sender: UIButton){
      self.delegate?.addTapped(cell: self)
      sender.isHidden = true
  }

@objc func subButtonTapped(sender: UIButton){
    self.delegate?.removeButtonTapped(cell: self)
    sender.isHidden = true
}
 }

  class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
   var totalPrice = Float()

   private var hiddenRows = Set<Int>()

  var finalList = [Item]()

  @objc func addTapped(cell: PostCell) {

      guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
      hiddenRows.insert(indexPath.row)
      cell.removeButton.isHidden = false
      let item = itemsArr[indexPath.row]
      finalList.append(item)
      collectionView?.reloadData()
      totalPrice += Float(item.price) ?? 0
       }

    @objc func removeButtonTapped(cell: PostCell) {

    guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
    hiddenRows.insert(indexPath.row)
    cell.myButton.isHidden = false
    let item = itemsArr[indexPath.row]
    finalList.removeAll{ $0.name == item.name}
    totalPrice -= Float(item.price) ?? 0
     }

  extension CollectionViewController {

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell
            cell.delegate = self

    let item = itemsArr[indexPath.row]
    let page = itemsArr[indexPath.item]

    cell.set(name: item.name, brand: item.brand, price: item.price, image: item.image_url)
     if hiddenRows.contains(indexPath.row) {
                cell.myButton.isHidden = true
                cell.removeButton.isHidden = false
            }else{
                cell.removeButton.isHidden = true
                cell.myButton.isHidden = false
            }

    return cell
}
</code>```

答:
Cells are reused you need to restore to default here in cellForItemAt

```<code> // restore default look here ( hide / show what you need )

 if hiddenRows.contains(indexPath.row) {
            cell.myButton.isHidden = true
            cell.removeButton.isHidden = false
        }else{
            cell.removeButton.isHidden = true
            cell.myButton.isHidden = false
        }
</code>```

Body:
I have a shopping cart check out flow using a UICollectionView with full page UICollectionViewCells. When the add button is pressed, the remove button is then visible and vice versa. For some reason when add and remove are repeatedly pressed it disrupts the other cells. It will show remove button on another cell when the add button on that cell was never even pressed. I am not sure what's wrong with my logic.

   protocol PostCellDelegate {
func removeButtonTapped(cell: PostCell)
func addTapped(cell: PostCell)
   }

    class PostCell: UICollectionViewCell {
  var currentPrice: Float = 0
  var delegate: PostCellDelegate?

   func set(name: String, brand: String, price: String, image: String){
       nameLabel.text = name
       brandLabel.text = brand
       priceLabel.text = "$\(price)"
    photoImageView.loadImage(urlString: image)

   }

 override init(frame: CGRect) {
     super.init(frame: frame)
    self.myButton.addTarget(self, action: #selector(addButtonTapped(sender:)), for: .touchUpInside)
    self.removeButton.addTarget(self, action: #selector(subButtonTapped(sender:)), for: .touchUpInside)
   self.contentView.addSubview(containerView)
    setupCellConstraints()

    }
@objc func addButtonTapped(sender: UIButton){
      self.delegate?.addTapped(cell: self)
      sender.isHidden = true
  }

@objc func subButtonTapped(sender: UIButton){
    self.delegate?.removeButtonTapped(cell: self)
    sender.isHidden = true
}
 }

  class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout, PostCellDelegate {
   var totalPrice = Float()

   private var hiddenRows = Set<Int>()

  var finalList = [Item]()

  @objc func addTapped(cell: PostCell) {

      guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
      hiddenRows.insert(indexPath.row)
      cell.removeButton.isHidden = false
      let item = itemsArr[indexPath.row]
      finalList.append(item)
      collectionView?.reloadData()
      totalPrice += Float(item.price) ?? 0
       }

    @objc func removeButtonTapped(cell: PostCell) {

    guard let indexPath = self.collectionView.indexPath(for: cell)  else {return}
    hiddenRows.insert(indexPath.row)
    cell.myButton.isHidden = false
    let item = itemsArr[indexPath.row]
    finalList.removeAll{ $0.name == item.name}
    totalPrice -= Float(item.price) ?? 0
     }

  extension CollectionViewController {

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cellId", for: indexPath) as! PostCell
            cell.delegate = self

    let item = itemsArr[indexPath.row]
    let page = itemsArr[indexPath.item]

    cell.set(name: item.name, brand: item.brand, price: item.price, image: item.image_url)
     if hiddenRows.contains(indexPath.row) {
                cell.myButton.isHidden = true
                cell.removeButton.isHidden = false
            }else{
                cell.removeButton.isHidden = true
                cell.myButton.isHidden = false
            }

    return cell
}

Body:
Cells are reused you need to restore to default here in cellForItemAt

 // restore default look here ( hide / show what you need )

 if hiddenRows.contains(indexPath.row) {
            cell.myButton.isHidden = true
            cell.removeButton.isHidden = false
        }else{
            cell.removeButton.isHidden = true
            cell.myButton.isHidden = false
        }


问:
KNN - Predict a single case in python
I'm using dataset from Kaggle - Cardiovascular Disease Dataset.
The model has been trained and what I want to do is to label a single input(a row of 13 values)
inserted in dynamic way.

Shape of Dataset is 13 Features + 1 Target, 66k rows

```<code>#prepare dataset for train and test
dfCardio = load_csv("cleanCardio.csv")
y = dfCardio['cardio']
x = dfCardio.drop('cardio',axis = 1, inplace=False)
model = knn = KNeighborsClassifier()
x_train,x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=42)
model.fit(x_train, y_train)
# make predictions for test data
y_pred = model.predict(x_test)
predictions = [round(value) for value in y_pred]
# evaluate predictions
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))
</code>```

ML is trained, what I want to do is to predict the label of this single row :

```<code>['69','1','151','22','37','0','65','140','90','2','1','0','0','1']
</code>```

to return 0 or 1 for Target.
So I wrote this code :

```<code>import numpy as np
import pandas as pd
single =  np.array(['69','1','151','22','37','0','65','140','90','2','1','0','0','1'])
singledf = pd.DataFrame(single)
final=singledf.transpose()
prediction = model.predict(final)
print(prediction)
</code>```

but it gives error : query data dimension must match training data dimension

how can I fix the labeling for single row ? why I'm not able to predict a single case ?

答:
Each instance in your dataset has 13 features and 1 label.

```<code>x = dfCardio.drop('cardio',axis = 1, inplace=False)
</code>```

This line in the code removes what I assume is the label column from the data, leaving only the (13) feature columns.

The feature vector on which you are trying to predict, is 14 elements long. You can only predict on feature vectors that are 13 elements long because that is what the model was trained on.

Title: KNN - Predict a single case in python

Body:
I'm using dataset from Kaggle - Cardiovascular Disease Dataset.
The model has been trained and what I want to do is to label a single input(a row of 13 values)
inserted in dynamic way.

Shape of Dataset is 13 Features + 1 Target, 66k rows

#prepare dataset for train and test
dfCardio = load_csv("cleanCardio.csv")
y = dfCardio['cardio']
x = dfCardio.drop('cardio',axis = 1, inplace=False)
model = knn = KNeighborsClassifier()
x_train,x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=42)
model.fit(x_train, y_train)
# make predictions for test data
y_pred = model.predict(x_test)
predictions = [round(value) for value in y_pred]
# evaluate predictions
accuracy = accuracy_score(y_test, predictions)
print("Accuracy: %.2f%%" % (accuracy * 100.0))

ML is trained, what I want to do is to predict the label of this single row :

['69','1','151','22','37','0','65','140','90','2','1','0','0','1']

to return 0 or 1 for Target.
So I wrote this code :

import numpy as np
import pandas as pd
single =  np.array(['69','1','151','22','37','0','65','140','90','2','1','0','0','1'])
singledf = pd.DataFrame(single)
final=singledf.transpose()
prediction = model.predict(final)
print(prediction)

but it gives error : query data dimension must match training data dimension

how can I fix the labeling for single row ? why I'm not able to predict a single case ?

Body:
Each instance in your dataset has 13 features and 1 label.

x = dfCardio.drop('cardio',axis = 1, inplace=False)

This line in the code removes what I assume is the label column from the data, leaving only the (13) feature columns.

The feature vector on which you are trying to predict, is 14 elements long. You can only predict on feature vectors that are 13 elements long because that is what the model was trained on.


问:
NodeJS / Express: inconsistent [ERR_HTTP_HEADERS_SENT] occurring
Here I have a POST method that gets called quite often.

```<code>app.post('/return_data', async (req, res) => {
    var response, file
    console.log("request recieved: " + req.body.room)
    await readFile('Data/'+req.body.room+'.json').then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})
</code>```

For some reason the response is intermittent. Sometimes it will log the following error.

```<code>Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:535:11)
    at ServerResponse.header (/home/ec2-user/dc-floorplans/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/home/ec2-user/dc-floorplans/node_modules/express/lib/response.js:194:10)
    at /home/ec2-user/dc-floorplans/app.js:127:13
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async /home/ec2-user/dc-floorplans/app.js:125:5 {
  code: 'ERR_HTTP_HEADERS_SENT'
}
</code>```

When I first start my web app, usually the first POST logs an error. After refreshing the page, the data comes through as intended. There is only one response in the function and so I'm puzzled as to why this error is occurring.

I know that readFile works because the data is logged in .then(). How can it be that sometimes data is sent to the client and other times it throws an error when the exact same process is happening?

Thanks in advance.

UPDATE -- FULL APP.JS:

```<code>app.set('view-engine', 'ejs');
app.use(express.urlencoded({ extended: false }))
app.use(cors())
app.use(flash())
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
app.use(express.static(__dirname + '/static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', checkAuthenticated, (req, res) => {
    res.render('index.ejs');
});

app.get('/login', checkNotAuthenticated, function(req, res, next) {
    res.render('login.ejs');
});

app.post('/login', checkNotAuthenticated, (req, res, next) => {
        passport.authenticate('local', (err, user, info) => {
           if(err) throw err
           if(!user) return res.redirect('/login')
           req.logIn(user, (err) => {
              if(err) return next(err)
              if(info.message==process.env.DEFAULTPW) {
                  console.log("Default password detected for: " + user.email)
                  return res.redirect('/')
              }
              return res.redirect('/')

           })
  })(req, res, next)
})

app.get('/update', checkAuthenticated, (req, res, next) => {
        res.render('update.ejs')
})

app.post('/update', checkAuthenticated, async (req, res, next) => {
    if(req.body.pw1 != req.body.pw2) { res.redirect('/update') }
        if(req.body.pw2 == process.env.DEFAULTPW) { res.redirect('/update') }
        const newpw = await encrypt(req.body.pw2)
        var queryresult
        await con.query("UPDATE login SET password = \'"+newpw+"\' WHERE email = \'"+req.body.email.toLowerCase()+"\'", (err, result, fields) => {
            if (err) {
                console.log(err)
                return res.redirect('/update')
            };
                console.log(result)
        queryresult = result
                if(result.changedRows == 0) {
                    return res.redirect('/update')
                }

        })
        return res.redirect('/')
    });

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

        console.log("New Data:")
    await pollLM(req.body.room).then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})

async function pollLM(room) {
    return new Promise((resolve, reject) => {
        const getData = pySpawn('python3.7', ['getData.py', room])
        getData.stdout.on('data', (data) => {
        resolve(data)
        })
    })
}

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

    console.log("request recieved: " + req.body.room)
    await readFile('Data/'+req.body.room+'.json').then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})

async function readFile(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, (err, data) => {
            if (err) reject(err);
            console.log(typeof(data))
            resolve(data)
        })
    })
}

app.post('/update_reload_time', (req, res) => {
    console.log("reload time updated to: " + req.body.time)
    fs.writeFile('Data/delay.json', JSON.stringify(req.body), () => {
        console.log("delay updated to: " + req.body.time)
    })
})

app.get('/reload_time', async (req, res) => {

    await readFile('Data/delay.json').then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})

app.delete('/logout', (req, res) => {
    req.logOut()
    res.redirect('/login')
})

// Page routing...

function checkAuthenticated(req, res, next) {
    if(req.isAuthenticated()) {
        return next()
    }
    res.redirect('/login')
}

function checkNotAuthenticated(req, res, next) {
    if(req.isAuthenticated()) {
        return res.redirect('/')
    }
    next()
}

function encrypt(text) {
    const key = crypto.scryptSync(process.env.CRYPTOPW, process.env.SALT, 24)
        const cipher = crypto.createCipher('aes-192-cbc', key)

        let encrypted = ''
        cipher.on('readable', () => {
            let chunk
            while(null != (chunk = cipher.read())) {
                encrypted += chunk.toString('hex')
            }
        })

        cipher.write(text)
        cipher.end()
        return encrypted
}

function decrypt(text) {
    const key = crypto.scryptSync(process.env.CRYPTOPW, process.env.SALT, 24)
      const decipher = crypto.createDecipher('aes-192-cbc', key)

      let decrypted = '';
      decipher.on('readable', () => {
        while(null !== (chunk = decipher.read())) {
          decrypted += chunk.toString('utf8')
        }
      })

      const encrypted = text
      decipher.write(encrypted, 'hex')
      decipher.end()
      return decrypted
}

</code>```

答:
All you have to look for is where you response twice on the same call.

For example:

```<code>app.post('test', (req,res)=>{
 res.send('1')
 res.json('{1:2}')
})
</code>```

will always return this error, because you are responding twice.

You have to investigate your routes one by one, I would start here:

```<code>app.post('/update', checkAuthenticated, async (req, res, next) => {
if(req.body.pw1 != req.body.pw2) { res.redirect('/update') }
    if(req.body.pw2 == process.env.DEFAULTPW) { res.redirect('/update') }
    const newpw = await encrypt(req.body.pw2)
    var queryresult
    await con.query("UPDATE login SET password = \'"+newpw+"\' WHERE email = \'"+req.body.email.toLowerCase()+"\'", (err, result, fields) => {
        if (err) {
            console.log(err)
            return res.redirect('/update')
        };
            console.log(result)
    queryresult = result
            if(result.changedRows == 0) {
                return res.redirect('/update')
            }

    })
    return res.redirect('/')
});
</code>```

You are calling res.redirect explicitly and on condition. Have you checked if both conditions meet simultaneously? I guess here is one weak point.

And I would check this one

```<code>    app.post('/login', checkNotAuthenticated, (req, res, next) => {
        passport.authenticate('local', (err, user, info) => {
           if(err) throw err
           if(!user) return res.redirect('/login')
           req.logIn(user, (err) => {
              if(err) return next(err)
              if(info.message==process.env.DEFAULTPW) {
                  console.log("Default password detected for: " + user.email)
                  return res.redirect('/')
              }
              return res.redirect('/')

           })
  })(req, res, next)
})
</code>```

Again there potentially meet two conditions. Check them out. Other parts look fine to me.

Body:
Here I have a POST method that gets called quite often.

app.post('/return_data', async (req, res) => {
    var response, file
    console.log("request recieved: " + req.body.room)
    await readFile('Data/'+req.body.room+'.json').then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})

For some reason the response is intermittent. Sometimes it will log the following error.

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:535:11)
    at ServerResponse.header (/home/ec2-user/dc-floorplans/node_modules/express/lib/response.js:771:10)
    at ServerResponse.send (/home/ec2-user/dc-floorplans/node_modules/express/lib/response.js:194:10)
    at /home/ec2-user/dc-floorplans/app.js:127:13
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async /home/ec2-user/dc-floorplans/app.js:125:5 {
  code: 'ERR_HTTP_HEADERS_SENT'
}

When I first start my web app, usually the first POST logs an error. After refreshing the page, the data comes through as intended. There is only one response in the function and so I'm puzzled as to why this error is occurring.

I know that readFile works because the data is logged in .then(). How can it be that sometimes data is sent to the client and other times it throws an error when the exact same process is happening?

Thanks in advance.

UPDATE -- FULL APP.JS:

app.set('view-engine', 'ejs');
app.use(express.urlencoded({ extended: false }))
app.use(cors())
app.use(flash())
app.use(session({
    secret: process.env.SESSION_SECRET,
    resave: false,
    saveUninitialized: false
}))
app.use(passport.initialize())
app.use(passport.session())
app.use(methodOverride('_method'))
app.use(express.static(__dirname + '/static'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', checkAuthenticated, (req, res) => {
    res.render('index.ejs');
});

app.get('/login', checkNotAuthenticated, function(req, res, next) {
    res.render('login.ejs');
});

app.post('/login', checkNotAuthenticated, (req, res, next) => {
        passport.authenticate('local', (err, user, info) => {
           if(err) throw err
           if(!user) return res.redirect('/login')
           req.logIn(user, (err) => {
              if(err) return next(err)
              if(info.message==process.env.DEFAULTPW) {
                  console.log("Default password detected for: " + user.email)
                  return res.redirect('/')
              }
              return res.redirect('/')

           })
  })(req, res, next)
})

app.get('/update', checkAuthenticated, (req, res, next) => {
        res.render('update.ejs')
})

app.post('/update', checkAuthenticated, async (req, res, next) => {
    if(req.body.pw1 != req.body.pw2) { res.redirect('/update') }
        if(req.body.pw2 == process.env.DEFAULTPW) { res.redirect('/update') }
        const newpw = await encrypt(req.body.pw2)
        var queryresult
        await con.query("UPDATE login SET password = \'"+newpw+"\' WHERE email = \'"+req.body.email.toLowerCase()+"\'", (err, result, fields) => {
            if (err) {
                console.log(err)
                return res.redirect('/update')
            };
                console.log(result)
        queryresult = result
                if(result.changedRows == 0) {
                    return res.redirect('/update')
                }

        })
        return res.redirect('/')
    });

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

        console.log("New Data:")
    await pollLM(req.body.room).then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})

async function pollLM(room) {
    return new Promise((resolve, reject) => {
        const getData = pySpawn('python3.7', ['getData.py', room])
        getData.stdout.on('data', (data) => {
        resolve(data)
        })
    })
}

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

    console.log("request recieved: " + req.body.room)
    await readFile('Data/'+req.body.room+'.json').then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})

async function readFile(path) {
    return new Promise((resolve, reject) => {
        fs.readFile(path, (err, data) => {
            if (err) reject(err);
            console.log(typeof(data))
            resolve(data)
        })
    })
}

app.post('/update_reload_time', (req, res) => {
    console.log("reload time updated to: " + req.body.time)
    fs.writeFile('Data/delay.json', JSON.stringify(req.body), () => {
        console.log("delay updated to: " + req.body.time)
    })
})

app.get('/reload_time', async (req, res) => {

    await readFile('Data/delay.json').then((data) => {
        console.log(data)
        return res.send(data)
    }).catch((e) => {
        console.log(e)
    })
})

app.delete('/logout', (req, res) => {
    req.logOut()
    res.redirect('/login')
})

// Page routing...

function checkAuthenticated(req, res, next) {
    if(req.isAuthenticated()) {
        return next()
    }
    res.redirect('/login')
}

function checkNotAuthenticated(req, res, next) {
    if(req.isAuthenticated()) {
        return res.redirect('/')
    }
    next()
}

function encrypt(text) {
    const key = crypto.scryptSync(process.env.CRYPTOPW, process.env.SALT, 24)
        const cipher = crypto.createCipher('aes-192-cbc', key)

        let encrypted = ''
        cipher.on('readable', () => {
            let chunk
            while(null != (chunk = cipher.read())) {
                encrypted += chunk.toString('hex')
            }
        })

        cipher.write(text)
        cipher.end()
        return encrypted
}

function decrypt(text) {
    const key = crypto.scryptSync(process.env.CRYPTOPW, process.env.SALT, 24)
      const decipher = crypto.createDecipher('aes-192-cbc', key)

      let decrypted = '';
      decipher.on('readable', () => {
        while(null !== (chunk = decipher.read())) {
          decrypted += chunk.toString('utf8')
        }
      })

      const encrypted = text
      decipher.write(encrypted, 'hex')
      decipher.end()
      return decrypted
}

Body:
All you have to look for is where you response twice on the same call.

For example:

app.post('test', (req,res)=>{
 res.send('1')
 res.json('{1:2}')
})

will always return this error, because you are responding twice.

You have to investigate your routes one by one, I would start here:

app.post('/update', checkAuthenticated, async (req, res, next) => {
if(req.body.pw1 != req.body.pw2) { res.redirect('/update') }
    if(req.body.pw2 == process.env.DEFAULTPW) { res.redirect('/update') }
    const newpw = await encrypt(req.body.pw2)
    var queryresult
    await con.query("UPDATE login SET password = \'"+newpw+"\' WHERE email = \'"+req.body.email.toLowerCase()+"\'", (err, result, fields) => {
        if (err) {
            console.log(err)
            return res.redirect('/update')
        };
            console.log(result)
    queryresult = result
            if(result.changedRows == 0) {
                return res.redirect('/update')
            }

    })
    return res.redirect('/')
});

You are calling res.redirect explicitly and on condition. Have you checked if both conditions meet simultaneously? I guess here is one weak point.

And I would check this one

    app.post('/login', checkNotAuthenticated, (req, res, next) => {
        passport.authenticate('local', (err, user, info) => {
           if(err) throw err
           if(!user) return res.redirect('/login')
           req.logIn(user, (err) => {
              if(err) return next(err)
              if(info.message==process.env.DEFAULTPW) {
                  console.log("Default password detected for: " + user.email)
                  return res.redirect('/')
              }
              return res.redirect('/')

           })
  })(req, res, next)
})

Again there potentially meet two conditions. Check them out. Other parts look fine to me.


问:
Query dataframe by column name as a variable
I know this question has already been asked here, but my question a bit different. Lets say I have following df:

```<code>import pandas as pd

df = pd.DataFrame({'A': ('a', 'b', 'c', 'd', 'e', 'a', 'b'), 'B': ('a', 'a', 'g', 'l', 'e', 'a', 'b'), 'C': ('b', 'b', 'g', 'a', 'e', 'a', 'b')})

myList = ['a', 'e', 'b']
</code>```

I use this line to count the total number of occurrence of each elements of myList in my df columns:

```<code>print(df.query('A in @myList ').A.count())
5
</code>```

Now, I am trying to execute the same thing by looping through columns names. Something like this:

```<code>for col in df.columns:
    print(df.query('col in @myList ').col.count())
</code>```

Also, I was wondering if using query for this is the most efficient way?
Thanks for the help.

答:
Use this :

```<code>df.isin(myList).sum()

A    5
B    5
C    6
dtype: int64
</code>```

It checks every cell in the dataframe through myList and returns True or False. Sum uses the 1 or 0 reference and gets the total for each column

Body:
I know this question has already been asked here, but my question a bit different. Lets say I have following df:

import pandas as pd

df = pd.DataFrame({'A': ('a', 'b', 'c', 'd', 'e', 'a', 'b'), 'B': ('a', 'a', 'g', 'l', 'e', 'a', 'b'), 'C': ('b', 'b', 'g', 'a', 'e', 'a', 'b')})

myList = ['a', 'e', 'b']

I use this line to count the total number of occurrence of each elements of myList in my df columns:

print(df.query('A in @myList ').A.count())
5

Now, I am trying to execute the same thing by looping through columns names. Something like this:

for col in df.columns:
    print(df.query('col in @myList ').col.count())

Also, I was wondering if using query for this is the most efficient way?
Thanks for the help.

Body:
Use this :

df.isin(myList).sum()

A    5
B    5
C    6
dtype: int64

It checks every cell in the dataframe through myList and returns True or False. Sum uses the 1 or 0 reference and gets the total for each column


问:
How do you evaluate a trained reinforcement learning agent whether it is trained or not?
I am new to reinforcement learning agent training. I have read about PPO algorithm and used stable baselines library to train an agent using PPO. So my question here is how do I evaluate a trained RL agent. Consider for a regression or classification problem I have metrics like r2_score or accuracy etc.. Are there any such parameters or how do I test the agent, conclude that the agent is trained well or bad.

Thanks

答:
A good way to evaluate an RL agent is to run it in the environment for N times, and calculate the average return from the N runs.

It is common to perform the above evaluation step throughout your training process, and graph the average return as training happens. You would expect the average return to go up, indicating that the training is doing something useful.

For example, in Figure 3 of the PPO paper, the authors graphed the average return with training steps, to show that PPO performs better than other algorithms.


问:
What's the jquery syntax for click function of submit button
my form has a submit button that's been defined this way:

```<code><input type="submit" name="submit-reg" value="Register" class="submit button">
</code>```

What is the syntax to call the button's jquery click() function?
I've tried:

```<code>$('#submit-reg').click(function()...
</code>```

But it's not working.

答:
try this...  </p>

```<code>$('#submit-reg').click(function(event){
event.stopPropagation();
//rest of your code will go here
});
</code>```

Body:
my form has a submit button that's been defined this way:

<input type="submit" name="submit-reg" value="Register" class="submit button">

What is the syntax to call the button's jquery click() function?
I've tried:

$('#submit-reg').click(function()...

But it's not working.

Body:
try this...

$('#submit-reg').click(function(event){
event.stopPropagation();
//rest of your code will go here
});


问:
Taking two cells as arguments, and return a specific value depending on the string value of the cells
I need to make a VBA function that uses the values of two cells as arguments, and then return something depending on the values of the cells. I was thinking something like this

```<code>   Function returnNewString (cell1,cell2):
    if cell1 == 'somestring' && cell2 == "someotherstring" then
    return "something"
    else if cell1 == 'somestring2' && cell2 == "someotherstring2" then
    return "something else"
   end function
</code>```

A function call of returnNewString(A1,B1) should therefore return 'something' in relation to the conditions.

答:
You can use nested If/Case statements. Pretty simple, just check the value of the first string then proceed to check the value of the 2nd.

In your particular situation, I would go for Select Case Statements, but it comes down to preference in the end.

```<code>Function returnNewString(sValue1 As String, sValue2 As String) As String

    Select Case sValue1
    Case "Some String"
        Select Case sValue2
        Case "SomeOtherString"
            returnNewString = "Something"
        Case "Some Other String 2"
            returnNewString = "Something else"
        End Select
    Case "Some String 2"
        Select Case sValue2
        Case "SomeOtherString"
            returnNewString = "Something"
        Case "Some Other String 2"
            returnNewString = "Something else"
        End Select
    End Select

End Function
</code>```

In the first Select case, you check the value of the first argument sValue1. Once you match that value, proceed to check the value of sValue2.

And the syntax you used in your example is incorrect - there are no == and && operators in VBA, and literal string values must be enclosed in double-quotes, not single quotes - single quotes are reserved for comments.

Body:
I need to make a VBA function that uses the values of two cells as arguments, and then return something depending on the values of the cells. I was thinking something like this

   Function returnNewString (cell1,cell2):
    if cell1 == 'somestring' && cell2 == "someotherstring" then
    return "something"
    else if cell1 == 'somestring2' && cell2 == "someotherstring2" then
    return "something else"
   end function

A function call of returnNewString(A1,B1) should therefore return 'something' in relation to the conditions.

Body:
You can use nested If/Case statements. Pretty simple, just check the value of the first string then proceed to check the value of the 2nd.

In your particular situation, I would go for Select Case Statements, but it comes down to preference in the end.

Function returnNewString(sValue1 As String, sValue2 As String) As String

    Select Case sValue1
    Case "Some String"
        Select Case sValue2
        Case "SomeOtherString"
            returnNewString = "Something"
        Case "Some Other String 2"
            returnNewString = "Something else"
        End Select
    Case "Some String 2"
        Select Case sValue2
        Case "SomeOtherString"
            returnNewString = "Something"
        Case "Some Other String 2"
            returnNewString = "Something else"
        End Select
    End Select

End Function

In the first Select case, you check the value of the first argument sValue1. Once you match that value, proceed to check the value of sValue2.

And the syntax you used in your example is incorrect - there are no == and && operators in VBA, and literal string values must be enclosed in double-quotes, not single quotes - single quotes are reserved for comments.


问:
Display By month using select statement
```<code>SELECT SUM(Total_A ) FROM Materials_List
</code>```

This is the snippet of code that I have.

I need it to calculate by month and display by month using SQL.

I also would like it to be a code I can use for any month in the year not just one month at a time.

答:
You seem to be looking for simple aggregation:

```<code>select
    year(materials_datetime) yr,
    month(materials_datetime) mn,
    sum(total_a) sum_total_a
from materials_list
group by
    year(materials_datetime),
    month(materials_datetime)
order by yr, mn
</code>```

This assumes that column materials_datetime contains the date/time that you want to use to aggregate the data.

Title: Display By month using select statement

Body:
SELECT SUM(Total_A ) FROM Materials_List

This is the snippet of code that I have.

I need it to calculate by month and display by month using SQL.

I also would like it to be a code I can use for any month in the year not just one month at a time.

Body:
You seem to be looking for simple aggregation:

select
    year(materials_datetime) yr,
    month(materials_datetime) mn,
    sum(total_a) sum_total_a
from materials_list
group by
    year(materials_datetime),
    month(materials_datetime)
order by yr, mn

This assumes that column materials_datetime contains the date/time that you want to use to aggregate the data.


问:
Accessing a List or Dictionary using a Variable for the name
Consider the following code:

plants = {
    "rose" : [10, 20],
    "lily" : [30, 40]
}
rose = [11, 22]
lily = [33, 44]

...

    for name in plants.items():
        # Get this value from the List 'name'
        x = name[0]
    # Get this value from the dictionary 'plants' where key = 'name'
        y = plants[name][0]
```

<p>This is an overly-simplified version of my code. </p>

<p>I have a dictionary named <code>plants</code> that has some keys & values in it that I use in my program. The key also corresponds to the name of a list that has some values processed elsewhere in my program.</p>

<p>I want Python to do this (<em>PSEUDO-CODE</em>):</p>

<pre class="lang-py prettyprint-override"><code>    for name in plants.items():
        # Get this value from the List 'name'
        x = "rose"[0]
    # Get this value from the dictionary 'plants' where key = 'name'
        y = plants["rose"][0]
</code>```

And of course continue the iteration..

EDIT
To give a little more context, one of my functions is constantly updating the values in the plants dictionary. The values in the lists are accumulated calculations based on those values.

They need to be used for different functions in my program so I want to keep them separate.

答:
This involves modifying your dictionary but it might be as close as you get to what you want to do.</p>

```<code>rose = [11, 22]
lily = [33, 44]
plants = {
    'rose' : [10, 20, rose],
    'lily' : [30, 40, lily]
    }
for key, value in plants.items () :
    print (key, value)
</code>```

Body:
Consider the following code:

plants = {
    "rose" : [10, 20],
    "lily" : [30, 40]
}
rose = [11, 22]
lily = [33, 44]

...

    for name in plants.items():
        # Get this value from the List 'name'
        x = name[0]
    # Get this value from the dictionary 'plants' where key = 'name'
        y = plants[name][0]

This is an overly-simplified version of my code.

I have a dictionary named plants that has some keys & values in it that I use in my program. The key also corresponds to the name of a list that has some values processed elsewhere in my program.

I want Python to do this (PSEUDO-CODE):

    for name in plants.items():
        # Get this value from the List 'name'
        x = "rose"[0]
    # Get this value from the dictionary 'plants' where key = 'name'
        y = plants["rose"][0]

And of course continue the iteration..

EDIT
To give a little more context, one of my functions is constantly updating the values in the plants dictionary. The values in the lists are accumulated calculations based on those values.

They need to be used for different functions in my program so I want to keep them separate.

Body:
This involves modifying your dictionary but it might be as close as you get to what you want to do.

rose = [11, 22]
lily = [33, 44]
plants = {
    'rose' : [10, 20, rose],
    'lily' : [30, 40, lily]
    }
for key, value in plants.items () :
    print (key, value)


问:
Cannot convert jupyter notebook to pdf
I get the following error when  I try to convert jupyter notebook to pdf.

I'd appreciate your help. Thank you.

答:
```<code>sudo apt-get install texlive-xetex
</code>```

will probably fix your issue

Title: Cannot convert jupyter notebook to pdf

Body:
sudo apt-get install texlive-xetex

will probably fix your issue


问:
Cannot create Integration Services Catalog without Azure Subscription
I have an existing SQL Server 2017 install. I added SSIS via a different installation media/setup. It instance now shows as having Integration Services installed. I have rebooted many times. I am using SSMS 18.4

I want to create a catalog, SSISDB, locally to the installed instance. The only option present is Create SSIS IR button. There is no separate OK/Cancel buttons.

How do I create the catalog locally?

答: Your window has cut off the buttons at the bottom.  SSMS has some high-DPI rendering issues.  Try a lower desktop resolution or [Tab]ing around that dialog.  EG


问:
Is there a way to set minimum width on individual columns in C1FlexGrid?
Working with vb.net WinForms. I can set minimum width for the column collection of the flexgrid, but is there a way to make the minimum width different for each column? I cannot find anything that supports this. Pretty straightforward question but if any more info is needed let me know. </p>

答:
The grid has a Cols property, you pass in the index of the column, then the Column has a width property:

Example:

```<code>grid.Cols[0].Width = 50
</code>```

References
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.C1FlexGrid.html
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.ColumnCollection.html
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.Column_members.html
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.Column~Width.html

Body:
The grid has a Cols property, you pass in the index of the column, then the Column has a width property:

Example:

grid.Cols[0].Width = 50

References
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.C1FlexGrid.html
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.ColumnCollection.html
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.Column_members.html
http://helpcentral.componentone.com/nethelp/c1flexgrid/C1.Win.C1FlexGrid.4~C1.Win.C1FlexGrid.Column~Width.html


问:
What's the best way of dealing with AWT Graphics contexts?
Some users of our Swing application have reported weird artefacts appearing on the display. This ranges from components not repainting themselves properly for a second or two, right upto whole portions of the application being repainted like tiled wallpaper over areas of the window.

The app has been worked on by developers of all levels between experienced Java guys to young chaps right out of university over the course of five years or so, and as you'd expect, some of the AWT code is an outright mess. I'm now faced with the task of trying to correct as much of the badness as I can over the next few months or so.

Some of this is easy to deal with. Deal with components only on the event dispatch thread, IO asynchronously, kind of thing, and I'm hopefully getting the message across to the rest of the team.

What I'd like to know is the best way of dealing with Graphics contexts, especially in a paintComponent() context. I see a lot of...

```<code>public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g;
    // ...Whole lotta drawing code...
}
</code>```

Is it better practice to do this?

```<code>public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g.create();
    // ...Whole lotta drawing code...
    gfx.dispose();
}
</code>```

If the g parameter is going to be reused in other paints then don't I need to restore it to a good state, undo AffineTransforms, etc.?

答: I heard that this has been fixed in jdk-1.6.12, but didn't try it.</p>

OwnerDisplayName: banjollity

ContentLicense: CC BY-SA 2.5

Body:
Some users of our Swing application have reported weird artefacts appearing on the display. This ranges from components not repainting themselves properly for a second or two, right upto whole portions of the application being repainted like tiled wallpaper over areas of the window.

The app has been worked on by developers of all levels between experienced Java guys to young chaps right out of university over the course of five years or so, and as you'd expect, some of the AWT code is an outright mess. I'm now faced with the task of trying to correct as much of the badness as I can over the next few months or so.

Some of this is easy to deal with. Deal with components only on the event dispatch thread, IO asynchronously, kind of thing, and I'm hopefully getting the message across to the rest of the team.

What I'd like to know is the best way of dealing with Graphics contexts, especially in a paintComponent() context. I see a lot of...

public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g;
    // ...Whole lotta drawing code...
}

Is it better practice to do this?

public void paintComponent( Graphics g ) {
    super.paintComponent( g );
    Graphics2D gfx = (Graphics2D)g.create();
    // ...Whole lotta drawing code...
    gfx.dispose();
}

If the g parameter is going to be reused in other paints then don't I need to restore it to a good state, undo AffineTransforms, etc.?

OwnerDisplayName: Marko


问:
How to impersonate a GCP service account from credentials generated by Application Default Credentials
I have a service account and I am granting 'ServiceAccountUser' role on this service account to one of the real user. The user has Application Default Credentials set as part of his configuration to avoid login screen on every run. I am not sure what is the best way for this user to run a code that manipulates certain resources accessible only to the service account. I do not want to use Service Account Key JSON file for security reasons. I am trying following code

```<code>import google.auth
service_account_email='my-service-account@my-project.iam.gserviceaccount.com'
adc_credentials,adc_project=google.auth.default()

delegated_credentials=adc_credentials.with_subject(service_account_email)
</code>```

I am getting error:
AttributeError: 'Credentials' object has no attribute 'with_subject'

答:
As specified Here Service Account User Role grants you the permission to deploy resourrces with the service account, not the permission of becvoming this account.

If the concern is that the credentials when they are long term are easily compromised then you can use Short lived credentials

For impersonating a service Account you need the role of Service account token creator. here is an article that explaines this impersonation process.

Body:
I have a service account and I am granting 'ServiceAccountUser' role on this service account to one of the real user. The user has Application Default Credentials set as part of his configuration to avoid login screen on every run. I am not sure what is the best way for this user to run a code that manipulates certain resources accessible only to the service account. I do not want to use Service Account Key JSON file for security reasons. I am trying following code

import google.auth
service_account_email='my-service-account@my-project.iam.gserviceaccount.com'
adc_credentials,adc_project=google.auth.default()

delegated_credentials=adc_credentials.with_subject(service_account_email)

I am getting error:
AttributeError: 'Credentials' object has no attribute 'with_subject'


问:
Heroku 503 Service Unavailable
I am currently building a simple CRUD app using ExpressJS, and host it on Heroku using free account.

The problem I ran into is:

GET API for getting all items works on localhost, but show status 503 when hosting on Heroku;

POST API for updating one item works on localhost, but same issue as GET API above;

All 503 errors are after 30s of loading, this should be a setting from Heroku.

I do have other API end points that work on both local and Heroku server:

GET API for getting one item using ID

My guessing:

The issue should not be a code issue

There is some issue when the code is deployed and Heroku cannot process this request

I tried to find some articles on the web but this seems hard to diagnose, anyone who has experience please let me know how I can solve this issue. Appreciate your comments.

My Mongoose Schema

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

const ThoughtSchema = mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model("Thought", ThoughtSchema);
</code>```

2 end points that do not work

```<code>// Returns all thoughts
router.get("/", async (req, res) => {
  try {
    const thought = await Thought.find();
    res.json(thought);
  } catch (err) {
    res.json({ message: err });
  }
});

// Submit a post
router.post("/", async (req, res) => {
  const thought = new Thought({
    title: req.body.title,
    content: req.body.content
  });

  try {
    const savedThought = await thought.save();
    res.json(savedThought);
  } catch (err) {
    res.json({ message: err });
  }
});
</code>```

The end point that works

```<code>// Specific thought
router.get("/:thoughtId", async (req, res) => {
  try {
    const thought = await Thought.findById(req.params.thoughtId);
    res.json(thought);
  } catch (err) {
    res.json({ message: err });
  }
});
</code>```

My package.json for this express app

```<code>{
  "name": "my-thoughts-app",
  "version": "0.1.0",
  "description": "An app to records user's thoughts",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/PayneTang/my-thoughts-app.git"
  },
  "author": "Payne Tang",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/PayneTang/my-thoughts-app/issues"
  },
  "homepage": "https://github.com/PayneTang/my-thoughts-app#readme",
  "dependencies": {
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mongoose": "^5.8.11"
  },
  "devDependencies": {
    "typescript": "^3.7.5"
  }
}
</code>```

EDIT:
My index.js

```<code>const express = require("express");
const path = require("path");
const app = express();
const mongoose = require("mongoose");
const thoughtRoute = require("./routes/thought");
require("dotenv").config();

console.log(process.env);

// Mongoose settings
mongoose.connect(
  process.env.DB_CONNECTION,
  { useNewUrlParser: true, useUnifiedTopology: true },
  () => {
    console.log("Connected to DB!");
  }
);

app.use(express.json());
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.use("/api/thought", thoughtRoute);
app.get("/api/test", (req, res) => {
  res.send("hi");
});

// Serve client side
app.use(express.static(path.join(__dirname, "client/build")));
app.use(express.static(path.join(__dirname, "client/public")));
// app.get("*", (req, res) => {
//   res.sendFile(path.join(__dirname, "client/build/index.html"));
// });

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log("Listening on port " + PORT + "...");
});
</code>```

答:
The root cause after checking is due to the access restriction from Heroku to Mongo atlas.

After adding 0.0.0.0/0 for IP whitelist, I am able to get data from MongoDB.

Reference: https://docs.atlas.mongodb.com/security-whitelist/#add-whitelist-entries

Title: Heroku 503 Service Unavailable

Body:
I am currently building a simple CRUD app using ExpressJS, and host it on Heroku using free account.

The problem I ran into is:

GET API for getting all items works on localhost, but show status 503 when hosting on Heroku;

POST API for updating one item works on localhost, but same issue as GET API above;

All 503 errors are after 30s of loading, this should be a setting from Heroku.

I do have other API end points that work on both local and Heroku server:

GET API for getting one item using ID

My guessing:

The issue should not be a code issue

There is some issue when the code is deployed and Heroku cannot process this request

I tried to find some articles on the web but this seems hard to diagnose, anyone who has experience please let me know how I can solve this issue. Appreciate your comments.

My Mongoose Schema

const mongoose = require("mongoose");

const ThoughtSchema = mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  content: {
    type: String,
    required: true
  },
  date: {
    type: Date,
    default: Date.now
  }
});

module.exports = mongoose.model("Thought", ThoughtSchema);

2 end points that do not work

// Returns all thoughts
router.get("/", async (req, res) => {
  try {
    const thought = await Thought.find();
    res.json(thought);
  } catch (err) {
    res.json({ message: err });
  }
});

// Submit a post
router.post("/", async (req, res) => {
  const thought = new Thought({
    title: req.body.title,
    content: req.body.content
  });

  try {
    const savedThought = await thought.save();
    res.json(savedThought);
  } catch (err) {
    res.json({ message: err });
  }
});

The end point that works

// Specific thought
router.get("/:thoughtId", async (req, res) => {
  try {
    const thought = await Thought.findById(req.params.thoughtId);
    res.json(thought);
  } catch (err) {
    res.json({ message: err });
  }
});

My package.json for this express app

{
  "name": "my-thoughts-app",
  "version": "0.1.0",
  "description": "An app to records user's thoughts",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/PayneTang/my-thoughts-app.git"
  },
  "author": "Payne Tang",
  "license": "ISC",
  "bugs": {
    "url": "https://github.com/PayneTang/my-thoughts-app/issues"
  },
  "homepage": "https://github.com/PayneTang/my-thoughts-app#readme",
  "dependencies": {
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "mongoose": "^5.8.11"
  },
  "devDependencies": {
    "typescript": "^3.7.5"
  }
}

EDIT:
My index.js

const express = require("express");
const path = require("path");
const app = express();
const mongoose = require("mongoose");
const thoughtRoute = require("./routes/thought");
require("dotenv").config();

console.log(process.env);

// Mongoose settings
mongoose.connect(
  process.env.DB_CONNECTION,
  { useNewUrlParser: true, useUnifiedTopology: true },
  () => {
    console.log("Connected to DB!");
  }
);

app.use(express.json());
app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "*");
  res.header(
    "Access-Control-Allow-Headers",
    "Origin, X-Requested-With, Content-Type, Accept"
  );
  next();
});

app.use("/api/thought", thoughtRoute);
app.get("/api/test", (req, res) => {
  res.send("hi");
});

// Serve client side
app.use(express.static(path.join(__dirname, "client/build")));
app.use(express.static(path.join(__dirname, "client/public")));
// app.get("*", (req, res) => {
//   res.sendFile(path.join(__dirname, "client/build/index.html"));
// });

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log("Listening on port " + PORT + "...");
});


问:
Web page button to pass value to excel spreadsheet displayed on another page
is there a way to add several simple buttons to a web page that when pressed by a user, adds a fixed value to cell in a spreadsheet viewable on another page,on the same site, without viewing that other page. I would also like that to be the only way to add any data to that spreadsheet.

I Have been asked for more information. so i have included the code i have so far, which works fine however i would like to change where the change is outputted to.
I would like the word "Press" to be in a cell on a spreadsheet on another page on the same site and for that word to change to the word "Pressed" when the button is pressed.

```<code><body>

       <!-Changing the text->
<button id=" Button1 ">Press Me</button>
    <div id=" firstTxt1 ">Press</div>

<script>
// Changing text script
document.getElementById(" Button1 ").onclick = function (){
    document.getElementById(" firstTxt1 ").innerHTML = "Pressed";

}

</script>
    </body>
</code>```

答:
For a web Page html only solution is not the normal way. Generally, a web app would be used instead to communicate events between different views - something like a dotnet core web app.

In your case it seems you have 3 elements:

"data entering" html web page,

spreadsheet,

"data" viewing html web page.

How you interface with the spread sheet depends on the type of spreadsheet you are using, and where it is located.
if it is a google sheet, this answer might help
spread sheet button with java script.

The question lacks a lot of detail, and is very general, but I hope this helps you get started

Body:
is there a way to add several simple buttons to a web page that when pressed by a user, adds a fixed value to cell in a spreadsheet viewable on another page,on the same site, without viewing that other page. I would also like that to be the only way to add any data to that spreadsheet.

I Have been asked for more information. so i have included the code i have so far, which works fine however i would like to change where the change is outputted to.
I would like the word "Press" to be in a cell on a spreadsheet on another page on the same site and for that word to change to the word "Pressed" when the button is pressed.

       <!-Changing the text->
<button id=" Button1 ">Press Me</button>

Press


问:
How can I use reflection to instance a class which takes ReadOnlySpan as a constructor argument?
I have code like this:

```<code>    // lookup the object type, instance passing the data as constructor
    //all registered types must implement ctor passed ReadOnlySpan<byte>
    public static object InterpretPayload(ReadOnlySpan<byte> bytes)
    {
        var key = bytes[0];
        if (!TypeLookup.ContainsKey(key))
            return null;
        Type type = TypeLookup[key];
        var created = Activator.CreateInstance(type, bytes);
        return created;
    }
</code>```

TypeLookup maps numeric values to class types, in a weird sort of factory method pattern. However when changing my codebase to use ReadOnlySpan over byte[] I now get a compiler error that bytes isn't an object, which it isn't.

Is there another way to do this? I believe Activator tries to find the best ctor based on what I pass in, seems I need to do this more explicitly. Can I use reflection another way or have I found a case reflection can't emulate calling the ctor directly?

答:
You have to use reflection to obtain a (relatively) strongly-typed delegate, so that the ReadOnlySpan instance can be passed without boxing (which is not allowed for this type due to magic special-cased lifetime management)

Starting from the example for Expression.Parameter:

```<code>using System.Linq.Expressions;

delegate object CtorPattern<T>(ReadOnlySpan<T> s);

// Creating a parameter for the expression tree.
ParameterExpression param = Expression.Parameter(typeof(ReadOnlySpan<byte>));

// get your type
// get your ConstructorInfo by calling type.GetConstructor(...)

// Creating an expression for the constructor call and specifying its parameter.
var ctorCall = Expression.New(type, ctorinfo, param);

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
var delegateCtor = Expression.Lambda<CtorPattern<byte>>(
ctorCall, new ParameterExpression[] { param }).Compile();

// call it
var created = delegateCtor(bytes);
</code>```

You may want to cache the delegateCtor object in your type lookup instead of creating it anew every time.

Body:
I have code like this:

    // lookup the object type, instance passing the data as constructor
    //all registered types must implement ctor passed ReadOnlySpan<byte>
    public static object InterpretPayload(ReadOnlySpan<byte> bytes)
    {
        var key = bytes[0];
        if (!TypeLookup.ContainsKey(key))
            return null;
        Type type = TypeLookup[key];
        var created = Activator.CreateInstance(type, bytes);
        return created;
    }

TypeLookup maps numeric values to class types, in a weird sort of factory method pattern. However when changing my codebase to use ReadOnlySpan over byte[] I now get a compiler error that bytes isn't an object, which it isn't.

Is there another way to do this? I believe Activator tries to find the best ctor based on what I pass in, seems I need to do this more explicitly. Can I use reflection another way or have I found a case reflection can't emulate calling the ctor directly?

Body:
You have to use reflection to obtain a (relatively) strongly-typed delegate, so that the ReadOnlySpan instance can be passed without boxing (which is not allowed for this type due to magic special-cased lifetime management)

Starting from the example for Expression.Parameter:

using System.Linq.Expressions;

delegate object CtorPattern<T>(ReadOnlySpan<T> s);

// Creating a parameter for the expression tree.
ParameterExpression param = Expression.Parameter(typeof(ReadOnlySpan<byte>));

// get your type
// get your ConstructorInfo by calling type.GetConstructor(...)

// Creating an expression for the constructor call and specifying its parameter.
var ctorCall = Expression.New(type, ctorinfo, param);

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
var delegateCtor = Expression.Lambda<CtorPattern<byte>>(
ctorCall, new ParameterExpression[] { param }).Compile();

// call it
var created = delegateCtor(bytes);

You may want to cache the delegateCtor object in your type lookup instead of creating it anew every time.