问:
NHibernate 3.1 Linq with Contains and Any
We are in the process of upgrading to NH3.1 which is going well -
everything is working as far as we can tell with existing code. One of
the motivations to move to NH3 from 2 has been to leverage the Linq
support and generally it is working really well. However I am
struggling with some more complex where clauses, specifically when I
want to check based on a sub-collection:

```<code>var results = from r in registrations
              where (
                         from p in persons
                         where p.ExplicitManagers.Any(m => m.Manager == manager)
                         select p
                     ).Contains(r.Registrant)
              select r;
</code>```

where the model is:

p is a Person and a registration r has a registrant of type Person

p contains a collection of ExplicitManager associative entities which
hold a reference to another Person (manager).

note: registrations is an IQueryable<Registration>.Query() and persons
in an IQueryable<Person>.Query().

Essentially I am trying to restrict the registrations to where person1
is an explicit manager of p. I can do this via joins but not through
the Contains subquery.

I get the following error:

"System.InvalidOperationException :
  Sequence contains more than one
  matching element"

the reason for doing this as a sub-query is because ultimately I need
to externalize the logic for checking the managers to make it reusable
(it actually is more complex but I have simplified it for this example
because it is the Any within a Contains which is causing the grief).

Contains seems to work fine when not having a sub-query with Any.
Is this something I am doing wrong, or is it something unsupported or
a bug, and is there another way of achieving the same thing?

Many thanks for any help you can give.

答:
Can you execute the sub query on its own without problems?</p>

```<code>var result = from p in persons
where p.ExplicitManagers.Any(m => m.Manager == manager)
select p;
</code>```

Body:
We are in the process of upgrading to NH3.1 which is going well -
everything is working as far as we can tell with existing code. One of
the motivations to move to NH3 from 2 has been to leverage the Linq
support and generally it is working really well. However I am
struggling with some more complex where clauses, specifically when I
want to check based on a sub-collection:

var results = from r in registrations
              where (
                         from p in persons
                         where p.ExplicitManagers.Any(m => m.Manager == manager)
                         select p
                     ).Contains(r.Registrant)
              select r;

where the model is:

p is a Person and a registration r has a registrant of type Person

p contains a collection of ExplicitManager associative entities which
hold a reference to another Person (manager).

note: registrations is an IQueryable<Registration>.Query() and persons
in an IQueryable<Person>.Query().

Essentially I am trying to restrict the registrations to where person1
is an explicit manager of p. I can do this via joins but not through
the Contains subquery.

I get the following error:

"System.InvalidOperationException :
  Sequence contains more than one
  matching element"

the reason for doing this as a sub-query is because ultimately I need
to externalize the logic for checking the managers to make it reusable
(it actually is more complex but I have simplified it for this example
because it is the Any within a Contains which is causing the grief).

Contains seems to work fine when not having a sub-query with Any.
Is this something I am doing wrong, or is it something unsupported or
a bug, and is there another way of achieving the same thing?

Many thanks for any help you can give.

Body:
Can you execute the sub query on its own without problems?

var result = from p in persons
where p.ExplicitManagers.Any(m => m.Manager == manager)
select p;


来源: stackexchange

问:
How to check if a file exists in Ansible?
I have to check whether a file exists in /etc/. If the file exists then I have to skip the task.
Here is the code I am using:

```<code>- name: checking the file exists
  command: touch file.txt
  when: $(! -s /etc/file.txt)
</code>```

答:
You can use Ansible stat module to register the file, and when module to apply the condition.</p>

```<code>- name: Register file
      stat:
        path: "/tmp/test_file"
      register: file_path

- name: Create file if it doesn't exists
      file:
        path: "/tmp/test_file"
        state: touch
      when: file_path.stat.exists == False
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have to check whether a file exists in /etc/. If the file exists then I have to skip the task.
Here is the code I am using:

- name: checking the file exists
  command: touch file.txt
  when: $(! -s /etc/file.txt)

Body:
You can use Ansible stat module to register the file, and when module to apply the condition.

- name: Register file
      stat:
        path: "/tmp/test_file"
      register: file_path

- name: Create file if it doesn't exists
      file:
        path: "/tmp/test_file"
        state: touch
      when: file_path.stat.exists == False


问:
Extract the content of a specific folder from a zip archive in Python3
I have a zip archive whose internal structure looks like this:

```<code>file.zip
  |
   --- foo/
  |
   --- bar/
        |
         --- file1.txt
        |
         --- dir/
              |
               --- file2.txt
</code>```

and I would like to extract the content of bar to an output directory using python3, getting something that looks like so:

```<code>output-dir/
    |
     --- file1.txt
    |
     --- dir/
          |
           --- file2.txt
</code>```

However, when I run the code below both bar and it's content is being extracted to output-dir

```<code>import zipfile

archive = zipfile.ZipFile('path/to/file.zip')

for archive_item in archive.namelist():
    if archive_item.startswith('bar/'):
        archive.extract(archive_item, 'path/to/output-dir')
</code>```

How can I tackle this problem?
Thanks!

答:
Instead of using ZipFile.extract, use ZipFile.open, open and shutil.copyfileobj in order to put the file exactly where you want it to be, using path manipulation to create the output path you need.

archive = zipfile.ZipFile('path/to/file.zip')
PREFIX = 'bar/'
out = pathlib.Path('path/to/output-dir')
for archive_item in archive.namelist():
    if archive_item.startswith(PREFIX):
        # strip out the leading prefix then join to `out`, note that you
        # may want to add some securing against path traversal if the zip
        # file comes from an untrusted source
        destpath = out.joinpath(archive_item[len(PREFIX):])
        # make sure destination directory exists otherwise `open` will fail
        os.makedirs(destpath.parent, exist_ok=True)
        with archive.open(archive_item) as source,
             open(destpath, 'wb') as dest:
            shutil.copyfileobj(source, dest)
```

something like that.

Body:
I have a zip archive whose internal structure looks like this:

file.zip
  |
   --- foo/
  |
   --- bar/
        |
         --- file1.txt
        |
         --- dir/
              |
               --- file2.txt

and I would like to extract the content of bar to an output directory using python3, getting something that looks like so:

output-dir/
    |
     --- file1.txt
    |
     --- dir/
          |
           --- file2.txt

However, when I run the code below both bar and it's content is being extracted to output-dir

import zipfile

archive = zipfile.ZipFile('path/to/file.zip')

for archive_item in archive.namelist():
    if archive_item.startswith('bar/'):
        archive.extract(archive_item, 'path/to/output-dir')

How can I tackle this problem?
Thanks!

Body:
Instead of using ZipFile.extract, use ZipFile.open, open and shutil.copyfileobj in order to put the file exactly where you want it to be, using path manipulation to create the output path you need.

archive = zipfile.ZipFile('path/to/file.zip')
PREFIX = 'bar/'
out = pathlib.Path('path/to/output-dir')
for archive_item in archive.namelist():
    if archive_item.startswith(PREFIX):
        # strip out the leading prefix then join to `out`, note that you
        # may want to add some securing against path traversal if the zip
        # file comes from an untrusted source
        destpath = out.joinpath(archive_item[len(PREFIX):])
        # make sure destination directory exists otherwise `open` will fail
        os.makedirs(destpath.parent, exist_ok=True)
        with archive.open(archive_item) as source,
             open(destpath, 'wb') as dest:
            shutil.copyfileobj(source, dest)

something like that.


问:
Vuelidate deep nested array of strings
I have data with following structure in my Vue file:

```<code>data() {
  return {
    formData: {
      name: 'foo',
      objects: [
        {id: 0, name: 'a', props: []},
        {id: 1, name: 'b', props: ['2', '23']},
        {id: 2, name: 'c', props: ['44']},
        {id: 3, name: 'd', props: []}
      ]
    },
    currentObj = null,
    currentPropIndex = null
  }
}
</code>```

The number of objects in the array objects is dynamic and so is the props array, where string values maybe added and removed. I need to use Vuelidate to validate each and every value of props array in each and every object when it's changed. So I tried this:

```<code>validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      props: {
        $each: {
          required, numeric, maxLength: maxLength(5)
        }
      }
    }
  }
},
</code>```

Computed:

```<code>propsErrors() {
    const errors = [];
    if ( this.currentObj) {
      // const objIndex = _.findIndex(this.formData.objects, o => o.id === this.currentObj.id)
      if (!this.$v.formData.objects['props'][this.currentPropIndex].$dirty) {
        return errors;
      }
      !this.$v.formData.objects['props'][this.currentPropIndex].maxLength && errors.push('Max 5 digits')
      !this.$v.formData.objects['props'][this.currentPropIndex].required && errors.push('Required')
      !this.$v.formData.objects['props'][this.currentPropIndex].numeric && errors.push('Digits only')
    }
    return errors
  },
</code>```

And my Vuetify text field:

```<code><v-text-field single-line flat dense required
  v-model="object.props[index]"
  :error-messages="propsErrors"
  label="Prop"
  height="30"
  @click="setCurrents(protocol, index)"
  @blur="$v.formData.protocolPorts['manual_ports'][index].$touch()"
  @input="$v.formData.protocolPorts['manual_ports'][index].$touch()" />
</code>```

And setCurrents only sets the currently edited object and prop index:

```<code>setCurrents (protocol, index) {
    this.currentObj = protocol;
    this.currentPropIndex = index;
  }
</code>```

Once I test the page and click on the text field, I'm getting this error: Error in render: "TypeError: Cannot read property 'props' of undefined"

I tried to change propsErrors (objIndex is currently commented out in the code above)

```<code>this.$v.formData.objects[objIndex]['props'][index].maxLength && errors.push('Max 5 digits')
</code>```

Text Field (oi stands for object index):

```<code>@input="$v.formData.objects[oi].props[index].$touch()"
</code>```

And validations:

```<code>validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      required,
      $each: {
        props: {
          $each: {
            required, numeric, maxLength: maxLength(5)
          }
        }
      }
    }
  }
},
</code>```

Still keep getting errors. Any ideas, please?

答:
I've never used Vuelidate but I found this example was quite useful and reasonably similar to what you're trying to do https://vuelidate.js.org/#sub-collections-validation

Your data in the Vue instance should be changed from

```<code>currentObj = null,
currentPropIndex = null
</code>```

to

```<code>currentObj: null,
currentPropIndex: null
</code>```

Title: Vuelidate deep nested array of strings

Body:
I have data with following structure in my Vue file:

data() {
  return {
    formData: {
      name: 'foo',
      objects: [
        {id: 0, name: 'a', props: []},
        {id: 1, name: 'b', props: ['2', '23']},
        {id: 2, name: 'c', props: ['44']},
        {id: 3, name: 'd', props: []}
      ]
    },
    currentObj = null,
    currentPropIndex = null
  }
}

The number of objects in the array objects is dynamic and so is the props array, where string values maybe added and removed. I need to use Vuelidate to validate each and every value of props array in each and every object when it's changed. So I tried this:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      props: {
        $each: {
          required, numeric, maxLength: maxLength(5)
        }
      }
    }
  }
},

Computed:

propsErrors() {
    const errors = [];
    if ( this.currentObj) {
      // const objIndex = _.findIndex(this.formData.objects, o => o.id === this.currentObj.id)
      if (!this.$v.formData.objects['props'][this.currentPropIndex].$dirty) {
        return errors;
      }
      !this.$v.formData.objects['props'][this.currentPropIndex].maxLength && errors.push('Max 5 digits')
      !this.$v.formData.objects['props'][this.currentPropIndex].required && errors.push('Required')
      !this.$v.formData.objects['props'][this.currentPropIndex].numeric && errors.push('Digits only')
    }
    return errors
  },

And my Vuetify text field:

<v-text-field single-line flat dense required
  v-model="object.props[index]"
  :error-messages="propsErrors"
  label="Prop"
  height="30"
  @click="setCurrents(protocol, index)"
  @blur="$v.formData.protocolPorts['manual_ports'][index].$touch()"
  @input="$v.formData.protocolPorts['manual_ports'][index].$touch()" />

And setCurrents only sets the currently edited object and prop index:

setCurrents (protocol, index) {
    this.currentObj = protocol;
    this.currentPropIndex = index;
  }

Once I test the page and click on the text field, I'm getting this error: Error in render: "TypeError: Cannot read property 'props' of undefined"

I tried to change propsErrors (objIndex is currently commented out in the code above)

this.$v.formData.objects[objIndex]['props'][index].maxLength && errors.push('Max 5 digits')

Text Field (oi stands for object index):

@input="$v.formData.objects[oi].props[index].$touch()"

And validations:

validations: {
  formData: {
    name: { required, maxLength: maxLength(64) },
    objects: {
      required,
      $each: {
        props: {
          $each: {
            required, numeric, maxLength: maxLength(5)
          }
        }
      }
    }
  }
},

Still keep getting errors. Any ideas, please?

Body:
I've never used Vuelidate but I found this example was quite useful and reasonably similar to what you're trying to do https://vuelidate.js.org/#sub-collections-validation

Your data in the Vue instance should be changed from

currentObj = null,
currentPropIndex = null

to

currentObj: null,
currentPropIndex: null


问:
Vertx/RxJava/WebClient/ApiGateway/Reactive
I am working on Apigateway using vert.x and RxJava. I want to send reactive request for 2 Apis, get response from both of them and send combined JSON by HttpServer. But onComplete() executes to early and returns empty JSON. I think the problem arises from asynchronous character of the vert.x but I don't exactly what's wrong.

Here is my method:

```<code>private void dispatchBoth(RoutingContext routingContext) {

    Observer<String> observer = new Observer<String>() {

        JsonArray jsonArray = new JsonArray();

        @Override
        public void onSubscribe(Disposable disposable) {
            System.out.println("Start");

        }

        @Override
        public void onNext(String s) {
            Thread t = new Thread(() -> {
                if(s=="/api/userApi/selectAllUsers") {

                        WebClient client = WebClient.create(vertx);
                            client
                                .get(8081, "localhost", s)
                                .send(ar->{
                                    if (ar.succeeded()) {
                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                        System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });

                }else if(s=="/api/holidayApi/selectAllHolidays") {
                        WebClient client = WebClient.create(vertx);
                        client
                                .get(8080, "localhost", s)
                                .send(ar -> {

                                    if (ar.succeeded()) {

                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                       //  System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });
                    }
                });
                t.start();
        }
        @Override
        public void onError(Throwable throwable) {

        }

        @Override
        public void onComplete() {
                System.out.println(jsonArray.encodePrettily());
                routingContext.response().end(jsonArray.encodePrettily());
        }
    };
    Observable.fromArray(com).subscribe(observer);
}
</code>```

And that's the output I get on the console:

```<code>[ ]
[ {
  "holidayId" : 2,
  "userId" : 3,
  "place" : "Poland",
  "date" : {
    "year" : 2016,
    "month" : "DECEMBER",
    "dayOfMonth" : 29,
    "dayOfWeek" : "THURSDAY",
    "era" : "CE",
    "dayOfYear" : 364,
    "leapYear" : true,
    "monthValue" : 12,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "holidayId" : 10,
  "userId" : 1,
  "place" : "Netherland",
  "date" : {
    "year" : 2020,
    "month" : "JANUARY",
    "dayOfMonth" : 21,
    "dayOfWeek" : "TUESDAY",
    "era" : "CE",
    "dayOfYear" : 21,
    "leapYear" : true,
    "monthValue" : 1,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "userId" : 1,
  "name" : "Kacper",
  "phone_number" : "667667202"
}, {
  "userId" : 3,
  "name" : "Kamil",
  "phone_number" : "6734583443"
}, {
  "userId" : 4,
  "name" : "Janek",
  "phone_number" : "231253575"
}, {
  "userId" : 5,
  "name" : "Grzegorz",
  "phone_number" : "123456789"
}, {
  "userId" : 6,
  "name" : "Justin",
  "phone_number" : "111000111"
}, {
  "userId" : 8,
  "name" : "Mike",
  "phone_number" : "997"
}, {
  "userId" : 9,
  "name" : "Gorge",
  "phone_number" : "991"
} ]
</code>```

答:
onComplete executes on time: when the input flow of strings is finished. You need another way to wait the moment when all I/O operations are completed. This is a tricky part, I do not know if Vertx or RxJava can do this, but standard Java API can, using CompletableFuture.  So we create adapter from CompletableFuture to Handler, which holds the result of one I/O operation:

```<code>class HandelerFuture extends CompletableFuture<JsonArray>
         implements Handler<AsyncResult<HttpResponse<Buffer>>> {
    @Override
    public void handle(AsyncResult<HttpResponse<Buffer>> ar) {
        if (ar.succeeded()) {
            JsonArray array = ar.result().bodyAsJsonArray();
            super.complete(array);
        } else {
            super.completeExceptionally(ar.cause());
        }
    }
}
</code>```

Besides, you need not to wrap the body of onNext method in a Tread. Second, you need not to check what the url string is passed, as it does not make any difference. Third, you use Observer only to handle a list of url strings - this is overcomplication. Plain loop is sufficient.

```<code>CompletableFuture<HandelerFuture[]> dispatchBoth(String... urls) {
    ArrayList<HandelerFuture> futures = new ArrayList<>(); // all results
    for (String url : urls) {
        HandelerFuture future = new HandelerFuture();
        futures.add(future);
        WebClient client = WebClient.create(vertx);
        client.get(8081, "localhost", url)
              .send(future);
    }
    CompletableFuture all = new CompletableFuture();
    HandelerFuture[] array = futures.toArray(new HandelerFuture[0]);
    CompletableFuture.allOf(array)
            .thenRunAsync(() -> all.complete(array));
    return all;
}
</code>```

then it can be run as follows:

```<code>    CompletableFuture<HandelerFuture[]> future = dispatchBoth(com);
    HandelerFuture[] results = future.get();
    JsonArray finalArray;
    for (HandelerFuture result:results) {
        try {
            // extract partial json array
            JsonArray partialArray = result.get();
            // combine partialArray with finalArray somehow
        } catch (Exception e) {
            // this is the exception got in handle() method as ar.cause().
            e.printStackTrace();
        }
    }
    routingContext.response().end(finalArray.encodePrettily());
</code>```

You did not tell how you are going to combine json arrays, so I left this unimplemented.

Body:
I am working on Apigateway using vert.x and RxJava. I want to send reactive request for 2 Apis, get response from both of them and send combined JSON by HttpServer. But onComplete() executes to early and returns empty JSON. I think the problem arises from asynchronous character of the vert.x but I don't exactly what's wrong.

Here is my method:

private void dispatchBoth(RoutingContext routingContext) {

    Observer<String> observer = new Observer<String>() {

        JsonArray jsonArray = new JsonArray();

        @Override
        public void onSubscribe(Disposable disposable) {
            System.out.println("Start");

        }

        @Override
        public void onNext(String s) {
            Thread t = new Thread(() -> {
                if(s=="/api/userApi/selectAllUsers") {

                        WebClient client = WebClient.create(vertx);
                            client
                                .get(8081, "localhost", s)
                                .send(ar->{
                                    if (ar.succeeded()) {
                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                        System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });

                }else if(s=="/api/holidayApi/selectAllHolidays") {
                        WebClient client = WebClient.create(vertx);
                        client
                                .get(8080, "localhost", s)
                                .send(ar -> {

                                    if (ar.succeeded()) {

                                        HttpResponse<Buffer> response = ar.result();

                                        jsonArray.addAll(response.bodyAsJsonArray());
                                       //  System.out.println(jsonArray.encodePrettily());

                                    } else {
                                        System.out.println("Something went wrong " + ar.cause().getMessage());
                                    }
                                });
                    }
                });
                t.start();
        }
        @Override
        public void onError(Throwable throwable) {

        }

        @Override
        public void onComplete() {
                System.out.println(jsonArray.encodePrettily());
                routingContext.response().end(jsonArray.encodePrettily());
        }
    };
    Observable.fromArray(com).subscribe(observer);
}

And that's the output I get on the console:

[ ]
[ {
  "holidayId" : 2,
  "userId" : 3,
  "place" : "Poland",
  "date" : {
    "year" : 2016,
    "month" : "DECEMBER",
    "dayOfMonth" : 29,
    "dayOfWeek" : "THURSDAY",
    "era" : "CE",
    "dayOfYear" : 364,
    "leapYear" : true,
    "monthValue" : 12,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "holidayId" : 10,
  "userId" : 1,
  "place" : "Netherland",
  "date" : {
    "year" : 2020,
    "month" : "JANUARY",
    "dayOfMonth" : 21,
    "dayOfWeek" : "TUESDAY",
    "era" : "CE",
    "dayOfYear" : 21,
    "leapYear" : true,
    "monthValue" : 1,
    "chronology" : {
      "id" : "ISO",
      "calendarType" : "iso8601"
    }
  }
}, {
  "userId" : 1,
  "name" : "Kacper",
  "phone_number" : "667667202"
}, {
  "userId" : 3,
  "name" : "Kamil",
  "phone_number" : "6734583443"
}, {
  "userId" : 4,
  "name" : "Janek",
  "phone_number" : "231253575"
}, {
  "userId" : 5,
  "name" : "Grzegorz",
  "phone_number" : "123456789"
}, {
  "userId" : 6,
  "name" : "Justin",
  "phone_number" : "111000111"
}, {
  "userId" : 8,
  "name" : "Mike",
  "phone_number" : "997"
}, {
  "userId" : 9,
  "name" : "Gorge",
  "phone_number" : "991"
} ]

Body:
onComplete executes on time: when the input flow of strings is finished. You need another way to wait the moment when all I/O operations are completed. This is a tricky part, I do not know if Vertx or RxJava can do this, but standard Java API can, using CompletableFuture.  So we create adapter from CompletableFuture to Handler, which holds the result of one I/O operation:

class HandelerFuture extends CompletableFuture<JsonArray>
         implements Handler<AsyncResult<HttpResponse<Buffer>>> {
    @Override
    public void handle(AsyncResult<HttpResponse<Buffer>> ar) {
        if (ar.succeeded()) {
            JsonArray array = ar.result().bodyAsJsonArray();
            super.complete(array);
        } else {
            super.completeExceptionally(ar.cause());
        }
    }
}

Besides, you need not to wrap the body of onNext method in a Tread. Second, you need not to check what the url string is passed, as it does not make any difference. Third, you use Observer only to handle a list of url strings - this is overcomplication. Plain loop is sufficient.

CompletableFuture<HandelerFuture[]> dispatchBoth(String... urls) {
    ArrayList<HandelerFuture> futures = new ArrayList<>(); // all results
    for (String url : urls) {
        HandelerFuture future = new HandelerFuture();
        futures.add(future);
        WebClient client = WebClient.create(vertx);
        client.get(8081, "localhost", url)
              .send(future);
    }
    CompletableFuture all = new CompletableFuture();
    HandelerFuture[] array = futures.toArray(new HandelerFuture[0]);
    CompletableFuture.allOf(array)
            .thenRunAsync(() -> all.complete(array));
    return all;
}

then it can be run as follows:

    CompletableFuture<HandelerFuture[]> future = dispatchBoth(com);
    HandelerFuture[] results = future.get();
    JsonArray finalArray;
    for (HandelerFuture result:results) {
        try {
            // extract partial json array
            JsonArray partialArray = result.get();
            // combine partialArray with finalArray somehow
        } catch (Exception e) {
            // this is the exception got in handle() method as ar.cause().
            e.printStackTrace();
        }
    }
    routingContext.response().end(finalArray.encodePrettily());

You did not tell how you are going to combine json arrays, so I left this unimplemented.


问:
Check if array of objects key is empty and splice it
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]```
</div>
</div>
</p>

<p>In the above array there is an empty string "key" if the key value is <code>false</code> then need to splice the array of objects using index.</p>

<p>Below is the code which I have tried:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}</code>```

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

答:
If your wanting to do this by mutating the original array using splice.

Make sure you loop the array backwards, this prevents issues of the loop index going out of sync as you mutate the array.

Example below..

const dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
];

for (let ix = dataTobeDeleted.length -1; ix >= 0; ix --) {
  if (!dataTobeDeleted[ix][''])
    dataTobeDeleted.splice(ix, 1);
}

console.log(dataTobeDeleted);```

Body:
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]

In the above array there is an empty string "key" if the key value is false then need to splice the array of objects using index.

Below is the code which I have tried:

for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.


问:
Protractor test does not finish, seems to loop until the jasmine timeout error hits
I feel pretty dumb to not be able to get the most basic protractor test to work. Given protractor 5.4.1 i have a spec.js

```<code>describe('my example tests', () => {
  const EC = protractor.ExpectedConditions;
    it('tests google', async () => {
      await browser.waitForAngularEnabled(false);
      await browser.get("https://google.com");
      await browser.wait(EC.visibilityOf($('input')));
      await element(by.css("input")).click();});});
</code>```

and a conf of

```<code>exports.config = {

  directConnect: true,
  specs: ['tests/**/*.js'],
  capabilities: {
    browserName: 'chrome',
  },

  SELENIUM_PROMISE_MANAGER: false,

  jasmineNodeOpts: {
    defaultTimeoutInterval: 40000
  }
};
</code>```

when running protractor conf.js the browser opens, goes to the page and then nothing happens until the 40s jasmine timeout hits. What I get are ~25 warnings per second

W/element - more than one element found for locator By(css selector, input) - the first result will be used

as if some command is running in an endless loop until I get an error Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. which does not tell me much and is hard to google.

Has anyone experienced this issue?

答:
On the Google page, the locator $('input') matches many elements, which is why you got the warning. The first one was used, but unfortunately, the first one was hidden. so await browser.wait(EC.visibilityOf($('input'))); failed, which gave the timeout error.
Using a locator that locates a unique and not hidden input element on the page, like element(by.name('q')) ought to work better.

I like the Hetzner cloud protractor test helper which provides wrappers like waitToBeDisplayed whose error reporting is less generic, if I recall correctly (it has been a while since I used it).

Body:
I feel pretty dumb to not be able to get the most basic protractor test to work. Given protractor 5.4.1 i have a spec.js

describe('my example tests', () => {
  const EC = protractor.ExpectedConditions;
    it('tests google', async () => {
      await browser.waitForAngularEnabled(false);
      await browser.get("https://google.com");
      await browser.wait(EC.visibilityOf($('input')));
      await element(by.css("input")).click();});});

and a conf of

exports.config = {

  directConnect: true,
  specs: ['tests/**/*.js'],
  capabilities: {
    browserName: 'chrome',
  },

  SELENIUM_PROMISE_MANAGER: false,

  jasmineNodeOpts: {
    defaultTimeoutInterval: 40000
  }
};

when running protractor conf.js the browser opens, goes to the page and then nothing happens until the 40s jasmine timeout hits. What I get are ~25 warnings per second

W/element - more than one element found for locator By(css selector, input) - the first result will be used

as if some command is running in an endless loop until I get an error Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. which does not tell me much and is hard to google.

Has anyone experienced this issue?


问:
ORMLite with CursorAdapter in Android
I am modifying my Android app to work with ORMLite, and it currently uses a number of CursorAdapters, which I quite want to keep in an attempt to minimise coding.

I'm not 100% sure but t appears that when ORMLite creates an id field in the db, it always uses id, whereas CursorAdapter needs _id.

It is possible to get round this using a query like the following:

```<code>select id as _id ......
</code>```

but the Dao.queryRaw() method returns a list, not a Cursor, so the way I have done it is to open another SQLiteOpenHelper database connection and use rawQuery().

This works, but are there any better ways of doing it at all? It seems overkill to have two separate database connections, and perhaps storing up trouble later.

答:
Wrap your cursor with another one that treats "_id" as an alias to your real primary key column. Example:

```<code>cursor = new CursorWrapper(cursor) {
                @Override
                public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
                    if ("_id".equals(columnName)) columnName = "id";
                    return super.getColumnIndexOrThrow(columnName);
                }
            };
</code>```

ContentLicense: CC BY-SA 3.0

Title: ORMLite with CursorAdapter in Android

Body:
I am modifying my Android app to work with ORMLite, and it currently uses a number of CursorAdapters, which I quite want to keep in an attempt to minimise coding.

I'm not 100% sure but t appears that when ORMLite creates an id field in the db, it always uses id, whereas CursorAdapter needs _id.

It is possible to get round this using a query like the following:

select id as _id ......

but the Dao.queryRaw() method returns a list, not a Cursor, so the way I have done it is to open another SQLiteOpenHelper database connection and use rawQuery().

This works, but are there any better ways of doing it at all? It seems overkill to have two separate database connections, and perhaps storing up trouble later.

Body:
Wrap your cursor with another one that treats "_id" as an alias to your real primary key column. Example:

cursor = new CursorWrapper(cursor) {
                @Override
                public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {
                    if ("_id".equals(columnName)) columnName = "id";
                    return super.getColumnIndexOrThrow(columnName);
                }
            };


问:
Is it possible write commentary using SnakeYaml?
I was writing code for studying YAML files, and I'm trying to put a comment in the YAML file, but I just found out that it doesn't work the way it does.

My doubts are:
It is possible to insert comments when writing a document.
Am I doing it right?
If it is not possible with the SnakeYaml API, what other method is more plausible.

Codes

JAVA CODE

```<code>try {

    text = "#Some random Comentary"
         +  "Something: Something\n"
         +  "RandoText: Goes Here\n"
         +  "Number: true\n"
         +  "sometext: Something Else";

    Object obj = writeYaml.load(text);

    FileWriter writer = new FileWriter(directoryPath);

    writeYaml.dump(obj, writer);

} catch (Exception e) {}
</code>```

YAML was create

```<code>{RandoText: Goes Here, Number: true, sometext: Something Else}
</code>```

YAML I want create

```<code>{
      #Some random Comentary
      RandoText: Goes Here,
      Number: true,
      sometext: Something Else
    }
</code>```

答:
I found a solution to this problem, it is not the most plausible but let's get to the result.

I was reading the Snakeyaml documentation (I don't know if it was the official documentation), but it said that the documentation was out of date, so it wasn't much help.

So I decided to write the document by hand, my code ended up being like this:

```<code>try {

    FileWriter fileWriter = new FileWriter("filename.yaml");

    String text = "#Some random Cometary\n"
                + "RandomText: Goes Here,\n"
                + "Number: 10,\n"
                + "isBoolean: true";

    fileWriter.write(text);
    fileWriter.close();

} catch (Exception e) {};
</code>```

But I do not intend to abandon SnakeYaml for now, due to the fact of being able to read Yaml without having to waste time dealing with texot, Snake Yaml already does that, there is no reason to rewrite the text.

However, if someone has any other better method, give me a warning that will always be welcome.

ah! when I forget to say, I tried to make a document clone, but these documents do not go with the jar file when you close the project build.

Body:
I was writing code for studying YAML files, and I'm trying to put a comment in the YAML file, but I just found out that it doesn't work the way it does.

My doubts are:
It is possible to insert comments when writing a document.
Am I doing it right?
If it is not possible with the SnakeYaml API, what other method is more plausible.

Codes

JAVA CODE

try {

    text = "#Some random Comentary"
         +  "Something: Something\n"
         +  "RandoText: Goes Here\n"
         +  "Number: true\n"
         +  "sometext: Something Else";

    Object obj = writeYaml.load(text);

    FileWriter writer = new FileWriter(directoryPath);

    writeYaml.dump(obj, writer);

} catch (Exception e) {}

YAML was create

{RandoText: Goes Here, Number: true, sometext: Something Else}

YAML I want create

{
      #Some random Comentary
      RandoText: Goes Here,
      Number: true,
      sometext: Something Else
    }

Body:
I found a solution to this problem, it is not the most plausible but let's get to the result.

I was reading the Snakeyaml documentation (I don't know if it was the official documentation), but it said that the documentation was out of date, so it wasn't much help.

So I decided to write the document by hand, my code ended up being like this:

try {

    FileWriter fileWriter = new FileWriter("filename.yaml");

    String text = "#Some random Cometary\n"
                + "RandomText: Goes Here,\n"
                + "Number: 10,\n"
                + "isBoolean: true";

    fileWriter.write(text);
    fileWriter.close();

} catch (Exception e) {};

But I do not intend to abandon SnakeYaml for now, due to the fact of being able to read Yaml without having to waste time dealing with texot, Snake Yaml already does that, there is no reason to rewrite the text.

However, if someone has any other better method, give me a warning that will always be welcome.

ah! when I forget to say, I tried to make a document clone, but these documents do not go with the jar file when you close the project build.


问:
Confusion about the scope and visibility of variable and argument in a function
I don't understand why do the test1 and test2 will return 2 different output when they are the same.</p>

```<code>   python3.7.4

   fin=open('D:\Python\Think Python\words.txt')

   def build_list_append(file):
       word_list=[]
       for line in fin:
           word=line.strip()
           word_list.append(word)
       return word_list

   def test1(worklist1=build_list_append(fin)):
       print("This is test1,It will return a non-empty list")
       print(len(worklist1))

   def test2(worklist2=build_list_append(fin)):
       print("This is test2,It will return an empty list")
       print(len(worklist2))

</code>```

答:
Try running the program again, except with the fin = open(...) statement inside the function build_list_append() (make sure to add a fin.close() at the end as well). Then, they'll act the same.

File objects in python (those returned by open()) belong to a class of object called a generator*. Generators are iterable, and lazily return element after element as necessary. What differentiates them from, say, lists, is that you can't go backwards in a generator - you can only ever get the next element. So when you run out of elements, you get nothing.

That's what's happening here. The loop for line in fin exhausts all the elements that the file object can produce, the first time it's executed. When you execute it again, the generator has no more to give, and so the for loop doesn't run, and you get an empty list. Unless you re-create the generator from the start, by calling open() again, it has run out of elements.

*it's more complicated than this, and technically file objects aren't generators, but they act sufficiently similar to draw the comparison.

Body:
I don't understand why do the test1 and test2 will return 2 different output when they are the same.

   python3.7.4

   fin=open('D:\Python\Think Python\words.txt')

   def build_list_append(file):
       word_list=[]
       for line in fin:
           word=line.strip()
           word_list.append(word)
       return word_list

   def test1(worklist1=build_list_append(fin)):
       print("This is test1,It will return a non-empty list")
       print(len(worklist1))

   def test2(worklist2=build_list_append(fin)):
       print("This is test2,It will return an empty list")
       print(len(worklist2))


问:
C# - Finding a string between two strings
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

```<code>int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);
</code>```

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.

答:
You can use a Split method for that and access a second item from the end

var str = "Value->Value2->Value3->ImportantValue->val";
var items = str.Split(new []{"->"}, StringSplitOptions.None);
var importantValue = items[items.Length - 2];
```

C# 8 introduced an new approach for indices, so you can use var importantValue = items[^2]; syntax as well

You also may check a length of resulting array, that it has at least two elements

Body:
I have a string that looks like this: Value->Value2->Value3->ImportantValue->val.

I would like to extract ImportantValue. I have read other posts concerning this question but none of them works for me. I tried this:

int pFrom = path.IndexOf("->") + "->".Length;
int pTo = path.LastIndexOf("->val");
String result = path.Substring(pFrom, pTo - pFrom);

It returns Value2->Value3->ImportantValue->val because it gives out the string between the first -> and ->val. Any ideas on how I would change the above code so that it returns ImportantValue? Thanks in advance.

EDIT

Sorry, I forgot to specify that ImportantValue is always different. The entire string also changes, meaning it will have more three Values. But the ImportantValue is always the second to last element so I will mark the answer from Paul Kertscher as the right one and upvote the other similar answers.

Body:
You can use a Split method for that and access a second item from the end

var str = "Value->Value2->Value3->ImportantValue->val";
var items = str.Split(new []{"->"}, StringSplitOptions.None);
var importantValue = items[items.Length - 2];

C# 8 introduced an new approach for indices, so you can use var importantValue = items[^2]; syntax as well

You also may check a length of resulting array, that it has at least two elements


问:
Russian language in e-TextEditor or Cygwin
I'm using e-TextEditor for some tasks and can't figure, why when i using some Russian text and process it in bundle script i'm always getting something like http://gyazo.com/f38c69babe1f95ff786711fe684aee77.png . I'm think this is cygwin bug, because webkit must render it correct in UTF-8 encoding. I'm tested some guides thats describes how to enable correct Russian encoding in cygwin, but with no results. I'm running Windows 7 x64.</p>

答:
I HAD problem visualising Russian text from a program running on Windows Pro 10. I just open control, clock & regions, region and administrative. When yo see "Language for non-Unicode programs" just click "Change system locale..." and select the language. Restart computer and this is all.

I can see Russian text in software installed on Windows 10 Pro and the operating systems keeps same language; in my case English.

ContentLicense: CC BY-SA 2.5


问:
Flutter State Management (BloC): Stateless vs Stateful widget
So I am reading through Bloc for state management for flutter.

Since Bloc allows you to sink and stream (rebuilding a widget based on the input), then is it possible to build an app mostly with stateless widgets?

As an example, let say I make lots of single stateless class widgets, thus almost everything is compartmentalized into its own stateless widget.

With the Bloc state management, I could simply rebuild a certain stateless child widget to reflect the change.

In this approach, I don't see the need of using the stateful widget. Of course, being a total beginner in flutter, I wanted to hear if this approach has any merit to it.

Is this a good approach? Any info will be much appreciated.

答:
You can use only Stateless Widget. But there is one problem that you should close streams before the app is disposed of. It can be handled in two ways:

First, you can use a Stateful widget and close streams of bloc in the dispose method of stateful.

Using BlocProvider. In this case, Bloc Provider is a Stateful widget only. It closes streams automatically. Then you can use bloc using BlocProvider in Stateless Widget.

But it doesn't mean that we don't need stateful widgets. Stateful widgets are important in animation for example. Animation, text input or any local changes in the widget itself shouldn't be handled in bloc or other state management. it is the duty of widget itself.


问:
unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /var/lib/snapd/void/Dockerfile: no such file or directory
I installed docker on Ubuntu with snap (snappy?), and then I ran this:

```<code>ln -sf /usr/bin/snap /usr/local/bin/docker
</code>```

when I run docker build I get:

```<code>unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /var/lib/snapd/void/Dockerfile: no such file or
</code>```

directory

答:
I've got the same error using Ubuntu, and I noticed that I had installed the wrong  Docker.
Instead of (docker - transitional package) install (docker.io - Linux container runtime)</p>

```<code>apt install docker.io
</code>```

Body:
I installed docker on Ubuntu with snap (snappy?), and then I ran this:

ln -sf /usr/bin/snap /usr/local/bin/docker

when I run docker build I get:

unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /var/lib/snapd/void/Dockerfile: no such file or

directory

Body:
I've got the same error using Ubuntu, and I noticed that I had installed the wrong  Docker.
Instead of (docker - transitional package) install (docker.io - Linux container runtime)

apt install docker.io


问:
How to assign colors to table cells depending on their values in Spotfire

Spotfire

I created a cross table in Spotfire as below.

I want to create the same table using html in text area.
I created the table and added values using calculated values.But I have no idea how to set the background color dynamically.

＜TD style="HEIGHT: 21px; WIDTH: 248px; PADDING-LEFT: 20px;" bgcolor={Drop Down List value or Calculated Value}>45＜/TD＞

Color rules are as below.

Red= Production≧50

Yellow=　50＞Production≧30

Green=   Production＜40

Any Idea?

Thanks for your support in advance.

答:
If you have multiple rows and cells to be populated with color, you can do some sample like this

function refreshWidth() {

    $('#table_id td.y_n').each(function(){
        if ($(this).text() == 'N') {
            $(this).css('background-color','#f00');
        }
        else if ($(this).text() == 'Y') {
            $(this).css('background-color','green');
        }
    });
}

//MutationObserver to refresh when needed. Works better than running every second as that causes issues with exporting in newer versions of Spotfire
var target = document.getElementById('watcher');
var observer = new MutationObserver(refreshWidth);
var config = { attributes: true, childList: true, characterData: true, subtree: true};
observer.observe(target, config);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="watcher">

<table id="table_id">
 <tr><th>Question</th><th>Y/N?</th></tr>
 <tr><td>I am me.</td><td class="y_n"><SpotfireControl id="2bb8174ce9a8465a84be2ef7c0eb2797" /></td></tr>
 <tr><td>I am him.</td><td class="y_n"><SpotfireControl id="9ef686aa45d847ee98fafb94c7dfe880" /></td></tr>
 <tr><td>I am not sure.</td><td class="y_n"><SpotfireControl id="e8ceaec4965c480587bbf352e46e7d2a" /></td></tr>
 <tr><td>This is a table.</td><td class="y_n"><SpotfireControl id="67b9c407bef24eb888ece4875b5807c2" /></td></tr>

</table>

</div></code>```

Body:
If you have multiple rows and cells to be populated with color, you can do some sample like this

function refreshWidth() {

    $('#table_id td.y_n').each(function(){
        if ($(this).text() == 'N') {
            $(this).css('background-color','#f00');
        }
        else if ($(this).text() == 'Y') {
            $(this).css('background-color','green');
        }
    });
}

//MutationObserver to refresh when needed. Works better than running every second as that causes issues with exporting in newer versions of Spotfire
var target = document.getElementById('watcher');
var observer = new MutationObserver(refreshWidth);
var config = { attributes: true, childList: true, characterData: true, subtree: true};
observer.observe(target, config);

<div id="watcher">

<table id="table_id">
 <tr><th>Question</th><th>Y/N?</th></tr>
 <tr><td>I am me.</td><td class="y_n"><SpotfireControl id="2bb8174ce9a8465a84be2ef7c0eb2797" /></td></tr>
 <tr><td>I am him.</td><td class="y_n"><SpotfireControl id="9ef686aa45d847ee98fafb94c7dfe880" /></td></tr>
 <tr><td>I am not sure.</td><td class="y_n"><SpotfireControl id="e8ceaec4965c480587bbf352e46e7d2a" /></td></tr>
 <tr><td>This is a table.</td><td class="y_n"><SpotfireControl id="67b9c407bef24eb888ece4875b5807c2" /></td></tr>

</table>

</div>


问:
Javadoc error on @RequiredArgsConstructor(onConstructor=@__(@Inject))
I am trying to generate the javadoc using JDK 8 for a bunch of codes using lombok.

I am getting the error below:

```<code>error: cannot find symbol
[ERROR] @RequiredArgsConstructor(onConstructor=@__(@Inject))
[ERROR] ^
[ERROR] symbol: class __
</code>```

Any advice will be much appreciated on how to resolve the error above.

Update: the error is happening using the maven javadoc plugin configured as below:

```<code>        <plugin>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>2.10.3</version>
            <!--
            <configuration>
                <doclet>ch.raffael.doclets.pegdown.PegdownDoclet</doclet>
                <docletArtifact>
                    <groupId>ch.raffael.pegdown-doclet</groupId>
                    <artifactId>pegdown-doclet</artifactId>
                    <version>1.1.1</version>
                </docletArtifact>
                <useStandardDocletOptions>true</useStandardDocletOptions>
            </configuration>
            -->
        </plugin>
</code>```

答:
Adding here just for future reference as on my case I was trying to build on Intelij and the error was due to compiler annotation processors being disabled.

To enable it, go to Intelij preferences, open "Build, Execution, Deployment" -> "Compiler" -> "Annotation Processors" and make sure "Enable annotation processing" is enabled

Body:
I am trying to generate the javadoc using JDK 8 for a bunch of codes using lombok.

I am getting the error below:

error: cannot find symbol
[ERROR] @RequiredArgsConstructor(onConstructor=@__(@Inject))
[ERROR] ^
[ERROR] symbol: class __

Any advice will be much appreciated on how to resolve the error above.

Update: the error is happening using the maven javadoc plugin configured as below:

        <plugin>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>2.10.3</version>

        </plugin>


问:
Select rows with max(id) having max(payment_date)
I've been trying to get the max(id) for the max(payment_date) of every account_id, as there are instances where there's different entries for the same max(payment_date). The ids are the payment references for the account_ids. So every account_id needs to have one entry with the max(payment_date) and the max(id) for that date. Problem is that there are entries where the max(id) for the account_id is not for the max(payment_date), or I would have just used max(id). The code below is not working because of this, since it will exclude entries where the max(id) is not for the max(payment_date). Thanks in advance.</p>

```<code>select *
from (
  select payments.*
  from (
    select account_id, max(payment_date) as last_payment, max(id) as last_payment1
    from energy.payments
    where state = 'success'
      and amount_pennies > 0
      and description not ilike '%credit%'
      group by account_id
  ) as last_payment_table
  inner join energy.payments as payments
         on payments.account_id = last_payment_table.account_id
        and payments.payment_date = last_payment_table.last_payment
        and payments.id = last_payment_table.last_payment1
) as paymentst1
</code>```

答:
Use distinct on.  I can't really follow your query (sample data is such a big help!)  But the idea is:

```<code>select distinct on (p.account_id) p.*
from energy.payments p
order by p.account_id, p.payment_date desc, p.id desc;
</code>```

You can add additional logic for filtering or whatever.  That logic is not explained in your question but is suggested by the code you've included.

Body:
I've been trying to get the max(id) for the max(payment_date) of every account_id, as there are instances where there's different entries for the same max(payment_date). The ids are the payment references for the account_ids. So every account_id needs to have one entry with the max(payment_date) and the max(id) for that date. Problem is that there are entries where the max(id) for the account_id is not for the max(payment_date), or I would have just used max(id). The code below is not working because of this, since it will exclude entries where the max(id) is not for the max(payment_date). Thanks in advance.

select *
from (
  select payments.*
  from (
    select account_id, max(payment_date) as last_payment, max(id) as last_payment1
    from energy.payments
    where state = 'success'
      and amount_pennies > 0
      and description not ilike '%credit%'
      group by account_id
  ) as last_payment_table
  inner join energy.payments as payments
         on payments.account_id = last_payment_table.account_id
        and payments.payment_date = last_payment_table.last_payment
        and payments.id = last_payment_table.last_payment1
) as paymentst1

Body:
Use distinct on.  I can't really follow your query (sample data is such a big help!)  But the idea is:

select distinct on (p.account_id) p.*
from energy.payments p
order by p.account_id, p.payment_date desc, p.id desc;

You can add additional logic for filtering or whatever.  That logic is not explained in your question but is suggested by the code you've included.


问:
Get height and width of a layout programmatically
I have designed an layout in which LinearLayout has 2 children LinearLayout and FrameLayout and in each child I put different views.

I just wanted to measure height and width of FrameLayout so that I could serve my purpose.

In program I am using

```<code>int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getHeight();
width=fr.getWidth();
</code>```

returns value as 0 for both

Even I tried with following code
int height,width;

```<code>FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getMeasuredHeight();
width=fr.getMeasuredWidth();
</code>```

returns same value 0

and finally I tried with following code,
int height,width;

```<code>FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getgetLayoutParams().height();
width=fr.getLayoutParams().width;
</code>```

returns me -2 and -1

I want the solution to get height and width of any layout programmatically?

答:
Just wanted to add an answer here, since Koltin has some convenience methods to do this, which are a lot less ugly than adding and removing a onGlobalLayoutListener:

```<code>view.doOnLayout {
    it.measuredWidth
    it.measuredHeight
}
</code>```

You can see more of the convinience methods here.

Body:
I have designed an layout in which LinearLayout has 2 children LinearLayout and FrameLayout and in each child I put different views.

I just wanted to measure height and width of FrameLayout so that I could serve my purpose.

In program I am using

int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getHeight();
width=fr.getWidth();

returns value as 0 for both

Even I tried with following code
int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getMeasuredHeight();
width=fr.getMeasuredWidth();

returns same value 0

and finally I tried with following code,
int height,width;

FrameLayout fr=(FrameLayout)findviewbyid(R.id.fr);
height=fr.getgetLayoutParams().height();
width=fr.getLayoutParams().width;

returns me -2 and -1

I want the solution to get height and width of any layout programmatically?

Body:
Just wanted to add an answer here, since Koltin has some convenience methods to do this, which are a lot less ugly than adding and removing a onGlobalLayoutListener:

view.doOnLayout {
    it.measuredWidth
    it.measuredHeight
}

You can see more of the convinience methods here.


问:
Force the source url to download automatically by adding the url headers
I have a source URL that displays the pdf document in the browser. It supposes to download automatically.

Sample URL : http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf

Exactly I want to implement how amazon s3 temporary url works (they added all the headers in the url)

response-content-disposition=attachment

Please don't suggest me to use the following code, as front-end expect an URL

```<code>header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);
</code>```

答:
I believe this is a function of your browser instead of the actual code. Most modern browsers have a function to automatically open up PDF's inside a browser window. This setting is specific to your browser.

Google Chrome:

Settings -> Site Settings -> PDF Documents

Body:
I have a source URL that displays the pdf document in the browser. It supposes to download automatically.

Sample URL : http://doc.local.com/storage/temporary/2020-02-19/c3e175b4706492be8c0d90e497c86ea7/test.pdf

Exactly I want to implement how amazon s3 temporary url works (they added all the headers in the url)

response-content-disposition=attachment

Please don't suggest me to use the following code, as front-end expect an URL

header("Content-Length: " . filesize($file));
header("Content-Type: application/octet-stream;");
readfile($file);


问:
Move cursor to end of file in vim
When I want the cursor to go to the end of the file (i.e. the end of the last line) in Vim, I have to type six keystrokes:

<ESC>G$a - which translates to ESC + Shiftg + Shift4 + a on my keyboard layout.

How can I do this more efficiently?

Since I regularly work on many different machines, I cannot always change .vimrc, so I'm looking for answers without having to edit or create that file.

答:
Go to Top     - Double g

Go to Bottom  - Shift + g

Title: Move cursor to end of file in vim


问:
Value repeated while XML to Dataframe parsing
The purpose of the code is to take elements from xml files and parse them into a csv file.

Lately I have updated the code so the codes goes to Phones (another child of ProjectData) takes elements from Set and Get attaches them together with underscore and parses them into the first column with the header name Identify
This is my code

```<code>from xml.etree import ElementTree as ET
from collections import defaultdict
from pathlib import Path
import csv
from pathlib import Path

directory = 'C:/Users/TRY/try.xml'

with open('try.csv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter=';')
   #◙ writer = csv.writer(f)

    headers = ['identify','id', 'service_code', 'rational', 'qualify', 'description_num', 'description_txt','Counter', 'set_data_xin', 'set_data_xax', 'set_data_value', 'set_data_x']

    writer.writerow(headers)

    xml_files_list = list(map(str,Path(directory).glob('**/*.xml')))
    for xml_file in xml_files_list:
        tree = ET.parse(xml_file)
        root = tree.getroot()
        p_get = tree.find('.//Phones/Get').text
        p_set = tree.find('.//Phones/Set').text

        start_nodes = root.findall('.//START')
        for sn in start_nodes:
            row = defaultdict(str)

            # <<<<< Indentation was wrong here
            for k,v in sn.attrib.items():
                row[k] = v
            for rn in sn.findall('.//Rational'):
                row['Rational'] = rn.text

            for qu in sn.findall('.//Qualify'):
                row['Qualify'] = qu.text

            for ds in sn.findall('.//Description'):
                row['Description_txt'] = ds.text
                row['Description_text_id'] = ds.attrib['text_id']

            for counter, st in enumerate( sn.findall('.//SetData') ):
                for k,v in st.attrib.items():
                    if v.startswith("-"):
                        v = v.replace("-","",1)
                    v=v.replace(',', '.')
                    row['SetData_'+ str(k)] = v
                row["Counter"] = counter
                row_data = [row[i] for i in headers]
                row_data[0]=p_get + '_' + p_set
                writer.writerow(row_data)
                row = defaultdict(str)

</code>```

This is the xml file

<?xml version="1.0" encoding="utf-8"?>
<ProjectData>
 <Phones>
    <Date />
    <Prog />
    <Box />
    <Feature />
    <IN>MAFWDS</IN>
    <Set>234234</Set>
    <Pr>23423</Pr>
    <Number>afasfhrtv</Number>
    <Simple>dfasd</Simple>
    <Nr />
    <Get>6070106091</Get>
    <Reno>1233</Reno>
  </Phones>
<FINAL>
    <START id="B001" service_code="0x5196">
      <Docs Docs_type="START">
        <Rational>225196</Rational>
        <Qualify>6251960000A0DE</Qualify>
      </Docs>
      <Description num="1213f2312">The parameter</Description>
      <DataFile dg="12" dg_id="let">
        <SetData value="32" />
      </DataFile>
    </START>
    <START id="C003" service_code="0x517B">
      <Docs Docs_type="START">
        <Rational>23423</Rational>
        <Qualify>342342</Qualify>
      </Docs>
      <Description num="3423423f3423">The third</Description>
      <DataFile dg="55" dg_id="big">
        <SetData x="E1" value="21259" />
        <SetData x="E2" value="02" />
      </DataFile>
    </START>
    <START id="Z048" service_code="0x5198">
      <RawData rawdata_type="ASDS">
        <Rational>225198</Rational>
        <Qualify>3432433</Qualify>
      </RawData>
      <Description num="434234234">The forth</Description>
      <DataFile unit="21" unit_id="FEDS">
        <FileX unit="eg" discrete="false" axis_pts="19" name="Vsome" text_id="bx5" unit_id="GDFSD" />
        <SetData xin="5" xax="233" value="323" />
        <SetData xin="123" xax="77" value="555" />
        <SetData xin="17" xax="65" value="23" />
      </DataFile>
    </START>
</FINAL>
</ProjectData>

```

The output looks like this and how it should look like.

The problem is that the column identify is being repeated. I want so it doesn’t repeat.
I have tried to play with the code and move this variable around the code but no success, finding it hard to solve this problem since column is composed from elements of another child of the xml file.

答:
Your code sets row_data[0] per each row_data which is written to the csv file, and because of that it is repeated on each line in the csv file.

If you want to only see it once per original row, you must set it directly in row before the inner loop for counter, st in enumerate( sn.findall('.//SetData') ):

For example:

```<code>        row['identify']=p_get + '_' + p_set
        for counter, st in enumerate( sn.findall('.//SetData') ):
            for k,v in st.attrib.items():
                if v.startswith("-"):
                    v = v.replace("-","",1)
                v=v.replace(',', '.')
                row['SetData_'+ str(k)] = v
            row["Counter"] = counter
            row_data = [row[i] for i in headers]
            writer.writerow(row_data)
            row = defaultdict(str)
</code>```

Body:
The purpose of the code is to take elements from xml files and parse them into a csv file.

Lately I have updated the code so the codes goes to Phones (another child of ProjectData) takes elements from Set and Get attaches them together with underscore and parses them into the first column with the header name Identify
This is my code

from xml.etree import ElementTree as ET
from collections import defaultdict
from pathlib import Path
import csv
from pathlib import Path

directory = 'C:/Users/TRY/try.xml'

with open('try.csv', 'w', newline='') as f:
    writer = csv.writer(f, delimiter=';')
   #◙ writer = csv.writer(f)

    headers = ['identify','id', 'service_code', 'rational', 'qualify', 'description_num', 'description_txt','Counter', 'set_data_xin', 'set_data_xax', 'set_data_value', 'set_data_x']

    writer.writerow(headers)

    xml_files_list = list(map(str,Path(directory).glob('**/*.xml')))
    for xml_file in xml_files_list:
        tree = ET.parse(xml_file)
        root = tree.getroot()
        p_get = tree.find('.//Phones/Get').text
        p_set = tree.find('.//Phones/Set').text

        start_nodes = root.findall('.//START')
        for sn in start_nodes:
            row = defaultdict(str)

            # <<<<< Indentation was wrong here
            for k,v in sn.attrib.items():
                row[k] = v
            for rn in sn.findall('.//Rational'):
                row['Rational'] = rn.text

            for qu in sn.findall('.//Qualify'):
                row['Qualify'] = qu.text

            for ds in sn.findall('.//Description'):
                row['Description_txt'] = ds.text
                row['Description_text_id'] = ds.attrib['text_id']

            for counter, st in enumerate( sn.findall('.//SetData') ):
                for k,v in st.attrib.items():
                    if v.startswith("-"):
                        v = v.replace("-","",1)
                    v=v.replace(',', '.')
                    row['SetData_'+ str(k)] = v
                row["Counter"] = counter
                row_data = [row[i] for i in headers]
                row_data[0]=p_get + '_' + p_set
                writer.writerow(row_data)
                row = defaultdict(str)

This is the xml file

<?xml version="1.0" encoding="utf-8"?>
<ProjectData>
 <Phones>
    <Date />
    <Prog />
    <Box />
    <Feature />
    <IN>MAFWDS</IN>
    <Set>234234</Set>
    <Pr>23423</Pr>
    <Number>afasfhrtv</Number>
    <Simple>dfasd</Simple>
    <Nr />
    <Get>6070106091</Get>
    <Reno>1233</Reno>
  </Phones>
<FINAL>
    <START id="B001" service_code="0x5196">
      <Docs Docs_type="START">
        <Rational>225196</Rational>
        <Qualify>6251960000A0DE</Qualify>
      </Docs>
      <Description num="1213f2312">The parameter</Description>
      <DataFile dg="12" dg_id="let">
        <SetData value="32" />
      </DataFile>
    </START>
    <START id="C003" service_code="0x517B">
      <Docs Docs_type="START">
        <Rational>23423</Rational>
        <Qualify>342342</Qualify>
      </Docs>
      <Description num="3423423f3423">The third</Description>
      <DataFile dg="55" dg_id="big">
        <SetData x="E1" value="21259" />
        <SetData x="E2" value="02" />
      </DataFile>
    </START>
    <START id="Z048" service_code="0x5198">
      <RawData rawdata_type="ASDS">
        <Rational>225198</Rational>
        <Qualify>3432433</Qualify>
      </RawData>
      <Description num="434234234">The forth</Description>
      <DataFile unit="21" unit_id="FEDS">
        <FileX unit="eg" discrete="false" axis_pts="19" name="Vsome" text_id="bx5" unit_id="GDFSD" />
        <SetData xin="5" xax="233" value="323" />
        <SetData xin="123" xax="77" value="555" />
        <SetData xin="17" xax="65" value="23" />
      </DataFile>
    </START>
</FINAL>
</ProjectData>

The output looks like this and how it should look like.

The problem is that the column identify is being repeated. I want so it doesn’t repeat.
I have tried to play with the code and move this variable around the code but no success, finding it hard to solve this problem since column is composed from elements of another child of the xml file.

Body:
Your code sets row_data[0] per each row_data which is written to the csv file, and because of that it is repeated on each line in the csv file.

If you want to only see it once per original row, you must set it directly in row before the inner loop for counter, st in enumerate( sn.findall('.//SetData') ):

For example:

        row['identify']=p_get + '_' + p_set
        for counter, st in enumerate( sn.findall('.//SetData') ):
            for k,v in st.attrib.items():
                if v.startswith("-"):
                    v = v.replace("-","",1)
                v=v.replace(',', '.')
                row['SetData_'+ str(k)] = v
            row["Counter"] = counter
            row_data = [row[i] for i in headers]
            writer.writerow(row_data)
            row = defaultdict(str)


问:
How can i deploy angular app as https://USERNAME.github.io on Github Pages
I am trying to create a portfolio with angular and deploying it on my user github page (username.github.io), but I'm not being able to make it work...

Steps I'm doing:

1- Created a repository called "username.github.io" on my github root;

2- ng new portfolio --dir=.  (So the project will be created on the "username.github.io folder");

3- Changing "angular.json" file so the outputPath is "dist/" only, removing the work portfolio from it;

4- ng build --base-href=https://username.github.io/;

5- ngh;

6- Commit and push changes to master;

No error messages show up, but then when i try to reach the url "username.github.io" it shows up error 404.

I've tried a bunch of different configurations and each time a different thing happens. On github my repo is configurated to use the master branch (this is the default configuration and can't be changed for user pages).

EDIT:

You can check you it on: https://arthurobdfv.github.io/

And the repo: https://github.com/Arthurobdfv/arthurobdfv.github.io

答:
With the help of this wonderful community I got it working by addind the "branch" option on the ngh command!!!

For users and organization pages, differently from a project page, github looks for the compiled and built files on the master branch, and the ngh command makes the build available on the "gh-pages" branch by default.


问:
Java program using gnome-java will not compile
When trying to compile this small Java program to make use of the Notifier class from java-gnome (built from latest bzr branch):

```<code>import org.gnome.notify;

class Notifier {

public void Main(String[] args) {

        Notification n = new Notification("Test notification", "Blah.", "");
        n.setTimeout(2000);
        n.show();

    }
}
</code>```

I get the following output when compiling with:

```<code>$ javac -cp .:/usr/local/share/java/gtk-4.0.jar Notifier.java

Notifier.java:1: package org.gnome does not exist
import org.gnome.notify;
            ^
Notifier.java:7: cannot find symbol
symbol  : class Notification
location: class Notifier
Notification n = new Notification("Test notification", "Blah.", "");
    ^
Notifier.java:7: cannot find symbol
symbol  : class Notification
location: class Notifier
Notification n = new Notification("Test notification", "Blah.", "");
                         ^
3 errors
</code>```

/usr/local/share/java/gtk-4.0.jar definately exists at that location and does contain the used classes. What is wrong? Many thanks.

答:
Perhaps this is just a typo in your question, but the import line should read:

```<code>import org.gnome.notify.*;
</code>```

Note the trailing asterisk.

Also, your main method should be static.

Body:
When trying to compile this small Java program to make use of the Notifier class from java-gnome (built from latest bzr branch):

import org.gnome.notify;

class Notifier {

public void Main(String[] args) {

        Notification n = new Notification("Test notification", "Blah.", "");
        n.setTimeout(2000);
        n.show();

    }
}

I get the following output when compiling with:

$ javac -cp .:/usr/local/share/java/gtk-4.0.jar Notifier.java

Notifier.java:1: package org.gnome does not exist
import org.gnome.notify;
            ^
Notifier.java:7: cannot find symbol
symbol  : class Notification
location: class Notifier
Notification n = new Notification("Test notification", "Blah.", "");
    ^
Notifier.java:7: cannot find symbol
symbol  : class Notification
location: class Notifier
Notification n = new Notification("Test notification", "Blah.", "");
                         ^
3 errors

/usr/local/share/java/gtk-4.0.jar definately exists at that location and does contain the used classes. What is wrong? Many thanks.

Body:
Perhaps this is just a typo in your question, but the import line should read:

import org.gnome.notify.*;

Note the trailing asterisk.

Also, your main method should be static.


问:
$merge is saving only one document not all the fetched document: mongodb
Here is my query

```<code> db.orders.aggregate([
                {
                '$match': {
                         'date': ISODate("2020-02-11T18:30:00Z")
                }},
                {
                '$unwind': {
                        'path': '$orders',
                 }},
                {
                 $lookup:
                   {
                        from: 'retailprice',
                        let: { productCode: '$orders.productCode' },
                        pipeline: [
                        {
                                $match: {
                                frequency: 'FR',
                                $expr: {
                                        $eq: ["$productCode", "$$productCode"]
                                     }
                                  }
                        }
                        ], as: 'retailprices'
                    }
                },
                { '$unwind': '$retailprice' },
              {
                $lookup:
                     {
                        from: 'discounts',
                        let: { productCode: '$orders.productCode' },
                        pipeline: [
                        {
                                $match: {
                                frequency: 'FR',
                                $expr: {
                                        $eq: ["$productCode", "$$productCode"]
                                }
                             }
                        }
                        ], as: 'discounts'
                }},
                { '$unwind': '$discounts' },
                {
                        '$project':{
                        'productCode':'$orders.productCode' ,
                        'vendorId':'$vendorId',
                        'dealerId':'$dealerId',
                        'quantity':'$orders.quantity'
                        }
                },{'$merge':'test'}
        ]).pretty()
</code>```

So the output of this query without {'$merge':'test'} is :

```<code> {
    "_id" : ObjectId("5e3a710af2657521e8c5668a"),
    "productCode" : "TCE1",
    "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
    "quantity" : 30,
   }
 {
    "_id" : ObjectId("5e3a710af2657521e8c5668a"),
    "productCode" : "ECE1",
    "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
    "quantity" : 67,
   }
</code>```

But when I use {'$merge':'test'} to save the output into the new collection it saves only one document which is:

```<code>{
    "_id" : ObjectId("5e3a710af2657521e8c5668a"),
    "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
    "productCode" : "ECE1",
    "quantity" : 67,
    "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07")
 }
</code>```

Now why is this? I assume its because "_id":ObjectId("5e3a710af2657521e8c5668a") is same in both the documents if the query output is checked, if that's the case how it can be tackled. How can both the documents be saved using $merge, I do not want to use $out as it replaces the whole document whenever the query is run again or rather how can i save all the fetched documents into a new collection

答:
You're assuming right when thinking about an _id issue : the $unwind stage produce one document per array element, all with the same _id (which is, as other fields, replicated from the original document)
And the trick is... very simple! Add "_id":0 to your $project stage. Then mongodb will create a new _id on $merge insertion.

```<code>...
        {
                '$project':{
                '_id':0,
                'productCode':'$orders.productCode' ,
                'vendorId':'$vendorId',
                'dealerId':'$dealerId',
                'quantity':'$orders.quantity'
                }
        },
...
</code>```

But notice that with that way, mongoDB will allways create new insertion, and never update an existing one. If you need more precise behaviour, check the $merge optionnal properties

Body:
Here is my query

 db.orders.aggregate([
                {
                '$match': {
                         'date': ISODate("2020-02-11T18:30:00Z")
                }},
                {
                '$unwind': {
                        'path': '$orders',
                 }},
                {
                 $lookup:
                   {
                        from: 'retailprice',
                        let: { productCode: '$orders.productCode' },
                        pipeline: [
                        {
                                $match: {
                                frequency: 'FR',
                                $expr: {
                                        $eq: ["$productCode", "$$productCode"]
                                     }
                                  }
                        }
                        ], as: 'retailprices'
                    }
                },
                { '$unwind': '$retailprice' },
              {
                $lookup:
                     {
                        from: 'discounts',
                        let: { productCode: '$orders.productCode' },
                        pipeline: [
                        {
                                $match: {
                                frequency: 'FR',
                                $expr: {
                                        $eq: ["$productCode", "$$productCode"]
                                }
                             }
                        }
                        ], as: 'discounts'
                }},
                { '$unwind': '$discounts' },
                {
                        '$project':{
                        'productCode':'$orders.productCode' ,
                        'vendorId':'$vendorId',
                        'dealerId':'$dealerId',
                        'quantity':'$orders.quantity'
                        }
                },{'$merge':'test'}
        ]).pretty()

So the output of this query without {'$merge':'test'} is :

 {
    "_id" : ObjectId("5e3a710af2657521e8c5668a"),
    "productCode" : "TCE1",
    "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
    "quantity" : 30,
   }
 {
    "_id" : ObjectId("5e3a710af2657521e8c5668a"),
    "productCode" : "ECE1",
    "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07"),
    "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
    "quantity" : 67,
   }

But when I use {'$merge':'test'} to save the output into the new collection it saves only one document which is:

{
    "_id" : ObjectId("5e3a710af2657521e8c5668a"),
    "dealerId" : ObjectId("5e1d82156a67173cb877f67d"),
    "productCode" : "ECE1",
    "quantity" : 67,
    "vendorId" : ObjectId("5e3d05ba964d0e06c4bb0f07")
 }

Now why is this? I assume its because "_id":ObjectId("5e3a710af2657521e8c5668a") is same in both the documents if the query output is checked, if that's the case how it can be tackled. How can both the documents be saved using $merge, I do not want to use $out as it replaces the whole document whenever the query is run again or rather how can i save all the fetched documents into a new collection

Body:
You're assuming right when thinking about an _id issue : the $unwind stage produce one document per array element, all with the same _id (which is, as other fields, replicated from the original document)
And the trick is... very simple! Add "_id":0 to your $project stage. Then mongodb will create a new _id on $merge insertion.

...
        {
                '$project':{
                '_id':0,
                'productCode':'$orders.productCode' ,
                'vendorId':'$vendorId',
                'dealerId':'$dealerId',
                'quantity':'$orders.quantity'
                }
        },
...

But notice that with that way, mongoDB will allways create new insertion, and never update an existing one. If you need more precise behaviour, check the $merge optionnal properties


问:
Sort Data By the 2nd Last Letter in a cell then the first- Google Apps Script / Google Sheets
In the image shown (highlighted Bright Green G:H), I would have liked to sort the data according to the 2nd last letter - not the first. This would have meant F01A1 should have been appeared higher in list than E09C1, and then would have been selected in the A column.

How could I have the data Sorted by 2nd Last Letter in Cell, in Column G:H ?

答:
try in row 1:</p>

```<code>=ARRAYFORMULA(QUERY({G:H, RIGHT(H:H, 2)}, "select Col1,Col2 order by Col3", 0))
</code>```

Body:
try in row 1:

=ARRAYFORMULA(QUERY({G:H, RIGHT(H:H, 2)}, "select Col1,Col2 order by Col3", 0))