问:
Why model has undefined state with repository pattern?
I'm trying to use repository pattern with TypeScript
Now I have base.repository that implements all of the functions that I need, I made it a generic type, and I wanna pass the model while injecting it in constructor, but for some reason, while passing the value, I have undefined state of the particular model, what am I doing wrong?

In the console.log() it shows me that the model is undefined while in file register.service.ts it shows me also undefined, but I passed it as generic.

register.service.ts

```<code>import { BaseRepository } from "../repositories/base.repository";
import { Creator } from '../data/models/Creator'
import { RegisterDto } from "../types/dtos/register.dto";
import { Injectable } from '@nestjs/common'
import { RegisterMapper } from '../mappers/register.mapper'
import { errors } from '../errors'
import { mailer } from '../utils/nodemailer'

@Injectable()
export class RegisterService {
    constructor(
      private readonly repository: BaseRepository<Creator>,
      private readonly mapper: RegisterMapper
    ) { }

    async createAccount (doc: RegisterDto) {
      const emailExist = await this.existByEmail(doc.email)
      if (emailExist) {
        return errors.EMAIL_EXIST()
      }
      const created = await this.repository.create(this.mapper.toDomain(doc))
      await mailer(doc.email)
      return created
    }

    private async existByEmail(email: string): Promise<boolean> {
      console.log(email)
      console.log(this.repository)
      const response = await this.repository.get({ email })
      return !!response.email;
    }
}
</code>```

base.repository.ts

```<code>import { ModelType } from '@typegoose/typegoose/lib/types'
import { DuplicateKeyError } from '../errors/DuplicateKeyError'
import { DocumentNotFoundError } from '../errors/DocumentNotFoundError'
import { Model } from 'mongoose'
import { Inject, Injectable, Optional } from '@nestjs/common'

@Injectable()
export class BaseRepository<T = any> {
    constructor(
        @Optional() @Inject('MODEL') private Model: any
    ) { }

    async create (object): Promise<T> {
        const Model = this.Model
        console.log(Model)
        const uniqueKey = Model.getUniqueKey ? Model.getUniqueKey() : null
        if (uniqueKey && object[uniqueKey]) {
            const criteria = {
                [uniqueKey]: object[uniqueKey]
            }
            const existing = await Model.findOne(criteria)
            if (existing) {
                throw new DuplicateKeyError(Model, criteria)
            }
        }

        const model = new Model(object)
        return model.save()
    }

    async update (criteria, object, options = {}) {
        const Model = this.Model

        const uniqueKey = Model.getUniqueKey ? Model.getUniqueKey() : '_id'

        const data = { ...object }
        delete data[uniqueKey]
        delete data.createdAt

        return this.updateRaw(criteria, { $set: { ...data } }, options)
    }

    async updateRaw (criteria, data, options = {}) {
        const query = this._getDbQuery(criteria, options)
        const result = await this.Model.findOneAndUpdate(query, data, { new: true, ...options })

        if (!result) {
            throw new DocumentNotFoundError(this.Model, query)
        }

        return result
    }

    async save (modelInstance) {
        return modelInstance.save()
    }

    async get (criteria, options: any = {}): Promise<T | undefined> {
        console.log(Model)
        const promise = await this.Model.findOne(this._getDbQuery(criteria, options)).exec()

        if (options.select) {
            promise.select(options.select)
        }

        return promise
    }

    async find (criteria, options): Promise<ReturnType<ModelType<T>['find']>> {
        return this.Model.find(this._getDbQuery(criteria, options))
    }

    async resolve (criteria): Promise<T> {
        return this.Model.resolve(this._getDbQuery(criteria))
    }

    async count (query) {
        return this.Model.countDocuments(this._getDbQuery(query))
    }

    async delete (criteria) {
        return this.Model.remove(this._getDbQuery(criteria))
    }

    _getDbQuery (criteria, options: any = {}) {
        if ('getDbQuery' in criteria) {
            const dbQuery = criteria.getDbQuery(options)
            return 'find' in dbQuery
                ? dbQuery.find
                : dbQuery
        } else {
            return criteria
        }
    }

}
</code>```

What should I do to get the actual model in this repository?

答:
I have added inject tokens in each service before repository Injection

Now the code looks as follows

```<code>import { BaseRepository } from "../repositories/base.repository";
import { Creator } from '../data/models/Creator'
import { RegisterDto } from "../types/dtos/register.dto";
import { Injectable } from '@nestjs/common'
import { RegisterMapper } from '../mappers/register.mapper'
import { errors } from '../errors'
import { mailer } from '../utils/nodemailer'
import { CREATOR } from '../utils'

@Injectable()
export class RegisterService {
  registerMapper = new RegisterMapper()
    constructor(
      @Inject(CREATOR) private readonly repository: BaseRepository<Creator>,
    ) { }

    async createAccount (doc: RegisterDto) {
      const emailExist = await this.existByEmail(doc.email)
      if (emailExist) {
        return errors.EMAIL_EXIST()
      }
      const created = await this.repository.create(this.mapper.toDomain(doc))
      await mailer(doc.email)
      return created
    }

    private async existByEmail(email: string): Promise<boolean> {
      console.log(email)
      console.log(this.repository)
      const response = await this.repository.get({ email })
      return !!response.email;
    }
}
</code>```

inject-tokens.ts

```<code>export const CREATOR = 'CREATOR'
</code>```

Body:
I'm trying to use repository pattern with TypeScript
Now I have base.repository that implements all of the functions that I need, I made it a generic type, and I wanna pass the model while injecting it in constructor, but for some reason, while passing the value, I have undefined state of the particular model, what am I doing wrong?

In the console.log() it shows me that the model is undefined while in file register.service.ts it shows me also undefined, but I passed it as generic.

register.service.ts

import { BaseRepository } from "../repositories/base.repository";
import { Creator } from '../data/models/Creator'
import { RegisterDto } from "../types/dtos/register.dto";
import { Injectable } from '@nestjs/common'
import { RegisterMapper } from '../mappers/register.mapper'
import { errors } from '../errors'
import { mailer } from '../utils/nodemailer'

@Injectable()
export class RegisterService {
    constructor(
      private readonly repository: BaseRepository<Creator>,
      private readonly mapper: RegisterMapper
    ) { }

    async createAccount (doc: RegisterDto) {
      const emailExist = await this.existByEmail(doc.email)
      if (emailExist) {
        return errors.EMAIL_EXIST()
      }
      const created = await this.repository.create(this.mapper.toDomain(doc))
      await mailer(doc.email)
      return created
    }

    private async existByEmail(email: string): Promise<boolean> {
      console.log(email)
      console.log(this.repository)
      const response = await this.repository.get({ email })
      return !!response.email;
    }
}

base.repository.ts

import { ModelType } from '@typegoose/typegoose/lib/types'
import { DuplicateKeyError } from '../errors/DuplicateKeyError'
import { DocumentNotFoundError } from '../errors/DocumentNotFoundError'
import { Model } from 'mongoose'
import { Inject, Injectable, Optional } from '@nestjs/common'

@Injectable()
export class BaseRepository<T = any> {
    constructor(
        @Optional() @Inject('MODEL') private Model: any
    ) { }

    async create (object): Promise<T> {
        const Model = this.Model
        console.log(Model)
        const uniqueKey = Model.getUniqueKey ? Model.getUniqueKey() : null
        if (uniqueKey && object[uniqueKey]) {
            const criteria = {
                [uniqueKey]: object[uniqueKey]
            }
            const existing = await Model.findOne(criteria)
            if (existing) {
                throw new DuplicateKeyError(Model, criteria)
            }
        }

        const model = new Model(object)
        return model.save()
    }

    async update (criteria, object, options = {}) {
        const Model = this.Model

        const uniqueKey = Model.getUniqueKey ? Model.getUniqueKey() : '_id'

        const data = { ...object }
        delete data[uniqueKey]
        delete data.createdAt

        return this.updateRaw(criteria, { $set: { ...data } }, options)
    }

    async updateRaw (criteria, data, options = {}) {
        const query = this._getDbQuery(criteria, options)
        const result = await this.Model.findOneAndUpdate(query, data, { new: true, ...options })

        if (!result) {
            throw new DocumentNotFoundError(this.Model, query)
        }

        return result
    }

    async save (modelInstance) {
        return modelInstance.save()
    }

    async get (criteria, options: any = {}): Promise<T | undefined> {
        console.log(Model)
        const promise = await this.Model.findOne(this._getDbQuery(criteria, options)).exec()

        if (options.select) {
            promise.select(options.select)
        }

        return promise
    }

    async find (criteria, options): Promise<ReturnType<ModelType<T>['find']>> {
        return this.Model.find(this._getDbQuery(criteria, options))
    }

    async resolve (criteria): Promise<T> {
        return this.Model.resolve(this._getDbQuery(criteria))
    }

    async count (query) {
        return this.Model.countDocuments(this._getDbQuery(query))
    }

    async delete (criteria) {
        return this.Model.remove(this._getDbQuery(criteria))
    }

    _getDbQuery (criteria, options: any = {}) {
        if ('getDbQuery' in criteria) {
            const dbQuery = criteria.getDbQuery(options)
            return 'find' in dbQuery
                ? dbQuery.find
                : dbQuery
        } else {
            return criteria
        }
    }

}

What should I do to get the actual model in this repository?

Body:
I have added inject tokens in each service before repository Injection

Now the code looks as follows

import { BaseRepository } from "../repositories/base.repository";
import { Creator } from '../data/models/Creator'
import { RegisterDto } from "../types/dtos/register.dto";
import { Injectable } from '@nestjs/common'
import { RegisterMapper } from '../mappers/register.mapper'
import { errors } from '../errors'
import { mailer } from '../utils/nodemailer'
import { CREATOR } from '../utils'

@Injectable()
export class RegisterService {
  registerMapper = new RegisterMapper()
    constructor(
      @Inject(CREATOR) private readonly repository: BaseRepository<Creator>,
    ) { }

    async createAccount (doc: RegisterDto) {
      const emailExist = await this.existByEmail(doc.email)
      if (emailExist) {
        return errors.EMAIL_EXIST()
      }
      const created = await this.repository.create(this.mapper.toDomain(doc))
      await mailer(doc.email)
      return created
    }

    private async existByEmail(email: string): Promise<boolean> {
      console.log(email)
      console.log(this.repository)
      const response = await this.repository.get({ email })
      return !!response.email;
    }
}

inject-tokens.ts

export const CREATOR = 'CREATOR'


来源: stackexchange

问:
How can I prevent overflow of nested grid's content of div?
MCVE

I would like to nest a grid within another grid, and have a tall content box within the nested grid's content div. However no matter I set the overflow property of this content div to scroll, the content box grows causing the outer grid to exceed the viewport. So the viewport gets a scrollbar. The scrollbar of the content div is present but disabled.

// html

  Outer Grid Header

    Inner Grid Header

    Tall Box

```
```// style scss
*{
  padding: 0px;
  margin: 0px;
}

.outergrid {
  display: grid;
  grid-template-rows: 50px 100%;
  grid-gap: 10px;
  background-color: #0ff;
  div {
    background-color: #afa;
  }
}
.row1{
  grid-row: 1;
}
.row2{
  grid-row: 2;
  display: grid;
  grid-template-rows: 50px 100%;
  grid-gap: 5px;
  .header {
    grid-row: 1;
    background-color: #ffa;
  }
  .contentbox {
     grid-row: 2;
     overflow: scroll;
     .tallcontent {
       background-color: #89f;
       height: 1000px;
     }
  }
}
```

screenshot highlighting the problem

答:
If I understood you correctly, then perhaps this solution (pure CSS, without SCSS) below can help you. The solution is to enforce a constraint on the height of the parent elements.

* {
  padding: 0px;
  margin: 0px;
}

.outergrid {
  --grid-gap: 10px;
  display: grid;
  grid-template-rows: 50px calc(100% - 50px - var(--grid-gap));
  grid-gap: var(--grid-gap);
  background-color: #0ff;
  max-height: 100vh;
}

.outergrid div {
  background-color: #afa;
}

.row1 {
  grid-row: 1;
}

.row2 {
  --grid-gap: 5px;
  grid-row: 2;
  display: grid;
  max-height: 100%;
  grid-template-rows: 50px calc(100% - 50px - var(--grid-gap));
  grid-gap: var(--grid-gap);
}

.row2 .header {
  grid-row: 1;
  background-color: #ffa;
}

.row2 .contentbox {
  grid-row: 2;
  overflow: scroll;
}

.row2 .contentbox .tallcontent {
  background-color: #89f;
  height: 1000px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="outergrid">
  <div class="row1">
    Outer Grid Header
  </div>
  <div class="row2">
    <div class="header">
      Inner Grid Header
    </div>
    <div class="contentbox">
      <div class="tallcontent">
        Tall Content
      </div>
    </div>
  </div>
</div></code>```

ContentLicense: CC BY-SA 4.0

Body:
MCVE

I would like to nest a grid within another grid, and have a tall content box within the nested grid's content div. However no matter I set the overflow property of this content div to scroll, the content box grows causing the outer grid to exceed the viewport. So the viewport gets a scrollbar. The scrollbar of the content div is present but disabled.

// html

  Outer Grid Header

    Inner Grid Header

    Tall Box

// style scss
*{
  padding: 0px;
  margin: 0px;
}

.outergrid {
  display: grid;
  grid-template-rows: 50px 100%;
  grid-gap: 10px;
  background-color: #0ff;
  div {
    background-color: #afa;
  }
}
.row1{
  grid-row: 1;
}
.row2{
  grid-row: 2;
  display: grid;
  grid-template-rows: 50px 100%;
  grid-gap: 5px;
  .header {
    grid-row: 1;
    background-color: #ffa;
  }
  .contentbox {
     grid-row: 2;
     overflow: scroll;
     .tallcontent {
       background-color: #89f;
       height: 1000px;
     }
  }
}

screenshot highlighting the problem

Body:
If I understood you correctly, then perhaps this solution (pure CSS, without SCSS) below can help you. The solution is to enforce a constraint on the height of the parent elements.

* {
  padding: 0px;
  margin: 0px;
}

.outergrid {
  --grid-gap: 10px;
  display: grid;
  grid-template-rows: 50px calc(100% - 50px - var(--grid-gap));
  grid-gap: var(--grid-gap);
  background-color: #0ff;
  max-height: 100vh;
}

.outergrid div {
  background-color: #afa;
}

.row1 {
  grid-row: 1;
}

.row2 {
  --grid-gap: 5px;
  grid-row: 2;
  display: grid;
  max-height: 100%;
  grid-template-rows: 50px calc(100% - 50px - var(--grid-gap));
  grid-gap: var(--grid-gap);
}

.row2 .header {
  grid-row: 1;
  background-color: #ffa;
}

.row2 .contentbox {
  grid-row: 2;
  overflow: scroll;
}

.row2 .contentbox .tallcontent {
  background-color: #89f;
  height: 1000px;
}

<div class="outergrid">
  <div class="row1">
    Outer Grid Header
  </div>
  <div class="row2">
    <div class="header">
      Inner Grid Header
    </div>
    <div class="contentbox">
      <div class="tallcontent">
        Tall Content
      </div>
    </div>
  </div>
</div>


问:
Is there a way to get all combinations of overlap between values in dictionary, or from within a list
I have a few lists

```<code>A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']
</code>```

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

```<code>my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}
</code>```

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

```<code>   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))
</code>```

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

```<code>   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC
</code>```

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

答:
[Edited solution after exchange in comments]

```<code>import itertools as it

A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']

master_dict = dict(A=A, B=B, C=C, D=D, F=F)
for i in range(len(master_dict)):
    for combo in it.combinations(master_dict.keys(), i):
        new_key = "".join(combo)
        print(combo)
        if (len(combo)>1):
            mixed_dict[new_key] = set.intersection(*[set(master_dict[c][0]) for c in combo])
            print("---->" + str(mixed_dict[new_key]))
</code>```

... with a couple of commented out print statements to show you what's going on. At the end of the script, you have a new_dict which looks like this:

I didn't add the combinations of length 1 on purpose, but you can remove the if() condition above to get them back.

Body:
I have a few lists

A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']

I passed them in combinations to a dictionary. For example, I joined lists A and B as a key 'AB' in my new dictionary and appended the values from both lists like the list of values to that key 'AB'.

my_dict={"AB":[['D','KIT','SAP'],['F','G','LUFT','SAP']]}

My aim to get the overlap between the lists in multiple combination. For that, I could get with the following one liner.

   for k,v in my_dict.items():
        print(k,list(set.intersection(*[set(x) for x in v])))

AB ['SAP']

However, the problem here is that when I have more lists and more combinations it is tedious to define manually a dictionary with all possible combinations.

The aim is to achieve all possible combinations of lists. From the above-mentioned example, I have the following combination of lists. In this case that would be 5*5 +1 = 26 combinations. And in the end, I would like to get the overlap for each of the following combinations.

   AB, AC, AD, AF
    ABC, ABD, ABF
    ABCD, ABCDF
    ABCDF
BC, BD, BF
DF, DC
FC

The question is how could I achieve that in a pythonic way. Any suggestions are much appreciated.

As a side note, I do not want a dictionary in between if this combination of overlap is possible from the lists itself.

Thanks

Body:
[Edited solution after exchange in comments]

import itertools as it

A =['D','KIT','SAP'],
B= ['F','G','LUFT','SAP'],
C= ['I','SAP'],
D= ['SAP','LUF','KIT'],
F= ['SAP','LUF','KIT','HASS']

master_dict = dict(A=A, B=B, C=C, D=D, F=F)
for i in range(len(master_dict)):
    for combo in it.combinations(master_dict.keys(), i):
        new_key = "".join(combo)
        print(combo)
        if (len(combo)>1):
            mixed_dict[new_key] = set.intersection(*[set(master_dict[c][0]) for c in combo])
            print("---->" + str(mixed_dict[new_key]))

... with a couple of commented out print statements to show you what's going on. At the end of the script, you have a new_dict which looks like this:

I didn't add the combinations of length 1 on purpose, but you can remove the if() condition above to get them back.


问:
How do I port code for Borland C++ builder to Linux?
I have source code for a Windows DLL that is written in C++ and uses Visual Component Library. Now my task is to port that to Linux, but I don't have source code for the VCL itself, or any kind of documentation (and I have never worked with Borland C++; in my Windows days I used MFC).

This should not be all that hard, since my DLL does not have any GUI: as far as I can see, it mostly uses VCL for multithreading. I ran into a class that inherits from TThread and that is where I got stuck. I did some search on the Internet, but found no documentation for VCL so far. I would like to avoid buying a book on Borland C++ Builder, because I don't have time to wait for it to arrive from the Amazon. I cannot consider buying the package for Windows, because at work I only have a Linux box.

Any suggestions?

答: The Boost libraries, and wxWidgets, will provide analogs to the VCL classes.</p>

OwnerDisplayName: ajanicij

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: tpdi


问:
Change background-image with jQuery - doesn´t work
```<code>$('#areaView').css('background-image', 'url(/areaNr1.jpg)');
</code>```

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!

答:
The code I provided is in mydomain.com/jQuery/myfile.js and the image also is in that folder.

Then you mustn't prefix the URL with a / - that makes it point to the web root.

Use just areaNr1.jpg - note hoever that the URL will be relative to the HTML file, not the JS file in this case so you may need to change the path further.

ContentLicense: CC BY-SA 3.0

Body:
$('#areaView').css('background-image', 'url(/areaNr1.jpg)');

I don´t know what to say, I have no idea why this code doesn´t work. The old background-image disappears, but the new one never appears.

I have checked and areaNr1.jpg exists in the same folder as the code. Allthough the function isn´t in the same folder as #areaView, but that should not matter, right?

Any ideas why this doesn´t work?

Thanks for your help!


问:
Map in map : TypeError: Cannot read properties of undefined (reading 'map')
I have these datas :

```<code>[
    {
        "id": "1",
        "name": "test1",
        "secondary": [
            "testS1", "testS2"
        ]
    },
    {
        "id": "2",
        "name": "test2",
        "secondary": [
            "testS3", "testS4"
        ]
    }
]
</code>```

I map all exercices from a json file, and now I wish to loop props.exercices.secondary of each object.
Here is my try :

```<code>export default function AllExos(props) {
    return <div>
        {props.exercices.map(exo => {
            return <div key={exo.name}>
                <div>
                     <h2>{exo.id}</h2>
                     <p>Display secondary :
                            {exo.secondary.map(k => {
                                return <span key={k}>{k}</span>
                            })}
                     </p>
                 </div>
             </div>
        })}
    </div>
}
</code>```

I don't understand why I get the error TypeError: Cannot read properties of undefined (reading 'map'). I am looping in the 'props.exercices', right ?

答:
You can use optional chaining.</p>
```<code>props?.exercices?.map(...)
</code>```

Body:
I have these datas :

[
    {
        "id": "1",
        "name": "test1",
        "secondary": [
            "testS1", "testS2"
        ]
    },
    {
        "id": "2",
        "name": "test2",
        "secondary": [
            "testS3", "testS4"
        ]
    }
]

I map all exercices from a json file, and now I wish to loop props.exercices.secondary of each object.
Here is my try :

export default function AllExos(props) {
    return

        {props.exercices.map(exo => {
            return

{exo.id}

Display secondary :
                            {exo.secondary.map(k => {
                                return {k}
                            })}

        })}

}

I don't understand why I get the error TypeError: Cannot read properties of undefined (reading 'map'). I am looping in the 'props.exercices', right ?

Body:
You can use optional chaining.

props?.exercices?.map(...)


问:
Strip blanks at the beginning & trailing blanks in AWK
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

```<code>001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith
</code>```

My objective is to achieve the following set of data (without the leading/trailing spaces)

```<code>001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

I have tried the following without satisfaction.

```<code>awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith
</code>```

答:
If, as you said in your question, you don't want leading or trailing spaces on the lines removed then using any sed:

```<code>$ sed 's/ *| */|/g' file
001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

otherwise if you actually did want the leading/trailing blanks removed too then with GNU or BSD sed for -E:

```<code>$ sed -E 's/(^| *)\|( *|$)/|/g' file
001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith
</code>```

Body:
I am asking for your assistance to strip blanks/spaces before & at the end each field. ie Remove the trailing space from the $1, the same apply to the beginning & trailing spaces in $2, and the leading spaces from $3 using AWK on AIX 7.2 platform. Below is some data in the file Employee.txt

001 |  George John Aden Brown   | gbrown
002 |   Barry Street White      | bwhite
003 |    Kelly Jones            | kjones
004 |   Jolene Davidson Smith   | jsmith

My objective is to achieve the following set of data (without the leading/trailing spaces)

001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

I have tried the following without satisfaction.

awk -F"|" '{ print $1 "|" gsub(" ", "", $2) "|" $3 }' Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[ \t]/,"",$2) "|" $3 }'  Employee.txt
awk -F"|" '{ print $1 "|" gsub(/[[:blank:]]/, "", $2) "|" $3 }' Employee.txt

001 |8| gbrown
002 |11| bwhite
003 |17| kjones
004 |8| jsmith

Body:
If, as you said in your question, you don't want leading or trailing spaces on the lines removed then using any sed:

$ sed 's/ *| */|/g' file
001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith

otherwise if you actually did want the leading/trailing blanks removed too then with GNU or BSD sed for -E:

$ sed -E 's/(^| *)\|( *|$)/|/g' file
001|George John Aden Brown|gbrown
002|Barry Street White|bwhite
003|Kelly Jones|kjones
004|Jolene Davidson Smith|jsmith


问:
Need assistance on function to determine largest list Haskell
I need to create a function that reads from a list of courses (such as the one shown below), and return which courses has the largest number of programming languages.

Here is the list

```<code>progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"]),
     ("CptS355" , ["Haskell", "Python", "PostScript", "Java"]),
     ("CptS360" , ["C"]),
     ("CptS370" , ["Java"]),
     ("CptS315" , ["Python"]),
     ("CptS411" , ["C", "C++"]),
     ("CptS451" , ["Python", "C#", "SQL"]),
     ("CptS475" , ["Python", "R"])
     ]
</code>```

It needs to be compatible with the following

```<code>The type of the max_count function should be compatible with one of the following:
max_count :: [(a1, [a2])] -> (a1, Int)
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)
</code>```

So far, I have attempted the following code

```<code>max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')
</code>```

This has not worked in the slightest, and I am at a blank for what to do. Any help is appreciated.

答:
Your main problem is that you are assuming that max_helper takes a class/language-list pair as its second argument, when it takes a class/language-count as returned by max_count. (You are also incorrectly applying x to max_helper, rather than the other way around.

```<code>max_count :: [(a1, [a2])] -> (a1, Int)
max_count [] = error "bad"
max_count [(a, b)] = (a, length b)
max_count (x:xs) = max_helper x (max_count xs)
        where
        max_helper (a,bs) (a', b')
            | length bs > b' = (a, length bs)
            | otherwise = (a', b')
</code>```

However, you can define this more declaratively. First, you don't care about the actual languages, only their count. Replace the lists with their lengths by taking advantage of the fact that fmap f (a, b) == (a, f b):

```<code>> map (fmap length) progLanguages
[("CptS121",1),("CptS122",1),("CptS223",1),("CptS233",1),("CptS321",1),("CptS322",2),("CptS355",4),("CptS360",1),("CptS370",1),("CptS315",1),("CptS411",2),("CptS451",3),("CptS475",2)]
</code>```

Now what you want is the maximum of this list, but using a comparison function that ignores the class name and only looks at the lengths. You can construct such a function using Data.Ord.comparing:

```<code>-- "b" > "a", but 1 < 2
> comparing snd ("b", 1), ("a", 2)
LT
</code>```

You can use this comparison function with Data.List.maximumBy:

```<code>> import Data.List
> import Data.Ord
> max_count = maximumBy (comparing snd) . map (fmap length)
> max_count progLanguages
("CptS355",4)
> :t max_count
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)
</code>```

Body:
I need to create a function that reads from a list of courses (such as the one shown below), and return which courses has the largest number of programming languages.

Here is the list

progLanguages =
     [ ("CptS121" , ["C"]),
     ("CptS122" , ["C++"]),
     ("CptS223" , ["C++"]),
     ("CptS233" , ["Java"]),
     ("CptS321" , ["C#"]),
     ("CptS322" , ["Python", "JavaScript"]),
     ("CptS355" , ["Haskell", "Python", "PostScript", "Java"]),
     ("CptS360" , ["C"]),
     ("CptS370" , ["Java"]),
     ("CptS315" , ["Python"]),
     ("CptS411" , ["C", "C++"]),
     ("CptS451" , ["Python", "C#", "SQL"]),
     ("CptS475" , ["Python", "R"])
     ]

It needs to be compatible with the following

The type of the max_count function should be compatible with one of the following:
max_count :: [(a1, [a2])] -> (a1, Int)
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)

So far, I have attempted the following code

max_count [] = error "bad"
max_count [x] = x
max_count (x:xs) = x max_helper (max_count xs)
     where
     max_helper (a,b) (a',b')
          | length b > length b' = (a, length b)
          | otherwise = (a', length b')

This has not worked in the slightest, and I am at a blank for what to do. Any help is appreciated.

Body:
Your main problem is that you are assuming that max_helper takes a class/language-list pair as its second argument, when it takes a class/language-count as returned by max_count. (You are also incorrectly applying x to max_helper, rather than the other way around.

max_count :: [(a1, [a2])] -> (a1, Int)
max_count [] = error "bad"
max_count [(a, b)] = (a, length b)
max_count (x:xs) = max_helper x (max_count xs)
        where
        max_helper (a,bs) (a', b')
            | length bs > b' = (a, length bs)
            | otherwise = (a', b')

However, you can define this more declaratively. First, you don't care about the actual languages, only their count. Replace the lists with their lengths by taking advantage of the fact that fmap f (a, b) == (a, f b):

> map (fmap length) progLanguages
[("CptS121",1),("CptS122",1),("CptS223",1),("CptS233",1),("CptS321",1),("CptS322",2),("CptS355",4),("CptS360",1),("CptS370",1),("CptS315",1),("CptS411",2),("CptS451",3),("CptS475",2)]

Now what you want is the maximum of this list, but using a comparison function that ignores the class name and only looks at the lengths. You can construct such a function using Data.Ord.comparing:

-- "b" > "a", but 1 < 2
> comparing snd ("b", 1), ("a", 2)
LT

You can use this comparison function with Data.List.maximumBy:

> import Data.List
> import Data.Ord
> max_count = maximumBy (comparing snd) . map (fmap length)
> max_count progLanguages
("CptS355",4)
> :t max_count
max_count :: Foldable t => [(a1, t a2)] -> (a1, Int)


问:
Groovy JSONArray : org.json.JSONException: when decoding string with \"
I get no way to parse this Json which seems to be valid for me :

```<code>def diffOfApi='''[{"op":"replace","path":"/data/0/messageBody","value":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<WCS reference=\"336042800000431486\"><PREPARATION_REQUEST requestId=\"WDP_PICKVRAC3\" date=\"2022-02-08 18:33:39\"><CONTAINERS><CONTAINER containerId=\"336042800000431486_21_21121\" handle=\"CREATE\" wmsOrderId=\"WDP_PICKVRAC3\" site=\"CPEEPF\" status=\"CREATED\" referenceDate=\"2022-02-08 18:33:39\" purgeAuthorized=\"false\"><BARCODES><BARCODE main=\"false\" reusable=\"false\">336042800000431486</BARCODE></BARCODES><PACKAGING>TX</PACKAGING><WEIGHT_CHECKING mode=\"NO\"/></CONTAINER></CONTAINERS></PREPARATION_REQUEST></WCS>"}]'''

JSONArray jsonArray = new JSONArray(diffOfApi);
</code>```

I get this error :

```<code>Reason:
org.json.JSONException: Expected a ',' or '}' at 71 [character 72 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
    at org.json.JSONObject.<init>(JSONObject.java:229)
    at org.json.JSONTokener.nextValue(JSONTokener.java:363)
    at org.json.JSONArray.<init>(JSONArray.java:115)
    at org.json.JSONArray.<init>(JSONArray.java:144)
    at TEST.run(TEST:32)
    at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
    at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
    at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:442)
    at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:433)
    at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:412)
    at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:404)
    at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:281)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
    at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
    at TempTestCase1644483473725.run(TempTestCase1644483473725.groovy:25)
</code>```

I think it is due to " encapsulated xml in item value

Any idea to make it working ?

答:
you have incorrectly encoded json string.

if json contains doublequote in a value " - it must be encoded as \" but inside the groovy/java code each \ also must be encoded with \\

so when you have following in code:

```<code>def x = '''{"x":"abc\"def"}'''
</code>```

then actual x value at runtime would be

{"x":"abc"def"}
```
<p>that is incorrect json</p>
<p>so, <code>x</code> should be defined as</p>
```def x = '''{"x":"abc\\"def"}'''
```
<p>to have runtime value</p>
<pre class="lang-js prettyprint-override"><code>{"x":"abc\"def"}
</code>```

Body:
I get no way to parse this Json which seems to be valid for me :

def diffOfApi='''[{"op":"replace","path":"/data/0/messageBody","value":"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<WCS reference=\"336042800000431486\"><PREPARATION_REQUEST requestId=\"WDP_PICKVRAC3\" date=\"2022-02-08 18:33:39\"><CONTAINERS><CONTAINER containerId=\"336042800000431486_21_21121\" handle=\"CREATE\" wmsOrderId=\"WDP_PICKVRAC3\" site=\"CPEEPF\" status=\"CREATED\" referenceDate=\"2022-02-08 18:33:39\" purgeAuthorized=\"false\"><BARCODES><BARCODE main=\"false\" reusable=\"false\">336042800000431486</BARCODE></BARCODES><PACKAGING>TX</PACKAGING><WEIGHT_CHECKING mode=\"NO\"/></CONTAINER></CONTAINERS></PREPARATION_REQUEST></WCS>"}]'''

JSONArray jsonArray = new JSONArray(diffOfApi);

I get this error :

Reason:
org.json.JSONException: Expected a ',' or '}' at 71 [character 72 line 1]
    at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
    at org.json.JSONObject.<init>(JSONObject.java:229)
    at org.json.JSONTokener.nextValue(JSONTokener.java:363)
    at org.json.JSONArray.<init>(JSONArray.java:115)
    at org.json.JSONArray.<init>(JSONArray.java:144)
    at TEST.run(TEST:32)
    at com.kms.katalon.core.main.ScriptEngine.run(ScriptEngine.java:194)
    at com.kms.katalon.core.main.ScriptEngine.runScriptAsRawText(ScriptEngine.java:119)
    at com.kms.katalon.core.main.TestCaseExecutor.runScript(TestCaseExecutor.java:442)
    at com.kms.katalon.core.main.TestCaseExecutor.doExecute(TestCaseExecutor.java:433)
    at com.kms.katalon.core.main.TestCaseExecutor.processExecutionPhase(TestCaseExecutor.java:412)
    at com.kms.katalon.core.main.TestCaseExecutor.accessMainPhase(TestCaseExecutor.java:404)
    at com.kms.katalon.core.main.TestCaseExecutor.execute(TestCaseExecutor.java:281)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:142)
    at com.kms.katalon.core.main.TestCaseMain.runTestCase(TestCaseMain.java:133)
    at com.kms.katalon.core.main.TestCaseMain$runTestCase$0.call(Unknown Source)
    at TempTestCase1644483473725.run(TempTestCase1644483473725.groovy:25)

I think it is due to " encapsulated xml in item value

Any idea to make it working ?

Body:
you have incorrectly encoded json string.

if json contains doublequote in a value " - it must be encoded as \" but inside the groovy/java code each \ also must be encoded with \\

so when you have following in code:

def x = '''{"x":"abc\"def"}'''

then actual x value at runtime would be

{"x":"abc"def"}

that is incorrect json

so, x should be defined as

def x = '''{"x":"abc\\"def"}'''

to have runtime value

{"x":"abc\"def"}


问:
Bumblebee Android studio Plugin [id: 'com.android.application', version: '7.1.0', apply: false] was not found in any of the following sources:
I updated my android studio from Android studio fox to Android studio Bumblebee 2021.1.1
but none of my projects can run in Android studio Bumblebee 2021.1.1. I ended up getting this beautiful error.

Here is my gradle file

```<code>plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

答:
Add the buildscript in your build.gradle (project module)</p>
```<code>  buildscript {

    repositories {
        google()
        mavenCentral()
    }
    dependencies {

        classpath 'your dependecy path'

    }
}

plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.5.30' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

Body:
I updated my android studio from Android studio fox to Android studio Bumblebee 2021.1.1
but none of my projects can run in Android studio Bumblebee 2021.1.1. I ended up getting this beautiful error.

Here is my gradle file

plugins {
    id 'com.android.application' version '7.1.0' apply false
    id 'com.android.library' version '7.1.0' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

Body:
Add the buildscript in your build.gradle (project module)

  buildscript {

    repositories {
        google()
        mavenCentral()
    }
    dependencies {

        classpath 'your dependecy path'

    }
}

plugins {
    id 'com.android.application' version '7.1.1' apply false
    id 'com.android.library' version '7.1.1' apply false
    id 'org.jetbrains.kotlin.android' version '1.5.30' apply false
}

task clean(type: Delete) {
    delete rootProject.buildDir
}


问:
Pandas dataframe groupby text value that occurs in two columns
My dataframe looks like this:

     v1           v2        distance
0   be          belong      0.666667
4   increase    decrease    0.666667
9   analyze     assay       0.666667
11  bespeak     circulate   0.769231
21  induce      generate    0.800000
24  decrease    delay       0.750000
26  cause       trip        0.666667
27  isolate     distinguish 0.750000
28  give        infect      0.666667
29  result      prove       0.800000
31  describe    explain     0.714286
33  report      circulate   0.666667
36  affect      expose      0.666667
40  explain     intercede   0.705882
41  suppress    restrict    0.833333
```

With v1 and v2 being verbs and distance is their similarity. I want to create clusters of similar words, based on their appearance in the dataframe.

For example, the word circulate appears be similar with both bespeak and report. So I would like to have a cluster of these 3 words. Groupby doesn't help since they are string values. Can someone help?

答:
This seems like a graph problem.

You could try to use networkx:

```<code>import networkx as nx

G = nx.from_pandas_edgelist(df, 'v1', 'v2')

clusters = nx.connected_components(G)
</code>```

output:

```<code>[{'be', 'belong'}, {'delay', 'increase', 'decrease'}, {'analyze', 'assay'},
 {'report', 'bespeak', 'circulate'}, {'induce', 'generate'}, {'trip', 'cause'},
 {'distinguish', 'isolate'}, {'infect', 'give'}, {'prove', 'result'},
 {'intercede', 'describe', 'explain'}, {'affect', 'expose'}, {'restrict', 'suppress'}]
</code>```

As graph:

Small function to plot the graph in jupyter:

```<code>def nxplot(G):
    from networkx.drawing.nx_agraph import to_agraph
    A = to_agraph(G)
    A.layout('dot')
    A.draw('/tmp/graph.png')
    from IPython.display import Image
    return Image(filename='/tmp/graph.png')
</code>```

Body:
My dataframe looks like this:

     v1           v2        distance
0   be          belong      0.666667
4   increase    decrease    0.666667
9   analyze     assay       0.666667
11  bespeak     circulate   0.769231
21  induce      generate    0.800000
24  decrease    delay       0.750000
26  cause       trip        0.666667
27  isolate     distinguish 0.750000
28  give        infect      0.666667
29  result      prove       0.800000
31  describe    explain     0.714286
33  report      circulate   0.666667
36  affect      expose      0.666667
40  explain     intercede   0.705882
41  suppress    restrict    0.833333

With v1 and v2 being verbs and distance is their similarity. I want to create clusters of similar words, based on their appearance in the dataframe.

For example, the word circulate appears be similar with both bespeak and report. So I would like to have a cluster of these 3 words. Groupby doesn't help since they are string values. Can someone help?

Body:
This seems like a graph problem.

You could try to use networkx:

import networkx as nx

G = nx.from_pandas_edgelist(df, 'v1', 'v2')

clusters = nx.connected_components(G)

output:

[{'be', 'belong'}, {'delay', 'increase', 'decrease'}, {'analyze', 'assay'},
 {'report', 'bespeak', 'circulate'}, {'induce', 'generate'}, {'trip', 'cause'},
 {'distinguish', 'isolate'}, {'infect', 'give'}, {'prove', 'result'},
 {'intercede', 'describe', 'explain'}, {'affect', 'expose'}, {'restrict', 'suppress'}]

As graph:

Small function to plot the graph in jupyter:

def nxplot(G):
    from networkx.drawing.nx_agraph import to_agraph
    A = to_agraph(G)
    A.layout('dot')
    A.draw('/tmp/graph.png')
    from IPython.display import Image
    return Image(filename='/tmp/graph.png')


问:
How to merge two datatables on a common column in c# and fill 0's in the second table where they don't match?
I am pretty new to c#, I have two datatables A and B which I would like to join / merge on a common column.

A:

```<code>id    | colA
1     | 30
------|------
2     | 20
------|------
3     | 10
</code>```

B:

```<code>id    | colB
1     | 30
------|------
2     | 20
</code>```

I would like to join / merge table B on A and get the result:

result:

```<code>id    | colA |colB
1     | 30   | 10
------|------|------
2     | 20   | 20
------|------|------
3     | 10   | 0   <-- fill 0's
</code>```

Can someone please provide a reference to a previously similar question or a simple explanation?
Thank you!

答:
Try following :</p>
```<code>           DataTable dtA = new DataTable("A");

            dtA.Columns.Add("id", typeof(int));
            dtA.Columns.Add("colA", typeof(int));

            dtA.Rows.Add(new object[] { 1,30 });
            dtA.Rows.Add(new object[] { 2,20 });
            dtA.Rows.Add(new object[] { 3,10 });

            DataTable dtB = new DataTable("B");

            dtB.Columns.Add("id", typeof(int));
            dtB.Columns.Add("colB", typeof(int));

            dtB.Rows.Add(new object[] { 1, 30 });
            dtB.Rows.Add(new object[] { 2, 20 });

            DataTable dtC = new DataTable("C");
            dtC = dtA.Copy();

            dtC.Columns.Add("colB");
            dtC.Columns["colB"].DefaultValue = 0;

            foreach (DataRow row in dtC.AsEnumerable())
            {
                row["colB"] = dtB.AsEnumerable().Where(x => x.Field<int>("id") == row.Field<int>("id")).Sum(x => x.Field<int>("colB"));
            }
</code>```

Body:
I am pretty new to c#, I have two datatables A and B which I would like to join / merge on a common column.

A:

id    | colA
1     | 30
------|------
2     | 20
------|------
3     | 10

B:

id    | colB
1     | 30
------|------
2     | 20

I would like to join / merge table B on A and get the result:

result:

id    | colA |colB
1     | 30   | 10
------|------|------
2     | 20   | 20
------|------|------
3     | 10   | 0   <-- fill 0's

Can someone please provide a reference to a previously similar question or a simple explanation?
Thank you!

Body:
Try following :

           DataTable dtA = new DataTable("A");

            dtA.Columns.Add("id", typeof(int));
            dtA.Columns.Add("colA", typeof(int));

            dtA.Rows.Add(new object[] { 1,30 });
            dtA.Rows.Add(new object[] { 2,20 });
            dtA.Rows.Add(new object[] { 3,10 });

            DataTable dtB = new DataTable("B");

            dtB.Columns.Add("id", typeof(int));
            dtB.Columns.Add("colB", typeof(int));

            dtB.Rows.Add(new object[] { 1, 30 });
            dtB.Rows.Add(new object[] { 2, 20 });

            DataTable dtC = new DataTable("C");
            dtC = dtA.Copy();

            dtC.Columns.Add("colB");
            dtC.Columns["colB"].DefaultValue = 0;

            foreach (DataRow row in dtC.AsEnumerable())
            {
                row["colB"] = dtB.AsEnumerable().Where(x => x.Field<int>("id") == row.Field<int>("id")).Sum(x => x.Field<int>("colB"));
            }


问:
How to understand memory reference in assembly using ghidra
When analyzing the assembly listing in Ghidra, the following instructions are not clear to me:

```<code>MOV    ECX,dword ptr [R13 + 8192]
LEA    RDX,[R13 + RSI*0x1 + 8196]
</code>```

In the MOV, I assume that the register ECX will get the value pointed to the register R13 + 8129 positions (or 2048 bytes). Is this assumption current?

In the LEA, the pointer of the R13 + value of RSI + 8196 position (2049 byte) is assigned to RDX. Is it correct?

Otherwise, how should I interpret those instructions?

答:
The numbers are called "displacement", they are added to the values left of them.

mov ecx, dword ptr [r13 + 8192] adds the value of r13 and 8192, and copies the 32 bit value at the resulting address into ecx.

lea rdx, [r13 + rsi*0x1 + 8196] adds the value of r13, the result of the multiplication of the value of rsi by 1 (giving the value of rsi), and 8196, and loads the sum into rdx.

These displacements are offsets for the addressable memory units, here bytes. A displacement of 8192 means the byte address 8192 bytes away from the base address.

Body:
When analyzing the assembly listing in Ghidra, the following instructions are not clear to me:

MOV    ECX,dword ptr [R13 + 8192]
LEA    RDX,[R13 + RSI*0x1 + 8196]

In the MOV, I assume that the register ECX will get the value pointed to the register R13 + 8129 positions (or 2048 bytes). Is this assumption current?

In the LEA, the pointer of the R13 + value of RSI + 8196 position (2049 byte) is assigned to RDX. Is it correct?

Otherwise, how should I interpret those instructions?


问:
Authorisation error in snowflake while connecting using python
```<code>import snowflake.connector
#create connection
conn=snowflake.connector.connect( user='', url = '',
 password='',account='',warehouse='',database='',schema='')
#create cursor
CS = conn.cursor()
conn.cursor().execute("USE ROLE ")
#conn.cursor().execute("USE SCHEMA ")
CS.execute("alter external table demo_data refresh")
</code>```

I am getting error like SQL compilation error: External table 'A_PQSN_342_JUI_01.DBA.DEMO_DATA' does not exist or not authorized. Can you please help in this issue

答:
Only the external table owner (i.e. the role with the OWNERSHIP privilege on the external table) or higher can execute this command: https://docs.snowflake.com/en/sql-reference/sql/alter-external-table.html#usage-notes

So most probably your role has insufficient privileges to alter the table.

Or the table is really not existing :-)

Body:
import snowflake.connector
#create connection
conn=snowflake.connector.connect( user='', url = '',
 password='',account='',warehouse='',database='',schema='')
#create cursor
CS = conn.cursor()
conn.cursor().execute("USE ROLE ")
#conn.cursor().execute("USE SCHEMA ")
CS.execute("alter external table demo_data refresh")

I am getting error like SQL compilation error: External table 'A_PQSN_342_JUI_01.DBA.DEMO_DATA' does not exist or not authorized. Can you please help in this issue


问:
Join between two tables with two rows
I have two tables:

Table A:

Name
Value

ABC
95

XYZ
85

Table B:

Category
Value

MaxVal
90

MinVal
80

I want to achieve this result 85 is between 80 and 90 value, so we filter out only XYZ and not ABC :

Result

XYZ

I'm trying as below:

```<code>SELECT Name as Result from TableA a, TableB b, TableB c
where a.value < b.value and a.value > c.value
and b.value=c.value and 1=1;
</code>```

Is there a better way to do this?

答:
Get rid of b.value=c.value, which is filtering out all records and select proper categories from tables b and c:

```<code>SELECT Name as Result from TableA a, TableB b, TableB c
where a.value < b.value and b.category = 'MaxVal'
and a.value > c.value and c.category = 'MinVal';
</code>```

Here's another option, in my opinion more readable:

```<code>SELECT Name as Result FROM TableA
 WHERE a.value > (SELECT value FROM TableB WHERE category = 'MinVal')
   AND a.value < (SELECT value FROM TableB WHERE category = 'MaxVal');
</code>```

Title: Join between two tables with two rows

Body:
I have two tables:

Table A:

Name
Value

ABC
95

XYZ
85

Table B:

Category
Value

MaxVal
90

MinVal
80

I want to achieve this result 85 is between 80 and 90 value, so we filter out only XYZ and not ABC :

Result

XYZ

I'm trying as below:

SELECT Name as Result from TableA a, TableB b, TableB c
where a.value  c.value
and b.value=c.value and 1=1;

Is there a better way to do this?

Body:
Get rid of b.value=c.value, which is filtering out all records and select proper categories from tables b and c:

SELECT Name as Result from TableA a, TableB b, TableB c
where a.value < b.value and b.category = 'MaxVal'
and a.value > c.value and c.category = 'MinVal';

Here's another option, in my opinion more readable:

SELECT Name as Result FROM TableA
 WHERE a.value > (SELECT value FROM TableB WHERE category = 'MinVal')
   AND a.value < (SELECT value FROM TableB WHERE category = 'MaxVal');


问:
ControlToValidate: how to debug?
I'm getting some error: ControlToValidate of '' cannot be empty (ControlToValidate de '' ne peut pas être vide in french).

Most of the time, this error occurs after the add of new controls in the page/user control, and it's not too difficult to figure out with control is lacking ValidationGroup.

But what can you do to find out the cause of this error when it's a legacy screen with tons of controls, with ajax and telerik components? I'm mainly looking for tips / best practices to debug such issues.

Thanks in advance.

答:
This error occurs if you have a validator control on your page without filling in the control to validate property. It has nothing to do with validationgroups as far as I know.

To answer your question, I would say a regular expression will be the 'easiest' way to do so.

Title: ControlToValidate: how to debug?


问:
How to get the values of dictionary python?
I have the below python dictionary stored as dictPython

```<code>{
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",

        },
    ],
}
</code>```

I need to get the values of vanityName, localizedName and also the values from name->localized and name->preferredLocale.

I tried dictPython.keys() and it returned dict_keys(['paging', 'elements']).

Also I tried dictPython.values() and it returned me what is inside of the parenthesis({}).

I need to get [vv, ViV, ViV, US, en]

答:
So something like this?</p>
```<code>[[x['organizationalTarget~']['vanityName'],
  x['organizationalTarget~']['localizedName'],
  x['organizationalTarget~']['name']['localized']['en_US'],
  x['organizationalTarget~']['name']['preferredLocale']['country'],
  x['organizationalTarget~']['name']['preferredLocale']['language'],
 ] for x in s['elements']]
</code>```

Body:
I have the below python dictionary stored as dictPython

{
    "paging": {"count": 10, "start": 0, "links": []},
    "elements": [
        {
            "organizationalTarget~": {
                "vanityName": "vv",
                "localizedName": "ViV",
                "name": {
                    "localized": {"en_US": "ViV"},
                    "preferredLocale": {"country": "US", "language": "en"},
                },
                "primaryOrganizationType": "NONE",
                "locations": [],
                "id": 109,
            },
            "role": "ADMINISTRATOR",

        },
    ],
}

I need to get the values of vanityName, localizedName and also the values from name->localized and name->preferredLocale.

I tried dictPython.keys() and it returned dict_keys(['paging', 'elements']).

Also I tried dictPython.values() and it returned me what is inside of the parenthesis({}).

I need to get [vv, ViV, ViV, US, en]

Body:
So something like this?

[[x['organizationalTarget~']['vanityName'],
  x['organizationalTarget~']['localizedName'],
  x['organizationalTarget~']['name']['localized']['en_US'],
  x['organizationalTarget~']['name']['preferredLocale']['country'],
  x['organizationalTarget~']['name']['preferredLocale']['language'],
 ] for x in s['elements']]


问:
IHostBuilder configuration cannot load xml files
I have a co-worker who have a problem with posting here, he will be the one answering comments and validating answer. Here is his question:

I'm using Net5 with Microsoft.Extensions.Hosting. Instead of appsettings.json, I need to use xml files. I have App.config to specify common app settings (log4net config, etc.) and AcquisitionManagerConfiguration.xml for the settings on each installation (hardware stuff).

I went like this :
Program.cs

```<code>public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            IHostBuilder ihb = Host.CreateDefaultBuilder(args);
            ihb.ConfigureAppConfiguration((hostingContext, configuration) =>
            {

                //configuration.Sources.Clear();
                configuration.SetBasePath(AppContext.BaseDirectory);
                configuration.AddXmlFile("AcquisitionManagerConfiguration.xml", optional: false, reloadOnChange: true)
                   .AddXmlFile("App.config", optional: false, reloadOnChange: true);

                configuration.AddEnvironmentVariables();

            }).ConfigureServices((hostingContext, services) =>
            {

                services.AddHttpClient();
                services.Configure<AcquisitionManagerConfiguration>(hostingContext.Configuration.GetSection("AcquisitionManagerConfiguration"));
                services.AddTransient<AcquisitionManager.AcquisitionManager>();
                services.AddTransient<IServiceClient, ServiceClient>();
                services.AddHostedService<Worker>();
            });
            return ihb;
        }
    }
</code>```

AcquisitionManager.cs

```<code>public AcquisitionManager(IServiceClient serviceClient, IOptions<AcquisitionManagerConfiguration> config)
{
client = serviceClient;
configuration = config.Value;
}
</code>```

and the first xml

```<code>    <?xml version="1.0" encoding="utf-8" ?>
    <AcquisitionManagerConfiguration>
        <val>1</val>
    </AcquisitionManagerConfiguration>
</code>```

AcquisitionManagerConfiguration.cs matches exactly the xml, it worked fine if I manually deserialize.

But using the hosting system, I never have anything in config.Value.

Any idea what I'm doing wrong ?
I didn't find the solution so I posted here.
Thanks for the help.

答:
The problem come from the xml structure:

As this is application configuration the structure from this:

    <?xml version="1.0" encoding="utf-8" ?>
    <AcquisitionManagerConfiguration>
        <val>1</val>
    </AcquisitionManagerConfiguration>
```
<p>become this:</p>
<pre class="lang-xml prettyprint-override"><code>    <?xml version="1.0" encoding="utf-8" ?>
    <Configuration>
        <AcquisitionManagerConfiguration>
            <val>1</val>
        </AcquisitionManagerConfiguration>
    </Configuration>
</code>```

Body:
I have a co-worker who have a problem with posting here, he will be the one answering comments and validating answer. Here is his question:

I'm using Net5 with Microsoft.Extensions.Hosting. Instead of appsettings.json, I need to use xml files. I have App.config to specify common app settings (log4net config, etc.) and AcquisitionManagerConfiguration.xml for the settings on each installation (hardware stuff).

I went like this :
Program.cs

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args)
        {
            IHostBuilder ihb = Host.CreateDefaultBuilder(args);
            ihb.ConfigureAppConfiguration((hostingContext, configuration) =>
            {

                //configuration.Sources.Clear();
                configuration.SetBasePath(AppContext.BaseDirectory);
                configuration.AddXmlFile("AcquisitionManagerConfiguration.xml", optional: false, reloadOnChange: true)
                   .AddXmlFile("App.config", optional: false, reloadOnChange: true);

                configuration.AddEnvironmentVariables();

            }).ConfigureServices((hostingContext, services) =>
            {

                services.AddHttpClient();
                services.Configure<AcquisitionManagerConfiguration>(hostingContext.Configuration.GetSection("AcquisitionManagerConfiguration"));
                services.AddTransient<AcquisitionManager.AcquisitionManager>();
                services.AddTransient<IServiceClient, ServiceClient>();
                services.AddHostedService<Worker>();
            });
            return ihb;
        }
    }

AcquisitionManager.cs

public AcquisitionManager(IServiceClient serviceClient, IOptions<AcquisitionManagerConfiguration> config)
{
client = serviceClient;
configuration = config.Value;
}

and the first xml

    <?xml version="1.0" encoding="utf-8" ?>
    <AcquisitionManagerConfiguration>
        <val>1</val>
    </AcquisitionManagerConfiguration>

AcquisitionManagerConfiguration.cs matches exactly the xml, it worked fine if I manually deserialize.

But using the hosting system, I never have anything in config.Value.

Any idea what I'm doing wrong ?
I didn't find the solution so I posted here.
Thanks for the help.

Body:
The problem come from the xml structure:

As this is application configuration the structure from this:

    <?xml version="1.0" encoding="utf-8" ?>
    <AcquisitionManagerConfiguration>
        <val>1</val>
    </AcquisitionManagerConfiguration>

become this:

    <?xml version="1.0" encoding="utf-8" ?>
    <Configuration>
        <AcquisitionManagerConfiguration>
            <val>1</val>
        </AcquisitionManagerConfiguration>
    </Configuration>


问:
Invalid Syntax on variables in python
May I know why there be a invalid syntax on my f variable on the first elif loop?</p>
```<code>def bsd():
if price_of_properties <= 180000:
    price = 180000*0.1
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))
elif price_of_properties > 180000 <= 360000:
    price = (((180000*0.1) + (price_of_properties - 180000 + (180000* 0.2)))
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))
elif price_of_properties > 360000 <= 100000:
    price = (((180000*0.1) + (180000*0.2) +(price_of_properties - 180000 + (640000* 0.3)))
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))
</code>```

答:
Your second and third assignments to  the price variable have unbalaned parentheses ((more opens than closes).

This will cause an error on the following lines though I think Python 3.11 may fix that, reporting errors more accurately. You can probably fix this by adding a closing parenthesis on each of those two lines. Or removing the first. But check the formulae after you do so, in case you make the wrong choice.

And, yes, the extra opening parenthesis in that first paragraph was intended :-)

Title: Invalid Syntax on variables in python

Body:
May I know why there be a invalid syntax on my f variable on the first elif loop?

def bsd():
if price_of_properties <= 180000:
    price = 180000*0.1
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))
elif price_of_properties > 180000 <= 360000:
    price = (((180000*0.1) + (price_of_properties - 180000 + (180000* 0.2)))
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))
elif price_of_properties > 360000 <= 100000:
    price = (((180000*0.1) + (180000*0.2) +(price_of_properties - 180000 + (640000* 0.3)))
    f = '{0:.2f}'.format(price)
    print("BSD is $" + str(f))


问:
Download a single folder or directory from a GitHub repo
How can I download only a specific folder or directory from a remote Git repo hosted on GitHub?

Say the example GitHub repo lives here:

```<code>git@github.com:foobar/Test.git
</code>```

Its directory structure:

```<code>Test/
├── foo/
│   ├── a.py
│   └── b.py
└── bar/
    ├── c.py
    └── d.py
</code>```

I want to download only the foo folder and not clone the whole Test project.

答:
You can do a simple download of the directory tree:

```<code>git archive --remote git@github.com:foobar/Test.git HEAD:foo | tar xf -
</code>```

But if you mean to check it out, and be able to do commits and push them back, no you can't do that.

Body:
How can I download only a specific folder or directory from a remote Git repo hosted on GitHub?

Say the example GitHub repo lives here:

git@github.com:foobar/Test.git

Its directory structure:

Test/
├── foo/
│   ├── a.py
│   └── b.py
└── bar/
    ├── c.py
    └── d.py

I want to download only the foo folder and not clone the whole Test project.

Body:
You can do a simple download of the directory tree:

git archive --remote git@github.com:foobar/Test.git HEAD:foo | tar xf -

But if you mean to check it out, and be able to do commits and push them back, no you can't do that.


问:
Program gets frozen because of a loop
I'm making a program which calculates the date by giving the program a date and number of days to add to that date in input. In order to do this, I need to make a switch and make it repeat with a loop, but for some reasons, the program gets frozen and doesn't do anything after the user inserts the number of days to add. I've tried removing loop and the program works.
Looking forward to someone who might help me fix this.

Here's the part of the code from getting number of days to add to the end of loop:

```<code>    cin>>addDays;

    while (addDays > 0) {
        switch (month) {

            //months with 31 days
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            {
                finalDay = day + addDays;
                if (finalDay > 31) {
                    addDays = finalDay - 31;
                    month++;
                    day = 1;
                }
                break;
            }

            //months with 30 days
            case 4:
            case 6:
            case 9:
            case 11:
            {
                finalDay = day + addDays;
                if (finalDay > 30) {
                    addDays = finalDay - 30;
                    month++;
                    day = 1;
                }
                break;
            }

            //december
            case 12:
            {
                finalDay = day + addDays; //oggi è 10. Voglio aggiungere 30
                if (finalDay > 31) {       //40 è maggiore di 31
                    addDays = finalDay - 31;    //l'aggiunta 30 diventa 40 - 31 che fa 9
                    year++;
                    day = 1;
                    month = 1;
                }
                break;
            }

            //february
            case 2:
            {
                finalDay = day + addDays;
                if (year % 4 == 0) {
                    if (finalDay > 29) {
                        addDays = finalDay - 29;
                        month++;
                        day = 1;
                    }
                }
                else {
                    if (finalDay > 28) {
                        addDays = finalDay - 28;
                        month++;
                        day = 1;
                    }
                }
                break;
            }
        }
    }
</code>```

答:
Thank you very much for your help! You made me understand where the mistake was. I've fixed it and it now works perfectly. But because I'm not as experienced as you and I was having difficulties to read that code, instead of doing as you did, I've added an else to every if inside the switch, which resets addDays to 0, because assignment statements copy their value, they don't move it, for some reasons I wasn't thinking about this stupid and basic thing.

And also thanks for letting me notice about the uncomplete leap year algorithm.
Here's the fixed code. Have a good day!

```<code>cin>>addDays;

        while (addDays > 0) {
            switch (month) {

                //months with 31 days
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                {
                    finalDay = day + addDays;
                    if (finalDay > 31) {
                        addDays = finalDay - 31;
                        month++;
                        day = 0;
                    }
                    else {
                        addDays = 0;
                    }
                    break;
                }

                //months with 30 days
                case 4:
                case 6:
                case 9:
                case 11:
                {
                    finalDay = day + addDays;
                    if (finalDay > 30) {
                        addDays = finalDay - 30;
                        month++;
                        day = 0;
                    }
                    else {
                        addDays = 0;
                    }
                    break;
                }

                //december
                case 12:
                {
                    finalDay = day + addDays; //oggi è 10. Voglio aggiungere 30
                    if (finalDay > 31) {       //40 è maggiore di 31
                        addDays = finalDay - 31;    //l'aggiunta 30 diventa 40 - 31 che fa 9
                        year++;
                        day = 0;
                        month = 1;
                    }
                    else {
                        addDays = 0;
                    }
                    break;
                }

                //february
                case 2:
                {
                    finalDay = day + addDays;
                    if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
                        if (finalDay > 29) {
                            addDays = finalDay - 29;
                            month++;
                            day = 0;
                        }
                        else {
                            addDays = 0;
                        }

                    }
                    else {
                        if (finalDay > 28) {
                            addDays = finalDay - 28;
                            month++;
                            day = 0;
                        }
                        else {
                            addDays = 0;
                        }
                    }
                    break;
                }
            }
        }
</code>```

Title: Program gets frozen because of a loop

Body:
I'm making a program which calculates the date by giving the program a date and number of days to add to that date in input. In order to do this, I need to make a switch and make it repeat with a loop, but for some reasons, the program gets frozen and doesn't do anything after the user inserts the number of days to add. I've tried removing loop and the program works.
Looking forward to someone who might help me fix this.

Here's the part of the code from getting number of days to add to the end of loop:

    cin>>addDays;

    while (addDays > 0) {
        switch (month) {

            //months with 31 days
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            {
                finalDay = day + addDays;
                if (finalDay > 31) {
                    addDays = finalDay - 31;
                    month++;
                    day = 1;
                }
                break;
            }

            //months with 30 days
            case 4:
            case 6:
            case 9:
            case 11:
            {
                finalDay = day + addDays;
                if (finalDay > 30) {
                    addDays = finalDay - 30;
                    month++;
                    day = 1;
                }
                break;
            }

            //december
            case 12:
            {
                finalDay = day + addDays; //oggi è 10. Voglio aggiungere 30
                if (finalDay > 31) {       //40 è maggiore di 31
                    addDays = finalDay - 31;    //l'aggiunta 30 diventa 40 - 31 che fa 9
                    year++;
                    day = 1;
                    month = 1;
                }
                break;
            }

            //february
            case 2:
            {
                finalDay = day + addDays;
                if (year % 4 == 0) {
                    if (finalDay > 29) {
                        addDays = finalDay - 29;
                        month++;
                        day = 1;
                    }
                }
                else {
                    if (finalDay > 28) {
                        addDays = finalDay - 28;
                        month++;
                        day = 1;
                    }
                }
                break;
            }
        }
    }

Body:
Thank you very much for your help! You made me understand where the mistake was. I've fixed it and it now works perfectly. But because I'm not as experienced as you and I was having difficulties to read that code, instead of doing as you did, I've added an else to every if inside the switch, which resets addDays to 0, because assignment statements copy their value, they don't move it, for some reasons I wasn't thinking about this stupid and basic thing.

And also thanks for letting me notice about the uncomplete leap year algorithm.
Here's the fixed code. Have a good day!

cin>>addDays;

        while (addDays > 0) {
            switch (month) {

                //months with 31 days
                case 1:
                case 3:
                case 5:
                case 7:
                case 8:
                case 10:
                {
                    finalDay = day + addDays;
                    if (finalDay > 31) {
                        addDays = finalDay - 31;
                        month++;
                        day = 0;
                    }
                    else {
                        addDays = 0;
                    }
                    break;
                }

                //months with 30 days
                case 4:
                case 6:
                case 9:
                case 11:
                {
                    finalDay = day + addDays;
                    if (finalDay > 30) {
                        addDays = finalDay - 30;
                        month++;
                        day = 0;
                    }
                    else {
                        addDays = 0;
                    }
                    break;
                }

                //december
                case 12:
                {
                    finalDay = day + addDays; //oggi è 10. Voglio aggiungere 30
                    if (finalDay > 31) {       //40 è maggiore di 31
                        addDays = finalDay - 31;    //l'aggiunta 30 diventa 40 - 31 che fa 9
                        year++;
                        day = 0;
                        month = 1;
                    }
                    else {
                        addDays = 0;
                    }
                    break;
                }

                //february
                case 2:
                {
                    finalDay = day + addDays;
                    if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
                        if (finalDay > 29) {
                            addDays = finalDay - 29;
                            month++;
                            day = 0;
                        }
                        else {
                            addDays = 0;
                        }

                    }
                    else {
                        if (finalDay > 28) {
                            addDays = finalDay - 28;
                            month++;
                            day = 0;
                        }
                        else {
                            addDays = 0;
                        }
                    }
                    break;
                }
            }
        }


问:
Github API: add group as repo colalborator
I want to add a group as a collaborator to my github repo

Docs page is missing this part. I can successfully add a person as a collaborator using this request

```<code>curl \
  -X PUT \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/repos/octocat/hello-world/collaborators/USERNAME \
  -d '{"permission":"permission"}'
</code>```

but when I want to add a group(created under same organization) – I can't

Is there a possibility to do that?

答:
The answer is to go from another end:

add repo to the team. Here are API references

https://docs.github.com/en/rest/reference/teams#add-or-update-team-repository-permissions

Body:
I want to add a group as a collaborator to my github repo

Docs page is missing this part. I can successfully add a person as a collaborator using this request

curl \
  -X PUT \
  -H "Accept: application/vnd.github.v3+json" \
  https://api.github.com/repos/octocat/hello-world/collaborators/USERNAME \
  -d '{"permission":"permission"}'

but when I want to add a group(created under same organization) – I can't

Is there a possibility to do that?


问:
How to convert a file to binary stream in Javascript?
I am developing a website by using Next.js and trying to upload a file to OneDrive by using Microsoft Graph REST API.

The document says the request body should be the binary stream of the file to be uploaded, but I don't know how to convert it to binary stream.

I am using HTML input element to save file data to file:

{name: '200311 Weekly Safety Meeting - Coronavirus (2019-nCoV).pdf', lastModified: 1644421523745, lastModifiedDate: Wed Feb 09 2022 07:45:23 GMT-0800 (Pacific Standard Time), webkitRelativePath: '', size: 700913, …}

My code on the client side,

```<code>const uploadFile = async () => {
    const res = await axios.put('/api/onedrive/file', {
        accessToken: token,
        filename: file.name,
        content: file,
        parentId: '01XA3PFKG7YWH2K7QVIZCYRP33XLQEHLZG',
    });
    console.log(res.data);
};
</code>```

On the server side,

```<code>const upload = async (req, res) => {
const { filename, accessToken, content, parentId } = req.body;
const url = `https://graph.microsoft.com/v1.0/users/69e5bc0d-ef63-4040-88cf-0ada867b7afa/drive/items/${parentId}:/${filename}:/content`;

try {
    const result = await axios({
        method: 'put',
        url: url,
        body: content,
        headers: {
            Authorization: `Bearer ${accessToken}`,
        },
    });
    res.status(200).send(result.data);
} catch (err) {
    console.log(err);
    res.status(500).send(err);
}};
</code>```

答:
Thanks for reaching out

Please try the below code for converting file into binary format, see if it works

Code:

```<code>function GetBinaryDataFromFile(strFileName)
{
 var fso = new ActiveXObject("ADODB.Stream");
    fso.Type = 1
    fso.Open
    fso.LoadFromFile strFileName
}
</code>```

Body:
I am developing a website by using Next.js and trying to upload a file to OneDrive by using Microsoft Graph REST API.

The document says the request body should be the binary stream of the file to be uploaded, but I don't know how to convert it to binary stream.

I am using HTML input element to save file data to file:

{name: '200311 Weekly Safety Meeting - Coronavirus (2019-nCoV).pdf', lastModified: 1644421523745, lastModifiedDate: Wed Feb 09 2022 07:45:23 GMT-0800 (Pacific Standard Time), webkitRelativePath: '', size: 700913, …}

My code on the client side,

const uploadFile = async () => {
    const res = await axios.put('/api/onedrive/file', {
        accessToken: token,
        filename: file.name,
        content: file,
        parentId: '01XA3PFKG7YWH2K7QVIZCYRP33XLQEHLZG',
    });
    console.log(res.data);
};

On the server side,

const upload = async (req, res) => {
const { filename, accessToken, content, parentId } = req.body;
const url = `https://graph.microsoft.com/v1.0/users/69e5bc0d-ef63-4040-88cf-0ada867b7afa/drive/items/${parentId}:/${filename}:/content`;

try {
    const result = await axios({
        method: 'put',
        url: url,
        body: content,
        headers: {
            Authorization: `Bearer ${accessToken}`,
        },
    });
    res.status(200).send(result.data);
} catch (err) {
    console.log(err);
    res.status(500).send(err);
}};

Body:
Thanks for reaching out

Please try the below code for converting file into binary format, see if it works

Code:

function GetBinaryDataFromFile(strFileName)
{
 var fso = new ActiveXObject("ADODB.Stream");
    fso.Type = 1
    fso.Open
    fso.LoadFromFile strFileName
}


问:
I am trying to increase performance of my code and switching from XMLHttpRequest to fetch requests using asynchronous code
I want to confirm if I am not slowing down the code below. My goal is to increase the performance of the application. I was considering a promise.all but not sure if it is necessary as I believe the code is written now, all the fetch requests are running simultaneously?

The test functions don't need to wait for each other. I don't want to create a funnel where each test function waits for the other one to finish or each fetch request is waiting for the previous one to finish. The goal is to have them all running together. Is my code doing that at the moment? Thank you for your assistance.

```<code>

function test1() {
   //some code here

   fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest1=> //work with the data here)
    .catch(error => {console.log('Request failed', error);});
}

function test2() {
   //some code here

   fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest2 => //work with the data here)
    .catch(error => {console.log('Request failed', error);});

   fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest3 => //work with the data here)
    .catch(error => {console.log('Request failed', error);});

    fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest4 => //work with the data here)
    .catch(error => {console.log('Request failed', error);});
}

//....and hundreds like the above test functions down here

const checkStatusandContentType = async response => {
    const isJson = response.headers.get('content-type')?.includes('application/json');
    const isHtml = response.headers.get('content-type')?.includes('text/html');
    const data =  isJson ? await response.json()
                : isHtml ? await response.text()
                : null;

    // check for error response
    if (!response.ok) {
        // get error message from body or default to response status
        const error = (data && data.message) || response.status;
        return Promise.reject(error);
    }
    return data;
}

const HtmlToObject =  data => {
    const stringified = data;
    const processCode = stringified.substring(stringified.lastIndexOf("<X1>") + 4, stringified.indexOf("</X1>"));
    //CONTENT EXTRACT
    data = JSON.parse(processCode);
    return data;
};
</code>```

答:
TL;DR  fetch and XmlHTTPRequest perform the same.

You said you want to increase your application's performance. It's usually wise to dream up a way of measuring the performance when you do that.

Your performance measurement may be for just one desktop user with an excellent connection to the network. Or, it may be for hundreds of mobile devices using your app at the same time.

Browser HTML / Javascript apps using XmlHTTPRequest (XHR for short) or fetch requests are often designed to display something useful to your user, and then use the received data to make that display even more useful.  If your measure of performance is how long it takes for a single user to see something useful, you may already have acceptable peformance.   But if you have hundreds of mobile users, performance is harder to define.

You asked about whether XHR or fetch has better performance. From the point of view of your server, they are the same: both generate requests that your server must satisfy. They both generate the same requests; your server can't tell them apart. fetch requests are easier to code, as you have discovered.

Your code runs many requests. You showed us three but you said you have many more. Browsers restrict the number of concurrent outbound requests, and others wait for an available slot. Here's information about concurrent requests in an answer. Most browsers allow six concurrent requests to any given domain, and ten overall.

So, your concurrent fetch operations (or concurrent XHR operations, it doesn't matter which) will hit your server with six connections at once. That's fine for low-volume applications with good bandwidth. But if your app scales up to many users or must work over limited (mobile) bandwidth, you should consider whether you will overload your users' networks or your server.

Reducing the number of requests coming from your browser app, and perhaps returning more complete information in each request, is a good way to manage this server and network load.

Body:
I want to confirm if I am not slowing down the code below. My goal is to increase the performance of the application. I was considering a promise.all but not sure if it is necessary as I believe the code is written now, all the fetch requests are running simultaneously?

The test functions don't need to wait for each other. I don't want to create a funnel where each test function waits for the other one to finish or each fetch request is waiting for the previous one to finish. The goal is to have them all running together. Is my code doing that at the moment? Thank you for your assistance.

function test1() {
   //some code here

   fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest1=> //work with the data here)
    .catch(error => {console.log('Request failed', error);});
}

function test2() {
   //some code here

   fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest2 => //work with the data here)
    .catch(error => {console.log('Request failed', error);});

   fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest3 => //work with the data here)
    .catch(error => {console.log('Request failed', error);});

    fetch(URL)
   .then(checkStatusandContentType)
   .then(HtmlToObject)
   .then(subTest4 => //work with the data here)
    .catch(error => {console.log('Request failed', error);});
}

//....and hundreds like the above test functions down here

const checkStatusandContentType = async response => {
    const isJson = response.headers.get('content-type')?.includes('application/json');
    const isHtml = response.headers.get('content-type')?.includes('text/html');
    const data =  isJson ? await response.json()
                : isHtml ? await response.text()
                : null;

    // check for error response
    if (!response.ok) {
        // get error message from body or default to response status
        const error = (data && data.message) || response.status;
        return Promise.reject(error);
    }
    return data;
}

const HtmlToObject =  data => {
    const stringified = data;
    const processCode = stringified.substring(stringified.lastIndexOf("<X1>") + 4, stringified.indexOf("</X1>"));
    //CONTENT EXTRACT
    data = JSON.parse(processCode);
    return data;
};


问:
Clustering Loop Python
I am clustering a data set in python using kmeans. Before I clustered the data set, I determined the optimal number of clusters using an elbow curve.

The optimal number of clusters was 5. So after kmeans clustered the dataset, I had 5 different clusters.

So here’s my question. Now that I have 5 different clusters, I would like to cluster those 5 clusters again so that I can get smaller clusters. Once I have smaller clusters for each one of those 5 clusters, I would like to cluster those smaller clusters again. I would like to repeat this until I have only about 20 points in each cluster. The dataset has 1,000,000 + observations.

What is the best way to do this? Is there a way to build a clustering loop? Is there a completely different better way to do this? I know this isn’t a specific coding question, but I’d love to hear some thoughts.

答:
I'm going to provide some pseudocode since you didn't provide any details about yout code (which you should, by the way):

```<code>def cluster_until_20(data):
    if data.size() == 20:
        return data
    clusters = kmeans(data, 5)
    if any size of cluster in clusters != 20:
        return [cluster_until_20(cluster) for cluster in clusters]
    return clusters
</code>```

The key is using recursion with a list comprehension, that will go "deeper" in recursion as long as the size of data is != 20

Title: Clustering Loop Python

Body:
I'm going to provide some pseudocode since you didn't provide any details about yout code (which you should, by the way):

def cluster_until_20(data):
    if data.size() == 20:
        return data
    clusters = kmeans(data, 5)
    if any size of cluster in clusters != 20:
        return [cluster_until_20(cluster) for cluster in clusters]
    return clusters

The key is using recursion with a list comprehension, that will go "deeper" in recursion as long as the size of data is != 20


问:
Join tables from two databases in C#
With SQL Server I run this query with no problem...

```<code>SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
  INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'
</code>```

I join two tables that reside in two different databases (mdb and mdb2).

But how can I do it in my .NET application?
When I need to use this statement

```<code>string cmdText = "SELECT SUM(Esi) AS Dispo
                  FROM [mdb].[dbo].[Query1] AS A
                    INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
                  WHERE Alias LIKE 'SETUP%'";

this.OP = new SqlConnection(ConfigurationManager.ConnectionStrings["mdb2"].ConnectionString);
SqlCommand sqlCommand = new SqlCommand(cmdText, this.OP);
</code>```

I can't execute it, since this.OP is the connection to mdb2... And for mdb?

How can I connect to both databases simultanously?

答:
The SQL connection is to the server - the Initial catalog in a connection string behaves like use - it sets the default DB.

So your 3 part SQL query should work as is. So possibly

Make sure that the SQL login used by your app (or the account of your AppPool if using Web and Integrated Security) has the necessary access to both databases. (use RunAs on SQL Enterprise Manager as this account and try to run the query)

You might try escaping [Alias]

Also, if there is coupling between mdb1 and mdb2 (e.g. SPROCS in mdb1 use tables in mdb2 etc), for ease of maintenance, you might consider adding views in mdb1 for mdb2 objects. This allows for easy identification of cross-database dependencies. In this case, your query can use views which look like they are in the same database, although the underlying dependency on mdb2 is still there.

Title: Join tables from two databases in C#

Body:
With SQL Server I run this query with no problem...

SELECT SUM(Esi) AS Dispo
FROM [mdb].[dbo].[Query1] AS A
  INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
WHERE Alias LIKE 'SETUP%'

I join two tables that reside in two different databases (mdb and mdb2).

But how can I do it in my .NET application?
When I need to use this statement

string cmdText = "SELECT SUM(Esi) AS Dispo
                  FROM [mdb].[dbo].[Query1] AS A
                    INNER JOIN [mdb2].[dbo].[TieCol] as B ON A.Alias=B.IDAlias
                  WHERE Alias LIKE 'SETUP%'";

this.OP = new SqlConnection(ConfigurationManager.ConnectionStrings["mdb2"].ConnectionString);
SqlCommand sqlCommand = new SqlCommand(cmdText, this.OP);

I can't execute it, since this.OP is the connection to mdb2... And for mdb?

How can I connect to both databases simultanously?


问:
Jelastic - Wordpress Multi Region Error 500 when server stop
I just setup a Multi Region Wordpress Cluster on Jelastic from the marketplace. I have two environnement on two different region. My domain is pointing to a load balancer who is configured to send everything to server 1 and switch to the server 2 when server 1 crash/stop.

Everything works fine except when I shutdown server 1. The site is working but I can't access the admin (Error 500: Internal Server Error) and I figured that the problem appear also when I go to server 2 without the load balancer.

So I'm wondering if this is suppose to work like that ? Like the server 2 is only here to let the visitor have no downtime but you can't write anything in the database.

(I already tried to reinstall a similar environnement and I get the same issue)

答: Yes, such behaviour is expectable. This is caused by configuration of HA distributed shared storage based on GlusterFS. The only server1(master cluster) is an entry point for the writes and distributes content to the server2. As you probably has noted the Mutli-region cluster is on Beta and we're working on its improvment. In near future we will issue an add-on which will do reassigning the master role from one cluster to any other - in your case to delegate master role from server1 to server2 with a single click.