问:
Trying to clear an array with only one occurance
So here's the situation : i got an array who contain message between users, ->

```<code>Array
(
    [0] => Array
        (
            [id_message] => 17
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:50
            [content] => yo !!
            [msg_read] => 1
        )

    [1] => Array
        (
            [id_message] => 18
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:50
            [content] => yo !!
            [msg_read] => 1
        )

    [2] => Array
        (
            [id_message] => 16
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:48
            [content] => yo
            [msg_read] => 1
        )

    [3] => Array
        (
            [id_message] => 15
            [id_user_sending] => 4
            [id_user_receiving] => 1
            [date] => 2020-02-19 01:03:44
            [content] => kk
            [msg_read] => 1
        )

    [4] => Array
        (
            [id_message] => 14
            [id_user_sending] => 4
            [id_user_receiving] => 3
            [date] => 2020-02-19 01:03:27
            [content] => hey
            [msg_read] => 1
        )

    [5] => Array
        (
            [id_message] => 13
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:22
            [content] => salut !
            [msg_read] => 1
        )

    [6] => Array
        (
            [id_message] => 12
            [id_user_sending] => 4
            [id_user_receiving] => 1
            [date] => 2020-02-19 00:47:50
            [content] => yo ?
            [msg_read] => 1
        )

    [7] => Array
        (
            [id_message] => 11
            [id_user_sending] => 3
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:27
            [content] => hey dernier test !
            [msg_read] => 1
        )

    [8] => Array
        (
            [id_message] => 10
            [id_user_sending] => 2
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:17
            [content] => yo eksjsjs !
            [msg_read] => 1
        )

    [9] => Array
        (
            [id_message] => 9
            [id_user_sending] => 1
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:05
            [content] => salut !
            [msg_read] => 1
        )

)
</code>```

THE ID OF USER which connected is 4
I want clear this array with only one occurence for making a chat list with only one field by user (id 4) independently of how message there is between them.

So i code two function wheres i got à problem ---->

```<code>function is_not_yet_in_array($arraymult, $arraysimple)
{

  $i = 0;
  $j = 0;

  while (isset($arraymult[$i]))
  {
    // this conditions isnt correct I still dont know why

      if ( ($arraymult[$i]['id_user_sending'] == $arraysimple['id_user_sending'])
      ||  ($arraymult[$i]['id_user_receiving'] == $arraysimple['id_user_receiving']))
        return 0;
    $i++;
  }
  return 1;
}

function rend_moi_une_occurence_par_conv($raw_message)
{
  $array = array();
  $i = 0;
  $j = 0;

  while (isset($raw_message[$i]))
  {

    if (is_not_yet_in_array($array, $raw_message[$i]) == 1)
    {
      $array[$j] =  $raw_message[$i];
      $j++;
    }
    $i++;
  }
  return ($array);
}

$arraytoconvertinJson = rend_moi_une_occurence_par_conv($raw_message);
</code>```

Here the return of function rend_moi_une_occurencence_par_conv so i prionted $arraytoconvertinJson -->>

```<code>Array
(
    [0] => Array
        (
            [id_message] => 19
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 13:01:53
            [content] => yo
            [msg_read] => 1
        )

    [1] => Array
        (
            [id_message] => 11
            [id_user_sending] => 3
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:27
            [content] => hey dernier test !
            [msg_read] => 1
        )

)
</code>```

I'm pretty sure that my condition in the function is not yet in array isnt good but after 24h on it im looking for some help ..

This is the return i want, so the id of the user which connected is 4, i want get a mult array who contain the last message between him and himself and him and other users.

```<code>    Array
    (
        [0] => Array
            (
                [id_message] => 19
                [id_user_sending] => 4
                [id_user_receiving] => 2
                [date] => 2020-02-19 13:01:53
                [content] => yo
                [msg_read] => 1
            )

        [1] => Array
            (
                [id_message] => 11
                [id_user_sending] => 3
                [id_user_receiving] => 4
                [date] => 2020-02-19 00:47:27
                [content] => hey dernier test !
                [msg_read] => 1
            )
        [2] => Array
                (
                    [id_message] => 15
                    [id_user_sending] => 1
                    [id_user_receiving] => 4
                    [date] => 2020-02-19 00:47:27
                    [content] => hey dernier test !
                    [msg_read] => 1
                )
        [3] => Array
                    (
                      [id_message] =>
                        [id_user_sending] => 4
                        [id_user_receiving] => 4
                        [date] => 2020-02-19 00:47:27
                        [content] => hey dernier test !
                        [msg_read] => 1
                    )

    )
</code>```

This is the return i want, so the id of the user which connected is 4, i want get a mult array who contain the last message between him and himself and him and other users ( this is not a valid output i just modify value of id user sending/receving for the example).
-->

```<code>Array
(
    [0] => Array
        (
            [id_message] => 19
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 13:01:53
            [content] => yo
            [msg_read] => 1
        )

    [1] => Array
        (
            [id_message] => 11
            [id_user_sending] => 3
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:27
            [content] => hey dernier test !
            [msg_read] => 1
        )
    [2] => Array
            (
                [id_message] => 15
                [id_user_sending] => 1
                [id_user_receiving] => 4
                [date] => 2020-02-19 00:47:27
                [content] => hey dernier test !
                [msg_read] => 1
            )
    [3] => Array
                (
                  [id_message] =>
                    [id_user_sending] => 4
                    [id_user_receiving] => 4
                    [date] => 2020-02-19 00:47:27
                    [content] => hey dernier test !
                    [msg_read] => 1
                )

)
</code>```

Thank you guys for help, im new here so sry if its not perfectly clearly.

答:
I'm not 100% sure what you are asking, but this is to get the most recent messages sent to a user.

```<code>function getLatestMessages(array $messages, $receiverId) {
    $times = [];
    $chats = [];
    foreach ($messages as $message) {
        if ($message['id_user_receiving'] === $receiverId) {
            $senderId = $message['id_user_sending'];
            if (!isset($times[$senderId])) {
                $times[$senderId] = 0;
            }
            $date = new DateTime($message['date']);
            $unix = $date->getTimestamp();
            if ($unix > $times[$senderId]) {
                $times[$senderId] = $unix;
                $chats[$senderId] = $message;
            }
        }
    }
    return $chats;
}
</code>```

To get the most recent messages sent from everybody to user 3:

```<code>getLatestMessages($messages, 3);
</code>```

Result:

```<code>Array
(
    [1] => Array
        (
            [id_message] => 12
            [id_user_sending] => 1
            [id_user_receiving] => 3
            [date] => 2020-02-19 09:03:50
            [content] => Last message from user 1 to user 3
            [msg_read] => 1
        )

    [2] => Array
        (
            [id_message] => 77
            [id_user_sending] => 2
            [id_user_receiving] => 3
            [date] => 2020-02-19 10:03:50
            [content] => Only message from user 2 to user 3
            [msg_read] => 1
        )

)
</code>```

And here is the sample data I used.

```<code>$messages = [
    [
        'id_message' => 17,
        'id_user_sending' => 1,
        'id_user_receiving' => 1,
        'date' => '2020-02-19 01:03:50',
        'content' => 'Only message from user 1 to user 1',
        'msg_read' => 1
    ],
    [
        'id_message' => 53,
        'id_user_sending' => 3,
        'id_user_receiving' => 1,
        'date' => '2020-02-19 02:03:50',
        'content' => 'First message from user 3 to user 1',
        'msg_read' => 1
    ],
    [
        'id_message' => 32,
        'id_user_sending' => 3,
        'id_user_receiving' => 1,
        'date' => '2020-02-19 03:03:50',
        'content' => 'Last message from user 3 to user 1',
        'msg_read' => 1
    ],
    [
        'id_message' => 72,
        'id_user_sending' => 2,
        'id_user_receiving' => 2,
        'date' => '2020-02-19 04:03:50',
        'content' => 'Only message from user 2 to user 2',
        'msg_read' => 1
    ],
    [
        'id_message' => 4,
        'id_user_sending' => 1,
        'id_user_receiving' => 2,
        'date' => '2020-02-19 05:03:50',
        'content' => 'Only message from user 1 to user 2',
        'msg_read' => 1
    ],
    [
        'id_message' => 82,
        'id_user_sending' => 3,
        'id_user_receiving' => 2,
        'date' => '2020-02-19 06:03:50',
        'content' => 'Only message from user 3 to user 2',
        'msg_read' => 1
    ],
    [
        'id_message' => 145,
        'id_user_sending' => 1,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 07:03:50',
        'content' => 'First message from user 1 to user 3',
        'msg_read' => 1
    ],
    [
        'id_message' => 31,
        'id_user_sending' => 1,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 08:03:50',
        'content' => 'Second message from user 1 to user 3',
        'msg_read' => 1
    ],
    [
        'id_message' => 12,
        'id_user_sending' => 1,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 09:03:50',
        'content' => 'Last message from user 1 to user 3',
        'msg_read' => 1
    ],
    [
        'id_message' => 77,
        'id_user_sending' => 2,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 10:03:50',
        'content' => 'Only message from user 2 to user 3',
        'msg_read' => 1
    ],
];
</code>```

Body:
So here's the situation : i got an array who contain message between users, ->

Array
(
    [0] => Array
        (
            [id_message] => 17
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:50
            [content] => yo !!
            [msg_read] => 1
        )

    [1] => Array
        (
            [id_message] => 18
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:50
            [content] => yo !!
            [msg_read] => 1
        )

    [2] => Array
        (
            [id_message] => 16
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:48
            [content] => yo
            [msg_read] => 1
        )

    [3] => Array
        (
            [id_message] => 15
            [id_user_sending] => 4
            [id_user_receiving] => 1
            [date] => 2020-02-19 01:03:44
            [content] => kk
            [msg_read] => 1
        )

    [4] => Array
        (
            [id_message] => 14
            [id_user_sending] => 4
            [id_user_receiving] => 3
            [date] => 2020-02-19 01:03:27
            [content] => hey
            [msg_read] => 1
        )

    [5] => Array
        (
            [id_message] => 13
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 01:03:22
            [content] => salut !
            [msg_read] => 1
        )

    [6] => Array
        (
            [id_message] => 12
            [id_user_sending] => 4
            [id_user_receiving] => 1
            [date] => 2020-02-19 00:47:50
            [content] => yo ?
            [msg_read] => 1
        )

    [7] => Array
        (
            [id_message] => 11
            [id_user_sending] => 3
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:27
            [content] => hey dernier test !
            [msg_read] => 1
        )

    [8] => Array
        (
            [id_message] => 10
            [id_user_sending] => 2
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:17
            [content] => yo eksjsjs !
            [msg_read] => 1
        )

    [9] => Array
        (
            [id_message] => 9
            [id_user_sending] => 1
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:05
            [content] => salut !
            [msg_read] => 1
        )

)

THE ID OF USER which connected is 4
I want clear this array with only one occurence for making a chat list with only one field by user (id 4) independently of how message there is between them.

So i code two function wheres i got à problem ---->

function is_not_yet_in_array($arraymult, $arraysimple)
{

  $i = 0;
  $j = 0;

  while (isset($arraymult[$i]))
  {
    // this conditions isnt correct I still dont know why

      if ( ($arraymult[$i]['id_user_sending'] == $arraysimple['id_user_sending'])
      ||  ($arraymult[$i]['id_user_receiving'] == $arraysimple['id_user_receiving']))
        return 0;
    $i++;
  }
  return 1;
}

function rend_moi_une_occurence_par_conv($raw_message)
{
  $array = array();
  $i = 0;
  $j = 0;

  while (isset($raw_message[$i]))
  {

    if (is_not_yet_in_array($array, $raw_message[$i]) == 1)
    {
      $array[$j] =  $raw_message[$i];
      $j++;
    }
    $i++;
  }
  return ($array);
}

$arraytoconvertinJson = rend_moi_une_occurence_par_conv($raw_message);

Here the return of function rend_moi_une_occurencence_par_conv so i prionted $arraytoconvertinJson -->>

Array
(
    [0] => Array
        (
            [id_message] => 19
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 13:01:53
            [content] => yo
            [msg_read] => 1
        )

    [1] => Array
        (
            [id_message] => 11
            [id_user_sending] => 3
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:27
            [content] => hey dernier test !
            [msg_read] => 1
        )

)

I'm pretty sure that my condition in the function is not yet in array isnt good but after 24h on it im looking for some help ..

This is the return i want, so the id of the user which connected is 4, i want get a mult array who contain the last message between him and himself and him and other users.

    Array
    (
        [0] => Array
            (
                [id_message] => 19
                [id_user_sending] => 4
                [id_user_receiving] => 2
                [date] => 2020-02-19 13:01:53
                [content] => yo
                [msg_read] => 1
            )

        [1] => Array
            (
                [id_message] => 11
                [id_user_sending] => 3
                [id_user_receiving] => 4
                [date] => 2020-02-19 00:47:27
                [content] => hey dernier test !
                [msg_read] => 1
            )
        [2] => Array
                (
                    [id_message] => 15
                    [id_user_sending] => 1
                    [id_user_receiving] => 4
                    [date] => 2020-02-19 00:47:27
                    [content] => hey dernier test !
                    [msg_read] => 1
                )
        [3] => Array
                    (
                      [id_message] =>
                        [id_user_sending] => 4
                        [id_user_receiving] => 4
                        [date] => 2020-02-19 00:47:27
                        [content] => hey dernier test !
                        [msg_read] => 1
                    )

    )

This is the return i want, so the id of the user which connected is 4, i want get a mult array who contain the last message between him and himself and him and other users ( this is not a valid output i just modify value of id user sending/receving for the example).
-->

Array
(
    [0] => Array
        (
            [id_message] => 19
            [id_user_sending] => 4
            [id_user_receiving] => 2
            [date] => 2020-02-19 13:01:53
            [content] => yo
            [msg_read] => 1
        )

    [1] => Array
        (
            [id_message] => 11
            [id_user_sending] => 3
            [id_user_receiving] => 4
            [date] => 2020-02-19 00:47:27
            [content] => hey dernier test !
            [msg_read] => 1
        )
    [2] => Array
            (
                [id_message] => 15
                [id_user_sending] => 1
                [id_user_receiving] => 4
                [date] => 2020-02-19 00:47:27
                [content] => hey dernier test !
                [msg_read] => 1
            )
    [3] => Array
                (
                  [id_message] =>
                    [id_user_sending] => 4
                    [id_user_receiving] => 4
                    [date] => 2020-02-19 00:47:27
                    [content] => hey dernier test !
                    [msg_read] => 1
                )

)

Thank you guys for help, im new here so sry if its not perfectly clearly.

Body:
I'm not 100% sure what you are asking, but this is to get the most recent messages sent to a user.

function getLatestMessages(array $messages, $receiverId) {
    $times = [];
    $chats = [];
    foreach ($messages as $message) {
        if ($message['id_user_receiving'] === $receiverId) {
            $senderId = $message['id_user_sending'];
            if (!isset($times[$senderId])) {
                $times[$senderId] = 0;
            }
            $date = new DateTime($message['date']);
            $unix = $date->getTimestamp();
            if ($unix > $times[$senderId]) {
                $times[$senderId] = $unix;
                $chats[$senderId] = $message;
            }
        }
    }
    return $chats;
}

To get the most recent messages sent from everybody to user 3:

getLatestMessages($messages, 3);

Result:

Array
(
    [1] => Array
        (
            [id_message] => 12
            [id_user_sending] => 1
            [id_user_receiving] => 3
            [date] => 2020-02-19 09:03:50
            [content] => Last message from user 1 to user 3
            [msg_read] => 1
        )

    [2] => Array
        (
            [id_message] => 77
            [id_user_sending] => 2
            [id_user_receiving] => 3
            [date] => 2020-02-19 10:03:50
            [content] => Only message from user 2 to user 3
            [msg_read] => 1
        )

)

And here is the sample data I used.

$messages = [
    [
        'id_message' => 17,
        'id_user_sending' => 1,
        'id_user_receiving' => 1,
        'date' => '2020-02-19 01:03:50',
        'content' => 'Only message from user 1 to user 1',
        'msg_read' => 1
    ],
    [
        'id_message' => 53,
        'id_user_sending' => 3,
        'id_user_receiving' => 1,
        'date' => '2020-02-19 02:03:50',
        'content' => 'First message from user 3 to user 1',
        'msg_read' => 1
    ],
    [
        'id_message' => 32,
        'id_user_sending' => 3,
        'id_user_receiving' => 1,
        'date' => '2020-02-19 03:03:50',
        'content' => 'Last message from user 3 to user 1',
        'msg_read' => 1
    ],
    [
        'id_message' => 72,
        'id_user_sending' => 2,
        'id_user_receiving' => 2,
        'date' => '2020-02-19 04:03:50',
        'content' => 'Only message from user 2 to user 2',
        'msg_read' => 1
    ],
    [
        'id_message' => 4,
        'id_user_sending' => 1,
        'id_user_receiving' => 2,
        'date' => '2020-02-19 05:03:50',
        'content' => 'Only message from user 1 to user 2',
        'msg_read' => 1
    ],
    [
        'id_message' => 82,
        'id_user_sending' => 3,
        'id_user_receiving' => 2,
        'date' => '2020-02-19 06:03:50',
        'content' => 'Only message from user 3 to user 2',
        'msg_read' => 1
    ],
    [
        'id_message' => 145,
        'id_user_sending' => 1,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 07:03:50',
        'content' => 'First message from user 1 to user 3',
        'msg_read' => 1
    ],
    [
        'id_message' => 31,
        'id_user_sending' => 1,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 08:03:50',
        'content' => 'Second message from user 1 to user 3',
        'msg_read' => 1
    ],
    [
        'id_message' => 12,
        'id_user_sending' => 1,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 09:03:50',
        'content' => 'Last message from user 1 to user 3',
        'msg_read' => 1
    ],
    [
        'id_message' => 77,
        'id_user_sending' => 2,
        'id_user_receiving' => 3,
        'date' => '2020-02-19 10:03:50',
        'content' => 'Only message from user 2 to user 3',
        'msg_read' => 1
    ],
];


来源: stackexchange

问:
PostgreSQL json_agg, and trying to group by and order by (column must appear in GROUP BY)
I've read several of the stackoverflow's about this error, but I still don't get it.

```<code>-- Returns full JSON document of a user, and all their user_files.
with user_files_json as (
    select user_id,
           json_agg(
             json_build_object(
               'user_file_id', user_file_id,
               's3_key', s3_key,
               'settings', series_settings
             )
           ) as user_files
      from user_files
     where user_id = :user_id
  group by user_id
  order by user_file_id asc
)
select json_build_object(
         'user_id', user_id,
         'user_name', user_name,
         'job_type_name', job_type_name,
         'user_files', user_files
       )
  from user_files_json
  join users using(user_id)
  join job_type using(job_type_id);
</code>```

I want the files to list in order by their user_file_id. That's all. If I take out the order by things work, but files come out in the wrong order.

But I get an error saying:

```<code>column "user_files.user_file_id" must appear in the GROUP BY clause or be used in an aggregate function
</code>```

What I'm telling postgresql makes perfect sense to me as a human, but can someone explain to me what I'm doing wrong and how to fix it?

答:
ERROR: ORDER BY specified, but json_build_object is not an aggregate function
This is the error you get if you try sorting by a specific column inside json_build_object.
Instead try the following and it works </p>

```<code>select user_id,
       user_files
  from (
    select user_id, json_agg(json_build_object(
           'user_file_id', user_file_id,
           's3_key', s3_key,
           'settings', series_settings)order by user_file_id asc) as user_files
  from user_files
 where user_id = :user_id) tmp
group by user_id
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've read several of the stackoverflow's about this error, but I still don't get it.

-- Returns full JSON document of a user, and all their user_files.
with user_files_json as (
    select user_id,
           json_agg(
             json_build_object(
               'user_file_id', user_file_id,
               's3_key', s3_key,
               'settings', series_settings
             )
           ) as user_files
      from user_files
     where user_id = :user_id
  group by user_id
  order by user_file_id asc
)
select json_build_object(
         'user_id', user_id,
         'user_name', user_name,
         'job_type_name', job_type_name,
         'user_files', user_files
       )
  from user_files_json
  join users using(user_id)
  join job_type using(job_type_id);

I want the files to list in order by their user_file_id. That's all. If I take out the order by things work, but files come out in the wrong order.

But I get an error saying:

column "user_files.user_file_id" must appear in the GROUP BY clause or be used in an aggregate function

What I'm telling postgresql makes perfect sense to me as a human, but can someone explain to me what I'm doing wrong and how to fix it?

Body:
ERROR: ORDER BY specified, but json_build_object is not an aggregate function
This is the error you get if you try sorting by a specific column inside json_build_object.
Instead try the following and it works

select user_id,
       user_files
  from (
    select user_id, json_agg(json_build_object(
           'user_file_id', user_file_id,
           's3_key', s3_key,
           'settings', series_settings)order by user_file_id asc) as user_files
  from user_files
 where user_id = :user_id) tmp
group by user_id


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

The below is the array structure:

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

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

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

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

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

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

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

答:
```<code>const isCheckedValue = obj => !!(obj[''])
this.dataToBeDeleted = dataToBeDeleted.filter(isCheckedValue)
console.log(result)
</code>```

If you want to fix such objects simply use map

```<code>this.dataToBeDeleted = dataToBeDeleted.map(obj => {
   obj.isCheckedValue = obj['']
   delete obj[''] // mutations, not good :(
})

</code>```

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

The below is the array structure:

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

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

Below is the code which I have tried:

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

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

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

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

Body:
const isCheckedValue = obj => !!(obj[''])
this.dataToBeDeleted = dataToBeDeleted.filter(isCheckedValue)
console.log(result)

If you want to fix such objects simply use map

this.dataToBeDeleted = dataToBeDeleted.map(obj => {
   obj.isCheckedValue = obj['']
   delete obj[''] // mutations, not good :(
})


问:
Create new derived-class object from List.FindAll
I have a class called Myitem and a derived List class MyItemCollection...

```<code>public class MyItemCollection : List<MyItem> { ... }
public class MyItem { ... }
</code>```

I would like to use FindAll to return a new instance of the MyItemCollection class containing a sub-set of MyItem values...

```<code>public MyItemCollection GetInUse()
{
  return this.FindAll(x => x.InUse);
}
</code>```

However, as the FindAll returns List<MyItem> and not MyItemCollection the above fails.

Is it possible to get the .FindAll to return a MyItemsCollection object, or to initiate a MyItemsCollection object using the return from .FindAll?

I could do the following, which works, but I'd like to know if there's a better solution...

```<code>public MyItemCollection GetInUse(bool inUse)
{
  var col = new MyItemsCollection();
  foreach (var item in this.FindAll(x => x.InUse))
    col.Add(item);
  return col;
}
</code>```

答:
List<T> has a constructor that takes a IEnumerable<T> argument. You can expose a similar constructor in your class, and then do something like this:

```<code>public MyItemCollection GetInUse() => new MyItemCollection(this.Where(i => i.InUse));
</code>```

Alternatively, don't use your own collection. If you just want to add helper methods on a list, you can use extension methods:

```<code>public static IEnumerable<MyItem> GetInUse(this IEnumerable<MyItem> e)
  => e.Where(i => i.InUse);
</code>```

You can also design your classes to have these extended helpers through an interface.  This is handy if you have multiple unrelated classes with similar functionality. The extension methods can then either use the interface as the type argument to IEnumerable, or be generic themselves with generic constraints on the type.

Body:
I have a class called Myitem and a derived List class MyItemCollection...

public class MyItemCollection : List<MyItem> { ... }
public class MyItem { ... }

I would like to use FindAll to return a new instance of the MyItemCollection class containing a sub-set of MyItem values...

public MyItemCollection GetInUse()
{
  return this.FindAll(x => x.InUse);
}

However, as the FindAll returns List<MyItem> and not MyItemCollection the above fails.

Is it possible to get the .FindAll to return a MyItemsCollection object, or to initiate a MyItemsCollection object using the return from .FindAll?

I could do the following, which works, but I'd like to know if there's a better solution...

public MyItemCollection GetInUse(bool inUse)
{
  var col = new MyItemsCollection();
  foreach (var item in this.FindAll(x => x.InUse))
    col.Add(item);
  return col;
}

Body:
List<T> has a constructor that takes a IEnumerable<T> argument. You can expose a similar constructor in your class, and then do something like this:

public MyItemCollection GetInUse() => new MyItemCollection(this.Where(i => i.InUse));

Alternatively, don't use your own collection. If you just want to add helper methods on a list, you can use extension methods:

public static IEnumerable<MyItem> GetInUse(this IEnumerable<MyItem> e)
  => e.Where(i => i.InUse);

You can also design your classes to have these extended helpers through an interface.  This is handy if you have multiple unrelated classes with similar functionality. The extension methods can then either use the interface as the type argument to IEnumerable, or be generic themselves with generic constraints on the type.


问:
Fetch Error "Promise returned from fetchData is ignored"
I created a component which is fetching data from an api.

import React, {useState, useEffect} from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        console.log(data)
    };
    fetchData()

    return (

    );
};

export default Users;```

I created fetch function, but anyway i can't get the response from server. After passing about 2 minutes, i'm getting in console 503 error. Why the fetch doesn't work?

答:
Working example https://codepen.io/tedseds/pen/vYOKowM

Also, don't call fetchData() in the render it causes infinity requests

The working code:

```<code>const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
      setUsers(data)
    };

    return (
        <div>
        Response: {users.map(item=>`${item.name}, `)}
        </div>
    );
};
</code>```

Body:
I created a component which is fetching data from an api.

import React, {useState, useEffect} from 'react';

const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
        console.log(data)
    };
    fetchData()

    return (

    );
};

export default Users;

I created fetch function, but anyway i can't get the response from server. After passing about 2 minutes, i'm getting in console 503 error. Why the fetch doesn't work?

Body:
Working example https://codepen.io/tedseds/pen/vYOKowM

Also, don't call fetchData() in the render it causes infinity requests

The working code:

const Users = () => {
    const [users, setUsers] = useState([]);
    useEffect(() => {
        fetchData();
        console.log('effect')
    }, []);

    const fetchData = async () => {
        const url = `https://jsonplaceholder.typicode.com/users`;
        const response = await fetch(url, {
                method: 'GET', // *GET, POST, PUT, DELETE, etc.
                mode: 'cors', // no-cors, *cors, same-origin
            }
        );
        const data = await response.json();
      setUsers(data)
    };

    return (
        <div>
        Response: {users.map(item=>`${item.name}, `)}
        </div>
    );
};


问:
IllegalArgumentException: Invalid column null in Path of Security January of 2020
I came across the following code used how my projection in query of SQLiteQueryBuilder.

```<code>String[] selectFields = new String[5];
selectFields[0] = "pmp_id";
</code>```

In versions of path of security of Android until 01/01/2020 (dd/MM/yyyy) this code work correctly. In version of path of 01/01/2020 the app generate the error:

```<code>java.lang.IllegalArgumentException: Invalid column null
    at android.database.sqlite.SQLiteQueryBuilder.computeSingleProjectionOrThrow(SQLiteQueryBuilder.java:1142)
    at android.database.sqlite.SQLiteQueryBuilder.computeProjection(SQLiteQueryBuilder.java:1113)
    at android.database.sqlite.SQLiteQueryBuilder.buildQuery(SQLiteQueryBuilder.java:888)
    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:561)
    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:475)
</code>```

I already fixed the error this way:

```<code>String[] selectFields = { "pmp_id" };
</code>```

But i would like to understand why in old versions it works and in new ones it doesn't?

答:
new String[5] creates an array of five String references and you're only assigning to the first slot. Remaining slots stay null.

Why this started crashing after a recent update seems to be explained in this commit that changes SQLiteQueryBuilder to be stricter with its inputs:

This change also offers setStrictColumns() to require that all
  untrusted column names are valid, such as those in ContentValues.

Body:
I came across the following code used how my projection in query of SQLiteQueryBuilder.

String[] selectFields = new String[5];
selectFields[0] = "pmp_id";

In versions of path of security of Android until 01/01/2020 (dd/MM/yyyy) this code work correctly. In version of path of 01/01/2020 the app generate the error:

java.lang.IllegalArgumentException: Invalid column null
    at android.database.sqlite.SQLiteQueryBuilder.computeSingleProjectionOrThrow(SQLiteQueryBuilder.java:1142)
    at android.database.sqlite.SQLiteQueryBuilder.computeProjection(SQLiteQueryBuilder.java:1113)
    at android.database.sqlite.SQLiteQueryBuilder.buildQuery(SQLiteQueryBuilder.java:888)
    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:561)
    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:475)

I already fixed the error this way:

String[] selectFields = { "pmp_id" };

But i would like to understand why in old versions it works and in new ones it doesn't?


问:
Routing low-latency audio from one CoreAudio device to another
First, some background info:  I'm writing a MacOS/X application that uses CoreAudio to receive an audio signal from a CoreAudio device's input stream, do some real-time processing on the audio, and then send it back to that CoreAudio device's output stream for the user to hear.

This application uses the lower-level CoreAudio APIs (i.e. AudioDeviceAddIOProc, AudioDeviceStart, etc -- not AudioUnits) to grab exclusive access to a user-specified CoreAudio device, set it to the desired sample rate (96kHz), and do its thing.  It works very well, and I'm quite happy with its performance.

However, my program currently has a limitation -- it can only use a single CoreAudio device at a time.  What I'd like to do is extend my application so that the user can choose his "input CoreAudio device" and his "output CoreAudio device" independently of each other, rather than being restricted to using only a single CoreAudio device that supplies both the input audio source and the output audio sink.

My question is, what is the recommended technique for doing this?  I can require that both CoreAudio devices be settable to the same sample-rate, but even once I do that, I think I will have to handle various issues, such as:

integrating separate AudioDeviceStart()-initiated callbacks from the two devices, which I suspect will not be called in any well-defined order, and might even be called concurrently with respect to each other(?).  I would need to pass audio from one callback to the other somehow, ideally without significantly increasing audio latency.

Handling differences in the sample-clock rates of the two devices.  E.g. even if both devices are nominally set to 96kHz sample rate, I suspect it may actually be the case that e.g. the upstream device is producing samples at 95.99999kHz while the downstream device is consuming them at 96.000001kHz (or vice-versa), and that would eventually cause me to end up with either "not enough" or "too many" samples to feed the downstream device during a given rendering-callback, causing a glitch.

Any other gotchas they I haven't considered yet

How do other MacOS/X programs handle these issues?

答:
A time ago I played with a proof of concept playground audiomixer in C. Nothing of this is finished, but things do actually work. The library uses the lowest Core Audio API available, thus indeed with things like AudioDeviceCreateIOProcID and AudioObjectAddPropertyListener.

In short, this playground allows me to use multiple audio devices known to MacOS and route one or more audio streams between them while passing through different kinds of "nodes" along the way (think of a matrix mixer node for example).

First, in answer to you questions

AudioDeviceStart() initiated callbacks will fire each from a different (random) thread. Also, the callbacks will not be called in a deterministic order. I also found that the difference between the callbacks can vary a lot (seemingly depending on the audio device providing/asking for data).
To solve this problem I used a lock-free (that is, using atomic counters) ringbuffer.

Your concern about different clock domains is very real. Two devices running at 96KHz will run at different speeds. This can go well for a long time, but eventually one of them is going to run out of data and start to glitch. If the external devices are not externally synchronised together, using for example word or ptp, they'll run in their own time domain.
To pass audio between different time domains you'll have to async-sample-rate-convert the audio data. And the SRC will need to have the possibility to convert in very small ratios and adjust along the way. One of those doing this very well is Soxr. In the world of Core Audio there is a VarispeedNode, which allows you to do basically the same thing.
Big disadvantage of the async-src solution is the latency it introduces, however maybe you could specify "low-latency".

In your case the synchronisation of the different audio devices will be the biggest challenge. In my case I found the callbacks of different audio devices vary too much to select one for being "clock-master" so I ended up creating a standalone time domain by carefully timing the execution of the processing cycle. For this I used low level timing mechanisms like mach_wait_until() and mach_absolute_time() (there's not much documentation on that).

Aggregate devices

However, there might be another solution. Looking at the documentation in AudioHardware.h from the CoreAudio framework, there seems to be a way to create an aggregate device programmatically using AudioHardwareCreateAggregateDevice(). This allows you to let MacOS handle the synchronisation of different audio devices. Also note the kAudioAggregateDeviceIsPrivateKey key which allows you to create an aggregate device without publishing it to the whole system. So, the device won't show up in Audio MIDI Setup (I think). Please also note that this key makes the aggregate disappearing when the process which created it stops running. It might or might not be what you need, but this would be a very robust way of implementing using multiple audio devices.
If I were to write the software again, I definitely would look into this way of doing the synchronisation.

Other gotcha's and tips

In general when dealing with low-latency audio you want to achieve the most deterministic behaviour possible. But I'm sure you are aware of this.

Another gotcha is that the documentation of the Core Audio api is not available on Apple's developer website (https://developer.apple.com/documentation/coreaudio/core_audio_functions?language=objc). For that you'll have to dive into the headers of the Core Audio framework where you'll find a lot of useful documentation about using the API.

On my machine the headers are located at: /Library/Developer/CommandLineTools/SDKs/MacOSX10.15.sdk/System/Library/Frameworks/CoreAudio.framework/Versions/A/Headers

Further reading:

http://atastypixel.com/blog/four-common-mistakes-in-audio-development
http://www.rossbencina.com/code/real-time-audio-programming-101-time-waits-for-nothing
https://developer.apple.com/library/archive/qa/qa1467/_index.html


问:
How can i create an autocomplete with Jquery?
I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.

My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.

Here is what i have now:

```<code><script>
    $(document).ready(function(){
        // Defining the local dataset
        $.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
          console.log(data)
          //Autocomplete
        });
    });
</script>

<input type="text" id='firstfield' name='input_val'>
</code>```

This is what the data looks like, it's around 700 records; here are the first three:

```<code>"results": [
        {
            "item": "First",
            "id": "1847",
        },
        {
            "item": "Second",
            "id": "4442",
        },
        {
            "item": "Third",
            "id": "3847",
        }]
</code>```

I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!

答:
You could use the jQuery Typeahead Search plugin. Just set-up your form to use the proper nesting of classes as seen below.

$(() => {
  //$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
  let data = {
    "results": [
      { "item": "First",  "id": "1847" },
      { "item": "Second", "id": "4442" },
      { "item": "Third",  "id": "3847" }
    ]
  };
  $('#first-field').typeahead({
    source: {
      data: data.results.map(record => record.item)
    },
    callback: {
      onInit: function($el) {
        console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
      }
    }
  });
  //})
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js"></script>
<h1>jQuery Typeahead</h1>
<form>
  <div class="typeahead__container">
    <div class="typeahead__field">
      <div class="typeahead__query">
        <input id="first-field" name="first-field" placeholder="Search" autocomplete="off">
      </div>
      <div class="typeahead__button">
        <button type="submit"><i class="typeahead__search-icon"></i></button>
      </div>
    </div>
  </div>
</form></code>```

Body:
I'm creating a Django site, on a certain template i added an Ajax form and i would like to add an autocomplete feature, in order to make navigation easier.

My main problem is that the data i should search is a JSON array of objects, while most of the solutions i found work with normal arrays.

Here is what i have now:

<input type="text" id='firstfield' name='input_val'>

This is what the data looks like, it's around 700 records; here are the first three:

"results": [
        {
            "item": "First",
            "id": "1847",
        },
        {
            "item": "Second",
            "id": "4442",
        },
        {
            "item": "Third",
            "id": "3847",
        }]

I need this to be as fast as possible. Is there a JQuery/Ajax native solution for this? Or is there a specific library to do this? Any advice or solution is appreciated, thanks in advance!

Body:
You could use the jQuery Typeahead Search plugin. Just set-up your form to use the proper nesting of classes as seen below.

$(() => {
  //$.getJSON('http://127.0.0.1:8000/myapi/', function(data) {
  let data = {
    "results": [
      { "item": "First",  "id": "1847" },
      { "item": "Second", "id": "4442" },
      { "item": "Third",  "id": "3847" }
    ]
  };
  $('#first-field').typeahead({
    source: {
      data: data.results.map(record => record.item)
    },
    callback: {
      onInit: function($el) {
        console.log(`Typeahead initiated on: ${$el.prop('tagName')}#${$el.attr('id')}`);
      }
    }
  });
  //})
});

<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-typeahead/2.11.0/jquery.typeahead.min.js"></script>
<h1>jQuery Typeahead</h1>
<form>
  <div class="typeahead__container">
    <div class="typeahead__field">
      <div class="typeahead__query">
        <input id="first-field" name="first-field" placeholder="Search" autocomplete="off">
      </div>
      <div class="typeahead__button">
        <button type="submit"><i class="typeahead__search-icon"></i></button>
      </div>
    </div>
  </div>
</form>


问:
Distance matrix along a dimension
Assuming that I want to compute a distance matrix between every element in a vector, I can do that in the following way:

```<code>X = np.array([1, 2, 3])
dist = np.triu(np.expand_dims(X, 0) - np.expand_dims(X, 1))
# [[0 1 2]
#  [0 0 1]
#  [0 0 0]]
</code>```

However, I am not sure how should I do the same if X is a matrix, and I want to compute the pairwise distances for every vector. For example, assuming that I have the following matrix:

```<code>X = np.array([[1, 2, 3], [1, 5, 7],[7, 8, 9]])
</code>```

I would expect to get the following output:

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

答:
Use np.triu on 3D extended arrays subtracted version -

```<code>In [57]: np.triu(X[:,None,:]-X[:,:,None])
Out[57]:
array([[[0, 1, 2],
        [0, 0, 1],
        [0, 0, 0]],

       [[0, 1, 2],
        [0, 0, 1],
        [0, 0, 0]],

       [[0, 1, 2],
        [0, 0, 1],
        [0, 0, 0]]])
</code>```

Or to use your trusty np.expand_dims -

```<code>np.triu(np.expand_dims(X, 1) - np.expand_dims(X, 2))
</code>```

Or create a triu mask with something like np.tri and then mask -

```<code>mask = ~np.tri(X.shape[-1], dtype=bool)
out = mask*(X[:,None,:]-X[:,:,None])
</code>```

Title: Distance matrix along a dimension

Body:
Assuming that I want to compute a distance matrix between every element in a vector, I can do that in the following way:

X = np.array([1, 2, 3])
dist = np.triu(np.expand_dims(X, 0) - np.expand_dims(X, 1))
# [[0 1 2]
#  [0 0 1]
#  [0 0 0]]

However, I am not sure how should I do the same if X is a matrix, and I want to compute the pairwise distances for every vector. For example, assuming that I have the following matrix:

X = np.array([[1, 2, 3], [1, 5, 7],[7, 8, 9]])

I would expect to get the following output:

# [[[0 1 2],
#   [0 0 1],
#   [0 0 0]],
#
#  [[0 4 6],
#   [0 0 2],
#   [0 0 0]],
#
#  [[0 1 2],
#   [0 0 1],
#   [0 0 0]]]

Body:
Use np.triu on 3D extended arrays subtracted version -

In [57]: np.triu(X[:,None,:]-X[:,:,None])
Out[57]:
array([[[0, 1, 2],
        [0, 0, 1],
        [0, 0, 0]],

       [[0, 1, 2],
        [0, 0, 1],
        [0, 0, 0]],

       [[0, 1, 2],
        [0, 0, 1],
        [0, 0, 0]]])

Or to use your trusty np.expand_dims -

np.triu(np.expand_dims(X, 1) - np.expand_dims(X, 2))

Or create a triu mask with something like np.tri and then mask -

mask = ~np.tri(X.shape[-1], dtype=bool)
out = mask*(X[:,None,:]-X[:,:,None])


问:
How to increment a number but keep formatting
I have a small XML that I read in in order to get the test id. I need to increment that number but keep the same formatting.

```<code><?xml version="1.0" encoding="utf-8" ?>
<Test>
   <TestID>00001</TestID>
</Test>
</code>```

```<code>testID = xDoc.Descendants("TestID").First().Value;
</code>```

If I just convert testID to int it becomes 0. I need the output to be 00002 after increment and then I need to write it back to the XML file.

答:
You can try with XmlDocument

```<code>var xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
var testId = xmlDoc.SelectSingleNode("/Test/TestID");
testId.InnerText = (Convert.ToInt32(testId.InnerText)+1).ToString("D5");
xmlDoc.Save(filePath);
</code>```

Body:
I have a small XML that I read in in order to get the test id. I need to increment that number but keep the same formatting.

<?xml version="1.0" encoding="utf-8" ?>
<Test>
   <TestID>00001</TestID>
</Test>

testID = xDoc.Descendants("TestID").First().Value;

If I just convert testID to int it becomes 0. I need the output to be 00002 after increment and then I need to write it back to the XML file.

Body:
You can try with XmlDocument

var xmlDoc = new XmlDocument();
xmlDoc.Load(filePath);
var testId = xmlDoc.SelectSingleNode("/Test/TestID");
testId.InnerText = (Convert.ToInt32(testId.InnerText)+1).ToString("D5");
xmlDoc.Save(filePath);


问:
How to upload the same file using Angular?
I use the following code to upload a file in Angular:

HTML

```<code><div class="form-group">
 <label for="file">Choose File</label>
 <input type="file"
       id="file"
       (change)="uploadRenewals($event.target.files)">
</div>
</code>```

Typescript

```<code>fileToUpload: File = null;

uploadRenewals(files: FileList) {
  console.log('Uploading starts...', files);
  const formData: FormData = new FormData();
  this.fileToUpload = files.item(0);
  formData.append('file', this.fileToUpload, this.fileToUpload.name);
  this._docService.uploadRenewals(formData)
    .pipe(take(1))
    .subscribe((response: RenewalsResponse) => {
    console.log('Response is', response);
   }, (error) => {console.log(error);});
</code>```

Service

```<code>uploadRenewals(formData: FormData) {
 return this._http.post(this.baseUrl + '/docs/uploadRenewals', formData, { responseType: 'json' })
 .catch(this.errorHandler);
}
</code>```

The thing here is that it works when I upload different file each time, but when I try to upload the same file nothing is triggered and the uploadRenewals() function is never called.

Also I noticed that when I open the window (change)="uploadRenewals($event.target.files) the third time (after I chose the same file the 2nd time and nothing happened) and close it without selecting any file, the uploadRenewals() is called and in console is showed the below error:

```<code>ERROR TypeError: Cannot read property 'name' of null
</code>```

Any idea what is happening and how to fix this?

答:
EXPLANATION :

What you need is to clear the input file Element after each upload and for the second problem if you close the dialog and the event (change) fired with an empty event then when it comes to this line:

```<code>formData.append('file', this.fileToUpload, this.fileToUpload.name);
</code>```

this.fileToUpload is empty.

SOLUTION :

TS :

```<code>import {
  Component,
  OnInit,
  ViewChild,
  ElementRef
} from '@angular/core';

@ViewChild('fileInput', {
    static: false
}) fileInput: ElementRef;
fileToUpload: File = null;

uploadRenewals(files: FileList) {
    console.log('Uploading starts...', files);
    const formData: FormData = new FormData();
    this.fileToUpload = files.item(0);
    if (this.fileToUpload) { // this condition to avoid your the error that you mentioned
        formData.append('file', this.fileToUpload, this.fileToUpload.name);
        this._docService.uploadRenewals(formData)
            .pipe(take(1))
            .subscribe((response: RenewalsResponse) => {
                console.log('Response is', response);
                this.fileInput.nativeElement.value = null; //this clears the input file to let the event (change) fire again so you can upload the same file again
            }, (error) => {
                console.log(error);
            });
    }
}
</code>```

HTML :

```<code><div class="form-group">
 <label for="file">Choose File</label>
 <input #fileInput type="file"
       id="file"
       (change)="uploadRenewals($event.target.files)">
</div>
</code>```

Body:
I use the following code to upload a file in Angular:

HTML

 Choose File
 <input type="file"
       id="file"
       (change)="uploadRenewals($event.target.files)">

Typescript

fileToUpload: File = null;

uploadRenewals(files: FileList) {
  console.log('Uploading starts...', files);
  const formData: FormData = new FormData();
  this.fileToUpload = files.item(0);
  formData.append('file', this.fileToUpload, this.fileToUpload.name);
  this._docService.uploadRenewals(formData)
    .pipe(take(1))
    .subscribe((response: RenewalsResponse) => {
    console.log('Response is', response);
   }, (error) => {console.log(error);});

Service

uploadRenewals(formData: FormData) {
 return this._http.post(this.baseUrl + '/docs/uploadRenewals', formData, { responseType: 'json' })
 .catch(this.errorHandler);
}

The thing here is that it works when I upload different file each time, but when I try to upload the same file nothing is triggered and the uploadRenewals() function is never called.

Also I noticed that when I open the window (change)="uploadRenewals($event.target.files) the third time (after I chose the same file the 2nd time and nothing happened) and close it without selecting any file, the uploadRenewals() is called and in console is showed the below error:

ERROR TypeError: Cannot read property 'name' of null

Any idea what is happening and how to fix this?

Body:
EXPLANATION :

What you need is to clear the input file Element after each upload and for the second problem if you close the dialog and the event (change) fired with an empty event then when it comes to this line:

formData.append('file', this.fileToUpload, this.fileToUpload.name);

this.fileToUpload is empty.

SOLUTION :

TS :

import {
  Component,
  OnInit,
  ViewChild,
  ElementRef
} from '@angular/core';

@ViewChild('fileInput', {
    static: false
}) fileInput: ElementRef;
fileToUpload: File = null;

uploadRenewals(files: FileList) {
    console.log('Uploading starts...', files);
    const formData: FormData = new FormData();
    this.fileToUpload = files.item(0);
    if (this.fileToUpload) { // this condition to avoid your the error that you mentioned
        formData.append('file', this.fileToUpload, this.fileToUpload.name);
        this._docService.uploadRenewals(formData)
            .pipe(take(1))
            .subscribe((response: RenewalsResponse) => {
                console.log('Response is', response);
                this.fileInput.nativeElement.value = null; //this clears the input file to let the event (change) fire again so you can upload the same file again
            }, (error) => {
                console.log(error);
            });
    }
}

HTML :

<div class="form-group">
 <label for="file">Choose File</label>
 <input #fileInput type="file"
       id="file"
       (change)="uploadRenewals($event.target.files)">
</div>


问:
URL decoding: UnsupportedEncodingException in Java
What I understand from the documentation is that UnsupportedEncodingException can only be thrown if I specify a wrong encoding as the second parameter to URLDecoder.decode(String, String) method. Is it so? I need to know cases where this exception can be thrown.

Basically, I have this code segment in one of my functions:

```<code>if (keyVal.length == 2) {
    try {
        value = URLDecoder.decode(
            keyVal[1],
            "UTF-8");
    } catch (UnsupportedEncodingException e) {
          // Will it ever be thrown?
    }
}
</code>```

Since I am explicitly mentioning "UTF-8", is there any way this exception can be thrown? Do I need to do anything in the catch block? Or, if my understanding is completely wrong, please let me know.

答: In your special case - no, it won't be thrown. Unless you execute your code in a Java runtime that does not support "UTF-8".</p>

ContentLicense: CC BY-SA 3.0

Body:
What I understand from the documentation is that UnsupportedEncodingException can only be thrown if I specify a wrong encoding as the second parameter to URLDecoder.decode(String, String) method. Is it so? I need to know cases where this exception can be thrown.

Basically, I have this code segment in one of my functions:

if (keyVal.length == 2) {
    try {
        value = URLDecoder.decode(
            keyVal[1],
            "UTF-8");
    } catch (UnsupportedEncodingException e) {
          // Will it ever be thrown?
    }
}

Since I am explicitly mentioning "UTF-8", is there any way this exception can be thrown? Do I need to do anything in the catch block? Or, if my understanding is completely wrong, please let me know.


问:
R: a tidy way to count number of rows between pipes?
Using R and tidyr, I want to count the number of rows of a dataframe between two pipes; is there an elegant way to do this?

I ran into the problem when removing rows with only NA, then having to count the number of rows of the dataframe so far. Can I do this without storing the dataframe between the pipes?

Here is a reproducible example. I essentially need XXX to refer to the dataframe after drop_na().

```<code>library(dplyr)

scrap <- as.data.frame(matrix(1:16, ncol = 4))
scrap[4,] <- rep(NA, 4)

scrap %>%
  drop_na() %>%
  mutate(index=c(1:nrow(XXX)))
</code>```

I thought it would guess what I am doing if I do not refer to anything as below, but no.

```<code>scrap %>%
  drop_na() %>%
  mutate(index=c(1:nrow()))
</code>```

Error in nrow() : argument "x" is missing, with no default

Is there an elegant solution I am missing?

答:
Not sure if I understood your question, but using dplyr::row_number :

```<code>library(dplyr)
scrap %>%
  drop_na() %>%
  mutate(index=row_number())
</code>```

Returns:

```<code>  V1 V2 V3 V4 index
1  1  5  9 13     1
2  2  6 10 14     2
3  3  7 11 15     3
</code>```

Body:
Using R and tidyr, I want to count the number of rows of a dataframe between two pipes; is there an elegant way to do this?

I ran into the problem when removing rows with only NA, then having to count the number of rows of the dataframe so far. Can I do this without storing the dataframe between the pipes?

Here is a reproducible example. I essentially need XXX to refer to the dataframe after drop_na().

library(dplyr)

scrap <- as.data.frame(matrix(1:16, ncol = 4))
scrap[4,] <- rep(NA, 4)

scrap %>%
  drop_na() %>%
  mutate(index=c(1:nrow(XXX)))

I thought it would guess what I am doing if I do not refer to anything as below, but no.

scrap %>%
  drop_na() %>%
  mutate(index=c(1:nrow()))

Error in nrow() : argument "x" is missing, with no default

Is there an elegant solution I am missing?

Body:
Not sure if I understood your question, but using dplyr::row_number :

library(dplyr)
scrap %>%
  drop_na() %>%
  mutate(index=row_number())

Returns:

  V1 V2 V3 V4 index
1  1  5  9 13     1
2  2  6 10 14     2
3  3  7 11 15     3


答:
Simply:

```<code>var xDoc = XDocument.Parse(xml);
var testIdElement = xDoc.Root.Element("TestID");
testIdElement.Value = ((int)testIdElement + 1).ToString("D5");
</code>```

We convert the value of "TestID" to an int, increment it, then format it as a string with 5 digits, padded with leading zeros.

Title: How to increment a number but keep formatting

Body:
Simply:

var xDoc = XDocument.Parse(xml);
var testIdElement = xDoc.Root.Element("TestID");
testIdElement.Value = ((int)testIdElement + 1).ToString("D5");

We convert the value of "TestID" to an int, increment it, then format it as a string with 5 digits, padded with leading zeros.


问:
CASE query optimization
```<code>SELECT
  COUNT(CASE WHEN VALUE = 1 THEN 1 END) AS score_1,
  COUNT(CASE WHEN VALUE = 2 THEN 1 END) AS score_2,
  COUNT(CASE WHEN VALUE = 3 THEN 1 END) AS score_3,
  COUNT(CASE WHEN VALUE = 4 THEN 1 END) AS score_4,
  COUNT(CASE WHEN VALUE = 5 THEN 1 END) AS score_5,
  COUNT(CASE WHEN VALUE = 6 THEN 1 END) AS score_6,
  COUNT(CASE WHEN VALUE = 7 THEN 1 END) AS score_7,
  COUNT(CASE WHEN VALUE = 8 THEN 1 END) AS score_8,
  COUNT(CASE WHEN VALUE = 9 THEN 1 END) AS score_9,
  COUNT(CASE WHEN VALUE = 10 THEN 1 END) AS score_10
FROM
  `answers`
WHERE
`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59'
</code>```

Is there a way to optimize this query, because I have 4 million answer records in my DB, and it runs very slowly?

答:
Try running this one time to create an index:

CREATE INDEX ix_ca on answers(created_at)

That should speed your query up. If you are curious about why, see here:

What is an index in SQL?

Title: CASE query optimization

Body:
SELECT
  COUNT(CASE WHEN VALUE = 1 THEN 1 END) AS score_1,
  COUNT(CASE WHEN VALUE = 2 THEN 1 END) AS score_2,
  COUNT(CASE WHEN VALUE = 3 THEN 1 END) AS score_3,
  COUNT(CASE WHEN VALUE = 4 THEN 1 END) AS score_4,
  COUNT(CASE WHEN VALUE = 5 THEN 1 END) AS score_5,
  COUNT(CASE WHEN VALUE = 6 THEN 1 END) AS score_6,
  COUNT(CASE WHEN VALUE = 7 THEN 1 END) AS score_7,
  COUNT(CASE WHEN VALUE = 8 THEN 1 END) AS score_8,
  COUNT(CASE WHEN VALUE = 9 THEN 1 END) AS score_9,
  COUNT(CASE WHEN VALUE = 10 THEN 1 END) AS score_10
FROM
  `answers`
WHERE
`created_at` BETWEEN '2017-01-01 00:00:00' AND '2019-11-30 23:59:59'

Is there a way to optimize this query, because I have 4 million answer records in my DB, and it runs very slowly?


问:
FetchXML for SQL Join having filter
I am trying to build FetchXML equivalent of SQL query, I am quite new in using FetchXML:

```<code>SELECT o.opportunityid,c1.accountid
FROM dbo.opportunity o
LEFT JOIN dbo.account c1 on o.customerid = c1.accountid and o.customeridtype = 1
</code>```

into

```<code><fetch mapping="logical" version="1.0">
  <entity name="opportunity">
  <attribute name="opportunityid" />
    <link-entity name="account" from="accountid" to="customerid" alias="A1" link-type="outer" >
        <filter type="and" >
            <condition attribute="customeridtype" operator="eq" value="1" />
        </filter>
    <attribute name="accountid" />
    </link-entity>
</code>```

but this is throwing error saying that attribute "customeridtype" doesn't exist in entity "account". that attribute is from opportunity entity as in SQL query. How can I fix this?

答:
Take out the filter from inside link-entity xml node to outside entity node.

You can try XrmToolBox fetchxml builder or Kingswaysoft sql2fetchxml online tool.

```<code><fetch mapping="logical" version="1.0">
  <entity name="opportunity">
  <attribute name="opportunityid" />

    <filter type="and" >
        <condition attribute="customeridtype" operator="eq" value="1" />
    </filter>

    <link-entity name="account" from="accountid" to="customerid" alias="A1" link-type="outer" >
        <attribute name="accountid" />
    </link-entity>
</code>```

Title: FetchXML for SQL Join having filter

Body:
I am trying to build FetchXML equivalent of SQL query, I am quite new in using FetchXML:

SELECT o.opportunityid,c1.accountid
FROM dbo.opportunity o
LEFT JOIN dbo.account c1 on o.customerid = c1.accountid and o.customeridtype = 1

into

<fetch mapping="logical" version="1.0">
  <entity name="opportunity">
  <attribute name="opportunityid" />
    <link-entity name="account" from="accountid" to="customerid" alias="A1" link-type="outer" >
        <filter type="and" >
            <condition attribute="customeridtype" operator="eq" value="1" />
        </filter>
    <attribute name="accountid" />
    </link-entity>

but this is throwing error saying that attribute "customeridtype" doesn't exist in entity "account". that attribute is from opportunity entity as in SQL query. How can I fix this?

Body:
Take out the filter from inside link-entity xml node to outside entity node.

You can try XrmToolBox fetchxml builder or Kingswaysoft sql2fetchxml online tool.

<fetch mapping="logical" version="1.0">
  <entity name="opportunity">
  <attribute name="opportunityid" />

    <filter type="and" >
        <condition attribute="customeridtype" operator="eq" value="1" />
    </filter>

    <link-entity name="account" from="accountid" to="customerid" alias="A1" link-type="outer" >
        <attribute name="accountid" />
    </link-entity>


问:
To get subtring from a string
I am having issue to extract substring from string.
The input values are like

```<code>{Resultset: 234, edf, ejj, Resultvalue: hsh, 23,hhs}
{ hashvalue: 233, ehdh, Resultset: 2dd34, edf, ejj}
3rd value:
{hashvalue: 233, ehdh, Resultset: 2dd34, Resultvalue: hsh, 23,hhs}
4th value
{hashvalue: 233, ehdh, Resultset:, Resultvalue: hsh, 23,hhs}
5th value
Null
6th value
{hashvalue: 233, ehdh, Resultvalue: hsh, 23,hhs}
</code>```

Output should be like

Resultset: 234, edf, ejj
Resultset: 2dd34, edf, ejj
Resultset: 2dd34
Resultset:
Null
Null
Like this.
```

I tried but the expected string sometimes comes at first and sometimes at last. Sometime i get more than expected string.

I think, need regular expression to search for two characters and when first : appears don't go for second }

答:
You can use REGEXP_SUBSTR for this. Look for the string 'Resultset' followed by several non-comma, then one comma, then several non-comma, then one comma, then several non-comma.

```<code>regexp_substr(colname, 'Resultset[^,]*,[^,]*,[^,]*')
</code>```

Title: To get subtring from a string

Body:
I am having issue to extract substring from string.
The input values are like

{Resultset: 234, edf, ejj, Resultvalue: hsh, 23,hhs}
{ hashvalue: 233, ehdh, Resultset: 2dd34, edf, ejj}
3rd value:
{hashvalue: 233, ehdh, Resultset: 2dd34, Resultvalue: hsh, 23,hhs}
4th value
{hashvalue: 233, ehdh, Resultset:, Resultvalue: hsh, 23,hhs}
5th value
Null
6th value
{hashvalue: 233, ehdh, Resultvalue: hsh, 23,hhs}

Output should be like

Resultset: 234, edf, ejj
Resultset: 2dd34, edf, ejj
Resultset: 2dd34
Resultset:
Null
Null
Like this.

I tried but the expected string sometimes comes at first and sometimes at last. Sometime i get more than expected string.

I think, need regular expression to search for two characters and when first : appears don't go for second }

Body:
You can use REGEXP_SUBSTR for this. Look for the string 'Resultset' followed by several non-comma, then one comma, then several non-comma, then one comma, then several non-comma.

regexp_substr(colname, 'Resultset[^,]*,[^,]*,[^,]*')


问:
How do I use adapter position to retrieve data from firebase to a new activity
SearchPage where I search the books from firebase

```<code>public class SearchPage extends AppCompatActivity {
EditText searchbar;

RecyclerView recyclerView;
DatabaseReference reference;

ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
ArrayList<String> Desc;
SearchAdapter searchAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_page);

    searchbar = (EditText) findViewById(R.id.searchbar);
    reference = FirebaseDatabase.getInstance().getReference();
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    BookNameList = new ArrayList<>();
    PublisherList = new ArrayList<>();
    AuthorNameList = new ArrayList<>();
    Shelfnols = new ArrayList<>();
    PicList = new ArrayList<>();
    Desc=new ArrayList<>();

    searchbar.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().isEmpty()) {
                setAdapter(s.toString());

            }
            else{
                BookNameList.clear();
                AuthorNameList.clear();
                PicList.clear();
                PublisherList.clear();
                Shelfnols.clear();
                Desc.clear();

            }
        }

        private void setAdapter(final String searchedString) {
            reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    Shelfnols.clear();
                    Desc.clear();

                    int counter=0;
                    for(DataSnapshot snapshot:dataSnapshot.getChildren()){
                        String uid = snapshot.getKey();

                       Log.i(uid,"ids");
                        String desc = snapshot.child("Desc").getValue(String.class);
                        String bookname = snapshot.child("bookname").getValue(String.class);
                        String author = snapshot.child("author").getValue(String.class);
                        String image = snapshot.child("image").getValue(String.class);
                        String publisher = snapshot.child("Publisher").getValue(String.class);
                        String shelfno = snapshot.child("Shelf_no").getValue(String.class);
                        try {

                            if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);

                                counter++;
                            } else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);
                                counter++;
                            }
                        }
                        catch (Exception e){
                            Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
                        }

                        if(counter==15){
                            break;
                        }
                        SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
                        recyclerView.setAdapter(searchAdapter);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }

            });
        }
    });

}
</code>```

this the adapter class SearchAdapter where I am getting the adapter position on click

```<code>public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
final public String id="bookname";

    Context context;
    ArrayList<String> BookNameList;
    ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
DatabaseReference reference;

class SearchViewHolder extends RecyclerView.ViewHolder{
    ImageView bookimage;
    TextView bookname, authorname,publisher,shelfno;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        bookimage =  itemView.findViewById(R.id.Bookimg);
        bookname =  itemView.findViewById(R.id.BookName);
        authorname =  itemView.findViewById(R.id.AuthorName);
        publisher =  itemView.findViewById(R.id.Publications);
        shelfno =  itemView.findViewById(R.id.Shelfno);
        booklayout=itemView.findViewById(R.id.LinLayout);
        reference = FirebaseDatabase.getInstance().getReference();
        reference.keepSynced(true);

    }
}

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
}

@NonNull
@Override
public SearchAdapter.SearchViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
     return new SearchAdapter.SearchViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
    holder.bookname.setText(BookNameList.get(position));
    holder.authorname.setText(AuthorNameList.get(position));
    holder.publisher.setText(PublisherList.get(position));
    holder.shelfno.setText(Shelfnols.get(position));

           holder.itemView.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {

                 Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
                   Intent i = new Intent(context,Bookdetailslayout.class);

                 context.startActivity(i);
               }
           });

    Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);

}

@Override
public int getItemCount() {
    return BookNameList.size();
}
</code>```

this is my new activity where i want the book details to be shown

```<code>public class Bookdetailslayout extends SearchPage {

DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookdetailslayout);
    image=(ImageView)findViewById(R.id.img) ;

    bookname = (TextView)findViewById(R.id.bkname);
    author = (TextView) findViewById(R.id.aname);
    publisher = (TextView) findViewById(R.id.pname);
    desc = (TextView) findViewById(R.id.bkdescription);
    location = (TextView) findViewById(R.id.bklocation);
    String Bname=getIntent().getStringExtra("bookname");
    Log.i(Bname, "onCreate: ");

    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");

}
</code>```

till now I was able to set onclick to new activity and get the position of the click as item 1,2,etc...how do I use this position to get data from firebase to the new activity

答:
i used this in my adapter class to get position

```<code> public void onClick(View v) {

                   Intent i = new Intent(context,Bookdetailslayout.class);
                   i.putExtra("bookname",BookNameList.get(position));

                   i.putExtra("Image",PicList.get(position));
                   i.putExtra("author_name",AuthorNameList.get(position));
                   i.putExtra("publisher_name",PublisherList.get(position));
                   context.startActivity(i);
               }
           });
</code>```

then in the next activity

```<code> String imgs=getIntent().getStringExtra("Image");
    String Bname=getIntent().getStringExtra("bookname");
    title.setText(Bname);
    String Author=getIntent().getStringExtra("author_name");
    author.setText(Author);
    String publisher=getIntent().getStringExtra("publisher_name");
    pub.setText(publisher);
    Toast.makeText(this,"image "+imgs,Toast.LENGTH_LONG).show();
    Picasso.get().load(imgs).into(image);
</code>```

and it works ..thanks for all the help here

Body:
SearchPage where I search the books from firebase

public class SearchPage extends AppCompatActivity {
EditText searchbar;

RecyclerView recyclerView;
DatabaseReference reference;

ArrayList<String> BookNameList;
ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
ArrayList<String> Desc;
SearchAdapter searchAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_page);

    searchbar = (EditText) findViewById(R.id.searchbar);
    reference = FirebaseDatabase.getInstance().getReference();
    reference.keepSynced(true);
    recyclerView = (RecyclerView) findViewById(R.id.rv);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
    BookNameList = new ArrayList<>();
    PublisherList = new ArrayList<>();
    AuthorNameList = new ArrayList<>();
    Shelfnols = new ArrayList<>();
    PicList = new ArrayList<>();
    Desc=new ArrayList<>();

    searchbar.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (!s.toString().isEmpty()) {
                setAdapter(s.toString());

            }
            else{
                BookNameList.clear();
                AuthorNameList.clear();
                PicList.clear();
                PublisherList.clear();
                Shelfnols.clear();
                Desc.clear();

            }
        }

        private void setAdapter(final String searchedString) {
            reference.child("books").addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    BookNameList.clear();
                    AuthorNameList.clear();
                    PicList.clear();
                    PublisherList.clear();
                    Shelfnols.clear();
                    Desc.clear();

                    int counter=0;
                    for(DataSnapshot snapshot:dataSnapshot.getChildren()){
                        String uid = snapshot.getKey();

                       Log.i(uid,"ids");
                        String desc = snapshot.child("Desc").getValue(String.class);
                        String bookname = snapshot.child("bookname").getValue(String.class);
                        String author = snapshot.child("author").getValue(String.class);
                        String image = snapshot.child("image").getValue(String.class);
                        String publisher = snapshot.child("Publisher").getValue(String.class);
                        String shelfno = snapshot.child("Shelf_no").getValue(String.class);
                        try {

                            if (bookname.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);

                                counter++;
                            } else if (author.toLowerCase().contains(searchedString.toLowerCase())) {
                                BookNameList.add(bookname);
                                AuthorNameList.add(author);
                                PublisherList.add(publisher);
                                Shelfnols.add(shelfno);
                                PicList.add(image);
                                Desc.add(desc);
                                counter++;
                            }
                        }
                        catch (Exception e){
                            Toast.makeText(getApplicationContext(),"not found",Toast.LENGTH_LONG).show();
                        }

                        if(counter==15){
                            break;
                        }
                        SearchAdapter searchAdapter = new SearchAdapter(SearchPage.this, BookNameList, AuthorNameList, PicList, PublisherList, Shelfnols);
                        recyclerView.setAdapter(searchAdapter);
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }

            });
        }
    });

}

this the adapter class SearchAdapter where I am getting the adapter position on click

public class SearchAdapter extends RecyclerView.Adapter<SearchAdapter.SearchViewHolder> {
final public String id="bookname";

    Context context;
    ArrayList<String> BookNameList;
    ArrayList<String> AuthorNameList;
ArrayList<String> PicList;
ArrayList<String> PublisherList;
ArrayList<String> Shelfnols;
LinearLayout booklayout;
DatabaseReference reference;

class SearchViewHolder extends RecyclerView.ViewHolder{
    ImageView bookimage;
    TextView bookname, authorname,publisher,shelfno;

    public SearchViewHolder(@NonNull View itemView) {
        super(itemView);
        bookimage =  itemView.findViewById(R.id.Bookimg);
        bookname =  itemView.findViewById(R.id.BookName);
        authorname =  itemView.findViewById(R.id.AuthorName);
        publisher =  itemView.findViewById(R.id.Publications);
        shelfno =  itemView.findViewById(R.id.Shelfno);
        booklayout=itemView.findViewById(R.id.LinLayout);
        reference = FirebaseDatabase.getInstance().getReference();
        reference.keepSynced(true);

    }
}

public SearchAdapter(Context context, ArrayList<String> bookNameList, ArrayList<String> authorNameList, ArrayList<String> picList,ArrayList<String> publisherList,ArrayList<String> shelfnols) {
    this.context = context;
    BookNameList = bookNameList;
    AuthorNameList = authorNameList;
    PicList = picList;
    PublisherList=publisherList;
    Shelfnols=shelfnols;
}

@NonNull
@Override
public SearchAdapter.SearchViewHolder  onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(context).inflate(R.layout.activity_search_layout,parent,false);
     return new SearchAdapter.SearchViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull SearchViewHolder holder, final int position) {
    holder.bookname.setText(BookNameList.get(position));
    holder.authorname.setText(AuthorNameList.get(position));
    holder.publisher.setText(PublisherList.get(position));
    holder.shelfno.setText(Shelfnols.get(position));

           holder.itemView.setOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {

                 Toast.makeText(context,"clicked "+position,Toast.LENGTH_LONG).show();
                   Intent i = new Intent(context,Bookdetailslayout.class);

                 context.startActivity(i);
               }
           });

    Glide.with(context).asBitmap().load(PicList.get(position)).placeholder(R.mipmap.ic_launcher_round).into(holder.bookimage);

}

@Override
public int getItemCount() {
    return BookNameList.size();
}

this is my new activity where i want the book details to be shown

public class Bookdetailslayout extends SearchPage {

DatabaseReference reference;
TextView bookname,author,publisher,desc,location;
ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_bookdetailslayout);
    image=(ImageView)findViewById(R.id.img) ;

    bookname = (TextView)findViewById(R.id.bkname);
    author = (TextView) findViewById(R.id.aname);
    publisher = (TextView) findViewById(R.id.pname);
    desc = (TextView) findViewById(R.id.bkdescription);
    location = (TextView) findViewById(R.id.bklocation);
    String Bname=getIntent().getStringExtra("bookname");
    Log.i(Bname, "onCreate: ");

    DatabaseReference databaseReference=FirebaseDatabase.getInstance().getReference().child("books");

}

till now I was able to set onclick to new activity and get the position of the click as item 1,2,etc...how do I use this position to get data from firebase to the new activity

Body:
i used this in my adapter class to get position

 public void onClick(View v) {

                   Intent i = new Intent(context,Bookdetailslayout.class);
                   i.putExtra("bookname",BookNameList.get(position));

                   i.putExtra("Image",PicList.get(position));
                   i.putExtra("author_name",AuthorNameList.get(position));
                   i.putExtra("publisher_name",PublisherList.get(position));
                   context.startActivity(i);
               }
           });

then in the next activity

 String imgs=getIntent().getStringExtra("Image");
    String Bname=getIntent().getStringExtra("bookname");
    title.setText(Bname);
    String Author=getIntent().getStringExtra("author_name");
    author.setText(Author);
    String publisher=getIntent().getStringExtra("publisher_name");
    pub.setText(publisher);
    Toast.makeText(this,"image "+imgs,Toast.LENGTH_LONG).show();
    Picasso.get().load(imgs).into(image);

and it works ..thanks for all the help here


问:
Need to integrate QuickBooks mac version with my Asp.Net Web Application someone please guide me the steps and how I can achieve it
Need to integrate QuickBooks mac version with my Asp.Net Web Application someone please guide me the steps and how I can achieve it. The main functionality I need to add the invoice into QuickBooks db(files) when its is generated in my system and if updated status should revert in system back and update the status of that invoice.</p>

答:
QuickBooks for Mac does not support any sort of integration or API.

You will need to use QuickBooks for Windows or QuickBooks Online instead.


问:
Get inner type of generic type in Typescript
How do I get the inner type of a generic type in Typescript? So the T of myType<T>?

For example:

```<code>export class MyClass {
  myMethod(): Observable<{ prop1: string, ... }> {
    ....
  }
}

type myClassReturn = ReturnType<MyClass['myMethod']>;
// Sets the type to 'Observable<{ prop1: string, ... }>'.
// How do I set this to just '{ prop1: string, ... }'?
</code>```

Thanks

答:
You can use infer keyword in order to get type parameters from generic types. Consider:

```<code>type GetInsideObservable<X> = X extends Observable<infer I> ? I : never;

// in your case it would be:
type A = GetInsideObservable<ReturnType<MyClass['myMethod']>> // { prop1: string, ... }
</code>```

Body:
How do I get the inner type of a generic type in Typescript? So the T of myType<T>?

For example:

export class MyClass {
  myMethod(): Observable<{ prop1: string, ... }> {
    ....
  }
}

type myClassReturn = ReturnType<MyClass['myMethod']>;
// Sets the type to 'Observable<{ prop1: string, ... }>'.
// How do I set this to just '{ prop1: string, ... }'?

Thanks

Body:
You can use infer keyword in order to get type parameters from generic types. Consider:

type GetInsideObservable<X> = X extends Observable<infer I> ? I : never;

// in your case it would be:
type A = GetInsideObservable<ReturnType<MyClass['myMethod']>> // { prop1: string, ... }


问:
Why echo of combined variables in for loop doesn't work?
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

```<code>#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
</code>```

Console output:

```<code>./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell
</code>```

Thanks

答:
Also works with printf

```<code>for i in {1..3}; {
    varname=v$i
    read -p "Insert value $i: " value
    printf -v $varname "$value"
    echo  "you wrote $value"
}

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3
</code>```

Body:
what is wrong with "echo" line in my loop?
It should echo value of v1 after 1st input, v2 after 2nd input and v3 after 3rd input. Instead it's just echoes $i. Why is it ignoring $v ?
After loop is done, I do "manual check" of the saver variables and they apparently exist.

Script:

#!/bin/bash
for i in {1..3}
 do
  read -p "Insert value $i: " v$i
  echo "you wrote " $v$i          #I have problem in this line
 done

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3

Console output:

./input_2.sh
Insert value 1: what
you wrote  1              #output should be: you wrote what
Insert value 2: the
you wrote  2              #output should be: you wrote the
Insert value 3: hell
you wrote  3              #output should be: you wrote hell

check of saved values:
what
the
hell

Thanks

Body:
Also works with printf

for i in {1..3}; {
    varname=v$i
    read -p "Insert value $i: " value
    printf -v $varname "$value"
    echo  "you wrote $value"
}

echo
echo "check of saved values:"
echo $v1
echo $v2
echo $v3


问:
Use git to generate a folder to upload throught FTP
I have a PHP project (an wordpress plugin). When i need to publish this project to a remote test or production server, I have to send files through common FTP. In order not to upload all files, I'd like to obtain only modified files from the last build.

Is there an way to use GIT to, given two different branches or commits, create a folder with files changed or added between this two branches/commit. This would give me all files I have to upload.

I've tried using git diff branch1..branch2 > result.diff, but that would give me a single text file with all changes, and that wont't help with the FTP upload process, I'd like to copy all changed/added files to a folder, following the same folder structure, so i could just upload this folder.

Edit:

Based on @LeGEC answer, I wrote a little command line utility that read the results of gitDiff and generate a folder with the files. If someone is interested, its on GitHub:

https://github.com/marlonbrum/Br1.GitPack

答:
You can try one of :

```<code>git diff --name-only
git diff --name-status
</code>```

and see which one suits your needs the best.

git diff also has a --diff-filter option, which you probably want to combine with --no-renames in this situation, so that a renamed file correctly appears in the "deleted" list :

```<code># list the files whose content has been modified, and should be copied :
git diff --no-renames --name-only --diff-filter=ACM

# list the files that have been deleted from the repo, and should be *removed* :
git diff --no-renames --name-only --diff-filter=D
</code>```

Body:
You can try one of :

git diff --name-only
git diff --name-status

and see which one suits your needs the best.

git diff also has a --diff-filter option, which you probably want to combine with --no-renames in this situation, so that a renamed file correctly appears in the "deleted" list :

# list the files whose content has been modified, and should be copied :
git diff --no-renames --name-only --diff-filter=ACM

# list the files that have been deleted from the repo, and should be *removed* :
git diff --no-renames --name-only --diff-filter=D


问:
C# encoding a file in EBCDIC with packed decimals
I have to prepare a file for an outside entity, and this entity uses an IBM mainframe with COBOL and requires the file to be encoded in EBCDIC. I am creating the file in C#. I guess this is a two-part question...firstly, is the code below sufficient to ensure that the file will be generated in a manner that they can read?

```<code>StreamWriter sw = new StreamWriter(@"C:\EBCDICFileEquivalent.txt", false, Encoding.GetEncoding(37));
</code>```

Secondly, several fields in the file require packed decimal, in the format S(9)13 COMP-3. Since I have already specified EBCDIC encoding, can I just write the decimal number (e.g. 1234500000001) to the file using:

```<code>sw.WriteLine("1234500000001C");
</code>```

...and have it turn out correctly in the generated file?

Have never done anything with EBCDIC or COMP-3.

答:
Secondly, several fields in the file
  require packed decimal, in the format
  S(9)13 COMP-3. Since I have already
  specified EBCDIC encoding, can I just
  write the decimal number (e.g.
  1234500000001) to the file using:

sw.WriteLine("1234500000001C");

...and have it turn out correctly in
  the generated file?

No, you can't.  That statement would write the EBCDIC bytes:

F1 F2 F3 F4 F5 F0 F0 F0 F0 F0 F0 F0 F1 C3

But this field is COMP-3.  That's not encoded characters; it's BCD with a sign nybble (C=positive, D=negative, F=unsigned).

12 34 50 00 00 00 1C

Assuming code page 37 is correct, you could write this to the file using the string "\u0012\u0094&\u0000\u0000\u001C", but it would make much more sense to write these non-text fields in binary mode.

Body:
I have to prepare a file for an outside entity, and this entity uses an IBM mainframe with COBOL and requires the file to be encoded in EBCDIC. I am creating the file in C#. I guess this is a two-part question...firstly, is the code below sufficient to ensure that the file will be generated in a manner that they can read?

StreamWriter sw = new StreamWriter(@"C:\EBCDICFileEquivalent.txt", false, Encoding.GetEncoding(37));

Secondly, several fields in the file require packed decimal, in the format S(9)13 COMP-3. Since I have already specified EBCDIC encoding, can I just write the decimal number (e.g. 1234500000001) to the file using:

sw.WriteLine("1234500000001C");

...and have it turn out correctly in the generated file?

Have never done anything with EBCDIC or COMP-3.