问:
Given a list of filenames, group filenames with all derivatives based on similarity of the filename
I might not be searching the best terms to find a solution but so far nothing I've found has been able to solve my problem and I really don't know where to start or even what mechanisms to investigate.

I have a large list of image files in various locations on my hard drive and I'm trying to clean it up by removing the duplicates. Most of these are easy to find using hash codes but I have a lot of corrupted or edited versions which aren't so easy to find. I know I'll need some user interaction to identify and delete (archive) the unwanted files and I'll be doing some further processing to make sure metadata such as dates and geotagging are correct (also used to potentially match files) and then display similar images with all known data through a simple html interface.

One of the steps I've identified is grouping similarly named files or files which have part of another filename in its name. Sometimes these can be completely unrelated and so the user interaction will be required.

Below is a sample of files, what I would like is to group them into filenames which are similar, disregarding path and file extension.

```<code>[
"/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
"/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
"/Users/stu/Photos/2013/IMAG0097.jpg",
"/Users/stu/Photos/2014/IMAG0097.jpg",
"/Users/stu/Photos/2013/IMAG0126.jpg",
"/Users/stu/Photos/Holidays/IMAG0132.jpg",
"/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg",
"/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg",
"/Users/stu/Downloads/Photos/IMG_20140412_195105.png",
"/Users/stu/Photos/2014/IMG_20140412_195110.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png",
"/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg",
"/Users/stu/Photos/2013/IMAG0126-edited.jpg",
"/Users/stu/Photos/2013/IMAG0126546.jpg"
]
</code>```

The list of files above should output something like this:

```<code>{
    "IMG_20140413_072335": [
        "/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
        "/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg"
    ],
    "IMAG0097": [
        "/Users/stu/Photos/2013/IMAG0097.jpg",
        "/Users/stu/Photos/2014/IMAG0097.jpg"
    ],
    "IMAG0126": [
        "/Users/stu/Photos/2013/IMAG0126.jpg",
        "/Users/stu/Photos/2013/IMAG0126-edited.jpg",
        "/Users/stu/Photos/2013/IMAG0126546.jpg"
    ],
    "IMAG0132": [
        "/Users/stu/Photos/Holidays/IMAG0132.jpg"
    ],
    "IMG_20140322_142557": [
        "/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg"
    ],
    "IMG_20140330_200132": [
        "/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg"
    ],
    "IMG_20140412_195105": [
        "/Users/stu/Downloads/Photos/IMG_20140412_195105.png"
    ],
    "IMG_20140412_195110": [
        "/Users/stu/Photos/2014/IMG_20140412_195110.png"
    ],
    "IMG_20140413_143245": [
        "/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245.png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png"
    ]
}
</code>```

Any ideas how to do this in Python3?

Thanks

Edit: I just added a few more examples to the sample set of filenames.

答:
the following worked for me:

```<code>from pprint import pprint
d = dict()

for i in t:
    tmp = os.path.basename(i).split(".")[0] # if file with extension given return the name before "."
                                            # else return the base name, without changes

    k = tmp.split("(")[0]                   # the (..) is a typical windows signiture for simillar names
                                            # if so split and take the name before it

    d.setdefault(k,[])                      # the line reassures the uniquenes of the records
    if k in tmp:
        d[k].append(i)

# SENTINEL
if sum([len(i) for i in d.values()]) !=len(t):
    raise ValueError("The sanity check wasn't successful !")

pprint(d)
</code>```

RESULT:

```<code>{'IMAG0097': ['/Users/stu/Photos/2013/IMAG0097.jpg',
              '/Users/stu/Photos/2014/IMAG0097.jpg'],
 'IMAG0126': ['/Users/stu/Photos/2013/IMAG0126.jpg'],
 'IMAG0132': ['/Users/stu/Photos/Holidays/IMAG0132.jpg'],
 'IMG_20140322_142557-edited': ['/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg'],
 'IMG_20140330_200132': ['/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg'],
 'IMG_20140412_195105': ['/Users/stu/Downloads/Photos/IMG_20140412_195105.png'],
 'IMG_20140412_195110': ['/Users/stu/Photos/2014/IMG_20140412_195110.png'],
 'IMG_20140413_072335': ['/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335.jpg',
                         '/Users/stu/Documents/Backup/IMG_20140413_072335(4).png',
                         '/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg',
                         '/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg'],
 'IMG_20140413_143245': ['/Users/stu/Photos/2014/IMG_20140413_143245(6).png',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(7).png',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245.png',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg',
                         '/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg',
                         '/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png']}
</code>```

Body:
I might not be searching the best terms to find a solution but so far nothing I've found has been able to solve my problem and I really don't know where to start or even what mechanisms to investigate.

I have a large list of image files in various locations on my hard drive and I'm trying to clean it up by removing the duplicates. Most of these are easy to find using hash codes but I have a lot of corrupted or edited versions which aren't so easy to find. I know I'll need some user interaction to identify and delete (archive) the unwanted files and I'll be doing some further processing to make sure metadata such as dates and geotagging are correct (also used to potentially match files) and then display similar images with all known data through a simple html interface.

One of the steps I've identified is grouping similarly named files or files which have part of another filename in its name. Sometimes these can be completely unrelated and so the user interaction will be required.

Below is a sample of files, what I would like is to group them into filenames which are similar, disregarding path and file extension.

[
"/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
"/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
"/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
"/Users/stu/Photos/2013/IMAG0097.jpg",
"/Users/stu/Photos/2014/IMAG0097.jpg",
"/Users/stu/Photos/2013/IMAG0126.jpg",
"/Users/stu/Photos/Holidays/IMAG0132.jpg",
"/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg",
"/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg",
"/Users/stu/Downloads/Photos/IMG_20140412_195105.png",
"/Users/stu/Photos/2014/IMG_20140412_195110.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
"/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245.png",
"/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
"/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
"/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
"/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png",
"/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
"/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg",
"/Users/stu/Photos/2013/IMAG0126-edited.jpg",
"/Users/stu/Photos/2013/IMAG0126546.jpg"
]

The list of files above should output something like this:

{
    "IMG_20140413_072335": [
        "/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335.jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(4).png",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg",
        "/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg",
        "/Users/stu/Photos/2013/IMG_20140413_072335.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_01.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335_9352.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_072335-9237.jpg"
    ],
    "IMAG0097": [
        "/Users/stu/Photos/2013/IMAG0097.jpg",
        "/Users/stu/Photos/2014/IMAG0097.jpg"
    ],
    "IMAG0126": [
        "/Users/stu/Photos/2013/IMAG0126.jpg",
        "/Users/stu/Photos/2013/IMAG0126-edited.jpg",
        "/Users/stu/Photos/2013/IMAG0126546.jpg"
    ],
    "IMAG0132": [
        "/Users/stu/Photos/Holidays/IMAG0132.jpg"
    ],
    "IMG_20140322_142557": [
        "/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg"
    ],
    "IMG_20140330_200132": [
        "/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg"
    ],
    "IMG_20140412_195105": [
        "/Users/stu/Downloads/Photos/IMG_20140412_195105.png"
    ],
    "IMG_20140412_195110": [
        "/Users/stu/Photos/2014/IMG_20140412_195110.png"
    ],
    "IMG_20140413_143245": [
        "/Users/stu/Photos/2014/IMG_20140413_143245(6).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(7).png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245.png",
        "/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png",
        "/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg",
        "/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg",
        "/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png"
    ]
}

Any ideas how to do this in Python3?

Thanks

Edit: I just added a few more examples to the sample set of filenames.

Body:
the following worked for me:

from pprint import pprint
d = dict()

for i in t:
    tmp = os.path.basename(i).split(".")[0] # if file with extension given return the name before "."
                                            # else return the base name, without changes

    k = tmp.split("(")[0]                   # the (..) is a typical windows signiture for simillar names
                                            # if so split and take the name before it

    d.setdefault(k,[])                      # the line reassures the uniquenes of the records
    if k in tmp:
        d[k].append(i)

# SENTINEL
if sum([len(i) for i in d.values()]) !=len(t):
    raise ValueError("The sanity check wasn't successful !")

pprint(d)

RESULT:

{'IMAG0097': ['/Users/stu/Photos/2013/IMAG0097.jpg',
              '/Users/stu/Photos/2014/IMAG0097.jpg'],
 'IMAG0126': ['/Users/stu/Photos/2013/IMAG0126.jpg'],
 'IMAG0132': ['/Users/stu/Photos/Holidays/IMAG0132.jpg'],
 'IMG_20140322_142557-edited': ['/Users/stu/Photos/2014/IMG_20140322_142557-edited.jpg'],
 'IMG_20140330_200132': ['/Users/stu/Downloads/Photos/IMG_20140330_200132.jpg'],
 'IMG_20140412_195105': ['/Users/stu/Downloads/Photos/IMG_20140412_195105.png'],
 'IMG_20140412_195110': ['/Users/stu/Photos/2014/IMG_20140412_195110.png'],
 'IMG_20140413_072335': ['/Users/stu/Photos/2014/IMG_20140413_072335(2).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335(3).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335.jpg',
                         '/Users/stu/Documents/Backup/IMG_20140413_072335(4).png',
                         '/Users/stu/Documents/Backup/IMG_20140413_072335(5).jpg',
                         '/Users/stu/Documents/Backup/IMG_20140413_072335(6).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335(7).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_072335(1).jpg'],
 'IMG_20140413_143245': ['/Users/stu/Photos/2014/IMG_20140413_143245(6).png',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(7).png',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(1).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(2).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(11).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(10).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245.png',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(3).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(8).jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(4).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(5).jpg',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(9).png',
                         '/Users/stu/Downloads/Photos/IMG_20140413_143245(3)-edited.jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(8)-edited.jpg',
                         '/Users/stu/Photos/Holidays/IMG_20140413_143245(4)-edited.jpg',
                         '/Users/stu/Photos/Holidays/IMG_20140413_143245(5)-edited.jpg',
                         '/Users/stu/Photos/2014/IMG_20140413_143245(9)-edited.png']}


来源: stackexchange

问:
How to indicate to TypeScript that a property of an object extends object?
I am essentially trying to create a class that makes all properties of an object accessible through a get function on the object. These get operations should be chainable. An example of my desired behavior:

End Goal

```<code>const original = {
  property: {
    interiorProperty: 'value';
  }
};
const wrapped = new Wrapper(original);

console.log(wrapped.get('property'));
// {
//   interiorProperty: 'value';
// }

console.log(wrapped.get('property').get('interiorProperty'));
// 'value'
</code>```

My reasoning for doing this is for better property access in an Angular template.

However, some properties of the object (or properties of properties) will eventually be primitives. I thought I was accounting for this - however, TypeScript disagrees.

Current Code

```<code>class Wrapper<OriginalType extends object> {
  private originalObject: OriginalType;

  constructor(obj: OriginalType) {
    this.originalObject = obj;
  }

  public get<Key extends keyof OriginalType>(key: Key) {
    const value = this.originalObject[key];
    if (typeof value === 'object') {
      // Error: Argument of type 'OriginalType[Key]' is not assignable to parameter of type 'object'.
      return new Wrapper(value);
    }
    return value;
  }
}
</code>```

Full TypeScript error:

```<code>Argument of type 'OriginalType[Key]' is not assignable to parameter of type 'object'.
  Type 'OriginalType[keyof OriginalType]' is not assignable to type 'object'.
    Type 'OriginalType[string] | OriginalType[number] | OriginalType[symbol]' is not assignable to type 'object'.
      Type 'OriginalType[string]' is not assignable to type 'object'.ts(2345)
</code>```

I don't understand why the typeof check doesn't tell TypeScript that value extends object inside of the if block. I thought perhaps it had to do with the type Key not being narrowed, but when I got fancy with the typing there (key: OriginalType[Key] extends object ? Key : never) it still had no effect.

I'm sure there's a way to accomplish this and the problem is simply my expertise, but for the life of me I can't figure it out.

答:
You have a typo on the extend, object should be Object

```<code>class Wrapper<OriginalType extends Object> {
  private originalObject: OriginalType;

  constructor(obj: OriginalType) {
    this.originalObject = obj;
  }

  public get<Key extends keyof OriginalType>(key: Key) {
    const value = this.originalObject[key];
    if (typeof value === 'object') {
      return new Wrapper(value); // ok
    }
    return value;
  }
}
</code>```

Playground

ContentLicense: CC BY-SA 4.0

Body:
I am essentially trying to create a class that makes all properties of an object accessible through a get function on the object. These get operations should be chainable. An example of my desired behavior:

End Goal

const original = {
  property: {
    interiorProperty: 'value';
  }
};
const wrapped = new Wrapper(original);

console.log(wrapped.get('property'));
// {
//   interiorProperty: 'value';
// }

console.log(wrapped.get('property').get('interiorProperty'));
// 'value'

My reasoning for doing this is for better property access in an Angular template.

However, some properties of the object (or properties of properties) will eventually be primitives. I thought I was accounting for this - however, TypeScript disagrees.

Current Code

class Wrapper<OriginalType extends object> {
  private originalObject: OriginalType;

  constructor(obj: OriginalType) {
    this.originalObject = obj;
  }

  public get<Key extends keyof OriginalType>(key: Key) {
    const value = this.originalObject[key];
    if (typeof value === 'object') {
      // Error: Argument of type 'OriginalType[Key]' is not assignable to parameter of type 'object'.
      return new Wrapper(value);
    }
    return value;
  }
}

Full TypeScript error:

Argument of type 'OriginalType[Key]' is not assignable to parameter of type 'object'.
  Type 'OriginalType[keyof OriginalType]' is not assignable to type 'object'.
    Type 'OriginalType[string] | OriginalType[number] | OriginalType[symbol]' is not assignable to type 'object'.
      Type 'OriginalType[string]' is not assignable to type 'object'.ts(2345)

I don't understand why the typeof check doesn't tell TypeScript that value extends object inside of the if block. I thought perhaps it had to do with the type Key not being narrowed, but when I got fancy with the typing there (key: OriginalType[Key] extends object ? Key : never) it still had no effect.

I'm sure there's a way to accomplish this and the problem is simply my expertise, but for the life of me I can't figure it out.

Body:
You have a typo on the extend, object should be Object

class Wrapper<OriginalType extends Object> {
  private originalObject: OriginalType;

  constructor(obj: OriginalType) {
    this.originalObject = obj;
  }

  public get<Key extends keyof OriginalType>(key: Key) {
    const value = this.originalObject[key];
    if (typeof value === 'object') {
      return new Wrapper(value); // ok
    }
    return value;
  }
}

Playground


问:
Which model/technique to use for specific sentence extraction?
I have a dataset of tens of thousands of dialogues / conversations between a customer and customer support. These dialogues, which could be forum posts, or long-winded email conversations, have been hand-annotated to highlight the sentence containing the customers problem. For example:

Dear agent, I am writing to you because I have a very annoying problem with my washing machine. I bought it three weeks ago and was very happy with it. However, this morning the door does not lock properly. Please help

Dear customer.... etc

The highlighted sentence would be:

However, this morning the door does not lock properly.

What approaches can I take to model this, so that in future I can automatically extract the customers problem? The domain of the datasets are broad, but within the hardware space, so it could be appliances, gadgets, machinery etc.

What is this type of problem called?
I thought this might be called "intent recognition", but most guides seem to refer to multiclass classification. The sentence either is or isn't the customers problem. I considered analysing each sentence and performing binary classification, but I'd like to explore options that take into account the context of the rest of the conversation if possible.

What resources are available to research how to implement this in Python (using tensorflow or pytorch)

I found a model on HuggingFace which has been pre-trained with customer dialogues, and have read the research paper, so I was considering fine-tuning this as a starting point, but I only have experience with text (multiclass/multilabel) classification when it comes to transformers.

答:
If you want to get a specific sentence (without any modification) from the original input text, that is often referred to as  'span classification'  where the output is the index of the first and last word of the specific sentence.
The state-of-the-art now is the attention models like BERT
.You can check the Bert models that are designed for the 'span classification' problem in huggingface as RobertaForQuestionAnswering https://huggingface.co/docs/transformers/model_doc/roberta#transformers.TFRobertaForQuestionAnswering that uses TensorFlow or PyTorch library.</p>


问:
R dbWriteTable More Than One Class Warning
I've had a working R script that uses the dbWriteTable command to write to a SQL Server table. It has worked well without issue for a while ... until the last few days.

Now when I run the dbWriteTable command, I get the following warning:

```<code>Found more than one class "blob" in cache; using the first, from namespace 'blob'
Also defined by ‘jsonlite’
</code>```

Interestingly enough the table appears to write successfully.

Here is some sample code:

```<code>library("DBI")

db_test <- dbConnect(
  odbc(),
  driver = "SQL Server",
  server = "test_server",
  port = 1234,
  database = "test_db"
)

dbWriteTable(
  conn = db_test,
  name = SQL("dbo.swc_test_write_table"),
  value = df_test,
  overwrite = TRUE
)
</code>```

I've tried explicitly naming the package, DBI::dbWriteTable, but it throws the same warning. For reference, I'm not using using the jsonlite package, but I have it installed.

Any thoughts on why this is happening?

答:
Same problem here, seems to be interfering with encoding, possibly

EDIT:
Sorry for the "me too" post. I checked around a bit more and it's caused for me at least by the loading of the tidyverse library. Loading only DBI and odbc for me resolves the warning.

Body:
I've had a working R script that uses the dbWriteTable command to write to a SQL Server table. It has worked well without issue for a while ... until the last few days.

Now when I run the dbWriteTable command, I get the following warning:

Found more than one class "blob" in cache; using the first, from namespace 'blob'
Also defined by ‘jsonlite’

Interestingly enough the table appears to write successfully.

Here is some sample code:

library("DBI")

db_test <- dbConnect(
  odbc(),
  driver = "SQL Server",
  server = "test_server",
  port = 1234,
  database = "test_db"
)

dbWriteTable(
  conn = db_test,
  name = SQL("dbo.swc_test_write_table"),
  value = df_test,
  overwrite = TRUE
)

I've tried explicitly naming the package, DBI::dbWriteTable, but it throws the same warning. For reference, I'm not using using the jsonlite package, but I have it installed.

Any thoughts on why this is happening?


问:
How to get ONLY Second line with SED
How can I get second line in a file using SED

```<code>@SRR005108.1 :3:1:643:216
GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
+
IIIIII/III*IIIIIIIIII+IIIII;IIAIII%>
</code>```

With the data that looks like above I want only to get

```<code> GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
</code>```

答:
You don't really need Sed, but if the pourpose is to learn... you can use -n

n read the next input line and starts processing the newline with the command rather than the first command

```<code>sed -n 2p somefile.txt
</code>```

Edit: You can also improve the performance using the tip that manatwork mentions in his comment:

```<code>sed -n '2{p;q}' somefile.txt
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to get ONLY Second line with SED

Body:
How can I get second line in a file using SED

@SRR005108.1 :3:1:643:216
GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC
+
IIIIII/III*IIIIIIIIII+IIIII;IIAIII%>

With the data that looks like above I want only to get

 GATTTCTGGCCCGCCGCTCGATAATACAGTAATTCC

Body:
You don't really need Sed, but if the pourpose is to learn... you can use -n

n read the next input line and starts processing the newline with the command rather than the first command

sed -n 2p somefile.txt

Edit: You can also improve the performance using the tip that manatwork mentions in his comment:

sed -n '2{p;q}' somefile.txt


问:
How can we use OVH s3 api to access ovh cloud storage in java
I want to use ovh s3 api to access ovh cloud storage in java using keystore, secret key , consumer key and region.
So using that i can upload files on ovh cloud storage .</p>

答:
Before using Java to connect to your backend I suggest you validate your connection with the CLI client like following

Get your tokens you will need to generated them as explained in this documentation : https://docs.ovh.com/gb/en/storage/getting_started_with_the_swift_S3_API/

Important steps are :

Source your openrc file

```<code>user@host:~$ source <user_name>-openrc.sh
</code>```

create your ec2 credentials

You will get a block with it as a response from this call

```<code>user@host:~$ openstack ec2 credentials create
</code>```

edit your aws credentials

be sure to provide the region and correct links to OVHcloud storage

```<code>user@host:~$ cat ~/.aws/credentials

[default]
aws_access_key_id = <access_key>
aws_secret_access_key = <secret_key>

user@host:~$ cat ~/.aws/config

[plugins]
endpoint = awscli_plugin_endpoint

[profile default]
region = <region>
s3 =
  endpoint_url = https://s3.<region>.cloud.ovh.net
  signature_version = s3v4
s3api =
  endpoint_url = https://s3.<region>.cloud.ovh.net
</code>```

Validate the connectivity of your bucket by listing your OVHcloud storage objects.

```<code>aws --profile default s3 ls
</code>```

Then you can connect from java code you can use the code sample from this post answer Setting AWS S3 Region

```<code>AWSCredentials cred = new BasicAWSCredentials(<accessKey>,<secretKey>);
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(cred))
.withClientConfiguration(<your configuration>)
.withRegion(Region.getRegion(Regions.AP_SOUTH_1));
</code>```

Important thing is to provide the endpoint/region because sdk defaults to US_WEST region

Body:
Before using Java to connect to your backend I suggest you validate your connection with the CLI client like following

Get your tokens you will need to generated them as explained in this documentation : https://docs.ovh.com/gb/en/storage/getting_started_with_the_swift_S3_API/

Important steps are :

Source your openrc file

user@host:~$ source <user_name>-openrc.sh

create your ec2 credentials

You will get a block with it as a response from this call

user@host:~$ openstack ec2 credentials create

edit your aws credentials

be sure to provide the region and correct links to OVHcloud storage

user@host:~$ cat ~/.aws/credentials

[default]
aws_access_key_id = <access_key>
aws_secret_access_key = <secret_key>

user@host:~$ cat ~/.aws/config

[plugins]
endpoint = awscli_plugin_endpoint

[profile default]
region = <region>
s3 =
  endpoint_url = https://s3.<region>.cloud.ovh.net
  signature_version = s3v4
s3api =
  endpoint_url = https://s3.<region>.cloud.ovh.net

Validate the connectivity of your bucket by listing your OVHcloud storage objects.

aws --profile default s3 ls

Then you can connect from java code you can use the code sample from this post answer Setting AWS S3 Region

AWSCredentials cred = new BasicAWSCredentials(<accessKey>,<secretKey>);
AmazonS3 s3client = AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(cred))
.withClientConfiguration(<your configuration>)
.withRegion(Region.getRegion(Regions.AP_SOUTH_1));

Important thing is to provide the endpoint/region because sdk defaults to US_WEST region


问:
How to fix the messing up with a button animation when a text appear and the button width grow but the text doesn't fit for a moment?
I've developed a button that expands and shows a text but there's a moment during the growing that the text doesn't fit and looks bad.

Do I have any option to delay the text display until the button is big enough to fit it?

#emailButton {
  background-color: grey;
  color: black;
  height: 48px;
  width: 48px;
  border: none;
  border-radius: 48px;
  transition: all 0.5s linear;
}

#emailButton:hover {
  background-color: blue;
  border: none;
  color: white;
  width: 225px;
  height: 67px;
  border-radius: 67px;
}

#emailButton:hover::before {
  content: "Some text here"
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="align-items-center" id="emailButton">
              <svg id="emailIcon" width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M18 0H2C0.9 0 0.00999999 0.9 0.00999999 2L0 14C0 15.1 0.9 16 2 16H18C19.1 16 20 15.1 20 14V2C20 0.9 19.1 0 18 0ZM18 14H2V4L10 9L18 4V14ZM10 7L2 2H18L10 7Z" fill="currentcolor"/>
              </svg>
            </button></code>```

答:
There are several things you could do, a mixture of font size and opacity for example.

As a simple example this snippet takes the font-size from 0px to 14px on the hover.

#emailButton{
    background-color: grey;
    color: black;
    height: 48px;
    width: 48px;
    border: none;
    border-radius: 48px;
    transition: all 0.5s linear;
}
#emailButton:hover{
    background-color: blue;
    border: none;
    color: white;
    width: 225px;
    height: 67px;
    border-radius: 67px;

}
#emailButton::before{
    content: "Some text here";
    transition: all 0.5s linear;
    z-index: 1;
    font-size: 0;
}
#emailButton:hover::before{
 font-size: 14px;
 z-index: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button class="align-items-center" id="emailButton">
              <svg id="emailIcon" width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M18 0H2C0.9 0 0.00999999 0.9 0.00999999 2L0 14C0 15.1 0.9 16 2 16H18C19.1 16 20 15.1 20 14V2C20 0.9 19.1 0 18 0ZM18 14H2V4L10 9L18 4V14ZM10 7L2 2H18L10 7Z" fill="currentcolor"/>
              </svg>
            </button></code>```

Body:
I've developed a button that expands and shows a text but there's a moment during the growing that the text doesn't fit and looks bad.

Do I have any option to delay the text display until the button is big enough to fit it?

#emailButton {
  background-color: grey;
  color: black;
  height: 48px;
  width: 48px;
  border: none;
  border-radius: 48px;
  transition: all 0.5s linear;
}

#emailButton:hover {
  background-color: blue;
  border: none;
  color: white;
  width: 225px;
  height: 67px;
  border-radius: 67px;
}

#emailButton:hover::before {
  content: "Some text here"
}

<button class="align-items-center" id="emailButton">
              <svg id="emailIcon" width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M18 0H2C0.9 0 0.00999999 0.9 0.00999999 2L0 14C0 15.1 0.9 16 2 16H18C19.1 16 20 15.1 20 14V2C20 0.9 19.1 0 18 0ZM18 14H2V4L10 9L18 4V14ZM10 7L2 2H18L10 7Z" fill="currentcolor"/>
              </svg>
            </button>

Body:
There are several things you could do, a mixture of font size and opacity for example.

As a simple example this snippet takes the font-size from 0px to 14px on the hover.

#emailButton{
    background-color: grey;
    color: black;
    height: 48px;
    width: 48px;
    border: none;
    border-radius: 48px;
    transition: all 0.5s linear;
}
#emailButton:hover{
    background-color: blue;
    border: none;
    color: white;
    width: 225px;
    height: 67px;
    border-radius: 67px;

}
#emailButton::before{
    content: "Some text here";
    transition: all 0.5s linear;
    z-index: 1;
    font-size: 0;
}
#emailButton:hover::before{
 font-size: 14px;
 z-index: 1;
}

<button class="align-items-center" id="emailButton">
              <svg id="emailIcon" width="20" height="16" viewBox="0 0 20 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M18 0H2C0.9 0 0.00999999 0.9 0.00999999 2L0 14C0 15.1 0.9 16 2 16H18C19.1 16 20 15.1 20 14V2C20 0.9 19.1 0 18 0ZM18 14H2V4L10 9L18 4V14ZM10 7L2 2H18L10 7Z" fill="currentcolor"/>
              </svg>
            </button>


问:
Change Circle shape of Thumb in Slider Jetpack compose
The Slider in Jetpack Compose allows changing the color of the thumb but not the shape.
I'm looking solution to change the shape of the thumb from circle to rectangle as represented in the attached image

I tried to add Slider.kt file to the project as mentioned here but, strangely, when I copy this code to the project I got a lot of errors, see attached screenshot

答:
Here is a source code for Slider composable.

You can copy it to your project, rename, and change the Thumb shape in the SliderThumb composable:

```<code>...
.shadow(if (enabled) elevation else 0.dp, CircleShape, clip = false)
.background(colors.thumbColor(enabled).value, CircleShape)
...
</code>```

Body:
Here is a source code for Slider composable.

You can copy it to your project, rename, and change the Thumb shape in the SliderThumb composable:

...
.shadow(if (enabled) elevation else 0.dp, CircleShape, clip = false)
.background(colors.thumbColor(enabled).value, CircleShape)
...


问:
AssertionError in torch_geometric.nn.GATConv
I am trying to use graph attention network (GAT) module in torch_geometric but keep running into AssertionError: Static graphs not supported in 'GATConv' with the following code.

class GraphConv_sum(nn.Module):
    def __init__(self, in_ch, out_ch, num_layers, block, adj):
        super(GraphConv_sum, self).__init__()
        adj_coo = coo_matrix(adj) # convert the adjacency matrix to COO format for Pytorch Geometric
        self.edge_index = torch.tensor([adj_coo.row, adj_coo.col], dtype=torch.long)
        self.g_conv = nn.ModuleList()

        self.act = nn.LeakyReLU()

        for n in range(num_layers):
            if n == 0:
                self.g_conv.append(block(in_ch, 16))
            elif n > 0 and n < num_layers - 1:
                self.g_conv.append(block(16, 16))
            else:
                self.g_conv.append(block(16, out_ch))

    def forward(self, x):
        for layer in self.g_conv:
            x = layer(x=x, edge_index=self.edge_index)
            x = self.act(x)
            print(x.shape)
        return x[:, 0, :]
```

When I replace block with GATConv followed by a standard training loop, this error happens (other conv layers such as GCNConv or SAGEConv didn't have any problems). I checked the documentation and made sure the input shape was correct (same for other conv layers).

In the source code, there is this assert x.dim() == 2, "Static graphs not supported in 'GATConv'" part in the forward method but apparently the batch dimension will come into play in the forward pass and x.dim() would be 3. The input shape with batch dimension is [1024, 6, 200]. However, if I manually change the assert condition to x.dim() == 3 the same error will still be raised as if the condition is not satisfied. I only have a high-level grasp of GAT so there might be something I am missing. Anyways, I have a few questions from this

Are there any implementation errors possible from my side that caused this error?

What is this assertion condition for? What is the static graph in this case?

I would appreciate any insights and help!! Thanks!

答: It turns out due to the attention weight calculation, GATConv doesn't support multiple feature matrices and single edge_index. More info: https://github.com/pyg-team/pytorch_geometric/issues/2844</p>

Body:
I am trying to use graph attention network (GAT) module in torch_geometric but keep running into AssertionError: Static graphs not supported in 'GATConv' with the following code.

class GraphConv_sum(nn.Module):
    def __init__(self, in_ch, out_ch, num_layers, block, adj):
        super(GraphConv_sum, self).__init__()
        adj_coo = coo_matrix(adj) # convert the adjacency matrix to COO format for Pytorch Geometric
        self.edge_index = torch.tensor([adj_coo.row, adj_coo.col], dtype=torch.long)
        self.g_conv = nn.ModuleList()

        self.act = nn.LeakyReLU()

        for n in range(num_layers):
            if n == 0:
                self.g_conv.append(block(in_ch, 16))
            elif n > 0 and n < num_layers - 1:
                self.g_conv.append(block(16, 16))
            else:
                self.g_conv.append(block(16, out_ch))

    def forward(self, x):
        for layer in self.g_conv:
            x = layer(x=x, edge_index=self.edge_index)
            x = self.act(x)
            print(x.shape)
        return x[:, 0, :]

When I replace block with GATConv followed by a standard training loop, this error happens (other conv layers such as GCNConv or SAGEConv didn't have any problems). I checked the documentation and made sure the input shape was correct (same for other conv layers).

In the source code, there is this assert x.dim() == 2, "Static graphs not supported in 'GATConv'" part in the forward method but apparently the batch dimension will come into play in the forward pass and x.dim() would be 3. The input shape with batch dimension is [1024, 6, 200]. However, if I manually change the assert condition to x.dim() == 3 the same error will still be raised as if the condition is not satisfied. I only have a high-level grasp of GAT so there might be something I am missing. Anyways, I have a few questions from this

Are there any implementation errors possible from my side that caused this error?

What is this assertion condition for? What is the static graph in this case?

I would appreciate any insights and help!! Thanks!


问:
Reading in a positive number in C
I'm trying to find the most efficient way to read in a positive number in C. I can't use just scanf("%u", &var) because scanf takes the two's complement of negative numbers thereby screwing up the number. I also don't really want to read characters in manually into a buffer, because that requires me to know before-hand the maximum number of digits, which really I only want to be limited by UINT_MAX.

Any ideas, things I've most probably overlooked?

答:
What about reading a signed int from the user, and if it is negative show an error to the user:

```<code>int var;
scanf("%d", &var);

if (var < 0) {
    printf("Error: %d is negative", var);
}
else {
    /* use the positive number */
    unsigned int positive = var;
    /* ... */
}
</code>```

Title: Reading in a positive number in C

Body:
What about reading a signed int from the user, and if it is negative show an error to the user:

int var;
scanf("%d", &var);

if (var < 0) {
    printf("Error: %d is negative", var);
}
else {
    /* use the positive number */
    unsigned int positive = var;
    /* ... */
}


问:
Google Document AI - Invalid argument
I am very new in google Document AI, I tried to use this code but still have this response. Do you have any idea what I'm doing wrong?
I have installed from nuget Google.Cloud.DocumentAI.V1

Status(StatusCode="InvalidArgument", Detail="Request contains an invalid argument.", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"@1643889903.765000000","description":"Error received from peer ipv4:142.250.186.42:443","file":"......\src\core\lib\surface\call.cc","file_line":1067,"grpc_message":"Request contains an invalid argument.","grpc_status":3}")

```<code>    public async void Start()
    {
        Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"path-to-json");

        try
        {
            //Generate a document
            string pdfFilePath = @"path-to-invoice-pdf";
            var bytes = File.ReadAllBytes(pdfFilePath);
            ByteString content = ByteString.CopyFrom(bytes);

            // Create client
            DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync();
            // Initialize request argument(s)

            ProcessRequest request = new ProcessRequest
            {
                ProcessorName = ProcessorName.FromProjectLocationProcessor("ProjectID", "eu", "ProcessorID"),
                SkipHumanReview = false,
                RawDocument = new RawDocument
                {
                    MimeType = "application/pdf",
                    Content = content
                }
            };

            // Make the request
            ProcessResponse response = await documentProcessorServiceClient.ProcessDocumentAsync(request);

            Document docResponse = response.Document;

            Console.WriteLine(docResponse.Text);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }
</code>```

答:
Quoted from this doc:

Note that if you wish to use DocumentProcessorServiceClient other than in the US, you must specify the endpoint when you construct the client. The endpoint is of the form {location}-documentai.googleapis.com, e.g. eu-documentai.googleapis.com. The simplest way to specify the endpoint is to use DocumentProcessorServiceClientBuilder:

```<code>DocumentProcessorServiceClient client = new DocumentProcessorServiceClientBuilder
{
    Endpoint = "eu-documentai.googleapis.com"
}.Build();

</code>```

Title: Google Document AI - Invalid argument

Body:
I am very new in google Document AI, I tried to use this code but still have this response. Do you have any idea what I'm doing wrong?
I have installed from nuget Google.Cloud.DocumentAI.V1

Status(StatusCode="InvalidArgument", Detail="Request contains an invalid argument.", DebugException="Grpc.Core.Internal.CoreErrorDetailException: {"created":"@1643889903.765000000","description":"Error received from peer ipv4:142.250.186.42:443","file":"......\src\core\lib\surface\call.cc","file_line":1067,"grpc_message":"Request contains an invalid argument.","grpc_status":3}")

    public async void Start()
    {
        Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", @"path-to-json");

        try
        {
            //Generate a document
            string pdfFilePath = @"path-to-invoice-pdf";
            var bytes = File.ReadAllBytes(pdfFilePath);
            ByteString content = ByteString.CopyFrom(bytes);

            // Create client
            DocumentProcessorServiceClient documentProcessorServiceClient = await DocumentProcessorServiceClient.CreateAsync();
            // Initialize request argument(s)

            ProcessRequest request = new ProcessRequest
            {
                ProcessorName = ProcessorName.FromProjectLocationProcessor("ProjectID", "eu", "ProcessorID"),
                SkipHumanReview = false,
                RawDocument = new RawDocument
                {
                    MimeType = "application/pdf",
                    Content = content
                }
            };

            // Make the request
            ProcessResponse response = await documentProcessorServiceClient.ProcessDocumentAsync(request);

            Document docResponse = response.Document;

            Console.WriteLine(docResponse.Text);

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

Body:
Quoted from this doc:

Note that if you wish to use DocumentProcessorServiceClient other than in the US, you must specify the endpoint when you construct the client. The endpoint is of the form {location}-documentai.googleapis.com, e.g. eu-documentai.googleapis.com. The simplest way to specify the endpoint is to use DocumentProcessorServiceClientBuilder:

DocumentProcessorServiceClient client = new DocumentProcessorServiceClientBuilder
{
    Endpoint = "eu-documentai.googleapis.com"
}.Build();


问:
flutter test not finding widget
I have this code that test if the button is on the screen:

```<code>void main() {
  testWidgets('Search for button', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      home: HomeView(),
    ));
    final button = find.byType(BotaoRedirecionamentoInterno);
    expect(button, findsWidgets);
  });
}
</code>```

Is working as I expected, but when I try this code that search for another type of button in the same view it doenst work:

```<code>void main() {
  testWidgets('Search for button', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      home: HomeView(),
    ));
    final button = find.byType(BotaoRedirecionamentoExterno);
    expect(button, findsWidgets);
  });
}
</code>```

I don't understand why because they are exactly one line below in the HomeView:

```<code>      Expanded(
        child: GridView.count(
          childAspectRatio: 6,
          padding: EdgeInsets.only(left: screenWidth * .05, right: screenWidth * .05),
          mainAxisSpacing: screenHeight * 0.02,
          crossAxisCount: 1,
          children: const [
            BotaoRedirecionamentoInterno(texto: "aaa", rota: '/bbbb'),
            BotaoRedirecionamentoExterno(texto: 'aaa', url: "bbb"),
            BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
            BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
            BotaoRedirecionamentoExterno(texto: "aaa", url: 'bbb'),
            BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
          ],
        ),
      )
</code>```

this is the error message :

```<code>══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
  Expected: at least one matching node in the widget tree
  Actual: _WidgetTypeFinder:<zero widgets with type "BotaoRedirecionamentoExterno" (ignoring
offstage widgets)>
</code>```

I discovered that if I change the position inside the GridView to this:

```<code> Expanded(
            child: GridView.count(
              childAspectRatio: 6,
              padding: EdgeInsets.only(left: screenWidth * .05, right: screenWidth * .05),
              mainAxisSpacing: screenHeight * 0.02,
              crossAxisCount: 1,
              children: const [
                BotaoRedirecionamentoExterno(texto: 'aaa', url: "bbb"),
                BotaoRedirecionamentoInterno(texto: "aaa", rota: '/bbbb'),

                BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
                BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
                BotaoRedirecionamentoExterno(texto: "aaa", url: 'bbb'),
                BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
              ],
            ),
          )
</code>```

The test finds the BotaoRedirecionamentoInterno but wont find BotaoRedirecionamentoExterno, so my guess is that is only finding the first widget inside the GridView.

Anyone could help me figure out what is happening ?

答:
Use dragUntilVisible which scrolls the GridView in right direction, look below one it will scroll till the BotaoRedirecionamentoExterno widget, you can replace it with any Key or Text..

```<code>await tester.dragUntilVisible(
    find.byType(BotaoRedirecionamentoExterno), // what you want to find
    find.byType(GridView), // widget you want to scroll
    const Offset(-250, -0), // delta to move
);
</code>```

Title: flutter test not finding widget

Body:
I have this code that test if the button is on the screen:

void main() {
  testWidgets('Search for button', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      home: HomeView(),
    ));
    final button = find.byType(BotaoRedirecionamentoInterno);
    expect(button, findsWidgets);
  });
}

Is working as I expected, but when I try this code that search for another type of button in the same view it doenst work:

void main() {
  testWidgets('Search for button', (WidgetTester tester) async {
    await tester.pumpWidget(MaterialApp(
      home: HomeView(),
    ));
    final button = find.byType(BotaoRedirecionamentoExterno);
    expect(button, findsWidgets);
  });
}

I don't understand why because they are exactly one line below in the HomeView:

      Expanded(
        child: GridView.count(
          childAspectRatio: 6,
          padding: EdgeInsets.only(left: screenWidth * .05, right: screenWidth * .05),
          mainAxisSpacing: screenHeight * 0.02,
          crossAxisCount: 1,
          children: const [
            BotaoRedirecionamentoInterno(texto: "aaa", rota: '/bbbb'),
            BotaoRedirecionamentoExterno(texto: 'aaa', url: "bbb"),
            BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
            BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
            BotaoRedirecionamentoExterno(texto: "aaa", url: 'bbb'),
            BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
          ],
        ),
      )

this is the error message :

══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
  Expected: at least one matching node in the widget tree
  Actual: _WidgetTypeFinder:<zero widgets with type "BotaoRedirecionamentoExterno" (ignoring
offstage widgets)>

I discovered that if I change the position inside the GridView to this:

 Expanded(
            child: GridView.count(
              childAspectRatio: 6,
              padding: EdgeInsets.only(left: screenWidth * .05, right: screenWidth * .05),
              mainAxisSpacing: screenHeight * 0.02,
              crossAxisCount: 1,
              children: const [
                BotaoRedirecionamentoExterno(texto: 'aaa', url: "bbb"),
                BotaoRedirecionamentoInterno(texto: "aaa", rota: '/bbbb'),

                BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
                BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
                BotaoRedirecionamentoExterno(texto: "aaa", url: 'bbb'),
                BotaoRedirecionamentoExterno(texto: "aaa", url: "bbb"),
              ],
            ),
          )

The test finds the BotaoRedirecionamentoInterno but wont find BotaoRedirecionamentoExterno, so my guess is that is only finding the first widget inside the GridView.

Anyone could help me figure out what is happening ?

Body:
Use dragUntilVisible which scrolls the GridView in right direction, look below one it will scroll till the BotaoRedirecionamentoExterno widget, you can replace it with any Key or Text..

await tester.dragUntilVisible(
    find.byType(BotaoRedirecionamentoExterno), // what you want to find
    find.byType(GridView), // widget you want to scroll
    const Offset(-250, -0), // delta to move
);


问:
File download from Artifactory breaks randomly with Jfrog CLI
I have a few scripts which uses the Jfrog CLI to download files from artifactory. These scripts are on RHEL7. There are few download commands (jfrog rt dl) which download software packages from Artifactory.

Randomly one of these package will fail with following error messages:

```<code>04:12:24 [Info] [Thread 2] [1]: 206 Partial Content...
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x9d2bfb]

goroutine 86 [running]:
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).doDownloadFileRange.func2()
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:659 +0x1b
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).doDownloadFileRange(0x64, {{0xc00003aa80, 0x25}, {0xc000354c40, 0x68}, {0xc000436320, 0x47}, {0x7ffecb4afe1c, 0x25}, {0xc000036168, ...}, ...}, ...)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:685 +0x619
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadFileRange.func1()
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:614 +0x16b
github.com/jfrog/jfrog-client-go/utils.(*RetryExecutor).Execute(0xc000521d60)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/utils/retryexecutor.go:33 +0x57
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadFileRange(0xc00036e900, {{0xc00003aa80, 0x25}, {0xc000354c40, 0x68}, {0xc000436320, 0x47}, {0x7ffecb4afe1c, 0x25}, {0xc000036168, ...}, ...}, ...)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:632 +0x48d
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadChunksConcurrently.func1(0x0, 0x0, 0x1)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:544 +0x229
created by github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadChunksConcurrently
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:543 +0x151
</code>```

The commands i use are like these(from different scripts):

```<code>
TMPDIR="/app/install/temp" jfrog rt dl artifactory-project/Backup_file.rep.gz  $REPO_FILE

jfrog rt dl artifactory-project/second_file.tar.gz /app/software/second_file.tar.gz

</code>```

I am using Jfrog CLI jf version 2.12.0

Initially when it failed with segmentation error messages i added TMPDIR, but that did not sort out the issue.
I took a look at a similar post Artifactory Crash due to Segmentation Violation
but it does not seem to the exact error as i get.

Anyone faced similar issues? Any ideas to fix this issue?

Also I did not face this issue on CentOS. Is there some incompatibility with RHEL7?

答:
This commit of jfrog-client-go fixes the issue.
jfrog-client-go v1.8.1 was released with this fix.

JFrog CLI 2.12.1 was also released and includes this fix.
It appears that the scenario which exposed this bug is a nil response or a response without a body. If this is caused by some instability in your network, there's a chance that jfrog-client-go's HTTP retry mechanism will mitigate and resolve the issue, now that it no longer crashes beicase of it.

It is worth upgrading JFrog CLI to version 2.12.1 (which is currently the latest) and seeing if the issue is completely resolved, or there are other issues, which may or may not be related to the code of JFrog CLI, which still need to be handled.

Body:
I have a few scripts which uses the Jfrog CLI to download files from artifactory. These scripts are on RHEL7. There are few download commands (jfrog rt dl) which download software packages from Artifactory.

Randomly one of these package will fail with following error messages:

04:12:24 [Info] [Thread 2] [1]: 206 Partial Content...
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x40 pc=0x9d2bfb]

goroutine 86 [running]:
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).doDownloadFileRange.func2()
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:659 +0x1b
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).doDownloadFileRange(0x64, {{0xc00003aa80, 0x25}, {0xc000354c40, 0x68}, {0xc000436320, 0x47}, {0x7ffecb4afe1c, 0x25}, {0xc000036168, ...}, ...}, ...)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:685 +0x619
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadFileRange.func1()
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:614 +0x16b
github.com/jfrog/jfrog-client-go/utils.(*RetryExecutor).Execute(0xc000521d60)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/utils/retryexecutor.go:33 +0x57
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadFileRange(0xc00036e900, {{0xc00003aa80, 0x25}, {0xc000354c40, 0x68}, {0xc000436320, 0x47}, {0x7ffecb4afe1c, 0x25}, {0xc000036168, ...}, ...}, ...)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:632 +0x48d
github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadChunksConcurrently.func1(0x0, 0x0, 0x1)
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:544 +0x229
created by github.com/jfrog/jfrog-client-go/http/httpclient.(*HttpClient).downloadChunksConcurrently
    /root/go/pkg/mod/github.com/jfrog/jfrog-client-go@v1.8.0/http/httpclient/client.go:543 +0x151

The commands i use are like these(from different scripts):

TMPDIR="/app/install/temp" jfrog rt dl artifactory-project/Backup_file.rep.gz  $REPO_FILE

jfrog rt dl artifactory-project/second_file.tar.gz /app/software/second_file.tar.gz

I am using Jfrog CLI jf version 2.12.0

Initially when it failed with segmentation error messages i added TMPDIR, but that did not sort out the issue.
I took a look at a similar post Artifactory Crash due to Segmentation Violation
but it does not seem to the exact error as i get.

Anyone faced similar issues? Any ideas to fix this issue?

Also I did not face this issue on CentOS. Is there some incompatibility with RHEL7?


问:
Routable componet of Razor Class Library not displayed in ASP.NET Core 6.0 WebAssembly
I have an ASP.NET Core 6.0 WebAssembly in which I have included a Razor class library. The library contains several components, including three that use the @page directive. After a login (implemented with IdentityServer4) it is directed to one of the routable components from the library. The problem: the component is not displayed...

I checked the following:

The library is referenced by the WebAssembly

In App.razor I added AdditionalAssemblies="new[] { typeof(Helper).Assembly, typeof(Confirmation).Assembly, typeof(HelperRegistration).Assembly }".

I found the following:

No errors are displayed in either the Visual Studio output or the browser DevTools console.

Nothing is noticeable in the Network tab of Browser DevTools.

protected async override Task OnInitializedAsync() of the routable component is called.

I tried this:

Call the StateHasChanged() method of the layout component from the OnInitializedAsync() method. The idea behind it was that
Trigger rendering of the component from the library.

The components in the Razor class library were previously implemented directly in the Blazor WebAssembly and that's how it all worked! My goal is to integrate the library later with lazy load.

答:
You should be able to test your library pages like this:

Set one of your library pages with a @page "/"

Set App AppAssemblyto point to a class library. Here's an example below.

```<code><Router AppAssembly="@typeof(Blazor.App.UI.App).Assembly">
...
</code>```

What happens.  Does the library route load as the default route?

Additional Information based on Response

I have this in one of my test solutions, which works.  Note I use fully qualified namespace names.  Blazor.App.UI.Index is the index page which is in the Blazor.App.UI assembly/namespace.  I also like to keep my Razor very clean, which is why the list is defined in the @code block.

```<code>@namespace Blazor.App.UI
@using System.Reflection

<Router AppAssembly="@typeof(Blazor.App.Core.ListOptions).Assembly" AdditionalAssemblies="@Assemblies">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {
    private List<Assembly> Assemblies => new List<Assembly>() { typeof(Blazor.App.UI.Index).Assembly  };
}
</code>```

In your line:

```<code>AdditionalAssemblies="new[] { typeof(Helper).Assembly, typeof(Confirmation).Assembly, typeof(HelperRegistration).Assembly }"
</code>```

Are Helper, Configuration and HelperRegistration in the same assembly?  If so then you should only reference the assembly once.

Body:
You should be able to test your library pages like this:

Set one of your library pages with a @page "/"

Set App AppAssemblyto point to a class library. Here's an example below.

<Router AppAssembly="@typeof(Blazor.App.UI.App).Assembly">
...

What happens.  Does the library route load as the default route?

Additional Information based on Response

I have this in one of my test solutions, which works.  Note I use fully qualified namespace names.  Blazor.App.UI.Index is the index page which is in the Blazor.App.UI assembly/namespace.  I also like to keep my Razor very clean, which is why the list is defined in the @code block.

@namespace Blazor.App.UI
@using System.Reflection

<Router AppAssembly="@typeof(Blazor.App.Core.ListOptions).Assembly" AdditionalAssemblies="@Assemblies">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <LayoutView Layout="@typeof(MainLayout)">
            <p role="alert">Sorry, there's nothing at this address.</p>
        </LayoutView>
    </NotFound>
</Router>

@code {
    private List<Assembly> Assemblies => new List<Assembly>() { typeof(Blazor.App.UI.Index).Assembly  };
}

In your line:

AdditionalAssemblies="new[] { typeof(Helper).Assembly, typeof(Confirmation).Assembly, typeof(HelperRegistration).Assembly }"

Are Helper, Configuration and HelperRegistration in the same assembly?  If so then you should only reference the assembly once.


问:
Distance finder not printing text
I'm trying to make this sign that, when you step close enough, shows a GUI.

To test it, I made it print("It works!") but It won't print anything.

LocalScript:

```<code>local Players = game:GetService('Players')
local LocalPlayer = Players.LocalPlayer

for _,Player in next, Players:GetChildren() do
    local character = Player.Character
    if character and character.Parent and Player ~= LocalPlayer then
        local Magnitude = (LocalPlayer.Character.HumanoidRootPart.Position - character.HumanoidRootPart.Position).magnitude

    end
end
while true do
    if Magnitude < 10 then
        print("It's working!")
    end
end
</code>```

答:
The issue is that you have put a LocalScript into a Part in the Workspace. If you check the LocalScript docs, you'll see that ...

a LocalScript will only run Lua code if it is a descendant of one of the following objects:

A Player’s Backpack, such as a child of a Tool

A Player’s character model

A Player’s PlayerGui

A Player’s PlayerScripts.

The ReplicatedFirst service

So to fix your issue, you either need to

A) convert your code to a Script and access the Player objects through the Players service. or

B) move the LocalScript to a place where it will start executing and update the code accordingly.

If you go the route of Option B, follow these steps :

First, move the LocalScript into StarterPlayer > StarterCharacterScripts. This will cause the script to execute when the player's character spawns into the world.

Then, update the code so that it can find the block and show the distance to the player.

```<code>local localPlayer = game.Players.LocalPlayer

-- locate the sign in the world
-- local signGui = game.Workspace:WaitForChild("Part"):WaitForChild("UI")

-- set the range where the sign should appear
local DISTANCE_TO_SHOW_SIGN = 10 -- studs

-- every game tick, calculate the distance between the part and the character
game.RunService.Heartbeat:Connect(function()
    -- escape if the player's character doesn't exist
    if not localPlayer.Character then
        return
    end

    -- calculate the distance to each of the players
    -- if two players are close enough to each other, show the sign
    local shouldShowSign = false
    local myPosition = localPlayer.Character.HumanoidRootPart.Position

    for _, otherPlayer in ipairs(game.Players:GetPlayers()) do
        if (otherPlayer ~= localPlayer) and (otherPlayer.Character) then
            local theirPosition = otherPlayer.Character.HumanoidRootPart.Position
            local distBetween = (myPosition - theirPosition)

            -- optimization : when calculating distance, try to avoid using square roots
            -- use pythagorean theorem : dist = sqrt(x^2 + y^2 + z^2)
            -- instead, use dist^2 = x^2 + y^2 + z^2
            if (distBetween * distBetween) < (DISTANCE_TO_SHOW_SIGN ^ 2) then
                shouldShowSign = true
                break
            end
        end
    end

    -- show the sign if two players are close enough together
    if shouldShowSign then
        print("it's working")
    end
    -- optimization : only set the visibility when it changes
    -- if signGui.Visible ~= shouldShowSign then
    --    signGui.Visible = shouldShowSign
    -- end
end)
</code>```

Title: Distance finder not printing text

Body:
I'm trying to make this sign that, when you step close enough, shows a GUI.

To test it, I made it print("It works!") but It won't print anything.

LocalScript:

local Players = game:GetService('Players')
local LocalPlayer = Players.LocalPlayer

for _,Player in next, Players:GetChildren() do
    local character = Player.Character
    if character and character.Parent and Player ~= LocalPlayer then
        local Magnitude = (LocalPlayer.Character.HumanoidRootPart.Position - character.HumanoidRootPart.Position).magnitude

    end
end
while true do
    if Magnitude < 10 then
        print("It's working!")
    end
end

Body:
The issue is that you have put a LocalScript into a Part in the Workspace. If you check the LocalScript docs, you'll see that ...

a LocalScript will only run Lua code if it is a descendant of one of the following objects:

A Player’s Backpack, such as a child of a Tool

A Player’s character model

A Player’s PlayerGui

A Player’s PlayerScripts.

The ReplicatedFirst service

So to fix your issue, you either need to

A) convert your code to a Script and access the Player objects through the Players service. or

B) move the LocalScript to a place where it will start executing and update the code accordingly.

If you go the route of Option B, follow these steps :

First, move the LocalScript into StarterPlayer > StarterCharacterScripts. This will cause the script to execute when the player's character spawns into the world.

Then, update the code so that it can find the block and show the distance to the player.

local localPlayer = game.Players.LocalPlayer

-- locate the sign in the world
-- local signGui = game.Workspace:WaitForChild("Part"):WaitForChild("UI")

-- set the range where the sign should appear
local DISTANCE_TO_SHOW_SIGN = 10 -- studs

-- every game tick, calculate the distance between the part and the character
game.RunService.Heartbeat:Connect(function()
    -- escape if the player's character doesn't exist
    if not localPlayer.Character then
        return
    end

    -- calculate the distance to each of the players
    -- if two players are close enough to each other, show the sign
    local shouldShowSign = false
    local myPosition = localPlayer.Character.HumanoidRootPart.Position

    for _, otherPlayer in ipairs(game.Players:GetPlayers()) do
        if (otherPlayer ~= localPlayer) and (otherPlayer.Character) then
            local theirPosition = otherPlayer.Character.HumanoidRootPart.Position
            local distBetween = (myPosition - theirPosition)

            -- optimization : when calculating distance, try to avoid using square roots
            -- use pythagorean theorem : dist = sqrt(x^2 + y^2 + z^2)
            -- instead, use dist^2 = x^2 + y^2 + z^2
            if (distBetween * distBetween) < (DISTANCE_TO_SHOW_SIGN ^ 2) then
                shouldShowSign = true
                break
            end
        end
    end

    -- show the sign if two players are close enough together
    if shouldShowSign then
        print("it's working")
    end
    -- optimization : only set the visibility when it changes
    -- if signGui.Visible ~= shouldShowSign then
    --    signGui.Visible = shouldShowSign
    -- end
end)


问:
DoTween DoPath's speed between waypoints
I have a question about DoPath's speeds between waypoints. I want constant speed from start to end but i couldn't achieve that. But speed changing between waypoints.

I couln't find solution for my problem.

```<code>Vector3 firstPoint = from+new Vector3(5f,5f,0);

pathList.Add(from);
pathList.Add(firstPoint);
pathList.Add(to);

Vector3[] pathArr = pathList.ToArray();

GameObject trail = Instantiate(config.fireWork, from, Quaternion.identity);
       trail.transform.DOPath(pathArr,3,PathType.CatmullRom,PathMode.TopDown2D).SetEase(Ease.Linear).SetLookAt(0.01f).SetDelay(1f);
</code>```

https://gfycat.com/highunknowngentoopenguin

I want constant speed from start to end.

答:
If you put .SetSpeedBased(true) the duration will represent the number of units the tween moves x second.

P.S.
You can also set .SetLoops(-1) execution will loop on path.

Body:
I have a question about DoPath's speeds between waypoints. I want constant speed from start to end but i couldn't achieve that. But speed changing between waypoints.

I couln't find solution for my problem.

Vector3 firstPoint = from+new Vector3(5f,5f,0);

pathList.Add(from);
pathList.Add(firstPoint);
pathList.Add(to);

Vector3[] pathArr = pathList.ToArray();

GameObject trail = Instantiate(config.fireWork, from, Quaternion.identity);
       trail.transform.DOPath(pathArr,3,PathType.CatmullRom,PathMode.TopDown2D).SetEase(Ease.Linear).SetLookAt(0.01f).SetDelay(1f);

https://gfycat.com/highunknowngentoopenguin

I want constant speed from start to end.


问:
Change DataTemplate Child Dynamically
I have a ListView which has a column for checkboxes. When a checkbox is checked, I want to swap it out with a progress ring. Then, when the activity I want is completed, I can hide the progress ring and display the checked checkbox. Is this possible? A DataTemplate only seems to accept one child

```<code><GridViewColumn x:Name="StatusHeader" Header="Status" Width="50">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Margin="5, 0" IsChecked="{Binding loaded}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>
</code>```

答:
The DataTemplate contains only one child, but this child can be without problem a Container such as a Grid or a StackPanel, which will contain your elements:

```<code><GridViewColumn x:Name="StatusHeader" Header="Status" Width="50">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <StackPanel>
                <CheckBox Margin="5, 0" IsChecked="{Binding loaded}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
                <ProgressBar />
            </StackPanel>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>
</code>```

Title: Change DataTemplate Child Dynamically

Body:
I have a ListView which has a column for checkboxes. When a checkbox is checked, I want to swap it out with a progress ring. Then, when the activity I want is completed, I can hide the progress ring and display the checked checkbox. Is this possible? A DataTemplate only seems to accept one child

<GridViewColumn x:Name="StatusHeader" Header="Status" Width="50">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <CheckBox Margin="5, 0" IsChecked="{Binding loaded}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

Body:
The DataTemplate contains only one child, but this child can be without problem a Container such as a Grid or a StackPanel, which will contain your elements:

<GridViewColumn x:Name="StatusHeader" Header="Status" Width="50">
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <StackPanel>
                <CheckBox Margin="5, 0" IsChecked="{Binding loaded}" Checked="CheckBox_Checked" Unchecked="CheckBox_Unchecked"/>
                <ProgressBar />
            </StackPanel>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>


问:
when first if statement true continue with next if statement
python 3.8.11

I want to call the function num_okay in another file. and I want to return the specific "solu" for each number if the if statement is true.

rn it's only returning the first if statement. but I want it to return all the if statements that are correct, not only the first time

and if the first if statement is false I want to continue running the next if statement

thankss

```<code>numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():

    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        return solu

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        return solu

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        return solu

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        return solu

    else:
        return "NO number is okay"
</code>```

答:
If you want to return all statements that are True, you could do the following:

numberA=1
numberB=2
numberC=3
numberD=4

result = []

def num_okay():
    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        result.append(solu)

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        result.append(solu)

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        result.append(solu)

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        result.append(solu)

    else:
        result.append("NO number is okay")
    return result

print(num_okay())
```

The above code return list of all matching statements. You could later convert it as per the use-case.

Body:
python 3.8.11

I want to call the function num_okay in another file. and I want to return the specific "solu" for each number if the if statement is true.

rn it's only returning the first if statement. but I want it to return all the if statements that are correct, not only the first time

and if the first if statement is false I want to continue running the next if statement

thankss

numberA=1

numberB=2

numberC=3

numberD=4

def num_okay():

    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        return solu

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        return solu

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        return solu

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        return solu

    else:
        return "NO number is okay"

Body:
If you want to return all statements that are True, you could do the following:

numberA=1
numberB=2
numberC=3
numberD=4

result = []

def num_okay():
    if numberA < 20 or numberA > 30:
        solu= 'numberA is okay'
        result.append(solu)

    if numberB < 20 or numberB > 30:
        solu = 'numberB is okay'
        result.append(solu)

    if numberC < 20 or numberC > 30:
        solu = 'numberC is okay'
        result.append(solu)

    if numberD < 20 or numberD > 30:
        solu = 'numberD is okay'
        result.append(solu)

    else:
        result.append("NO number is okay")
    return result

print(num_okay())

The above code return list of all matching statements. You could later convert it as per the use-case.


问:
How to exit process.stdin.on and then reopen process.stdin.on
I have struggling with an exercise. The client input a certain integer x, according with the integer x they will input x other y values, space-separated. The output will be the addition of each y itself, space-separated.

Example:

```<code>Input: 4            |  Input: 5
       21 35 55 66  |         333 53 99 12 55
Output:3 8 10 12    |  Output: 9 8 18 3 10
</code>```

and so on...

So far so good, my problem is that I don't understand process.stdin.on('data', function() ... )

I didn't find many videos or explanations about this.

From what I understood from 2 short videos of explanations, I did this:

```<code>let number = null;

let numOrder = [];

function clientsnum() {
  process.stdout.write("Enter number: ");

  process.stdin.on("data", function (data) {
    number = parseInt(data.toString().trim());
    process.stdin.pause();
  });

  process.stdin.on("pause", function () {
    console.log("Paused");
    process.stdout.write(`${numOrder} ${number}` + "\n"); //for debug
    order();
  });
}

function order() {
  console.log("got here");                   //for debug
  process.stdout.write("numberOrder: ");
  process.stdin.resume();
  process.stdin.on("data", function (data) {
    if (numOrder.length < number) {
      numOrder.push(parseInt(data.toString().trim()));
    } else {
      process.exit();
    }
  });
  process.on('exit', function() {
    console.log('Over')
  })
}
clientsnum();
</code>```

Sometimes, I can see it doubles on the array. Also, it changes the previous statement of "number".

The exercise show us a template where I saw in other pages, by code I can understand but by practice it doesn't work when I try it "process.stdin.on('end', ...)".

If someone wants to try explain it too. I would appreciate.

Here is the template:

```<code>function main(input) {
  process.stdout.write("hello " + input) //write output
}

process.stdin.resume()
process.stdin.setEncoding("utf-8")

var stdin_input = ""

process.stdin.on("data", function(input) {
  stdin_input += input          //read input from stdin
})

process.stdin.on("end", function (){
  main(stdin_input)
})
</code>```

答:
On my second day, after a good shower thinking. I got one solution.</p>
```<code>let numOfClient = null;

let orderID = [];

let answers = [];

let questions = ["Enter number of clients: ", "Order ID: "];

function question() {
  process.stdout.write(questions[0]);

  process.stdin.on("data", function (data) {
    answers.push(parseInt(data.toString().trim()));
    numOfClient = answers[0];

    if (answers.length < numOfClient + 1) {
      process.stdout.write(questions[1]);           // Here the question is not answered yet

      if (answers.length !== 1) {                   // So I need to wait for the next interation/loop
        orderID.push(answers[answers.length - 1]);
      }
    } else {
      orderID.push(answers[answers.length - 1]);    // To get the last loop answer
      process.exit();
    }
  });

  process.on("exit", function () {
    // for debug
    console.log(
      `Done, the answers [${answers}] , the numberOfClient ${numOfClient}, the orderID's [${orderID}] `
    );
  });
}

question();
</code>```

Body:
I have struggling with an exercise. The client input a certain integer x, according with the integer x they will input x other y values, space-separated. The output will be the addition of each y itself, space-separated.

Example:

Input: 4            |  Input: 5
       21 35 55 66  |         333 53 99 12 55
Output:3 8 10 12    |  Output: 9 8 18 3 10

and so on...

So far so good, my problem is that I don't understand process.stdin.on('data', function() ... )

I didn't find many videos or explanations about this.

From what I understood from 2 short videos of explanations, I did this:

let number = null;

let numOrder = [];

function clientsnum() {
  process.stdout.write("Enter number: ");

  process.stdin.on("data", function (data) {
    number = parseInt(data.toString().trim());
    process.stdin.pause();
  });

  process.stdin.on("pause", function () {
    console.log("Paused");
    process.stdout.write(`${numOrder} ${number}` + "\n"); //for debug
    order();
  });
}

function order() {
  console.log("got here");                   //for debug
  process.stdout.write("numberOrder: ");
  process.stdin.resume();
  process.stdin.on("data", function (data) {
    if (numOrder.length < number) {
      numOrder.push(parseInt(data.toString().trim()));
    } else {
      process.exit();
    }
  });
  process.on('exit', function() {
    console.log('Over')
  })
}
clientsnum();

Sometimes, I can see it doubles on the array. Also, it changes the previous statement of "number".

The exercise show us a template where I saw in other pages, by code I can understand but by practice it doesn't work when I try it "process.stdin.on('end', ...)".

If someone wants to try explain it too. I would appreciate.

Here is the template:

function main(input) {
  process.stdout.write("hello " + input) //write output
}

process.stdin.resume()
process.stdin.setEncoding("utf-8")

var stdin_input = ""

process.stdin.on("data", function(input) {
  stdin_input += input          //read input from stdin
})

process.stdin.on("end", function (){
  main(stdin_input)
})

Body:
On my second day, after a good shower thinking. I got one solution.

let numOfClient = null;

let orderID = [];

let answers = [];

let questions = ["Enter number of clients: ", "Order ID: "];

function question() {
  process.stdout.write(questions[0]);

  process.stdin.on("data", function (data) {
    answers.push(parseInt(data.toString().trim()));
    numOfClient = answers[0];

    if (answers.length < numOfClient + 1) {
      process.stdout.write(questions[1]);           // Here the question is not answered yet

      if (answers.length !== 1) {                   // So I need to wait for the next interation/loop
        orderID.push(answers[answers.length - 1]);
      }
    } else {
      orderID.push(answers[answers.length - 1]);    // To get the last loop answer
      process.exit();
    }
  });

  process.on("exit", function () {
    // for debug
    console.log(
      `Done, the answers [${answers}] , the numberOfClient ${numOfClient}, the orderID's [${orderID}] `
    );
  });
}

question();


问:
How to align icon with element instead of element text
I have a svg icon and a span element side by side. When the text overflows inside the span element, the svg also comes down along with it. I don't want it to happen.

Here is a  of what I'm doing.

As you can see, the arrow icon is proper in Section 1 but in Section 2, it comes down with the text.

Here is the HTML code -

.rightContent {
  border: 2px solid green;
  height: 100vh;
  overflow-y: scroll;
}

.sectionHeading {
  background: #f7f9fa;
  text-align: left;
  font-family: sf pro display, -apple-system, BlinkMacSystemFont, Roboto, segoe ui, Helvetica, Arial, sans-serif, apple color emoji, segoe ui emoji, segoe ui symbol;
  font-weight: 700;
  line-height: 1.2;
  letter-spacing: -.02rem;
  font-size: 1rem;
  padding-top: .75rem;
  padding-bottom: 1.05rem;
}

.sectionHeading p {
  padding: 0;
  margin: 0;
}

.sectionHeading svg {
  float: right;
}

.sectionHeading small {
  font-size: 0.75rem;
  font-weight: 500;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="rightContent col col-lg-3 col-md-3 sol-sm-3" style="border: 2px solid green;">
  <!-- Section 1: Introduction -->
  <div class="row">
    <div class="card">
      <div class="sectionHeading">
        <span>Section 1: Introduction</span>
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-down" viewBox="0 0 16 16">
                                <path d="M3.204 5h9.592L8 10.481 3.204 5zm-.753.659 4.796 5.48a1 1 0 0 0 1.506 0l4.796-5.48c.566-.647.106-1.659-.753-1.659H3.204a1 1 0 0 0-.753 1.659z"/>
                            </svg>
        <p></p>
        <small>14 / 14 | 1hr 5min</small>
      </div>
    </div>
  </div>

  <!-- Section 2: Experience -->
  <div class="row">
    <div class="card">
      <div class="sectionHeading">
        <span>Section 2: Experiences In The Corporate World</span>
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-down" viewBox="0 0 16 16">
                                <path d="M3.204 5h9.592L8 10.481 3.204 5zm-.753.659 4.796 5.48a1 1 0 0 0 1.506 0l4.796-5.48c.566-.647.106-1.659-.753-1.659H3.204a1 1 0 0 0-.753 1.659z"/>
                            </svg>
        <p></p>
        <small>19 / 19 | 2hr 15min</small>
      </div>
    </div>
  </div></code>```

Most of the questions already present deal with aligning icons with text, but as I mentioned earlier, I want to align icons with span element and keep it fixed there, instead of aligning it with text.

Please feel free to share your inputs. I'll be grateful to learn from others since I'm still learning CSS. Thank you.

答:
In your case the best choice is using positions,using your .sectionHeading or.card as the relative element.

Try it:

```<code>.sectionHeading { /* you can also use your div .card */
   position: relative;
}

svg { /* here you can also use a class name */
  position: absolute;
  top: 0;
  right: 0;
}
</code>```

Be in mind that maybe you will need to add a padding to your relative element, otherwise your svg will be leaning the border.

Body:
I have a svg icon and a span element side by side. When the text overflows inside the span element, the svg also comes down along with it. I don't want it to happen.

Here is a  of what I'm doing.

As you can see, the arrow icon is proper in Section 1 but in Section 2, it comes down with the text.

Here is the HTML code -

.rightContent {
  border: 2px solid green;
  height: 100vh;
  overflow-y: scroll;
}

.sectionHeading {
  background: #f7f9fa;
  text-align: left;
  font-family: sf pro display, -apple-system, BlinkMacSystemFont, Roboto, segoe ui, Helvetica, Arial, sans-serif, apple color emoji, segoe ui emoji, segoe ui symbol;
  font-weight: 700;
  line-height: 1.2;
  letter-spacing: -.02rem;
  font-size: 1rem;
  padding-top: .75rem;
  padding-bottom: 1.05rem;
}

.sectionHeading p {
  padding: 0;
  margin: 0;
}

.sectionHeading svg {
  float: right;
}

.sectionHeading small {
  font-size: 0.75rem;
  font-weight: 500;
}

        Section 1: Introduction
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-down" viewBox="0 0 16 16">
                                <path d="M3.204 5h9.592L8 10.481 3.204 5zm-.753.659 4.796 5.48a1 1 0 0 0 1.506 0l4.796-5.48c.566-.647.106-1.659-.753-1.659H3.204a1 1 0 0 0-.753 1.659z"/>
                            </svg>

        14 / 14 | 1hr 5min

        Section 2: Experiences In The Corporate World
        <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-caret-down" viewBox="0 0 16 16">
                                <path d="M3.204 5h9.592L8 10.481 3.204 5zm-.753.659 4.796 5.48a1 1 0 0 0 1.506 0l4.796-5.48c.566-.647.106-1.659-.753-1.659H3.204a1 1 0 0 0-.753 1.659z"/>
                            </svg>

        19 / 19 | 2hr 15min

Most of the questions already present deal with aligning icons with text, but as I mentioned earlier, I want to align icons with span element and keep it fixed there, instead of aligning it with text.

Please feel free to share your inputs. I'll be grateful to learn from others since I'm still learning CSS. Thank you.

Body:
In your case the best choice is using positions,using your .sectionHeading or.card as the relative element.

Try it:

.sectionHeading { /* you can also use your div .card */
   position: relative;
}

svg { /* here you can also use a class name */
  position: absolute;
  top: 0;
  right: 0;
}

Be in mind that maybe you will need to add a padding to your relative element, otherwise your svg will be leaning the border.


问:
SpringFox Swagger - Remove 200 Responses
I'm using Swagger annotations and SpringFox to produce a Swagger spec for my REST API (being built with Sprint Boot). I'm annotating each method with the @ApiResponse codes that will be returned. For example:

```<code>@DeleteMapping("/{pipelineName}")
@ApiOperation(value = "Delete a specific pipeline")
@ApiResponses({
    @ApiResponse(code = 204, message = "Pipeline has been deleted"),
    @ApiResponse(code = 404, message = "Pipeline does not exist")
})
public void deletePipeline(@PathVariable("pipelineName") @ApiParam(value = "Name of pipeline", required = true) String name){
    ...
}
</code>```

However, something (I assume SpringFox) is adding a 200 response code to every API call regardless of whether it's defined or not. I'm aware that I can remove this by adding a @ResponseStatus annotation to each method, but a) that seems like unneccessary duplication of the @ApiResponse definitions and b) some methods could return one of multiple 2xx codes.

Is there a way or removing the 200 code that is added by default?

答:
You need to mention useDefaultResponseMessages to false while creating the Docket object. Now it will document only that you have added in @ApiResponses.

```<code>new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.ty"))
            .build()
            .apiInfo(apiInfo)
            .useDefaultResponseMessages(false);
</code>```

Body:
I'm using Swagger annotations and SpringFox to produce a Swagger spec for my REST API (being built with Sprint Boot). I'm annotating each method with the @ApiResponse codes that will be returned. For example:

@DeleteMapping("/{pipelineName}")
@ApiOperation(value = "Delete a specific pipeline")
@ApiResponses({
    @ApiResponse(code = 204, message = "Pipeline has been deleted"),
    @ApiResponse(code = 404, message = "Pipeline does not exist")
})
public void deletePipeline(@PathVariable("pipelineName") @ApiParam(value = "Name of pipeline", required = true) String name){
    ...
}

However, something (I assume SpringFox) is adding a 200 response code to every API call regardless of whether it's defined or not. I'm aware that I can remove this by adding a @ResponseStatus annotation to each method, but a) that seems like unneccessary duplication of the @ApiResponse definitions and b) some methods could return one of multiple 2xx codes.

Is there a way or removing the 200 code that is added by default?

Body:
You need to mention useDefaultResponseMessages to false while creating the Docket object. Now it will document only that you have added in @ApiResponses.

new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.ty"))
            .build()
            .apiInfo(apiInfo)
            .useDefaultResponseMessages(false);


问:
Best Practises of @Repository in Spring boot framework
I have a Spring boot application which has a UserRepository but I have not annotated that repository with @Repository but still my application works fine.

Why @Repository annotation is optional in Spring boot and what is the best practise that should we annotate it or not in repository classes.

答: It is working because spring will scan the class path and identify given class is repository (DAO) based on the imports, when use @Repositary spring context know how to handle expections like re-throw to pre defined methods ..etc, and also this annotation help readability of the code.</p>


问:
Match split words from input field with JS
I have an input field value that gets split.

```<code><input type="text" id="findW" value="command prompt" />

const txtValue = document
  .getElementById("findW")
  .value.replace(/[.*+?^${ }()|[\]\\]/g, "\\$&");

const r2 = txtValue.split(" ");
console.log(`R2 with split looks like: ${r2}`);
</code>```

Every word resulted from splitting must be checked if appears in some elements in order to display them. I did it using jQuery but I would like to use vanilla JS.

```<code>let searchInElements = `.some-classes-to-search`;

//How can be rewritten in JS this jQuery below?
$(searchInElements).each(function (i, el) {
  if ($(this).text().match(r2)) {
    showElement(el);
  }
});
</code>```

Function used to display elements with the words from input:

```<code>function showElement(el) {
  el.closest("#idOfEl")
    ? (el.closest("#idOfEl").style.display = "block")
    : null;
}
</code>```

答:
It's not all that different really.</p>
```<code>let searchInElements = `.some-classes-to-search`;

// Vanilla
document.querySelectorAll(searchInElements).forEach(el => {
  if (el.innerText.trim().match(r2)) showElement(el);
})

function showElement(el) {
  if (parent = el.closest("#idOfEl")) parent.style.display = "block";
}
</code>```

Body:
I have an input field value that gets split.

<input type="text" id="findW" value="command prompt" />

const txtValue = document
  .getElementById("findW")
  .value.replace(/[.*+?^${ }()|[\]\\]/g, "\\$&");

const r2 = txtValue.split(" ");
console.log(`R2 with split looks like: ${r2}`);

Every word resulted from splitting must be checked if appears in some elements in order to display them. I did it using jQuery but I would like to use vanilla JS.

let searchInElements = `.some-classes-to-search`;

//How can be rewritten in JS this jQuery below?
$(searchInElements).each(function (i, el) {
  if ($(this).text().match(r2)) {
    showElement(el);
  }
});

Function used to display elements with the words from input:

function showElement(el) {
  el.closest("#idOfEl")
    ? (el.closest("#idOfEl").style.display = "block")
    : null;
}

Body:
It's not all that different really.

let searchInElements = `.some-classes-to-search`;

// Vanilla
document.querySelectorAll(searchInElements).forEach(el => {
  if (el.innerText.trim().match(r2)) showElement(el);
})

function showElement(el) {
  if (parent = el.closest("#idOfEl")) parent.style.display = "block";
}