问:
how can route an array as a parameter in angular?
I configured routing module as following:

const routes: Routes = [
  {
    path: "engineering/:branches",
    component: BranchesTabsComponent
  },
  {
    path: "humanities/:branches",
    component: BranchesTabsComponent
  },
];```
</div>
</div>
</p>
<p>and in the main-continer.component.ts:</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>titlesOfEngineeringTabs: string[] = ['E1','E2','E3'];
titlesOfHumanitiesTabs: string[] = ['H1','H2'];

constructor(private router: Router) {}

handleEnginTabs():void{
    this.router.navigate(['/engineering', this.titlesOfEngineeringTabs]);
}
handleHumanTabs():void{
    this.router.navigate(['/humanities', this.titlesOfHumanitiesTabs]);
}</code>```

and also main-continer.component.html contains:

<router-outlet></router-outlet>```
</div>
</div>
</p>
<p>and then in branches-tabs.component.ts have:</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>tabsLable: string[] = [''];

ngOnInit(): void {
     this.route.params.subscribe(param => this.tabsLable = param["branches"]);
}</code>```

till here, it is obvious that we want to replace <router-outlet> with branches-tabs component in which deferent tab labels are shown Depending on selected menu...
but I get this error:

```<code>*core.mjs:6485 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'
Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'*
</code>```

how can pass a string array as parameter and fix above error?
best regards

答:
Angular docs on navigate()

An array of URL fragments with which to construct the target URL. If
the path is static, can be the literal URL string. For a dynamic
path, pass an array of path segments, followed by the parameters for
each segment. The fragments are applied to the current URL or the
one provided in the relativeTo property of the options object, if
supplied.

If your intent is to have the url look like /engineering/E1/E2/E3 then you should apply the spread operator ... to the arrays and it would look like:

```<code>this.router.navigate(['/engineering', ...this.titlesOfEngineeringTabs]);
</code>```

Body:
I configured routing module as following:

const routes: Routes = [
  {
    path: "engineering/:branches",
    component: BranchesTabsComponent
  },
  {
    path: "humanities/:branches",
    component: BranchesTabsComponent
  },
];

and in the main-continer.component.ts:

titlesOfEngineeringTabs: string[] = ['E1','E2','E3'];
titlesOfHumanitiesTabs: string[] = ['H1','H2'];

constructor(private router: Router) {}

handleEnginTabs():void{
    this.router.navigate(['/engineering', this.titlesOfEngineeringTabs]);
}
handleHumanTabs():void{
    this.router.navigate(['/humanities', this.titlesOfHumanitiesTabs]);
}

and also main-continer.component.html contains:

<router-outlet></router-outlet>

and then in branches-tabs.component.ts have:

tabsLable: string[] = [''];

ngOnInit(): void {
     this.route.params.subscribe(param => this.tabsLable = param["branches"]);
}

till here, it is obvious that we want to replace <router-outlet> with branches-tabs component in which deferent tab labels are shown Depending on selected menu...
but I get this error:

*core.mjs:6485 ERROR Error: Uncaught (in promise): Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'
Error: Cannot match any routes. URL Segment: 'engineering;0=%DA%A9%D8%A7%D9%85%D9%BE%DB%8C%D9%88%D8%AA%D8%B1;1=%D8%B5%D9%86%D8%A7%DB%8C%D8%B9;2=%D9%85%D8%AA%D8%A7%D9%84%D9%88%D8%B1%DA%98%DB%8C'*

how can pass a string array as parameter and fix above error?
best regards

Body:
Angular docs on navigate()

An array of URL fragments with which to construct the target URL. If
the path is static, can be the literal URL string. For a dynamic
path, pass an array of path segments, followed by the parameters for
each segment. The fragments are applied to the current URL or the
one provided in the relativeTo property of the options object, if
supplied.

If your intent is to have the url look like /engineering/E1/E2/E3 then you should apply the spread operator ... to the arrays and it would look like:

this.router.navigate(['/engineering', ...this.titlesOfEngineeringTabs]);


来源: stackexchange

问:
Spring cloud stream - Kafka consumer consuming duplicate messages with StreamListener
With our spring boot app, we notice kafka consumer consuming message twice randomly once in a while only in prod env. We have 6 instances with 6 partitions deployed in PCF.We have caught messages with same offset and partition received twice in same topic which causes duplicates and is a business critical for us.
We haven't noticed this in non production env and it is hard to reproduce in non prod env. We have recently switched to Kafka and we are not able to find out the root issue.

We are using spring-cloud-stream/spring-cloud-stream-binder-kafka- 2.1.2
Here is the Config:

```<code>spring:
  cloud:
    stream:
      default.consumer.concurrency: 1
      default-binder: kafka
      bindings:
        channel:
          destination: topic
          content_type: application/json
          autoCreateTopics: false
          group: group
          consumer:
            maxAttempts: 1
      kafka:
        binder:
          autoCreateTopics: false
          autoAddPartitions: false
          brokers: brokers list
        bindings:
          channel:
            consumer:
              autoCommitOnError: true
              autoCommitOffset: true
              configuration:
                max.poll.interval.ms: 1000000
                max.poll.records: 1
                group.id: group
</code>```

We use @Streamlisteners to consume the messages.

Here is the instance we received duplicate and the error message captured in server logs.

ERROR 46 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator
: [Consumer clientId=consumer-3, groupId=group] Offset commit failed
on partition topic-0 at offset 1291358: The coordinator is not aware
of this member. ERROR 46 --- [container-0-C-1]
o.s.kafka.listener.LoggingErrorHandler   : Error while processing:
null OUT org.apache.kafka.clients.consumer.CommitFailedException:
Commit cannot be completed since the group has already rebalanced and
assigned the partitions to another member.  This means that the time
between subsequent calls to poll() was longer than the configured
max.poll.interval.ms,  which typically implies that the poll loop is
spending too much time message processing.   You can address this
either by increasing the session timeout or by reducing the maximum
size of batches returned in poll() with max.poll.records.
at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator$OffsetCommitResponseHandler.handle(ConsumerCoordinator.java:871)
~[kafka-clients-2.0.1.jar!/:na]

There is no crash and all the instances are healthy at the time of duplicate. Also there is confusion with error log - Error while processing: null since Message was successfully  processed twice. And max.poll.interval.ms: 100000 which is about 16 minutes and it is supposed to be enough time to process any message for the system and session timeout and heartbit config is default. Duplicate is received within 2 seconds in most of the instances.
Any configs that we are missing  ? Any suggestion/help is highly appreciated.

答: Also, keep in mind StreamListener and the annotation-based programming model has been deprecated for 3+ years and has been removed from the current main, which means the next release will not have it. Please migrate your solution to a functional based programming model</p>

ContentLicense: CC BY-SA 4.0

Body:
With our spring boot app, we notice kafka consumer consuming message twice randomly once in a while only in prod env. We have 6 instances with 6 partitions deployed in PCF.We have caught messages with same offset and partition received twice in same topic which causes duplicates and is a business critical for us.
We haven't noticed this in non production env and it is hard to reproduce in non prod env. We have recently switched to Kafka and we are not able to find out the root issue.

We are using spring-cloud-stream/spring-cloud-stream-binder-kafka- 2.1.2
Here is the Config:

spring:
  cloud:
    stream:
      default.consumer.concurrency: 1
      default-binder: kafka
      bindings:
        channel:
          destination: topic
          content_type: application/json
          autoCreateTopics: false
          group: group
          consumer:
            maxAttempts: 1
      kafka:
        binder:
          autoCreateTopics: false
          autoAddPartitions: false
          brokers: brokers list
        bindings:
          channel:
            consumer:
              autoCommitOnError: true
              autoCommitOffset: true
              configuration:
                max.poll.interval.ms: 1000000
                max.poll.records: 1
                group.id: group

We use @Streamlisteners to consume the messages.

Here is the instance we received duplicate and the error message captured in server logs.

ERROR 46 --- [container-0-C-1] o.a.k.c.c.internals.ConsumerCoordinator
: [Consumer clientId=consumer-3, groupId=group] Offset commit failed
on partition topic-0 at offset 1291358: The coordinator is not aware
of this member. ERROR 46 --- [container-0-C-1]
o.s.kafka.listener.LoggingErrorHandler   : Error while processing:
null OUT org.apache.kafka.clients.consumer.CommitFailedException:
Commit cannot be completed since the group has already rebalanced and
assigned the partitions to another member.  This means that the time
between subsequent calls to poll() was longer than the configured
max.poll.interval.ms,  which typically implies that the poll loop is
spending too much time message processing.   You can address this
either by increasing the session timeout or by reducing the maximum
size of batches returned in poll() with max.poll.records.
at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator$OffsetCommitResponseHandler.handle(ConsumerCoordinator.java:871)
~[kafka-clients-2.0.1.jar!/:na]

There is no crash and all the instances are healthy at the time of duplicate. Also there is confusion with error log - Error while processing: null since Message was successfully  processed twice. And max.poll.interval.ms: 100000 which is about 16 minutes and it is supposed to be enough time to process any message for the system and session timeout and heartbit config is default. Duplicate is received within 2 seconds in most of the instances.
Any configs that we are missing  ? Any suggestion/help is highly appreciated.


问:
Select Group based on condition - Crystal Report
I have a report where the data is displayed based on the value of a combobox, how do I display all the data if the combox is empty? I have done the below:

Under Select Expert -> Group

```<code>if {?@Div} <> " " then
    {SP;1.Col1} = {?@Div}
</code>```

Thank you

答:
Assuming the {?@Div} var contains an empty string "if combobox is empty" the condition could look like this:

```<code>{SP;1.Col1} = {?@Div}
Or {?@Div} = ''
</code>```

You might want to add an "All" group to the selection, then it would be something like:

```<code>{SP;1.Col1} = {?@Div}
Or {?@Div} = 'All'
</code>```

Body:
I have a report where the data is displayed based on the value of a combobox, how do I display all the data if the combox is empty? I have done the below:

Under Select Expert -> Group

if {?@Div} <> " " then
    {SP;1.Col1} = {?@Div}

Thank you

Body:
Assuming the {?@Div} var contains an empty string "if combobox is empty" the condition could look like this:

{SP;1.Col1} = {?@Div}
Or {?@Div} = ''

You might want to add an "All" group to the selection, then it would be something like:

{SP;1.Col1} = {?@Div}
Or {?@Div} = 'All'


问:
C# Custom Fonts not working in Xamarin Forms (Android). Xamarin 4.8. Windows 10, VS19
I'm having an issue with Xamarin Forms 4.8 custom fonts.

I've followed the guides to the letter, that is:

-Loaded my font files (.ttf or .otf) into my shared directory and marked them as Embedded resources.

-Added the ExportFont outside of my namespace.

When I reference the font anywhere it just builds the standard font. Here is a snippet of code:

```<code>using System;
using System.Collections.Generic;
using Xamarin.Forms;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Reflection;

[assembly: ExportFont("Stencil.ttf")]
[assembly: ExportFont("GreatVibes.otf")]
[assembly: ExportFont("Lobster-Regular.ttf", Alias= "MyFont")]

namespace BAAaM
{
    public partial class MainPage : ContentPage
    {

        public MainPage()
        {

            Grid topgrid = new Grid();
            topgrid.Children.Add(new Label { Text = "Test, please work", FontSize = 30, FontFamily = "Lobster-Regular" }, 0, 1);
this.Content = topgrid;
}
}
}
</code>```

I've experimented placing the fonts into my Android directory, under assets but that doesn't work either. Is Xamarin overwriting whatever I do with standard Font as part of the built in label functions? I have no problems changing the text size.

Thanks,

M

答:
I had this issue.

My solution: Changing file structure

FROM:
Assets/Fonts/PoppinsBold.ttf

To:
Fonts/PoppinsBold.ttf

Body:
I'm having an issue with Xamarin Forms 4.8 custom fonts.

I've followed the guides to the letter, that is:

-Loaded my font files (.ttf or .otf) into my shared directory and marked them as Embedded resources.

-Added the ExportFont outside of my namespace.

When I reference the font anywhere it just builds the standard font. Here is a snippet of code:

using System;
using System.Collections.Generic;
using Xamarin.Forms;
using Newtonsoft.Json.Linq;
using System.IO;
using System.Reflection;

[assembly: ExportFont("Stencil.ttf")]
[assembly: ExportFont("GreatVibes.otf")]
[assembly: ExportFont("Lobster-Regular.ttf", Alias= "MyFont")]

namespace BAAaM
{
    public partial class MainPage : ContentPage
    {

        public MainPage()
        {

            Grid topgrid = new Grid();
            topgrid.Children.Add(new Label { Text = "Test, please work", FontSize = 30, FontFamily = "Lobster-Regular" }, 0, 1);
this.Content = topgrid;
}
}
}

I've experimented placing the fonts into my Android directory, under assets but that doesn't work either. Is Xamarin overwriting whatever I do with standard Font as part of the built in label functions? I have no problems changing the text size.

Thanks,

M


问:
Find list of empty indices in a javascript array
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

```<code>["x", "", "", "x", "", "", ""]
</code>```

Would return something like:

```<code>[1,2,4,5,6]
</code>```

I have attempted something like this:

```<code>empty = roster.findIndex((obj) => Object.keys(obj).length === 0)
</code>```

However I can't come up with a way to iterate over the list.

答:
roster = ["x", "", "", "x", "", "", ""]

emptyIndexArray = []

for (i = 0; i < roster.length; i++) {
  if (roster[i] === "") {
    emptyIndexArray[emptyIndexArray.length] = i;
  }
}

emptyIndexArray.forEach(x => console.log(x));```

Body:
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

["x", "", "", "x", "", "", ""]

Would return something like:

[1,2,4,5,6]

I have attempted something like this:

empty = roster.findIndex((obj) => Object.keys(obj).length === 0)

However I can't come up with a way to iterate over the list.


问:
getting issue in docker when i run command docker compose up
i am new in docker, when i run the command docker-compose up i am getting below error in that

```<code>+ gpg --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 6E4F6AB321FDC07F2C332E3AC2BF0BC433CFC8B3
gpg: directory `/root/.gnupg' created
gpg: new configuration file `/root/.gnupg/gpg.conf' created
gpg: WARNING: options in `/root/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring `/root/.gnupg/secring.gpg' created
gpg: keyring `/root/.gnupg/pubring.gpg' created
gpg: requesting key 33CFC8B3 from hkp server ha.pool.sks-keyservers.net
?: ha.pool.sks-keyservers.net: Host not found
gpgkeys: HTTP fetch error 7: couldn't connect: Connection timed out
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
ERROR: Service 'php' failed to build: The command '/bin/sh -c set -xe   && for key in $GPG_KEYS; do         gpg --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys "$key";     done' returned a non-zero code: 2
</code>```

here i have attached my docker yml file, can anyone please help me how to resolve this issue ?

```<code>application:
    build: misc/docker/code
    volumes:
        - .:/var/www/seagull
    tty: true
db:
    image: mysql:5.6
    ports:
        - 3306:3306
    environment:
        MYSQL_ROOT_PASSWORD: toor
redis:
    image: redis
    ports:
        - 6379:6379
php:
    build: misc/docker/php-fpm/5.6
    expose:
        - "9000"
    volumes_from:
        - application
    links:
        - db
        - redis
    environment:
      - REDIS_BACKEND=redis:6379
nginx:
    build: misc/docker/nginx
    ports:
        - 80:80
    links:
        - php
    volumes_from:
        - application
    volumes:
        - ./var/log/nginx:/var/log/nginx
</code>```

答:
Keyserver issues are unfortunately very common -- Try a number of different methods, and the only method that's reasonably successful at combating the issue on a large scale is trying multiple keyservers in a loop until one succeeds. Usually, just re-starting the failing build is enough to get it to work, but there may be firewalls, etc in place that force a keyserver switch (keyserver.ubuntu.com is a good one that supports port 80 and is commonly allowed).

@ptsiampas Solved by getting it from multiple servers..

```<code>key='B42F6819007F00F88E364FD4036A9C25BF357DD4'; \
  gpg  --yes --always-trust --keyserver pgp.mit.edu --recv-keys "$key" || \
  gpg  --yes --always-trust --keyserver keyserver.pgp.com --recv-keys "$key" || \
  gpg  --yes --always-trust --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
  gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \
</code>```

@camilo0365 Solved it in this way.

```<code>for server in ha.pool.sks-keyservers.net \
              hkp://p80.pool.sks-keyservers.net:80 \
              keyserver.ubuntu.com \
              hkp://keyserver.ubuntu.com:80 \
              pgp.mit.edu; do
    gpg --keyserver "$server" --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 && break || echo "Trying new server..."
done
</code>```

you can use proxy, to solve your problem.

```<code>gpg --keyserver-options http-proxy="http://XXXXXXX"
        --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
</code>```

Also for

```<code>ERROR: Service 'php' failed to build:
</code>```

try docker-compose build --no-cache php-fpm

Body:
i am new in docker, when i run the command docker-compose up i am getting below error in that

+ gpg --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 6E4F6AB321FDC07F2C332E3AC2BF0BC433CFC8B3
gpg: directory `/root/.gnupg' created
gpg: new configuration file `/root/.gnupg/gpg.conf' created
gpg: WARNING: options in `/root/.gnupg/gpg.conf' are not yet active during this run
gpg: keyring `/root/.gnupg/secring.gpg' created
gpg: keyring `/root/.gnupg/pubring.gpg' created
gpg: requesting key 33CFC8B3 from hkp server ha.pool.sks-keyservers.net
?: ha.pool.sks-keyservers.net: Host not found
gpgkeys: HTTP fetch error 7: couldn't connect: Connection timed out
gpg: no valid OpenPGP data found.
gpg: Total number processed: 0
ERROR: Service 'php' failed to build: The command '/bin/sh -c set -xe   && for key in $GPG_KEYS; do         gpg --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys "$key";     done' returned a non-zero code: 2

here i have attached my docker yml file, can anyone please help me how to resolve this issue ?

application:
    build: misc/docker/code
    volumes:
        - .:/var/www/seagull
    tty: true
db:
    image: mysql:5.6
    ports:
        - 3306:3306
    environment:
        MYSQL_ROOT_PASSWORD: toor
redis:
    image: redis
    ports:
        - 6379:6379
php:
    build: misc/docker/php-fpm/5.6
    expose:
        - "9000"
    volumes_from:
        - application
    links:
        - db
        - redis
    environment:
      - REDIS_BACKEND=redis:6379
nginx:
    build: misc/docker/nginx
    ports:
        - 80:80
    links:
        - php
    volumes_from:
        - application
    volumes:
        - ./var/log/nginx:/var/log/nginx

Body:
Keyserver issues are unfortunately very common -- Try a number of different methods, and the only method that's reasonably successful at combating the issue on a large scale is trying multiple keyservers in a loop until one succeeds. Usually, just re-starting the failing build is enough to get it to work, but there may be firewalls, etc in place that force a keyserver switch (keyserver.ubuntu.com is a good one that supports port 80 and is commonly allowed).

@ptsiampas Solved by getting it from multiple servers..

key='B42F6819007F00F88E364FD4036A9C25BF357DD4'; \
  gpg  --yes --always-trust --keyserver pgp.mit.edu --recv-keys "$key" || \
  gpg  --yes --always-trust --keyserver keyserver.pgp.com --recv-keys "$key" || \
  gpg  --yes --always-trust --keyserver ha.pool.sks-keyservers.net --recv-keys "$key" ; \
  gpg --batch --verify /usr/local/bin/gosu.asc /usr/local/bin/gosu; \

@camilo0365 Solved it in this way.

for server in ha.pool.sks-keyservers.net \
              hkp://p80.pool.sks-keyservers.net:80 \
              keyserver.ubuntu.com \
              hkp://keyserver.ubuntu.com:80 \
              pgp.mit.edu; do
    gpg --keyserver "$server" --recv-keys B42F6819007F00F88E364FD4036A9C25BF357DD4 && break || echo "Trying new server..."
done

you can use proxy, to solve your problem.

gpg --keyserver-options http-proxy="http://XXXXXXX"
        --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D

Also for

ERROR: Service 'php' failed to build:

try docker-compose build --no-cache php-fpm


问:
Generate an associative array from an array of rows using one column as keys and another column as values
I have a MySQL result set with 2 values in each row.

Each time I loop through these results, I want to add them to an array.

I want one value to be the key, and the other to be the array value.

I tried this, but it doesn't seem to work:

```<code>$dataarray[] = $row['id'] => $row['data'];
</code>```

If I have:

```<code>$resultSet = [
    ['id' => 1, 'data' => 'one'],
    ['id' => 2, 'data' => 'two'],
    ['id' => 3, 'data' => 'three']
];
</code>```

I want to generate:

```<code>[
    1 => 'one',
    2 => 'two',
    3 => 'three'
]
</code>```

答:
It is more elegant/expressive/modern/concise to use array_column() instead of a foreach() for this task.

The first parameter is the input array of rows.

The second parameter is the column to become the values in the output array.

The third parameter is the column to become the keys in the output array.

Code: (Demo)

```<code>$array = [
    ['id' => 1, 'key' => 'foo', 'data' => 'a'],
    ['id' => 2, 'key' => 'bar', 'data' => 'b'],
    ['id' => 3, 'key' => 'barf', 'data' => 'c'],
];

var_export(
    array_column($array, 'data', 'id')
);
</code>```

Output:

```<code>array (
  1 => 'a',
  2 => 'b',
  3 => 'c',
)
</code>```

The Laravel equivalent method to call on a collection is pluck() like:

```<code>$collection->pluck('data', 'id')
</code>```

If you'd like to assign new first level keys but leave the rows unchanged, you write null as the second parameter of the native function call.

Code: (Demo)

```<code>var_export(
    array_column($array, null, 'id')
);
</code>```

Output:

```<code>array (
  1 =>
  array (
    'id' => 1,
    'key' => 'foo',
    'data' => 'a',
  ),
  2 =>
  array (
    'id' => 2,
    'key' => 'bar',
    'data' => 'b',
  ),
  3 =>
  array (
    'id' => 3,
    'key' => 'barf',
    'data' => 'c',
  ),
)
</code>```

A lesser realized, functionless technique would be to use array destructuring inside a body-less foreach() loop. (Demo)

```<code>$array = [
    ['id' => 1, 'data' => 'a'],
    ['id' => 2, 'data' => 'b'],
    ['id' => 3, 'data' => 'c'],
];

$result = [];
foreach ($array as ['id' => $id, 'data' => $result[$id]]);
var_export($result);
</code>```

This is equivalent to the earlier answers which advise this:

```<code>foreach ($array as $row) {
    $result[$row['id']] = $row['data'];
}
</code>```

Output:

```<code>array (
  1 => 'a',
  2 => 'b',
  3 => 'c',
)
</code>```

Body:
I have a MySQL result set with 2 values in each row.

Each time I loop through these results, I want to add them to an array.

I want one value to be the key, and the other to be the array value.

I tried this, but it doesn't seem to work:

$dataarray[] = $row['id'] => $row['data'];

If I have:

$resultSet = [
    ['id' => 1, 'data' => 'one'],
    ['id' => 2, 'data' => 'two'],
    ['id' => 3, 'data' => 'three']
];

I want to generate:

[
    1 => 'one',
    2 => 'two',
    3 => 'three'
]

Body:
It is more elegant/expressive/modern/concise to use array_column() instead of a foreach() for this task.

The first parameter is the input array of rows.

The second parameter is the column to become the values in the output array.

The third parameter is the column to become the keys in the output array.

Code: (Demo)

$array = [
    ['id' => 1, 'key' => 'foo', 'data' => 'a'],
    ['id' => 2, 'key' => 'bar', 'data' => 'b'],
    ['id' => 3, 'key' => 'barf', 'data' => 'c'],
];

var_export(
    array_column($array, 'data', 'id')
);

Output:

array (
  1 => 'a',
  2 => 'b',
  3 => 'c',
)

The Laravel equivalent method to call on a collection is pluck() like:

$collection->pluck('data', 'id')

If you'd like to assign new first level keys but leave the rows unchanged, you write null as the second parameter of the native function call.

Code: (Demo)

var_export(
    array_column($array, null, 'id')
);

Output:

array (
  1 =>
  array (
    'id' => 1,
    'key' => 'foo',
    'data' => 'a',
  ),
  2 =>
  array (
    'id' => 2,
    'key' => 'bar',
    'data' => 'b',
  ),
  3 =>
  array (
    'id' => 3,
    'key' => 'barf',
    'data' => 'c',
  ),
)

A lesser realized, functionless technique would be to use array destructuring inside a body-less foreach() loop. (Demo)

$array = [
    ['id' => 1, 'data' => 'a'],
    ['id' => 2, 'data' => 'b'],
    ['id' => 3, 'data' => 'c'],
];

$result = [];
foreach ($array as ['id' => $id, 'data' => $result[$id]]);
var_export($result);

This is equivalent to the earlier answers which advise this:

foreach ($array as $row) {
    $result[$row['id']] = $row['data'];
}

Output:

array (
  1 => 'a',
  2 => 'b',
  3 => 'c',
)


答:
It's not going to be length == 0 right, you want empty or doesn't contain x
Also find index returns the first index that match, you have to do a map.

See this solution here: EcmaScript6 findIndex method, can it return multiple values?

Recap:

```<code>let roster = ["x", "", "", "x", "", "", ""];
let indexes = ages.map((elm, idx) => (elm == '' || elm != 'x') ? idx : '').filter(String);
console.log( indexes );
</code>```

Title: Find list of empty indices in a javascript array

Body:
It's not going to be length == 0 right, you want empty or doesn't contain x
Also find index returns the first index that match, you have to do a map.

See this solution here: EcmaScript6 findIndex method, can it return multiple values?

Recap:

let roster = ["x", "", "", "x", "", "", ""];
let indexes = ages.map((elm, idx) => (elm == '' || elm != 'x') ? idx : '').filter(String);
console.log( indexes );


问:
Get multiple / dynamic EditText value in RecyclerView
I'm new with these case and I want to try to get the value of dynamic EditText(s) from RecyclerView.

And in the layout :

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_marginTop="@dimen/_10sdp"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tv_question"
        style="@style/textH4"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="bottom"
        android:text="Ini adalah tempat pertanyaan pertama" />

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/et_answer"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_120sdp"
        android:hint="Tulis jawaban anda"
        style="@style/EdittextPrimary"
        android:gravity="top"
        android:background="@drawable/bg_outline_grey"
        android:inputType="textMultiLine"
        android:layout_marginTop="@dimen/_10sdp"/>

</LinearLayout>
</code>```

The question is.. how do I get the EditText value and put it in an ArrayList ?

Newest update codes :
I add my Recycler Adapter, and tried these :

```<code>class RequestJoinAdapter(
    val onTextChanged: (text:String,position:Int)->Unit
) :
    RecyclerView.Adapter<RequestJoinAdapter.ViewHolder>() {

    var listData: MutableList<KeamananModel> = ArrayList()

    private var textValue = ""

    fun insertAll(data: List<KeamananModel>) {
        data.forEach {
            listData.add(it)
            notifyItemInserted(listData.size - 1)
        }
    }

    fun clear() {
        if (listData.isNotEmpty()) {
            listData.clear()
            notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemRequestJoinBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = listData[position]
        holder.bindTo(item)

        holder.binding.etAnswer.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun afterTextChanged(s: Editable?) {
                onTextChanged.invoke(s.toString(), position)
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                textValue = s.toString().toLowerCase()
            }
        })

    }

    override fun getItemCount() = listData.size

    inner class ViewHolder(val binding: ItemRequestJoinBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bindTo(item: KeamananModel) {

            val context = binding.root.context

            binding.tvQuestion.text = item.qt
        }

    }

    private fun isLog(msg: String) {
        Log.e("join grup:", msg)
    }

}
</code>```

and in my current Activity, I used to add some codes like

```<code>RequestJoinAdapter { text, position ->
            val values = ArrayList<Jawaban>()
            val hashSet = HashSet<Jawaban>()
            values.add(Jawaban(pertanyaan_no = position+1, jawaban = text))
            hashSet.addAll(values)
            values.clear()
            values.addAll(hashSet)
            val valuest = ArrayList<JawabanKeamanan>()
            val hashSets = HashSet<JawabanKeamanan>()
            valuest.add(JawabanKeamanan(values))
            hashSets.addAll(valuest)
            valuest.clear()
            valuest.addAll(hashSets)
            isLog("currentResult: $valuest")
        }
</code>```

How do I set my latest valuest into my var listJawaban: MutableList<JawabanKeamanan> = ArrayList() without any duplicate datas inside it ? What I want is like JawabanKeamanan(jawaban_keamanan=[Jawaban(pertanyaan_no=1, jawaban=t)], [Jawaban(pertanyaan_no=2, jawaban=u)]). Thanks..

答:
The simplest answer is to implement a TextWatcher to your EditText and have it return your data when your text is changed.

Now you may ask how can I get such data in my activty? Well it's pretty simple.
Create an interface in your adapter to communicate with your activity.

Pass your interface as a constructor parameter so when you initialize your adapter in the activity your methods are implemented.

Another solution for you is to add a button in each item of your list and call your interface method in the button's OnClickListener.

EDIT:
In the snippet below I have used a lambda function for when the text changes.

```<code>    class RequestJoinAdapter(
      private val onClickedItem: (ArrayList<String>)->Unit,
      val onTextChanged: (text:String,position:Int)->Unit
    ):
      RecyclerView.Adapter<RequestJoinAdapter.ViewHolder>() {

      var listData: MutableList<KeamananModel> = ArrayList()

      var listJawaban: MutableList<Jawaban> = ArrayList()

      private var textValue = ""

      fun insertAll(data: List<KeamananModel>) {
        data.forEach {
          listData.add(it)
          notifyItemInserted(listData.size - 1)
        }
      }

      fun clear() {
        if (listData.isNotEmpty()) {
          listData.clear()
          notifyDataSetChanged()
        }
      }

      override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
          ItemRequestJoinBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
          )
        )
      }

      override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = listData[position]
        holder.bindTo(item)

      }

      override fun getItemCount() = listData.size

      inner class ViewHolder(val binding: ItemRequestJoinBinding):
        RecyclerView.ViewHolder(binding.root) {

        fun bindTo(item: KeamananModel) {

          val context = binding.root.context

          binding.tvQuestion.text = item.qt

          binding.etAnswer.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun afterTextChanged(s: Editable?) {
              if (textValue.isNotEmpty()) {
                isLog(textValue)

                onTextChanged.invoke(s,absoluteAdapterPosition)
              } else {

              }
              listJawaban.add(Jawaban(pertanyaan_no = adapterPosition + 1, jawaban = textValue))
              isLog(listJawaban.toString())
            }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
          textValue = s.toString().toLowerCase()
        }
      })
    }

  }

  private fun isLog(msg: String) {
    Log.e("join grup:", msg)
  }

}
</code>```

Pay attention to the onTextChanged.invoke() method. This lambda function can be used like an interface to communicate between your adapter and your view. It will be triggered every time your text is changed.

Finally instantiate your adapter like below:

```<code>val adapter = RequestJoinAdapter({

    }, { text, position ->
        //onTextChanged
    })
</code>```

The position argument is there to help you know which TextView was changed

Body:
I'm new with these case and I want to try to get the value of dynamic EditText(s) from RecyclerView.

And in the layout :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_marginTop="@dimen/_10sdp"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.AppCompatTextView
        android:id="@+id/tv_question"
        style="@style/textH4"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:gravity="bottom"
        android:text="Ini adalah tempat pertanyaan pertama" />

    <androidx.appcompat.widget.AppCompatEditText
        android:id="@+id/et_answer"
        android:layout_width="match_parent"
        android:layout_height="@dimen/_120sdp"
        android:hint="Tulis jawaban anda"
        style="@style/EdittextPrimary"
        android:gravity="top"
        android:background="@drawable/bg_outline_grey"
        android:inputType="textMultiLine"
        android:layout_marginTop="@dimen/_10sdp"/>

</LinearLayout>

The question is.. how do I get the EditText value and put it in an ArrayList ?

Newest update codes :
I add my Recycler Adapter, and tried these :

class RequestJoinAdapter(
    val onTextChanged: (text:String,position:Int)->Unit
) :
    RecyclerView.Adapter<RequestJoinAdapter.ViewHolder>() {

    var listData: MutableList<KeamananModel> = ArrayList()

    private var textValue = ""

    fun insertAll(data: List<KeamananModel>) {
        data.forEach {
            listData.add(it)
            notifyItemInserted(listData.size - 1)
        }
    }

    fun clear() {
        if (listData.isNotEmpty()) {
            listData.clear()
            notifyDataSetChanged()
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemRequestJoinBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = listData[position]
        holder.bindTo(item)

        holder.binding.etAnswer.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun afterTextChanged(s: Editable?) {
                onTextChanged.invoke(s.toString(), position)
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                textValue = s.toString().toLowerCase()
            }
        })

    }

    override fun getItemCount() = listData.size

    inner class ViewHolder(val binding: ItemRequestJoinBinding) :
        RecyclerView.ViewHolder(binding.root) {

        fun bindTo(item: KeamananModel) {

            val context = binding.root.context

            binding.tvQuestion.text = item.qt
        }

    }

    private fun isLog(msg: String) {
        Log.e("join grup:", msg)
    }

}

and in my current Activity, I used to add some codes like

RequestJoinAdapter { text, position ->
            val values = ArrayList<Jawaban>()
            val hashSet = HashSet<Jawaban>()
            values.add(Jawaban(pertanyaan_no = position+1, jawaban = text))
            hashSet.addAll(values)
            values.clear()
            values.addAll(hashSet)
            val valuest = ArrayList<JawabanKeamanan>()
            val hashSets = HashSet<JawabanKeamanan>()
            valuest.add(JawabanKeamanan(values))
            hashSets.addAll(valuest)
            valuest.clear()
            valuest.addAll(hashSets)
            isLog("currentResult: $valuest")
        }

How do I set my latest valuest into my var listJawaban: MutableList<JawabanKeamanan> = ArrayList() without any duplicate datas inside it ? What I want is like JawabanKeamanan(jawaban_keamanan=[Jawaban(pertanyaan_no=1, jawaban=t)], [Jawaban(pertanyaan_no=2, jawaban=u)]). Thanks..

Body:
The simplest answer is to implement a TextWatcher to your EditText and have it return your data when your text is changed.

Now you may ask how can I get such data in my activty? Well it's pretty simple.
Create an interface in your adapter to communicate with your activity.

Pass your interface as a constructor parameter so when you initialize your adapter in the activity your methods are implemented.

Another solution for you is to add a button in each item of your list and call your interface method in the button's OnClickListener.

EDIT:
In the snippet below I have used a lambda function for when the text changes.

    class RequestJoinAdapter(
      private val onClickedItem: (ArrayList<String>)->Unit,
      val onTextChanged: (text:String,position:Int)->Unit
    ):
      RecyclerView.Adapter<RequestJoinAdapter.ViewHolder>() {

      var listData: MutableList<KeamananModel> = ArrayList()

      var listJawaban: MutableList<Jawaban> = ArrayList()

      private var textValue = ""

      fun insertAll(data: List<KeamananModel>) {
        data.forEach {
          listData.add(it)
          notifyItemInserted(listData.size - 1)
        }
      }

      fun clear() {
        if (listData.isNotEmpty()) {
          listData.clear()
          notifyDataSetChanged()
        }
      }

      override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
          ItemRequestJoinBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
          )
        )
      }

      override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = listData[position]
        holder.bindTo(item)

      }

      override fun getItemCount() = listData.size

      inner class ViewHolder(val binding: ItemRequestJoinBinding):
        RecyclerView.ViewHolder(binding.root) {

        fun bindTo(item: KeamananModel) {

          val context = binding.root.context

          binding.tvQuestion.text = item.qt

          binding.etAnswer.addTextChangedListener(object: TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
            override fun afterTextChanged(s: Editable?) {
              if (textValue.isNotEmpty()) {
                isLog(textValue)

                onTextChanged.invoke(s,absoluteAdapterPosition)
              } else {

              }
              listJawaban.add(Jawaban(pertanyaan_no = adapterPosition + 1, jawaban = textValue))
              isLog(listJawaban.toString())
            }
        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
          textValue = s.toString().toLowerCase()
        }
      })
    }

  }

  private fun isLog(msg: String) {
    Log.e("join grup:", msg)
  }

}

Pay attention to the onTextChanged.invoke() method. This lambda function can be used like an interface to communicate between your adapter and your view. It will be triggered every time your text is changed.

Finally instantiate your adapter like below:

val adapter = RequestJoinAdapter({

    }, { text, position ->
        //onTextChanged
    })

The position argument is there to help you know which TextView was changed


问:
SignalR js client is not able to start connection, even if logs are showing that connection is being made (only LongPooling works)
I am struggling with configuring and using signalR with .net core mvc 6. The purpose for the signalR hub is to send messages to js clients after invoking method in C# controller (js client is React application configured in MVC as ClientApp).

I enabled debugging for both client signalR instance and asp.net

here are the logs from ASP.NET:

```<code>      SPA proxy is ready. Redirecting to https://localhost:44440.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionManager[1]
      New connection ctA6QHwS4fvVGcufYvtlAA created.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionDispatcher[10]
      Sending negotiation response.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionDispatcher[4]
      Establishing new connection.
dbug: Microsoft.AspNetCore.SignalR.HubConnectionHandler[5]
      OnConnectedAsync started.
dbug: Microsoft.AspNetCore.SignalR.Internal.DefaultHubProtocolResolver[2]
      Found protocol implementation for requested protocol: json.
dbug: Microsoft.AspNetCore.SignalR.HubConnectionContext[1]
      Completed connection handshake. Using HubProtocol 'json'.
connected!! ctA6QHwS4fvVGcufYvtlAA
</code>```

and corresponding to them logs with js client:

```<code>Utils.ts:194 [2022-02-03T18:40:17.568Z] Debug: Starting HubConnection.
Utils.ts:194 [2022-02-03T18:40:17.568Z] Debug: Starting connection with transfer format 'Text'.
Utils.ts:194 [2022-02-03T18:40:17.576Z] Debug: Sending negotiation request: https://localhost:44440/hubs/order/negotiate?negotiateVersion=1.
Utils.ts:194 [2022-02-03T18:40:21.741Z] Debug: Skipping transport 'WebSockets' because it was disabled by the client.
Utils.ts:194 [2022-02-03T18:40:21.742Z] Debug: Selecting transport 'ServerSentEvents'.
Utils.ts:194 [2022-02-03T18:40:21.742Z] Trace: (SSE transport) Connecting.
Utils.ts:190 [2022-02-03T18:40:25.857Z] Information: SSE connected to https://localhost:44440/hubs/order?id=fxqgKpJnF5Dq5MX-RCfXcg
Utils.ts:194 [2022-02-03T18:40:25.857Z] Debug: The HttpConnection connected successfully.
Utils.ts:194 [2022-02-03T18:40:25.857Z] Debug: Sending handshake request.
Utils.ts:194 [2022-02-03T18:40:25.858Z] Trace: (SSE transport) sending data. String data of length 32.
Utils.ts:194 [2022-02-03T18:40:29.969Z] Trace: (SSE transport) request complete. Response status: 200.
Utils.ts:190 [2022-02-03T18:40:29.978Z] Information: Using HubProtocol 'json'.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: HttpConnection.stopConnection(undefined) called while in state Disconnecting.
index.js:1 [2022-02-03T18:40:59.997Z] Error: Connection disconnected with error 'Error: Server timeout elapsed without receiving a message from the server.'.
console.<computed> @ index.js:1
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: HubConnection.connectionClosed(Error: Server timeout elapsed without receiving a message from the server.) called while in state Connecting.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: Hub handshake failed with error 'Error: Server timeout elapsed without receiving a message from the server.' during start(). Stopping HubConnection.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: Call to HttpConnection.stop(Error: Server timeout elapsed without receiving a message from the server.) ignored because the connection is already in the disconnected state.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: HubConnection failed to start successfully because of error 'Error: Server timeout elapsed without receiving a message from the server.'.
</code>```

here is sample code from js client application:

```<code>    console.log("hub attached");

    const hubConnection = new HubConnectionBuilder()
      .withUrl(OrderHubUrl, {
        transport: HttpTransportType.ServerSentEvents,
        accessTokenFactory: () => user.accessToken ?? "",
      })
      .withAutomaticReconnect()
      .configureLogging(LogLevel.Trace)
      .build();

    this.dispatcher.state.saveState("hubConnection", hubConnection);

    const startConnection = async () => {
      try {
        await hubConnection.start();
        console.log("connected");
      } catch (e) {
        this.dispatcher.dispatch(Event.ShowModal, {
          actionName: "OK",
          header: "Error",
          content: e,
        });
      }
    };
    hubConnection.on("ReceiveMessage", (user, message) => {
      console.log("message received");
      console.log(user);
      console.log(message);
    });

    hubConnection.onreconnecting((e) => console.log("reconnecting", e));
    hubConnection.onreconnected((e) => console.log("reconnected", e));
    startConnection();
  }
</code>```

as you can see from logs on the top, signalR js client is not able to pass through start method. Instead after some time it throws an error message.

below is my Program.cs file, where i configured signalR (i am suspecting that maybe something wrong is here)

```<code>using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using OrderMaker.Authentication.Helpers;
using OrderMaker.Authentication.Services;
using OrderMaker.Entities;
using OrderMaker.Modules.Common.Services;
using OrderMaker.Modules.Order.Hubs;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddSignalR(c =>
{
    c.EnableDetailedErrors = true;
    c.ClientTimeoutInterval = TimeSpan.MaxValue;
    c.KeepAliveInterval = TimeSpan.MaxValue;
});

ConfigureConfiguration(builder.Configuration);
ConfigureServices(builder.Services, builder.Configuration);

var app = builder.Build();

app.UseAuthentication();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors(
          x => x
          .AllowAnyMethod()
          .AllowAnyHeader()
          .AllowCredentials());

app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");

app.MapHub<OrderHub>("/hubs/order");

app.Run();

void ConfigureConfiguration(ConfigurationManager configuration)
{
    using var client = new OrderMakerContext();
    client.Database.EnsureCreated();
}

void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
    services.AddControllers();
    // configure strongly typed settings objects
    var appSettingsSection = configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettingsSection);
    // configure jwt authentication
    var appSettings = appSettingsSection.Get<AppSettings>();
    var key = Encoding.ASCII.GetBytes(appSettings.Secret);
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        x.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                context.Token = context.Request.Cookies["order_maker_token"];
                // If the request is for our hub...
                var path = context.HttpContext.Request.Path;
                var accessToken = context.Request.Query["access_token"];
                if (!string.IsNullOrEmpty(accessToken) &&
                    (path.StartsWithSegments("/hubs/")))
                {
                    // Read the token out of the query string
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    }
    );

    services.AddScoped<IUserService, UserService>();
    services.AddSingleton<ILogService, LogService>();
}

</code>```

definition of my hub:

```<code>public class OrderHub : Hub
    {
        public async Task SendNotification(List<OrderModel> message)
        {
            await Clients.All.SendAsync("ReceiveMessage", message);
        }
        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync();
            Console.WriteLine("connected!! " + Context.ConnectionId);
        }
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
            Console.WriteLine("disconnected!!");
        }
    }

</code>```

And sample controller from where i want to send message to clients:

```<code>  private readonly IHubContext<OrderHub> _orderHubContext;
        public OrdersController(IHubContext<OrderHub> orderHubContext)
        {
            _orderHubContext = orderHubContext;
        }

        [Route("api/[controller]/")]
        [HttpPost]
        //[Authorize(Roles = $"{Role.Admin},{Role.Manager},{Role.Employee}")]
        public async Task<IActionResult> Post([FromBody] List<OrderModel> model)
        {
               /// some code for creating entities etc
               db.SaveChanges();
               /// notification to all clients that something new was added
               Console.Write(_orderHubContext.Clients.All.ToString());
               await _orderHubContext.Clients.All.SendAsync("ReceiveMessage", "hi there");
                }
            return Ok(new MessageResponse("Order added succesfully."));
    }

</code>```

basically i am lost, i spend two days already figuring out what may cause the issues, but i just can't make this thing working. I would really appreciate any sugestions or help. I tried to disable firewall, use different browser, etc without any success. Connection to hub is being made, c# app see that new connection but js client simply stuck in start() method for a while and throws an error message 'Error: Server timeout elapsed without receiving a message from the server.'.

Update: when i explicitly set type of transport in js clint to LongPolling hub is working as intended, but this is not ideal solution.

--- Update ---
All of those issues are happening only on local machine. I tried to check my luck and deploy to production app with transport fixed to SSE and it works without any issuess, as well as WebSocket transport. The only clue i have is that on localhost app is using kestrel and on server when i am hosting my app is using IIS.

答:
You could try to set the serverTimeout and KeepAliveInterval in your program.cs:

```<code>builder.Services.AddSignalR(c =>
{
    c.EnableDetailedErrors = true;
    c.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
    c.KeepAliveInterval = TimeSpan.FromSeconds(15);
});
</code>```

Reason:

If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value.
So,you'd better not set the value of KeepAliveInterval as  max value.

Body:
I am struggling with configuring and using signalR with .net core mvc 6. The purpose for the signalR hub is to send messages to js clients after invoking method in C# controller (js client is React application configured in MVC as ClientApp).

I enabled debugging for both client signalR instance and asp.net

here are the logs from ASP.NET:

      SPA proxy is ready. Redirecting to https://localhost:44440.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionManager[1]
      New connection ctA6QHwS4fvVGcufYvtlAA created.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionDispatcher[10]
      Sending negotiation response.
dbug: Microsoft.AspNetCore.Http.Connections.Internal.HttpConnectionDispatcher[4]
      Establishing new connection.
dbug: Microsoft.AspNetCore.SignalR.HubConnectionHandler[5]
      OnConnectedAsync started.
dbug: Microsoft.AspNetCore.SignalR.Internal.DefaultHubProtocolResolver[2]
      Found protocol implementation for requested protocol: json.
dbug: Microsoft.AspNetCore.SignalR.HubConnectionContext[1]
      Completed connection handshake. Using HubProtocol 'json'.
connected!! ctA6QHwS4fvVGcufYvtlAA

and corresponding to them logs with js client:

Utils.ts:194 [2022-02-03T18:40:17.568Z] Debug: Starting HubConnection.
Utils.ts:194 [2022-02-03T18:40:17.568Z] Debug: Starting connection with transfer format 'Text'.
Utils.ts:194 [2022-02-03T18:40:17.576Z] Debug: Sending negotiation request: https://localhost:44440/hubs/order/negotiate?negotiateVersion=1.
Utils.ts:194 [2022-02-03T18:40:21.741Z] Debug: Skipping transport 'WebSockets' because it was disabled by the client.
Utils.ts:194 [2022-02-03T18:40:21.742Z] Debug: Selecting transport 'ServerSentEvents'.
Utils.ts:194 [2022-02-03T18:40:21.742Z] Trace: (SSE transport) Connecting.
Utils.ts:190 [2022-02-03T18:40:25.857Z] Information: SSE connected to https://localhost:44440/hubs/order?id=fxqgKpJnF5Dq5MX-RCfXcg
Utils.ts:194 [2022-02-03T18:40:25.857Z] Debug: The HttpConnection connected successfully.
Utils.ts:194 [2022-02-03T18:40:25.857Z] Debug: Sending handshake request.
Utils.ts:194 [2022-02-03T18:40:25.858Z] Trace: (SSE transport) sending data. String data of length 32.
Utils.ts:194 [2022-02-03T18:40:29.969Z] Trace: (SSE transport) request complete. Response status: 200.
Utils.ts:190 [2022-02-03T18:40:29.978Z] Information: Using HubProtocol 'json'.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: HttpConnection.stopConnection(undefined) called while in state Disconnecting.
index.js:1 [2022-02-03T18:40:59.997Z] Error: Connection disconnected with error 'Error: Server timeout elapsed without receiving a message from the server.'.
console.<computed> @ index.js:1
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: HubConnection.connectionClosed(Error: Server timeout elapsed without receiving a message from the server.) called while in state Connecting.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: Hub handshake failed with error 'Error: Server timeout elapsed without receiving a message from the server.' during start(). Stopping HubConnection.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: Call to HttpConnection.stop(Error: Server timeout elapsed without receiving a message from the server.) ignored because the connection is already in the disconnected state.
Utils.ts:194 [2022-02-03T18:40:59.997Z] Debug: HubConnection failed to start successfully because of error 'Error: Server timeout elapsed without receiving a message from the server.'.

here is sample code from js client application:

    console.log("hub attached");

    const hubConnection = new HubConnectionBuilder()
      .withUrl(OrderHubUrl, {
        transport: HttpTransportType.ServerSentEvents,
        accessTokenFactory: () => user.accessToken ?? "",
      })
      .withAutomaticReconnect()
      .configureLogging(LogLevel.Trace)
      .build();

    this.dispatcher.state.saveState("hubConnection", hubConnection);

    const startConnection = async () => {
      try {
        await hubConnection.start();
        console.log("connected");
      } catch (e) {
        this.dispatcher.dispatch(Event.ShowModal, {
          actionName: "OK",
          header: "Error",
          content: e,
        });
      }
    };
    hubConnection.on("ReceiveMessage", (user, message) => {
      console.log("message received");
      console.log(user);
      console.log(message);
    });

    hubConnection.onreconnecting((e) => console.log("reconnecting", e));
    hubConnection.onreconnected((e) => console.log("reconnected", e));
    startConnection();
  }

as you can see from logs on the top, signalR js client is not able to pass through start method. Instead after some time it throws an error message.

below is my Program.cs file, where i configured signalR (i am suspecting that maybe something wrong is here)

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using OrderMaker.Authentication.Helpers;
using OrderMaker.Authentication.Services;
using OrderMaker.Entities;
using OrderMaker.Modules.Common.Services;
using OrderMaker.Modules.Order.Hubs;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddSignalR(c =>
{
    c.EnableDetailedErrors = true;
    c.ClientTimeoutInterval = TimeSpan.MaxValue;
    c.KeepAliveInterval = TimeSpan.MaxValue;
});

ConfigureConfiguration(builder.Configuration);
ConfigureServices(builder.Services, builder.Configuration);

var app = builder.Build();

app.UseAuthentication();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCors(
          x => x
          .AllowAnyMethod()
          .AllowAnyHeader()
          .AllowCredentials());

app.UseRouting();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");

app.MapHub<OrderHub>("/hubs/order");

app.Run();

void ConfigureConfiguration(ConfigurationManager configuration)
{
    using var client = new OrderMakerContext();
    client.Database.EnsureCreated();
}

void ConfigureServices(IServiceCollection services, IConfiguration configuration)
{
    services.AddControllers();
    // configure strongly typed settings objects
    var appSettingsSection = configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettingsSection);
    // configure jwt authentication
    var appSettings = appSettingsSection.Get<AppSettings>();
    var key = Encoding.ASCII.GetBytes(appSettings.Secret);
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false;
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
        x.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                context.Token = context.Request.Cookies["order_maker_token"];
                // If the request is for our hub...
                var path = context.HttpContext.Request.Path;
                var accessToken = context.Request.Query["access_token"];
                if (!string.IsNullOrEmpty(accessToken) &&
                    (path.StartsWithSegments("/hubs/")))
                {
                    // Read the token out of the query string
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    }
    );

    services.AddScoped<IUserService, UserService>();
    services.AddSingleton<ILogService, LogService>();
}

definition of my hub:

public class OrderHub : Hub
    {
        public async Task SendNotification(List<OrderModel> message)
        {
            await Clients.All.SendAsync("ReceiveMessage", message);
        }
        public override async Task OnConnectedAsync()
        {
            await base.OnConnectedAsync();
            Console.WriteLine("connected!! " + Context.ConnectionId);
        }
        public override async Task OnDisconnectedAsync(Exception exception)
        {
            await base.OnDisconnectedAsync(exception);
            Console.WriteLine("disconnected!!");
        }
    }

And sample controller from where i want to send message to clients:

  private readonly IHubContext<OrderHub> _orderHubContext;
        public OrdersController(IHubContext<OrderHub> orderHubContext)
        {
            _orderHubContext = orderHubContext;
        }

        [Route("api/[controller]/")]
        [HttpPost]
        //[Authorize(Roles = $"{Role.Admin},{Role.Manager},{Role.Employee}")]
        public async Task<IActionResult> Post([FromBody] List<OrderModel> model)
        {
               /// some code for creating entities etc
               db.SaveChanges();
               /// notification to all clients that something new was added
               Console.Write(_orderHubContext.Clients.All.ToString());
               await _orderHubContext.Clients.All.SendAsync("ReceiveMessage", "hi there");
                }
            return Ok(new MessageResponse("Order added succesfully."));
    }

basically i am lost, i spend two days already figuring out what may cause the issues, but i just can't make this thing working. I would really appreciate any sugestions or help. I tried to disable firewall, use different browser, etc without any success. Connection to hub is being made, c# app see that new connection but js client simply stuck in start() method for a while and throws an error message 'Error: Server timeout elapsed without receiving a message from the server.'.

Update: when i explicitly set type of transport in js clint to LongPolling hub is working as intended, but this is not ideal solution.

--- Update ---
All of those issues are happening only on local machine. I tried to check my luck and deploy to production app with transport fixed to SSE and it works without any issuess, as well as WebSocket transport. The only clue i have is that on localhost app is using kestrel and on server when i am hosting my app is using IIS.

Body:
You could try to set the serverTimeout and KeepAliveInterval in your program.cs:

builder.Services.AddSignalR(c =>
{
    c.EnableDetailedErrors = true;
    c.ClientTimeoutInterval = TimeSpan.FromSeconds(30);
    c.KeepAliveInterval = TimeSpan.FromSeconds(15);
});

Reason:

If the server hasn't sent a message within this interval, a ping message is sent automatically to keep the connection open. When changing KeepAliveInterval, change the ServerTimeout or serverTimeoutInMilliseconds setting on the client. The recommended ServerTimeout or serverTimeoutInMilliseconds value is double the KeepAliveInterval value.
So,you'd better not set the value of KeepAliveInterval as  max value.


问:
Tomcat Auto Deploy Feature is this good?
I downloaded and setup my Apache Tomcat 6 in our production server. I then started it to see if it's running, and found out that its okay.

It runs and then I place my project war file there.  I am about to restart the tomcat service when I notice that that my web archive file was already unzipped and my project web file is already set at the web apps folder.

I think, my setup has an auto-deploy feature but I kept on thinking if this is a good thing?

I have these questions in mind:

Does Tomcat really auto deploys web archive file and what is the frequency that it does?

Is this a nice feature?

So what if I leave my war file there, does that mean that Tomcat will reload or unzip the archive file every now and then?

Is what Tomcat does to my war file the same as when I properly restart my tomcat and let the tomcat service deploy my war file?

答: Be careful when using this autoDeploy feature. It will first 'undeploy' the application if an existing version exists and it will delete the context configuration file as well ($CATALINA_HOME/conf/[engine-name]/[host-name]/[app-name].xml).

ContentLicense: CC BY-SA 3.0


问:
Muting a video in a VideoView
I'm playing a video (from youtube) using a VideoView, like this:

```<code>VideoView video = (ViewView) this.findViewById(R.id.youtube_video);
MediaController controllers = new MediaController(this);
controllers.setAnchorView(video);
video.setMediaController(controllers);

video.setVideoURI(videoUri);
video.start()
</code>```

I would like to be able to mute the video, but so far the only thing I found is:

```<code>AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);
</code>```

Which works fine in that the video is muted, but the problem is that all of the streamed music is muted, and if there's another video (or audio) which I want to play it's also muted.

Is there a way to just target the specific stream to be muted?

Thanks.

答:
If you are coding in kotlin, Just use this line of code</p>
```<code>videoView.setOnPreparedListener { video->
            video.setVolume(0f,0f)
        }
</code>```

Title: Muting a video in a VideoView

Body:
I'm playing a video (from youtube) using a VideoView, like this:

VideoView video = (ViewView) this.findViewById(R.id.youtube_video);
MediaController controllers = new MediaController(this);
controllers.setAnchorView(video);
video.setMediaController(controllers);

video.setVideoURI(videoUri);
video.start()

I would like to be able to mute the video, but so far the only thing I found is:

AudioManager audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamMute(AudioManager.STREAM_MUSIC, true);

Which works fine in that the video is muted, but the problem is that all of the streamed music is muted, and if there's another video (or audio) which I want to play it's also muted.

Is there a way to just target the specific stream to be muted?

Thanks.

Body:
If you are coding in kotlin, Just use this line of code

videoView.setOnPreparedListener { video->
            video.setVolume(0f,0f)
        }


问:
Error "Previous SQL was not a query" in Python?
I am trying to call a stored procedure in Python but it keeps giving me the following error. The  procedure is written in SQL Server 2008 and I am using PyODBC to call the method and pass parameters to it.

```<code>import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+serveripaddr+';DATABASE='+database+';UID='+userid+';PWD='+password+'')
cursor = cnxn.cursor()
cursor.execute("{call p_GetTransactionsStats('KENYA', '41')}")
rows = cursor.fetchall()
</code>```

The last line results in the following exception:

```<code>ProgrammingError: No results.  Previous SQL was not a query.
</code>```

What could be the problem here?

答:
For future Googlers: I was getting this error and my stored procedure wasn't actually even inserting the data in the database table I wanted when run from pyodbc.  My problem was that I didn't close the cursor and commit after executing. Make sure you do

```<code>cursor.close()
connection.commit()
</code>```

after running cursor.execute() if you're doing more than just SELECTs

Body:
I am trying to call a stored procedure in Python but it keeps giving me the following error. The  procedure is written in SQL Server 2008 and I am using PyODBC to call the method and pass parameters to it.

import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+serveripaddr+';DATABASE='+database+';UID='+userid+';PWD='+password+'')
cursor = cnxn.cursor()
cursor.execute("{call p_GetTransactionsStats('KENYA', '41')}")
rows = cursor.fetchall()

The last line results in the following exception:

ProgrammingError: No results.  Previous SQL was not a query.

What could be the problem here?

Body:
For future Googlers: I was getting this error and my stored procedure wasn't actually even inserting the data in the database table I wanted when run from pyodbc.  My problem was that I didn't close the cursor and commit after executing. Make sure you do

cursor.close()
connection.commit()

after running cursor.execute() if you're doing more than just SELECTs


问:
Can sitemap XML files be outside of root directory
Can sitemap XML files be outside of root directory? I can't put the file into the Root of the website. Is there anything I can do?</p>

答:
According to https://www.sitemaps.org/protocol.html

The location of a Sitemap file determines the set of URLs that can be included in that Sitemap. A Sitemap file located at http://example.com/catalog/sitemap.xml can include any URLs starting with http://example.com/catalog/ but can not include URLs starting with http://example.com/images/.

So the short answer is - yes, it can be located outside of the root directory, but it will only consider paths starting from the subdirectory level up as valid. Which is not something most people want.


问:
How to specify a path to Meson custom_target() command?
I did a simple custom target in Meson:

```<code>
my_build = custom_target('my_build', command: ['../my_script.sh', '-arg1'], build_always_stale: true, output: 'fake')

</code>```

This works OK..., but when I try to use this as subproject from other Meson projects, I get a message that ../my_script.sh cannot be found.

How do I specify the path to my_script.sh, so that the script is always found, no matter called directly in this subproject, or from a root project?

答:
You need to specify the path to your script and you can do that like this:

scirpt_path = join_paths(meson.current_source_dir(), 'my_script.sh')

and your custom target will look like this:

my_build = custom_target('my_build', command: [script_path, '-arg1'], build_always_stale: true, output: 'fake')

The reason it works for you when you don't have a subproject is because you have a structure that your build directory is in the root of your project, so it is possible to find your script with ../my_script.sh

Body:
I did a simple custom target in Meson:

my_build = custom_target('my_build', command: ['../my_script.sh', '-arg1'], build_always_stale: true, output: 'fake')

This works OK..., but when I try to use this as subproject from other Meson projects, I get a message that ../my_script.sh cannot be found.

How do I specify the path to my_script.sh, so that the script is always found, no matter called directly in this subproject, or from a root project?


问:
R: Max/Min date returning NA
I have a year column & month column. I paste them into a new column and achieve the format of "yyyy-mm-dd". All "dd" are "01". I tried converting this column using "as.date", "as.POSIXct". However when I tried to find Max & Min, the result is NA. Below is the code I ran.</p>
```<code>##Add 0 as leading numeric for single numeric months
df$new_month_col <- ifelse(nchar(df$month) < 2,
paste0("0",df$month,sep = ""), df$month)

##Paste as new column "date"
df$date <- paste(df$year,"-",df$new_month_col,"-01",sep = "")

##Converting data type
df$date<- as.date(df$date, format = "%Y-%m-%d")
df$date<- as.POSIXct(df$date, format = "%Y-%m-%d")

max(df$date)
[1] NA
</code>```

Title: R: Max/Min date returning NA

Body:
I have a year column & month column. I paste them into a new column and achieve the format of "yyyy-mm-dd". All "dd" are "01". I tried converting this column using "as.date", "as.POSIXct". However when I tried to find Max & Min, the result is NA. Below is the code I ran.

##Add 0 as leading numeric for single numeric months
df$new_month_col <- ifelse(nchar(df$month) < 2,
paste0("0",df$month,sep = ""), df$month)

##Paste as new column "date"
df$date <- paste(df$year,"-",df$new_month_col,"-01",sep = "")

##Converting data type
df$date<- as.date(df$date, format = "%Y-%m-%d")
df$date<- as.POSIXct(df$date, format = "%Y-%m-%d")

max(df$date)
[1] NA

Body:
Something like this?

library(tidyverse)

df <- tibble(date = c("2022-1", "2021-10", "2020-9", NA))
df
#> # A tibble: 4 x 1
#>   date
#>   <chr>
#> 1 2022-1
#> 2 2021-10
#> 3 2020-9
#> 4 <NA>

df <- mutate(df, date = date %>% paste0("-01") %>% as.Date())
df
#> # A tibble: 4 x 1
#>   date
#>   <date>
#> 1 2022-01-01
#> 2 2021-10-01
#> 3 2020-09-01
#> 4 NA

min(df$date, na.rm = TRUE)
#> [1] "2020-09-01"
max(df$date, na.rm = TRUE)
#> [1] "2022-01-01"

Created on 2022-02-08 by the reprex package (v2.0.1)


问:
How to load all files from a directory?
Like the title says; how do I load every file in a directory? I'm interested in both c++ and lua.

Edit:
For windows I'd be glad for some real working code and especially for lua. I can do with boost::filesystem for c++.

答: For a C++ solution, have a look at the Boost.Filesystem library.</p>

OwnerDisplayName: Bumhunter

ContentLicense: CC BY-SA 2.5

Title: How to load all files from a directory?

LastEditorDisplayName: Bumhunter

OwnerDisplayName: Pukku

LastEditorDisplayName: Pukku


问:
Powershell to upload text string to blob through Azure Automation account
There is no local machine to store a intermittent file. Read data from Blob to string variable, after modification of text string, need to upload the content to destination azure blob through azure automation account using powershell. Everything need to be done in Azure automation account.</p>

答:
Read data from Blob to string variable

If it is the big blob, then Output the blob content to a stream else Output the blob content as string.

```<code>$StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccountName
$Blob = Get-AzureStorageBlob -Context $StorageAccount.Context -Container $container -Blob $Filename
$Text = $blob.ICloudBlob.DownloadText()
Write-Output $Text
</code>```

To get the contents of the blob as a string and pipe it to convertfrom-json directly:

```<code>$blobs | Get-AzureStorageBlobContent -AsString | ConvertFrom-Json ...
</code>```

There are different download options available for Text, Byte, File and Stream in ($Blob.ICloudBlob | Get-Member | where {$_.Name -like "Download*"} | select Name) gives you:

DownloadBlockList

DownloadBlockListAsync

DownloadRangeToByteArray

DownloadRangeToByteArrayAsync

DownloadRangeToStream

DownloadRangeToStreamAsync

DownloadText

DownloadTextAsync

DownloadToByteArray

DownloadToByteArrayAsync

DownloadToFile

DownloadToFileAsync

DownloadToStream

DownloadToStreamAsync

After modification of blob content, for uploading the modified content to the destination blob with the help of Azure Automation and PowerShell commands, please refer the below references will helps you for the following above:

Provision Azure Storage account, automatic file upload using PowerShell

Upload Files to Azure Blob Storage using Power Automate Desktop

Body:
Read data from Blob to string variable

If it is the big blob, then Output the blob content to a stream else Output the blob content as string.

$StorageAccount = Get-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageAccountName
$Blob = Get-AzureStorageBlob -Context $StorageAccount.Context -Container $container -Blob $Filename
$Text = $blob.ICloudBlob.DownloadText()
Write-Output $Text

To get the contents of the blob as a string and pipe it to convertfrom-json directly:

$blobs | Get-AzureStorageBlobContent -AsString | ConvertFrom-Json ...

There are different download options available for Text, Byte, File and Stream in ($Blob.ICloudBlob | Get-Member | where {$_.Name -like "Download*"} | select Name) gives you:

DownloadBlockList

DownloadBlockListAsync

DownloadRangeToByteArray

DownloadRangeToByteArrayAsync

DownloadRangeToStream

DownloadRangeToStreamAsync

DownloadText

DownloadTextAsync

DownloadToByteArray

DownloadToByteArrayAsync

DownloadToFile

DownloadToFileAsync

DownloadToStream

DownloadToStreamAsync

After modification of blob content, for uploading the modified content to the destination blob with the help of Azure Automation and PowerShell commands, please refer the below references will helps you for the following above:

Provision Azure Storage account, automatic file upload using PowerShell

Upload Files to Azure Blob Storage using Power Automate Desktop


问:
Opening Shiny App directly in the default browser
Normally the shiny app opens through the inbuilt browser within R-Studio.  Is it possible to open the app directly in the web browser, say Google Chrome, without going through the R-Studio.</p>

答:
Adding to other replies here, I feel it's worth mentioning that one does not necessarily need to give the full path to the external web browser, if you're happy with the default external browser, and you're using Rstudio (i.e. basically, if your goal is not to open Rstudio's own internal browser).

For Rstudio users, the following will do:

options(shiny.launch.browser = .rs.invokeShinyWindowExternal)

You can run it at the beginning of each session when you need this, or by including this line in your ~/.Rprofile if you like this to be default behaviour, which can be conveniently done with usethis::edit_r_profile().

For more details and alternative settings, see this post.


问:
Spring data mongodb sort on multiple fields
I want to sort on multiple fields in MongoDB using Spring data for MongoDB. Currently I am trying to achieve this using aggregation:

```<code>    Aggregation agg = newAggregation(
            match(Criteria.where("userId").is(userId)),
            sort(Sort.Direction.DESC, "type", "createdDate"),
    );
    AggregationResults<MyBean> results = mongoOperations.aggregate(agg, MyBean.class, MyBean.class);
</code>```

When I am doing this, it is sorting on the type and createdDate on DESC order. But I want DESC on type and ASC on createdDate.

I tried,

```<code>    sort(Sort.Direction.DESC, "type");
    sort(Sort.Direction.ASC, "createdDate");
</code>```

but this is sorting only on createdDate.

答:
Simple sorting without Aggregation object</p>
```<code>import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;

//query: existing mongo query
//mongoTemplate: @Autowired MongoTemplate object
//First create a list of Sort.Order and add multiple criteria's

List<Sort.Order> sortOnMultipleFIelds = new ArrayList<>();
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.DESC, "Field1"));
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.ASC, "Field2"));
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.DESC, "Field3"));

//Apply it on Query
            query.with(Sort.by(sortOnMultipleFIelds);

//Execute query
            List<ClassName> resultList= mongoTemplate.find(query, ClassName.class);
</code>```

Body:
I want to sort on multiple fields in MongoDB using Spring data for MongoDB. Currently I am trying to achieve this using aggregation:

    Aggregation agg = newAggregation(
            match(Criteria.where("userId").is(userId)),
            sort(Sort.Direction.DESC, "type", "createdDate"),
    );
    AggregationResults<MyBean> results = mongoOperations.aggregate(agg, MyBean.class, MyBean.class);

When I am doing this, it is sorting on the type and createdDate on DESC order. But I want DESC on type and ASC on createdDate.

I tried,

    sort(Sort.Direction.DESC, "type");
    sort(Sort.Direction.ASC, "createdDate");

but this is sorting only on createdDate.

Body:
Simple sorting without Aggregation object

import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;

//query: existing mongo query
//mongoTemplate: @Autowired MongoTemplate object
//First create a list of Sort.Order and add multiple criteria's

List<Sort.Order> sortOnMultipleFIelds = new ArrayList<>();
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.DESC, "Field1"));
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.ASC, "Field2"));
            sortOnMultipleFIelds.add(new Sort.Order(Sort.Direction.DESC, "Field3"));

//Apply it on Query
            query.with(Sort.by(sortOnMultipleFIelds);

//Execute query
            List<ClassName> resultList= mongoTemplate.find(query, ClassName.class);


问:
Controlling back pressure in Spring cloud stream
Is there a way to control the amount data that can be processed by a flux. Ex: Lets say I get millions of messages in a stream and I want to process this data. I want to be able to meter each of my k8s pods saying that I want to process 1000 messages a second, how can this be done in Flux? I have already tried limit rate and concurrency in flatmap but its not helping</p>
```<code>    Flux.fromIterable(a).limitRate(1000).publishOn(Schedulers.boundedElastic())
            .flatMap(local -> {
        System.out.println(System.currentTimeMillis() + ": time for : flatmap "+ local);

        return Mono.just(local);
    }, 1).subscribe();
</code>```

答: You can not control back-pressure at the moment due to the fact that reactive support in s-c-stream via s-c-function depends on the actual implementation of source/target binders and at the moment those are non-reactive and because of it there is no way to control back-pressure. Once we have truly reactive binders, you'll get back-pressure functionality</p>

Body:
Is there a way to control the amount data that can be processed by a flux. Ex: Lets say I get millions of messages in a stream and I want to process this data. I want to be able to meter each of my k8s pods saying that I want to process 1000 messages a second, how can this be done in Flux? I have already tried limit rate and concurrency in flatmap but its not helping

    Flux.fromIterable(a).limitRate(1000).publishOn(Schedulers.boundedElastic())
            .flatMap(local -> {
        System.out.println(System.currentTimeMillis() + ": time for : flatmap "+ local);

        return Mono.just(local);
    }, 1).subscribe();


问:
How can I disable a ComboBox item if the selected value is only relevant to a certain option?
I have 4 combo boxes on my windows form.

ComboBox1 has 2 items which are "STUDENT" and "PERSONNEL".

If the user selected "PERSONNEL" on ComboBox1, ComboBox2 to ComboBox4 would be disabled. But if the user changed it to "STUDENT", ComboBox2 to ComboBox4 is enabled again.

I tried an if statement:

```<code>If cbSORP.SelectedItem Is "PERSONNEL" Then
        cbCourse.Enabled = False
        cbYear.Enabled = False
        cbSection.Enabled = False
    Else
        cbCourse.Enabled = True
        cbYear.Enabled = True
        cbSection.Enabled = True
    End If
</code>```

I also tried putting it in a panel and using a timer but still no luck. I'm still learning so please go easy on me.

答:
you have to use ComboBox's Text property instead of SelectedItem property in SelectedIndexChanged event of ComboBox,

```<code>Private Sub cbSORP_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
   If cbSORP.Text = "PERSONNEL" Then
       cbCourse.Enabled = False
       cbYear.Enabled = False
       cbSection.Enabled = False
   ElseIf cbSORP.Text = "STUDENT" Then
       cbCourse.Enabled = True
       cbYear.Enabled = True
       cbSection.Enabled = True
   End If
End Sub
</code>```

Body:
I have 4 combo boxes on my windows form.

ComboBox1 has 2 items which are "STUDENT" and "PERSONNEL".

If the user selected "PERSONNEL" on ComboBox1, ComboBox2 to ComboBox4 would be disabled. But if the user changed it to "STUDENT", ComboBox2 to ComboBox4 is enabled again.

I tried an if statement:

If cbSORP.SelectedItem Is "PERSONNEL" Then
        cbCourse.Enabled = False
        cbYear.Enabled = False
        cbSection.Enabled = False
    Else
        cbCourse.Enabled = True
        cbYear.Enabled = True
        cbSection.Enabled = True
    End If

I also tried putting it in a panel and using a timer but still no luck. I'm still learning so please go easy on me.

Body:
you have to use ComboBox's Text property instead of SelectedItem property in SelectedIndexChanged event of ComboBox,

Private Sub cbSORP_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
   If cbSORP.Text = "PERSONNEL" Then
       cbCourse.Enabled = False
       cbYear.Enabled = False
       cbSection.Enabled = False
   ElseIf cbSORP.Text = "STUDENT" Then
       cbCourse.Enabled = True
       cbYear.Enabled = True
       cbSection.Enabled = True
   End If
End Sub


问:
How to write JSON string to parquet, avro file in scala without spark
I am want to write simple JSON string to parquet and avro file format in scala without spark framework.

My JSON string looks:

    {"emp_id":"123","emp_name":"Mike","emp_status":"true"}
```

I did not find any solution for that, Is it possible to write parquet and avro file from simple JSON string in scala without spark framework??

答:
Here is a example

build.sbt

ThisBuild / version := "0.1.0-SNAPSHOT"

ThisBuild / scalaVersion := "2.13.8"

lazy val root = (project in file("."))
  .settings(
    name := "parquet",
    libraryDependencies ++= Seq(
      "com.github.mjakubowski84" %% "parquet4s-core" % "2.1.0",
      "org.apache.hadoop" % "hadoop-client" % "3.3.1"
    ),
  )

```
<p><code>Test.scala</code></p>
<pre class="lang-scala prettyprint-override"><code>import com.github.mjakubowski84.parquet4s.{ ParquetReader, ParquetWriter, Path }

object Test {
  def main(args: Array[String]): Unit = {
    case class Emp(emp_id: String, emp_name: String, emp_status: String)

    val emps = Seq(
      Emp("123", "Mike", "true")
    )

    val path = Path("emp1.parquet")

    ParquetWriter.of[Emp].writeAndClose(path, emps)

    val parquetIterable = ParquetReader.as[Emp].read(path)
    try {
      parquetIterable.foreach(println)
    } finally parquetIterable.close()
  }
}
</code>```

And the output

```<code>Emp(123,Mike,true)
</code>```

Body:
I am want to write simple JSON string to parquet and avro file format in scala without spark framework.

My JSON string looks:

    {"emp_id":"123","emp_name":"Mike","emp_status":"true"}

I did not find any solution for that, Is it possible to write parquet and avro file from simple JSON string in scala without spark framework??

Body:
Here is a example

build.sbt

ThisBuild / version := "0.1.0-SNAPSHOT"

ThisBuild / scalaVersion := "2.13.8"

lazy val root = (project in file("."))
  .settings(
    name := "parquet",
    libraryDependencies ++= Seq(
      "com.github.mjakubowski84" %% "parquet4s-core" % "2.1.0",
      "org.apache.hadoop" % "hadoop-client" % "3.3.1"
    ),
  )

Test.scala

import com.github.mjakubowski84.parquet4s.{ ParquetReader, ParquetWriter, Path }

object Test {
  def main(args: Array[String]): Unit = {
    case class Emp(emp_id: String, emp_name: String, emp_status: String)

    val emps = Seq(
      Emp("123", "Mike", "true")
    )

    val path = Path("emp1.parquet")

    ParquetWriter.of[Emp].writeAndClose(path, emps)

    val parquetIterable = ParquetReader.as[Emp].read(path)
    try {
      parquetIterable.foreach(println)
    } finally parquetIterable.close()
  }
}

And the output

Emp(123,Mike,true)


问:
Find list of empty indices in a javascript array
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

```<code>["x", "", "", "x", "", "", ""]
</code>```

Would return something like:

```<code>[1,2,4,5,6]
</code>```

I have attempted something like this:

```<code>empty = roster.findIndex((obj) => Object.keys(obj).length === 0)
</code>```

However I can't come up with a way to iterate over the list.

答:
arr.map((item, index) => item === '' ? index : null).filter(item => item)
```

Body:
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

["x", "", "", "x", "", "", ""]

Would return something like:

[1,2,4,5,6]

I have attempted something like this:

empty = roster.findIndex((obj) => Object.keys(obj).length === 0)

However I can't come up with a way to iterate over the list.


问:
How to implement non-primitive FK correctly in EF Core via fluent
I've trying to create a new foreign key in entity framework core 6 but I am getting the following error?

The types of the properties specified for the foreign key {'RoleId' : RoleId} on entity type 'SomeEntity' do not match the
types of the properties in the principal key {'Id' : Guid} on entity
type 'DbsRole'. Provide properties that use the same types in the same
order.

How can I fix this via Fluent API without adding navigation properties to my entities as I am following DDD principles (bounded contexts etc)?

I thought the conversion handler would be sufficient but obviously not.

RoleId.cs

```<code>public record RoleId(Guid Value);
</code>```

SomeEntity.cs

```<code>public class SomeEntity : Entity<Guid>, IAggregateRoot
{
   public Guid Id {get; private set;} = null!;

   public string Name { get; private set; } = null!;

   public RoleId RoleId { get; private set; } = null!;
}
</code>```

MyContext.cs

```<code>public partial class MyContext : IdentityDbContext<MyUser, MyRole, Guid>
{
   public virtual DbSet<SomeEntity> SomeEntity { get; set; } = default!;

   //... snip...

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
      base.OnModelCreating(modelBuilder);

      _ = modelBuilder.Ignore<RoleId>();

      _ = modelBuilder.Entity<SomeEntity>(entity =>
      {
         _ = entity.HasKey(e => e.Id);

        _ = entity.Property(e => e.Name)
                  .IsRequired();

        _ = entity.HasIndex(e => e.Name);

        _ = entity.Property(e => e.RoleId)
                  .IsRequired()
                  .HasConversion(x => x.Value, x => new RoleId(x));

        _ = entity.HasOne<MyRole>()
                  .WithMany()
                  .IsRequired()
                  .HasForeignKey(p => p.RoleId);
       });
    }
}

</code>```

MyUser.cs

```<code>public class MyUser : IdentityUser<Guid>
{
  //... snip...
}
</code>```

MyRole.cs

```<code>public class MyRole : IdentityRole<Guid>
{
   // ...snip...
}
</code>```

Regards

Kyle

答:
How can I fix this via Fluent API without adding navigation properties to my entities as I am following DDD principles (bounded contexts etc)?

You can't (at least currently - up to EF Core 6.0 inclusive). Navigation properties have nothing to do with the problem, which is the type of the PK and FK properties. The error message is quite clear of what is expected

Provide properties that use the same types...

You may consider it EF Core limitation/shortcoming, but it is what it is, and you must follow EF Core data model rules if you want to use it for persisting your domain model.

Which in general means you shouldn't be using the domain model as data model directly. Bounded contexts, value objects, encapsulation - these are not natural for data models. With small exceptions, EF Core context represents a database, DbSet is a table, entity is a record in that table, and navigation properties are relationships. So the best would be if you create separate models and map between the two where needed. Yes, it requires additional efforts, but that's the only way you can follow the differences between the two models requirements.

But back on the concrete issue. EF Core requires both properties to have one and the same type. This means you either have to use Guid type for SomeEntity.RoleId, or use RoleId type for MyRole.Id. However the second is not possible with identity model, since both user, role and related things are constrained to have one and the same type of key (the last generic type argument, in your case Guid). So I'm afraid that if you want to use the domain model as data model directly, the only option currently in this particular case is to make SomeEntity.RoleId type Guid.

Body:
I've trying to create a new foreign key in entity framework core 6 but I am getting the following error?

The types of the properties specified for the foreign key {'RoleId' : RoleId} on entity type 'SomeEntity' do not match the
types of the properties in the principal key {'Id' : Guid} on entity
type 'DbsRole'. Provide properties that use the same types in the same
order.

How can I fix this via Fluent API without adding navigation properties to my entities as I am following DDD principles (bounded contexts etc)?

I thought the conversion handler would be sufficient but obviously not.

RoleId.cs

public record RoleId(Guid Value);

SomeEntity.cs

public class SomeEntity : Entity<Guid>, IAggregateRoot
{
   public Guid Id {get; private set;} = null!;

   public string Name { get; private set; } = null!;

   public RoleId RoleId { get; private set; } = null!;
}

MyContext.cs

public partial class MyContext : IdentityDbContext<MyUser, MyRole, Guid>
{
   public virtual DbSet<SomeEntity> SomeEntity { get; set; } = default!;

   //... snip...

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
      base.OnModelCreating(modelBuilder);

      _ = modelBuilder.Ignore<RoleId>();

      _ = modelBuilder.Entity<SomeEntity>(entity =>
      {
         _ = entity.HasKey(e => e.Id);

        _ = entity.Property(e => e.Name)
                  .IsRequired();

        _ = entity.HasIndex(e => e.Name);

        _ = entity.Property(e => e.RoleId)
                  .IsRequired()
                  .HasConversion(x => x.Value, x => new RoleId(x));

        _ = entity.HasOne<MyRole>()
                  .WithMany()
                  .IsRequired()
                  .HasForeignKey(p => p.RoleId);
       });
    }
}

MyUser.cs

public class MyUser : IdentityUser<Guid>
{
  //... snip...
}

MyRole.cs

public class MyRole : IdentityRole<Guid>
{
   // ...snip...
}

Regards

Kyle


问:
How to use Fiddler to debug traffic from Any app (eg. C#/WPF app)
I am tring to debug whats wrong with my HTTP requests from another question here on SO. So i read a bit about Fiddler and wanted to use it to debug my problem. But I can't seem to get traffic from my WPF application to go through Fiddler. I believe I need to configure a proxy. I am using a WebClient for a basic example, but I think i will require a WebRequest later. But for now, with a simple WebClient, how can I get it to go through Fiddler (I believe I have to set proxy to localhost:8888)?

UPDATE:

I don't know if i did the right thing or not but I tried

```<code>var wc = new WebClient();
WebProxy proxy = new WebProxy();
proxy.Address = new Uri("http://localhost:8888");
wc.Proxy = proxy;
</code>```

but failed - I don't see any traffic in Fiddler

I tried ...

```<code>var wc = new WebClient();
WebProxy proxy = new WebProxy("127.0.0.1", 8888);
wc.Proxy = proxy;
</code>```

still nothing

答:
Maybe a little late, but...

I get around this simply by appending a "dot" to localhost, so instead of accessing localhost, I try to access localhost. (notice the dot at the end of the hostname)

Credit where credit is due:
I got this unusual tip from this thread http://www.west-wind.com/weblog/posts/2009/Jan/14/Monitoring-HTTP-Output-with-Fiddler-in-NET-HTTP-Clients-and-WCF-Proxies#596591

Works fine!

Body:
I am tring to debug whats wrong with my HTTP requests from another question here on SO. So i read a bit about Fiddler and wanted to use it to debug my problem. But I can't seem to get traffic from my WPF application to go through Fiddler. I believe I need to configure a proxy. I am using a WebClient for a basic example, but I think i will require a WebRequest later. But for now, with a simple WebClient, how can I get it to go through Fiddler (I believe I have to set proxy to localhost:8888)?

UPDATE:

I don't know if i did the right thing or not but I tried

var wc = new WebClient();
WebProxy proxy = new WebProxy();
proxy.Address = new Uri("http://localhost:8888");
wc.Proxy = proxy;

but failed - I don't see any traffic in Fiddler

I tried ...

var wc = new WebClient();
WebProxy proxy = new WebProxy("127.0.0.1", 8888);
wc.Proxy = proxy;

still nothing