问:
Where can i find a list of error in SONOS documentation? error 1028 from SOAP response
in a soap call to add songs to a saved queue (AddURIToSavedQueue) in SONOS, I receive a response with error 1028 but I can't figure out what the problem is, could you tell me in the documentation where I can find the list of errors?

my call body

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <s:Body>
    <u:AddURIToSavedQueue xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">
        <InstanceID>0</InstanceID>
        <ObjectID>SQ:19</ObjectID>
        <UpdateID></UpdateID>
        <EnqueuedURI>https://xxx.it/xxx/xx-001.mp3</EnqueuedURI>
        <EnqueuedURIMetaData></EnqueuedURIMetaData>
        <AddAtIndex>0</AddAtIndex>
    </u:AddURIToSavedQueue>
  </s:Body>
</s:Envelope>
</code>```

my response

```<code><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <s:Body>
        <s:Fault>
            <faultcode>s:Client</faultcode>
            <faultstring>UPnPError</faultstring>
            <detail>
                <UPnPError xmlns="urn:schemas-upnp-org:control-1-0">
                    <errorCode>1028</errorCode>
                </UPnPError>
            </detail>
        </s:Fault>
    </s:Body>
</s:Envelope>
</code>```

this is my code in flutter (Dart)

```<code> addURI() async {
    var playlist = await Player().getDataFromPl();
    var brani = playlist['lista']['brano'];

    for (var brano in brani) {
      final localizedDt = tz.TZDateTime.from(DateTime.now(), rome);
      String formattedTime = DateFormat('HH:mm:ss').format(localizedDt);
      print('SONOS: $formattedTime');

      if (brano['ora'].compareTo(formattedTime) > 0) {
        final String soapEnvelope = """
                  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                    <s:Body>
                      <u:AddURIToSavedQueue xmlns:u="urn:schemas-upnp-org:service:AVTransport:1">
                          <InstanceID>0</InstanceID>
                          <ObjectID>$queueID</ObjectID>
                          <UpdateID></UpdateID>
                          <EnqueuedURI>https://xxx.xxx.it/${brano['nome']}</EnqueuedURI>
                          <EnqueuedURIMetaData></EnqueuedURIMetaData>
                          <AddAtIndex>${brani.indexOf(brano)}</AddAtIndex>
                      </u:AddURIToSavedQueue>
                    </s:Body>
                  </s:Envelope>
              """;

        final sonosUri =
            Uri.parse('http://$ipAddress/MediaRenderer/AVTransport/Control');

        final response = await http.post(
          sonosUri,
          headers: {
            'Content-Type': 'application/xml',
            'soapaction':
                'urn:schemas-upnp-org:service:AVTransport:1#AddURIToSavedQueue'
          },
          body: soapEnvelope,
        );
      }
    }

    stopSonos();
    playSonos();
  }
</code>```

Body:
in a soap call to add songs to a saved queue (AddURIToSavedQueue) in SONOS, I receive a response with error 1028 but I can't figure out what the problem is, could you tell me in the documentation where I can find the list of errors?

my call body

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
  <s:Body>

        <InstanceID>0</InstanceID>
        <ObjectID>SQ:19</ObjectID>
        <UpdateID></UpdateID>
        <EnqueuedURI>https://xxx.it/xxx/xx-001.mp3</EnqueuedURI>
        <EnqueuedURIMetaData></EnqueuedURIMetaData>
        <AddAtIndex>0</AddAtIndex>

  </s:Body>
</s:Envelope>

my response

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <s:Body>
        <s:Fault>
            <faultcode>s:Client</faultcode>
            <faultstring>UPnPError</faultstring>
            <detail>
                <UPnPError xmlns="urn:schemas-upnp-org:control-1-0">
                    <errorCode>1028</errorCode>
                </UPnPError>
            </detail>
        </s:Fault>
    </s:Body>
</s:Envelope>

this is my code in flutter (Dart)

 addURI() async {
    var playlist = await Player().getDataFromPl();
    var brani = playlist['lista']['brano'];

    for (var brano in brani) {
      final localizedDt = tz.TZDateTime.from(DateTime.now(), rome);
      String formattedTime = DateFormat('HH:mm:ss').format(localizedDt);
      print('SONOS: $formattedTime');

      if (brano['ora'].compareTo(formattedTime) > 0) {
        final String soapEnvelope = """
                  <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
                    <s:Body>

                          <InstanceID>0</InstanceID>
                          <ObjectID>$queueID</ObjectID>
                          <UpdateID></UpdateID>
                          <EnqueuedURI>https://xxx.xxx.it/${brano['nome']}</EnqueuedURI>
                          <EnqueuedURIMetaData></EnqueuedURIMetaData>
                          <AddAtIndex>${brani.indexOf(brano)}</AddAtIndex>

                    </s:Body>
                  </s:Envelope>
              """;

        final sonosUri =
            Uri.parse('http://$ipAddress/MediaRenderer/AVTransport/Control');

        final response = await http.post(
          sonosUri,
          headers: {
            'Content-Type': 'application/xml',
            'soapaction':
                'urn:schemas-upnp-org:service:AVTransport:1#AddURIToSavedQueue'
          },
          body: soapEnvelope,
        );
      }
    }

    stopSonos();
    playSonos();
  }


来源: stackexchange

问:
Whether there is a limit to deleting accounts per day when using Google Account Delete API
Using the Google User Account Delete API, four accounts divide a total of 70,000 accounts into 1/4 and proceed with deletion at the same time.

Three of the four accounts were not deleted due to the error shown in the picture below. Delete only one account API proceeds without any problems
enter image description here

When deleting accounts from the administrator page manually rather than API, the following message sometimes occurs.
enter image description here

Attempt: Approximately 70,000 accounts will be deleted with 4 accounts

Expected: 4 accounts will delete 70,000 accounts at the same time

Result: Only one account will proceed and the rest will receive an error message

ContentLicense: CC BY-SA 4.0


问:
How/Where to input Bearer Token in POST request in CucumberJS
Dear all cucumber experts, where should I input my bearer token in my cucumber feature file [Given, When, Then?] as well as the syntax for it? I apologise in advance as I am a newbie.

I have no progress after searching through various videos and tutorials.


问:
Errors in the use of Specification<T>, returns one object out of 2 matching the search criteria
Errors in the use of Specification, returns one object out of 2 matching the search criteria, while builder returns the correct value.
springDatabaseItemRepository.findAll(builder.build(), pageable);

I'm looking for 3 conditions: 1 of which joins all queries and works. The other two are one simple query, the second is join connected using or. And after processing, only the results of join are returned to me.

I tried to change the processing and conditions, tried to read the documentation, but it didn't give me anything. Also, if you call join and a simple query separately, the results are returned correct.


问:
how can i send tracking Campaign URL from my app to play console
I create link from Campaign Builder and remove ad network
and I try this code, but nothing appears on my play console. And some issue occurs about SDK 31 or above
/////////////////////
Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
/////////////////////
but function just use intent not pendingintent

```<code>
referrerClient.startConnection(object : InstallReferrerStateListener {
    override fun onInstallReferrerSetupFinished(responseCode: Int) {
        when (responseCode) {
            InstallReferrerResponse.OK -> {
                val response: ReferrerDetails? = try {
                    referrerClient.installReferrer
                } catch (e: RemoteException) {
                    e.printStackTrace()
                    return
                }
                val referrerUrl = response?.installReferrer
                trackInstallReferrer(referrerUrl)
                referrerClient.endConnection()
            }
            InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
            }
            InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
            }
        }
    }

    override fun onInstallReferrerServiceDisconnected() {}
})
private fun trackInstallReferrer(referrerUrl: String) {
    Handler(mainLooper).post {
        val receiver = CampaignTrackingReceiver()
        val intent = Intent("com.android.vending.INSTALL_REFERRER")
        intent.putExtra("referrer", referrerUrl)
        receiver.onReceive(applicationContext, intent)
    }
}
</code>```

What is wrong with my function or do you have any idea to give me?

and how long this tracking will show in my play console?

Body:
I create link from Campaign Builder and remove ad network
and I try this code, but nothing appears on my play console. And some issue occurs about SDK 31 or above
/////////////////////
Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
/////////////////////
but function just use intent not pendingintent

referrerClient.startConnection(object : InstallReferrerStateListener {
    override fun onInstallReferrerSetupFinished(responseCode: Int) {
        when (responseCode) {
            InstallReferrerResponse.OK -> {
                val response: ReferrerDetails? = try {
                    referrerClient.installReferrer
                } catch (e: RemoteException) {
                    e.printStackTrace()
                    return
                }
                val referrerUrl = response?.installReferrer
                trackInstallReferrer(referrerUrl)
                referrerClient.endConnection()
            }
            InstallReferrerResponse.FEATURE_NOT_SUPPORTED -> {
            }
            InstallReferrerResponse.SERVICE_UNAVAILABLE -> {
            }
        }
    }

    override fun onInstallReferrerServiceDisconnected() {}
})
private fun trackInstallReferrer(referrerUrl: String) {
    Handler(mainLooper).post {
        val receiver = CampaignTrackingReceiver()
        val intent = Intent("com.android.vending.INSTALL_REFERRER")
        intent.putExtra("referrer", referrerUrl)
        receiver.onReceive(applicationContext, intent)
    }
}

What is wrong with my function or do you have any idea to give me?

and how long this tracking will show in my play console?


问:
TypeScript: Can I infer number index value type?
I created a helper function to convert an object of numbered keys to a Map:

interface IndexedObject {
    [index: number]: unknown;
};

const objectToIndexedMap = (indexedObject: IndexedObject) => new Map(
    Object.entries(indexedObject).map(
        ([ index, field ]) => [ Number(index), field ]
    )
);
```
<p>I use it to convert objects I'm getting from the API to a more convenient Map, where I don't need to deal with string keys anymore. The problem is that the returned type is <code>Map<number, any></code>, while I'd like to use the type of those values in <code>IndexedObject</code>.</p>
<p>Is it possible to get that type and make my function return this specific type for Map values?</p>
<p>So for example this would throw an error:</p>
<pre class="lang-js prettyprint-override"><code>interface IndexedNumbers {
    [index: number]: number;
}

const indexedNumbers: IndexedNumbers = api.numbers; // pseudocode
const map = objectToIndexedMap(indexedNumbers);
const foo = map.get(0)!.toUpperCase(); // This should throw an error
</code>```

Of course I know I can hard-type it:

const map: Map<number, number> = objectToIndexedMap(indexedNumbers);
```

But I'd love TypeScript to do that for me. Is it possible?

Body:
I created a helper function to convert an object of numbered keys to a Map:

interface IndexedObject {
    [index: number]: unknown;
};

const objectToIndexedMap = (indexedObject: IndexedObject) => new Map(
    Object.entries(indexedObject).map(
        ([ index, field ]) => [ Number(index), field ]
    )
);

I use it to convert objects I'm getting from the API to a more convenient Map, where I don't need to deal with string keys anymore. The problem is that the returned type is Map<number, any>, while I'd like to use the type of those values in IndexedObject.

Is it possible to get that type and make my function return this specific type for Map values?

So for example this would throw an error:

interface IndexedNumbers {
    [index: number]: number;
}

const indexedNumbers: IndexedNumbers = api.numbers; // pseudocode
const map = objectToIndexedMap(indexedNumbers);
const foo = map.get(0)!.toUpperCase(); // This should throw an error

Of course I know I can hard-type it:

const map: Map<number, number> = objectToIndexedMap(indexedNumbers);

But I'd love TypeScript to do that for me. Is it possible?


问:
how to give tabindex to third party library like, ng2-datepicker from datepickermodule in angular
I am using <ngx-datepicker></ngx-datepicker> in my template which I have imported from DatePickerModule. Problem is, it is not keyboard accessible. How to make that calendar keyboard accessible and select date using keyboard?

I tried <ngx-datepicker tabindex="0"></ngx-datepicker>. But it did not set the focus on calendar and I was not able to select date using keyboard. I should be able to navigate through keyboard and select date using keyboard.


问:
Why does my code run different on google chrome inspection?
I have made a responsive navbar with html, css and basic js, that changes according to the width of the screen.

Although the code works perfectly and the navbar is responsive while resizing the window (that i preview my code to), when I test it with Google Chrome Inspect to see how it looks on other devices (phones, tablet, etc) it doesn't work, even though the width is smaller than the max-width i have set:

```<code>@media only screen and (max-width: 600px) {
  .toggle-button {
    display: flex;
  }
  .navbar-links {
    display: none;
    width: 100%;
  }
  .navbar {
    flex-direction: column;
    align-items: flex-start;
  }
  .navbar-links ul {
    flex-direction: column;
    width: 100%;
  }
  .navbar-links li {
    text-align: center;
  }

  .navbar-links li a {
    padding: 0.75rem 1rem;
  }
  .navbar-links.active {
    display: flex;
  }

}
</code>```

Body:
I have made a responsive navbar with html, css and basic js, that changes according to the width of the screen.

Although the code works perfectly and the navbar is responsive while resizing the window (that i preview my code to), when I test it with Google Chrome Inspect to see how it looks on other devices (phones, tablet, etc) it doesn't work, even though the width is smaller than the max-width i have set:

@media only screen and (max-width: 600px) {
  .toggle-button {
    display: flex;
  }
  .navbar-links {
    display: none;
    width: 100%;
  }
  .navbar {
    flex-direction: column;
    align-items: flex-start;
  }
  .navbar-links ul {
    flex-direction: column;
    width: 100%;
  }
  .navbar-links li {
    text-align: center;
  }

  .navbar-links li a {
    padding: 0.75rem 1rem;
  }
  .navbar-links.active {
    display: flex;
  }

}


问:
Load Images in Runtime
I'm using opencv and face recognition model to detect and Identify the face in webcam.

I saw that all Images in folder are encoded once then search faces .. but if I add the image in runtime it'll not pick up that image

can anyone help , how to load images in runtime if Images are not found in particular folder

Thanks,
Chiranjit

Title: Load Images in Runtime


问:
When removing & readding an element loaded through serialbus in Nodejs array my system crashes
So im writing this piece of code to maintain modules on a bus in NodeJs to replace older Delphi 4 code.

The module sends information in blocks, these blocks contain the encoded information and look like this:

```<code>{
  sender_module_group: { name: 'Sensor', number: 3, hex: 0x03 },
  receiver: <Buffer 01 03>,
  type: 0,
  data_type: { name: 'DATA_BLOCK', number: 33029, hex: 0x8105},
  length: <Buffer 16>,
  message: <Buffer 00 d5 23 13 ac ff fe a2 ba 53 a6 1b e7 aa d2 51 05 00 00 00 00 00>,
}
</code>```

During the initialization of the module there are in total around 50 blocks of data each stating what page of memory needs to be read next.

Each block is processed and slowly an object is filled with the data. The first time around on bootup, it works like a charm and all the data gets filled.

The issue arises when a module is dropped(a module can drop due bad connection, CRC checks failing in data transfer, etc).

Modules are dropped in the following way:

```<code> modules.splice(index, 1)
</code>```

Where index is the index of the object in the array of objects modules

When I then try to re-add the module after the connection is reestablished it will start with the first few blocks, these are similar to the original. However, at an x number of blocks, the code will crash/stop running the next block

I narrowed it down to the array of objects, could there be a shadow copy and how can in cleanse that one"?

Body:
So im writing this piece of code to maintain modules on a bus in NodeJs to replace older Delphi 4 code.

The module sends information in blocks, these blocks contain the encoded information and look like this:

{
  sender_module_group: { name: 'Sensor', number: 3, hex: 0x03 },
  receiver: <Buffer 01 03>,
  type: 0,
  data_type: { name: 'DATA_BLOCK', number: 33029, hex: 0x8105},
  length: <Buffer 16>,
  message: <Buffer 00 d5 23 13 ac ff fe a2 ba 53 a6 1b e7 aa d2 51 05 00 00 00 00 00>,
}

During the initialization of the module there are in total around 50 blocks of data each stating what page of memory needs to be read next.

Each block is processed and slowly an object is filled with the data. The first time around on bootup, it works like a charm and all the data gets filled.

The issue arises when a module is dropped(a module can drop due bad connection, CRC checks failing in data transfer, etc).

Modules are dropped in the following way:

 modules.splice(index, 1)

Where index is the index of the object in the array of objects modules

When I then try to re-add the module after the connection is reestablished it will start with the first few blocks, these are similar to the original. However, at an x number of blocks, the code will crash/stop running the next block

I narrowed it down to the array of objects, could there be a shadow copy and how can in cleanse that one"?


问:
Formik min date max date validation if Max date < min date i wanna to showing error
I have 2 input,from date to date and if user enter from date and to date while,to date don't < from date if happened i wanna to shwo error. I'm using FORMIK and YUP package

While I'm tried many method at the time didn't show error but if i didn't use when function, that time getting value on other hand some tims getting error


问:
Using YOLOv5 how to i print the detected class/classed along with their confidence score
I'm new at object detection. So i followed a youtube tutorial and created a custom model using YOLOv5 model, to detec brand logo from images of receipts.

The custom model I trained was a success (yay!), but, I'm now stuck trying to print the detected class/classes along with their confidence score.

I've been looking for a solution for past 1 week, please help!

I tried using both
results = model(img) results.print() results.save(save_dir='results')

and
detect.py --weights D:/brand_logo_classifier/yolov5/runs/train/exp17/weights/best.pt --source D:/brand_logo_classifier/data/validation/zara_moe_67.jpg  --print

but still couldn't get the class and the confidence score detected in the image.


问:
Call a component of vue 3 inside another component but in the part of

<template>

</template>
```

Title: Call a component of vue 3 inside another component but in the part of <script setup>

Body:
I have a vue3 component and I don't want to use it in the template of another component but in the script setup.

<template>

</template>


问:
gcloud transfer jobs does not recognize my azure credentials file
Whenever I try to use the gcloud transfer cli to create a transfer job from an azure blob container to a google cloud storage bucket, I am being thrown the following error :

```<code>ERROR: gcloud crashed (ValueError): Source creds file must be JSON or INI format.
</code>```

the file in the json path I fill in looks like this :

```<code>{"sasToken": "working_token"}
</code>```

and I also tried this

```<code>{
  "sasToken": "working_token"
}
</code>```

As it's stated here but none of them actually works.
I also tried to put the content of the file in the --source-creds-file option but it says this is not a path to a file, which is true.

When using the console to create the same job, it just works, so has anyone got the cli to work? Any idea?

Thanks in advance

Body:
Whenever I try to use the gcloud transfer cli to create a transfer job from an azure blob container to a google cloud storage bucket, I am being thrown the following error :

ERROR: gcloud crashed (ValueError): Source creds file must be JSON or INI format.

the file in the json path I fill in looks like this :

{"sasToken": "working_token"}

and I also tried this

{
  "sasToken": "working_token"
}

As it's stated here but none of them actually works.
I also tried to put the content of the file in the --source-creds-file option but it says this is not a path to a file, which is true.

When using the console to create the same job, it just works, so has anyone got the cli to work? Any idea?

Thanks in advance


问:
Send event from php controller
Good morning everyone.
I need to send a notification whenever a user swipes a tab on a particular sensor.
The problem is not the connection to the sensor, which at this moment already takes place and subject to user access.
Currently I have created a server socket inside my yii2 app to be able to send the notification event to the client and update them in real time.

This is my controller server

```<code>class ServerController extends Controller
{
    public function actionStart()
    {
        // $server = new CommandsServer();
        $server = new ChatServer();
        $server->port = 80; //This port must be busy by WebServer and we handle an error

        $server->on(WebSocketServer::EVENT_WEBSOCKET_OPEN_ERROR, function ($e) use ($server) {
            echo "Error opening port " . $server->port . "\n";
            $server->port += 1; //Try next port to open
            $server->start();
        });

        $server->on(WebSocketServer::EVENT_WEBSOCKET_OPEN, function ($e) use ($server) {
            echo "Server started at port " . $server->port;
        });

        $server->start();
    }
}
</code>```

This is my chat server which I created for testing

```<code><?php

namespace frontend\daemons;

use consik\yii2websocket\events\WSClientEvent;
use consik\yii2websocket\WebSocketServer;
use Ratchet\ConnectionInterface;

 class ChatServer extends WebSocketServer
{

    public function init()
    {
        parent::init();

        $this->on(self::EVENT_CLIENT_CONNECTED, function (WSClientEvent $e) {
            $e->client->name = null;
        });
    }

    protected function getCommand(ConnectionInterface $from, $msg)
    {
        $request = json_decode($msg, true);
        return !empty($request['action']) ? $request['action'] : parent::getCommand($from, $msg);
    }

   public function commandPing(ConnectionInterface $client, $msg)
    {
        $arr = ["Neo", "Morpheus", "Trinity", "Cypher", "Tank"];
        $res = ['type' => 'ping', 'message' => json_encode(array_rand($arr, 1))];
        foreach ($this->clients as $chatClient) {
            $chatClient->send(json_encode($res));
        }
    }
}
</code>```

Now, what I wish I could do is be able to use that commandPing inside another controller, but I haven't found a way I can implement this.

In this sense the round would be:
user swipes card on sensor -> the sensor calls my method to see if the user is actually authorized to enter -> I call commandPing (as an example) to send a notification to the customer (OK / KO )

On the web interface side I will then intercept the message via new Websocket (but this is not a problem)

Title: Send event from php controller

Body:
Good morning everyone.
I need to send a notification whenever a user swipes a tab on a particular sensor.
The problem is not the connection to the sensor, which at this moment already takes place and subject to user access.
Currently I have created a server socket inside my yii2 app to be able to send the notification event to the client and update them in real time.

This is my controller server

class ServerController extends Controller
{
    public function actionStart()
    {
        // $server = new CommandsServer();
        $server = new ChatServer();
        $server->port = 80; //This port must be busy by WebServer and we handle an error

        $server->on(WebSocketServer::EVENT_WEBSOCKET_OPEN_ERROR, function ($e) use ($server) {
            echo "Error opening port " . $server->port . "\n";
            $server->port += 1; //Try next port to open
            $server->start();
        });

        $server->on(WebSocketServer::EVENT_WEBSOCKET_OPEN, function ($e) use ($server) {
            echo "Server started at port " . $server->port;
        });

        $server->start();
    }
}

This is my chat server which I created for testing

<?php

namespace frontend\daemons;

use consik\yii2websocket\events\WSClientEvent;
use consik\yii2websocket\WebSocketServer;
use Ratchet\ConnectionInterface;

 class ChatServer extends WebSocketServer
{

    public function init()
    {
        parent::init();

        $this->on(self::EVENT_CLIENT_CONNECTED, function (WSClientEvent $e) {
            $e->client->name = null;
        });
    }

    protected function getCommand(ConnectionInterface $from, $msg)
    {
        $request = json_decode($msg, true);
        return !empty($request['action']) ? $request['action'] : parent::getCommand($from, $msg);
    }

   public function commandPing(ConnectionInterface $client, $msg)
    {
        $arr = ["Neo", "Morpheus", "Trinity", "Cypher", "Tank"];
        $res = ['type' => 'ping', 'message' => json_encode(array_rand($arr, 1))];
        foreach ($this->clients as $chatClient) {
            $chatClient->send(json_encode($res));
        }
    }
}

Now, what I wish I could do is be able to use that commandPing inside another controller, but I haven't found a way I can implement this.

In this sense the round would be:
user swipes card on sensor -> the sensor calls my method to see if the user is actually authorized to enter -> I call commandPing (as an example) to send a notification to the customer (OK / KO )

On the web interface side I will then intercept the message via new Websocket (but this is not a problem)


问:
Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent while placing Call
Whenever the call is placed on Android 13, it is causing the app to crash. I am using twilio in my react native project. Below is the sentry logs, which I am receiving.

```<code>java.lang.IllegalArgumentException: com.myapp.android: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
    at android.app.PendingIntent.checkFlags(PendingIntent.java:408)
    at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:491)
    at android.app.PendingIntent.getActivity(PendingIntent.java:477)
    at android.app.PendingIntent.getActivity(PendingIntent.java:441)
    at com.hoxfon.react.RNTwilioVoice.CallNotificationManager.createHangupNotification(CallNotificationManager.java:154)
    at com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule$3.onConnected(TwilioVoiceModule.java:309)
    at com.twilio.voice.Call$1$2.run(Call.java:641)
    at android.os.Handler.handleCallback(Handler.java:942)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)
    at java.lang.Thread.run(Thread.java:1012)
</code>```

My android/build.gradle looks like

```<code>buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        ndkVersion = "21.4.7075529"
        androidXCore = "1.7.0"
        // supportLibVersion = "xxx"
        playServicesVersion = "18.0.1" // or find latest version
        androidMapsUtilsVersion = "2.3.0"
        playCoreVersion = '1.10.3'
        googlePlayServicesAuthVersion = "20.1.0" // for google auth
        kotlinVersion = '1.5.0' // for audio palyer
    }
    repositories {
        google()
        mavenCentral()
        // maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {
        classpath('com.android.tools.build:gradle:7.0.4')
        // classpath('com.getkeepsafe.relinker:relinker:1.2.2') // added for twilio
        classpath('com.google.gms:google-services:4.3.10')
        classpath('com.google.firebase:firebase-messaging:23.1.1') //old 21.0.1
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" // for audio player
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
    project.ext {
        excludeAppGlideModule = true
    }
}
</code>```

Have already tried adding these in my android/app/build.gradle but it didn't work.

```<code>implementation 'androidx.work:work-runtime:2.7.1' //androidx.work:work-runtime:2.7.0-alpha05
    implementation 'androidx.work:work-runtime-ktx:2.7.1'
    configurations.all {
        resolutionStrategy {
            force 'androidx.work:work-runtime:2.7.1'
            force 'androidx.work:work-runtime-ktx:2.7.1'
        }
    }
</code>```

Any help would be really appreciated. My versions for dependencies are also mentioned below

```<code> "react": "17.0.2",
 "react-native": "0.66.1",
 "react-native-twilio-programmable-voice": "github:hoxfon/react-native-twilio-programmable-voice#feat/twilio-android-sdk-5",
"@react-native-firebase/app": "^14.3.0",
 "@react-native-firebase/messaging": "^14.3.0",
 "react-native-audio-recorder-player": "^3.3.4",
</code>```

Body:
Whenever the call is placed on Android 13, it is causing the app to crash. I am using twilio in my react native project. Below is the sentry logs, which I am receiving.

java.lang.IllegalArgumentException: com.myapp.android: Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
Strongly consider using FLAG_IMMUTABLE, only use FLAG_MUTABLE if some functionality depends on the PendingIntent being mutable, e.g. if it needs to be used with inline replies or bubbles.
    at android.app.PendingIntent.checkFlags(PendingIntent.java:408)
    at android.app.PendingIntent.getActivityAsUser(PendingIntent.java:491)
    at android.app.PendingIntent.getActivity(PendingIntent.java:477)
    at android.app.PendingIntent.getActivity(PendingIntent.java:441)
    at com.hoxfon.react.RNTwilioVoice.CallNotificationManager.createHangupNotification(CallNotificationManager.java:154)
    at com.hoxfon.react.RNTwilioVoice.TwilioVoiceModule$3.onConnected(TwilioVoiceModule.java:309)
    at com.twilio.voice.Call$1$2.run(Call.java:641)
    at android.os.Handler.handleCallback(Handler.java:942)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loopOnce(Looper.java:226)
    at android.os.Looper.loop(Looper.java:313)
    at com.facebook.react.bridge.queue.MessageQueueThreadImpl$4.run(MessageQueueThreadImpl.java:226)
    at java.lang.Thread.run(Thread.java:1012)

My android/build.gradle looks like

buildscript {
    ext {
        buildToolsVersion = "30.0.2"
        minSdkVersion = 21
        compileSdkVersion = 31
        targetSdkVersion = 31
        ndkVersion = "21.4.7075529"
        androidXCore = "1.7.0"
        // supportLibVersion = "xxx"
        playServicesVersion = "18.0.1" // or find latest version
        androidMapsUtilsVersion = "2.3.0"
        playCoreVersion = '1.10.3'
        googlePlayServicesAuthVersion = "20.1.0" // for google auth
        kotlinVersion = '1.5.0' // for audio palyer
    }
    repositories {
        google()
        mavenCentral()
        // maven { url 'https://plugins.gradle.org/m2/' }
    }
    dependencies {
        classpath('com.android.tools.build:gradle:7.0.4')
        // classpath('com.getkeepsafe.relinker:relinker:1.2.2') // added for twilio
        classpath('com.google.gms:google-services:4.3.10')
        classpath('com.google.firebase:firebase-messaging:23.1.1') //old 21.0.1
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" // for audio player
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
    project.ext {
        excludeAppGlideModule = true
    }
}

Have already tried adding these in my android/app/build.gradle but it didn't work.

implementation 'androidx.work:work-runtime:2.7.1' //androidx.work:work-runtime:2.7.0-alpha05
    implementation 'androidx.work:work-runtime-ktx:2.7.1'
    configurations.all {
        resolutionStrategy {
            force 'androidx.work:work-runtime:2.7.1'
            force 'androidx.work:work-runtime-ktx:2.7.1'
        }
    }

Any help would be really appreciated. My versions for dependencies are also mentioned below

 "react": "17.0.2",
 "react-native": "0.66.1",
 "react-native-twilio-programmable-voice": "github:hoxfon/react-native-twilio-programmable-voice#feat/twilio-android-sdk-5",
"@react-native-firebase/app": "^14.3.0",
 "@react-native-firebase/messaging": "^14.3.0",
 "react-native-audio-recorder-player": "^3.3.4",


问:
Twilio video virtual background processor tuning for sharp outlines
I'am using twilio video processors to add virtual backgrounds to  my video tracks. The problem is that the outlines of the speaking person  are not sharp, they are randomly mixed with the virtual background. Sometimes a entire part like the hand is being hidden by the backgound, especially whe the person is moving.
Here are my setting when starting the virtual effect :

```<code> this.virtualP = new VideoProcessors.VirtualBackgroundProcessor({
          assetsPath: '/assets/video-processors/',
          backgroundImage: img,
          fitType: VideoProcessors.ImageFit.Fill,
          maskBlurRadius: 10
        });
</code>```

I tried playing with the maskBlurRadius but did not get any real improvement.

Any hints ? Thanks

Body:
I'am using twilio video processors to add virtual backgrounds to  my video tracks. The problem is that the outlines of the speaking person  are not sharp, they are randomly mixed with the virtual background. Sometimes a entire part like the hand is being hidden by the backgound, especially whe the person is moving.
Here are my setting when starting the virtual effect :

 this.virtualP = new VideoProcessors.VirtualBackgroundProcessor({
          assetsPath: '/assets/video-processors/',
          backgroundImage: img,
          fitType: VideoProcessors.ImageFit.Fill,
          maskBlurRadius: 10
        });

I tried playing with the maskBlurRadius but did not get any real improvement.

Any hints ? Thanks


问:
Django - Display TextChoices
Imagine there is a model:

```<code>class CeleryStatus(models.Model):
    class Code(models.TextChoices):
        PENDING = 'pending', 'Pending'
        PROGRESS = 'progress', 'In progress'
        SUCCESS = 'success', 'Success'

    code = models.TextField(unique=True, choices=Code.choices)
    name = models.TextField()  # editable, for frontend
    description = models.TextField()
</code>```

Register the model in admin:

```<code>@admin.register(CeleryStatus)
class CeleryStatusAdmin(admin.ModelAdmin):
    list_display = ('code', 'name')
</code>```

The problem: in "Code" column there are not actual codes (progress) but like descriptions (In progress).

How to display actual code (what is written into database table) (progress instead of In progress)?

Title: Django - Display TextChoices

Body:
Imagine there is a model:

class CeleryStatus(models.Model):
    class Code(models.TextChoices):
        PENDING = 'pending', 'Pending'
        PROGRESS = 'progress', 'In progress'
        SUCCESS = 'success', 'Success'

    code = models.TextField(unique=True, choices=Code.choices)
    name = models.TextField()  # editable, for frontend
    description = models.TextField()

Register the model in admin:

@admin.register(CeleryStatus)
class CeleryStatusAdmin(admin.ModelAdmin):
    list_display = ('code', 'name')

The problem: in "Code" column there are not actual codes (progress) but like descriptions (In progress).

How to display actual code (what is written into database table) (progress instead of In progress)?


问:
ViewModel unit test expected success but actual is null
I want to write a simple test for my viewModel to check if it gets data from repository. The app itself working without problem but in test, i have the following test failed.

It looks like the viewModel init block not running, because it suppose to call getUpcomingMovies() method in init blocks and post value to upcomingMovies live data object. When i test it gets null value.

Looks like i am missing a minor thing, need help to solve this.
Here is the test:

```<code>@ExperimentalCoroutinesApi
class MoviesViewModelShould: BaseUnitTest() {

    private val repository: MoviesRepository = mock()
    private val upcomingMovies = mock<Response<UpcomingResponse>>()
    private val upcomingMoviesExpected = Result.success(upcomingMovies)

    @Test
    fun emitsUpcomingMoviesFromRepository() = runBlocking {
        val viewModel = mockSuccessfulCaseUpcomingMovies()

        assertEquals(upcomingMoviesExpected, viewModel.upcomingMovies.getValueForTest())
    }

    private fun mockSuccessfulCaseUpcomingMovies(): MoviesViewModel {
        runBlocking {
            whenever(repository.getUpcomingMovies(1)).thenReturn(
                flow {
                    emit(upcomingMoviesExpected)
                }
            )
        }
        return MoviesViewModel(repository)
    }
}
</code>```

And viewModel:

```<code>class MoviesViewModel(
    private val repository: MoviesRepository
): ViewModel() {

    val upcomingMovies: MutableLiveData<UpcomingResponse> = MutableLiveData()
    var upcomingMoviesPage = 0
    private var upcomingMoviesResponse: UpcomingResponse? = null

    init {
        getUpcomingMovies()
    }

    fun getUpcomingMovies() = viewModelScope.launch {
        upcomingMoviesPage++
        repository.getUpcomingMovies(upcomingMoviesPage).collect { result ->
            if (result.isSuccess) {
                result.getOrNull()!!.body()?.let {
                    if (upcomingMoviesResponse == null) {
                        upcomingMoviesResponse = it
                    } else {
                        val oldMovies = upcomingMoviesResponse?.results
                        val newMovies = it.results
                        oldMovies?.addAll(newMovies)
                    }
                    upcomingMovies.postValue(upcomingMoviesResponse ?: it)
                }
            }
        }
    }
}
</code>```

And the result is:

```<code>expected:<Success(Mock for Response, hashCode: 1625939772)> but was:<null>
Expected :Success(Mock for Response, hashCode: 1625939772)
Actual   :null
</code>```

Body:
I want to write a simple test for my viewModel to check if it gets data from repository. The app itself working without problem but in test, i have the following test failed.

It looks like the viewModel init block not running, because it suppose to call getUpcomingMovies() method in init blocks and post value to upcomingMovies live data object. When i test it gets null value.

Looks like i am missing a minor thing, need help to solve this.
Here is the test:

@ExperimentalCoroutinesApi
class MoviesViewModelShould: BaseUnitTest() {

    private val repository: MoviesRepository = mock()
    private val upcomingMovies = mock<Response<UpcomingResponse>>()
    private val upcomingMoviesExpected = Result.success(upcomingMovies)

    @Test
    fun emitsUpcomingMoviesFromRepository() = runBlocking {
        val viewModel = mockSuccessfulCaseUpcomingMovies()

        assertEquals(upcomingMoviesExpected, viewModel.upcomingMovies.getValueForTest())
    }

    private fun mockSuccessfulCaseUpcomingMovies(): MoviesViewModel {
        runBlocking {
            whenever(repository.getUpcomingMovies(1)).thenReturn(
                flow {
                    emit(upcomingMoviesExpected)
                }
            )
        }
        return MoviesViewModel(repository)
    }
}

And viewModel:

class MoviesViewModel(
    private val repository: MoviesRepository
): ViewModel() {

    val upcomingMovies: MutableLiveData<UpcomingResponse> = MutableLiveData()
    var upcomingMoviesPage = 0
    private var upcomingMoviesResponse: UpcomingResponse? = null

    init {
        getUpcomingMovies()
    }

    fun getUpcomingMovies() = viewModelScope.launch {
        upcomingMoviesPage++
        repository.getUpcomingMovies(upcomingMoviesPage).collect { result ->
            if (result.isSuccess) {
                result.getOrNull()!!.body()?.let {
                    if (upcomingMoviesResponse == null) {
                        upcomingMoviesResponse = it
                    } else {
                        val oldMovies = upcomingMoviesResponse?.results
                        val newMovies = it.results
                        oldMovies?.addAll(newMovies)
                    }
                    upcomingMovies.postValue(upcomingMoviesResponse ?: it)
                }
            }
        }
    }
}

And the result is:

expected:<Success(Mock for Response, hashCode: 1625939772)> but was:<null>
Expected :Success(Mock for Response, hashCode: 1625939772)
Actual   :null


问:
Different value after predicting the ConvLSTM2D model
I generated ConvLSTM2D model for forecasting some raster file, the actual value is between 20 until 50, but when I get the result it has range between 0.49 and 0.5. But, if I compare the test result with actual data, it has same pattern. I am a newbie here, so any respond will be appreciate a lot

This is my model below
`

```<code>seq = keras.Sequential(
    [
        keras.Input(shape=(None, 128, 128, 1)),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.Conv3D(filters=1, kernel_size=(3, 3, 3), activation='sigmoid', padding='same', data_format='channels_last'),
    ]
)
</code>```

I expect the result has some criteria (about range value) with the validation/training data.

Body:
I generated ConvLSTM2D model for forecasting some raster file, the actual value is between 20 until 50, but when I get the result it has range between 0.49 and 0.5. But, if I compare the test result with actual data, it has same pattern. I am a newbie here, so any respond will be appreciate a lot

This is my model below
`

seq = keras.Sequential(
    [
        keras.Input(shape=(None, 128, 128, 1)),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.ConvLSTM2D(filters=40, kernel_size=(3,3), padding='same', return_sequences=True),
        layers.BatchNormalization(),

        layers.Conv3D(filters=1, kernel_size=(3, 3, 3), activation='sigmoid', padding='same', data_format='channels_last'),
    ]
)

I expect the result has some criteria (about range value) with the validation/training data.


问:
Action.DIAL not received when dialing from native android contacts app
I am trying to make my application place calls instead of the default android dialer when calling from contacts application, working with Android 8-9 Samsung SM-G950F (if it matters) atm.

Currently coding in Xamarin C# android project, so my guess is that it's not so different from Java / Kotlin application developed in IntelliJ.
I have the following Intent filters in AndroidManifest:

```<code>        <activity android:name="com.app.ContactsDialerActivity" android:exported="true" android:enabled="true" android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.DIAL"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.DIAL"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:scheme="tel" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.CALL_PRIVILEGED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</code>```

Furthermore, my Manifest include the following permissions:

```<code><uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />
</code>```

All permissions was granted when application started.

In the Activity class I have the following attribute above the class name:

```<code>    [IntentFilter(new[] { Intent.ActionView, Intent.ActionDial },
                    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable })]
[Activity(Label = "ContactsDialerActivity", Name = "com.app.ContactsDialerActivity", Exported = true, Enabled = true)]
</code>```

I have implemented the below code in OnCreate() and in OnStart() method:

```<code> // Get the incoming call intent
        var callIntent = Intent;
        var callAction = callIntent.Action;
        var callData = callIntent.Data;

        // Check if the intent is a call intent
        Log.Info(TAG, "Intent action: " + callAction);

        if (callAction == Intent.ActionDial)
        {...}
</code>```

I was able to achieve default dialer as my application, and when trying to click on a tel: tag such as:

```<code><a href="tel:123"></a>
</code>```

Android actually prompt for application selection to place to the call (including my app) and I am getting the event in my application.
However, when trying to place a call from contacts application / phone dialer application I am not getting any prompt like the above.

Thanks in advance.

Body:
I am trying to make my application place calls instead of the default android dialer when calling from contacts application, working with Android 8-9 Samsung SM-G950F (if it matters) atm.

Currently coding in Xamarin C# android project, so my guess is that it's not so different from Java / Kotlin application developed in IntelliJ.
I have the following Intent filters in AndroidManifest:

        <activity android:name="com.app.ContactsDialerActivity" android:exported="true" android:enabled="true" android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.DIAL"/>
            <category android:name="android.intent.category.DEFAULT"/>
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.DIAL"/>
            <category android:name="android.intent.category.DEFAULT"/>
            <data android:scheme="tel" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.CALL_PRIVILEGED" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

Furthermore, my Manifest include the following permissions:

<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.WRITE_CALL_LOG" />

All permissions was granted when application started.

In the Activity class I have the following attribute above the class name:

    [IntentFilter(new[] { Intent.ActionView, Intent.ActionDial },
                    Categories = new[] { Intent.CategoryDefault, Intent.CategoryBrowsable })]
[Activity(Label = "ContactsDialerActivity", Name = "com.app.ContactsDialerActivity", Exported = true, Enabled = true)]

I have implemented the below code in OnCreate() and in OnStart() method:

 // Get the incoming call intent
        var callIntent = Intent;
        var callAction = callIntent.Action;
        var callData = callIntent.Data;

        // Check if the intent is a call intent
        Log.Info(TAG, "Intent action: " + callAction);

        if (callAction == Intent.ActionDial)
        {...}

I was able to achieve default dialer as my application, and when trying to click on a tel: tag such as:

Android actually prompt for application selection to place to the call (including my app) and I am getting the event in my application.
However, when trying to place a call from contacts application / phone dialer application I am not getting any prompt like the above.

Thanks in advance.


问:
Flann Matcher throwing error Unsupported format (Error)
When I run with less images, e.g 50-100 images, it work fine, but when I run with larger amount of images (200-700) it's throwing error. This is my code

```<code>from unittest import result
import cv2
import os
from glob import glob
import pickle
import numpy as np
import matplotlib as plt
import string

def get_train_and_test_img_features():
    train_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/query/*/*.png"
    #train_path = "/Users/Antonie/Project/Skripsi/myWork/Skripsi_Code/SIFTDocumentRetrieval/dataset3/test/*.png"
    test_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/target/*/*.png"

def get_sift_features(_in_path,_debug_view = False):
    img = cv2.imread(_in_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    sift = cv2.xfeatures2d.SIFT_create()
    kp,desc = sift.detectAndCompute(gray, None)
    img = cv2.drawKeypoints(gray, kp, img)
    #cv2.imshow('sift_keypoints', img)

    if _debug_view:
        img = cv2.drawKeypoints(gray, kp, img)
        cv2.imshow('sift_keypoints', img)

        cv2.waitKey(0)

    return kp,desc

def compare_features_flann(_kp1,_dsc1,_kp2,_dsc2,_thres=0):
    FLANN_INDEX_KDTREE = 3
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
    search_params = dict(checks=50)
    flann = cv2.FlannBasedMatcher(index_params, search_params)
    matches = flann.knnMatch(_dsc1, _dsc2, k=2)
    matches_mask = [[0, 0,] for i in range(len(matches))]

    good_points = []
    for i, (m, n) in enumerate(matches):
        if m.distance < 0.6 * n.distance:
            #matches_mask[i] = [1, 0]
            good_points.append(m)

    number_keypoints = 0
    if len(_kp1) <= len(_kp2):
        number_keypoints = len(_kp1)
    else:
        number_keypoints = len(_kp2)

    return good_points , len(good_points) / number_keypoints * 100

def compare_features_bf(_kp1,_dsc1,_kp2,_dsc2,_thres = 0):
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(_dsc1, _dsc2, k=2)
    good_points = []
    for i, (m, n) in enumerate(matches):
        if m.distance < 0.75 * n.distance:
            #matches_mask[i] = [1, 0]
            good_points.append(m)

    number_keypoints = 0
    if len(_kp1) <= len(_kp2):
        number_keypoints = len(_kp1)
    else:
        number_keypoints = len(_kp2)

    # print("KP 1: " + str(len(_kp1)))
    # print("Kp 2: " + str(len(_kp2)))
    # print("Match:", len(good_points))
    # print("Matches: ", len(good_points) / number_keypoints * 100)

    return good_points , len(good_points) / number_keypoints * 100

def create_query_database(_path):
    img_db = {}

    for file in glob(_path):
        kp, desc = get_sift_features(file)
        img_db[os.path.basename(file)] = {"keypoint": kp,
                                              "descriptors": desc}

    # # Database
    # with open('queries.txt', 'wb') as file:
    #    file.write(pickle.dumps(img_db))

    return img_db

def get_best_matches(_result_dict):
    mean = np.mean([val for key,val in _result_dict.items()])

    positive = {}
    negative = {}

    for key,val in _result_dict.items() :
        res = (val - mean)
        if  res > mean:
            positive[key] = val
        else:
            negative[key] = val

    return positive

if __name__ == "__main__":
    sift = cv2.xfeatures2d.SIFT_create()

    #lokasi
    target_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/target/*.*"
    #query_path = "/Users/Antonie/Project/logo-det/Dataset/logo/img_logo/*/*.png"
    #query_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/query/*/*.png"
    query_path = "/Users/Antonie/Project/Skripsi/myWork/Code/dataset_img4/Process2/Process2/*.png"

    query_db = create_query_database(query_path)

    for files in glob(target_path, recursive=True):
        results = {}
        kb1, des1 = get_sift_features(files)
        print(os.path.basename(files), "\n")
        for keys, values in query_db.items():
            kb2 = values["keypoint"]
            des2 = values["descriptors"]
            good, percentage = compare_features_flann(kb1, des1, kb2, des2)

            results[keys] = percentage

        #final_result = get_best_matches(results)
        final_result = sorted(results.items(), key=lambda x: x[1], reverse=True)[:4]
        sortdict = dict(final_result)
        #print(sortdict)

    out_list = []
    for i in sortdict.keys():
        out_list.append(i)

    nama_file = out_list
    print("ini daftar retrieve :  ",out_list)

    #print("ini hanya 1 : ", nama_file)

    for i in range(0, len(nama_file)):
        print(nama_file[i])

    # document_path = "/Users/Antonie/Project/Skripsi/myWork/Code/dataset_img4/firstPage/"
    # for root, dir, files in os.walk(query_path):
    #     if nama_file in files:
    #         print(os.path.join(root, nama_file))

    # #img_path= os.path.join(document_path, str(a))
    # img_path = document_path + str(out_list[1])
    # #print(a)
    # #bimg = cv2.imread(img_path)
    # #b = cv2.resize(bimg, (450,600))
    # #cv2.imshow("result", b)
    # #cv2.waitKey(0)

    #words = nama_file[0].split('_')
    #print(words)

    for j in nama_file:
        wordss = j.split('_')
        #wordss.append(j)
        print(str(wordss[0]) + '.pdf')

    #tugas next : split filename : PemkabBuleleng_1 (for logo)

        #print(final_result)

        #plt.figure()
        #plt.imshow(final_result[1])
        #plt.show()

    print("-----------------")
</code>```

Traceback (most recent call last):   File
"/Users/Antonie/Project/Skripsi/myWork/Code/siftFindDescriptor.py",
line 127, in
good, percentage = compare_features_flann(kb1, des1, kb2, des2)   File
"/Users/Antonie/Project/Skripsi/myWork/Code/siftFindDescriptor.py",
line 40, in compare_features_flann
matches = flann.knnMatch(_dsc1, dsc2, k=2) cv2.error: OpenCV(3.4.2)
/Users/travis/build/skvark/opencv-python/opencv/modules/flann/src/miniflann.cpp:315:
error: (-210:Unsupported format or combination of formats) in function
'buildIndex'

type=0

How can I fix it?

Body:
When I run with less images, e.g 50-100 images, it work fine, but when I run with larger amount of images (200-700) it's throwing error. This is my code

from unittest import result
import cv2
import os
from glob import glob
import pickle
import numpy as np
import matplotlib as plt
import string

def get_train_and_test_img_features():
    train_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/query/*/*.png"
    #train_path = "/Users/Antonie/Project/Skripsi/myWork/Skripsi_Code/SIFTDocumentRetrieval/dataset3/test/*.png"
    test_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/target/*/*.png"

def get_sift_features(_in_path,_debug_view = False):
    img = cv2.imread(_in_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    sift = cv2.xfeatures2d.SIFT_create()
    kp,desc = sift.detectAndCompute(gray, None)
    img = cv2.drawKeypoints(gray, kp, img)
    #cv2.imshow('sift_keypoints', img)

    if _debug_view:
        img = cv2.drawKeypoints(gray, kp, img)
        cv2.imshow('sift_keypoints', img)

        cv2.waitKey(0)

    return kp,desc

def compare_features_flann(_kp1,_dsc1,_kp2,_dsc2,_thres=0):
    FLANN_INDEX_KDTREE = 3
    index_params = dict(algorithm=FLANN_INDEX_KDTREE, trees=5)
    search_params = dict(checks=50)
    flann = cv2.FlannBasedMatcher(index_params, search_params)
    matches = flann.knnMatch(_dsc1, _dsc2, k=2)
    matches_mask = [[0, 0,] for i in range(len(matches))]

    good_points = []
    for i, (m, n) in enumerate(matches):
        if m.distance < 0.6 * n.distance:
            #matches_mask[i] = [1, 0]
            good_points.append(m)

    number_keypoints = 0
    if len(_kp1) <= len(_kp2):
        number_keypoints = len(_kp1)
    else:
        number_keypoints = len(_kp2)

    return good_points , len(good_points) / number_keypoints * 100

def compare_features_bf(_kp1,_dsc1,_kp2,_dsc2,_thres = 0):
    bf = cv2.BFMatcher()
    matches = bf.knnMatch(_dsc1, _dsc2, k=2)
    good_points = []
    for i, (m, n) in enumerate(matches):
        if m.distance < 0.75 * n.distance:
            #matches_mask[i] = [1, 0]
            good_points.append(m)

    number_keypoints = 0
    if len(_kp1) <= len(_kp2):
        number_keypoints = len(_kp1)
    else:
        number_keypoints = len(_kp2)

    # print("KP 1: " + str(len(_kp1)))
    # print("Kp 2: " + str(len(_kp2)))
    # print("Match:", len(good_points))
    # print("Matches: ", len(good_points) / number_keypoints * 100)

    return good_points , len(good_points) / number_keypoints * 100

def create_query_database(_path):
    img_db = {}

    for file in glob(_path):
        kp, desc = get_sift_features(file)
        img_db[os.path.basename(file)] = {"keypoint": kp,
                                              "descriptors": desc}

    # # Database
    # with open('queries.txt', 'wb') as file:
    #    file.write(pickle.dumps(img_db))

    return img_db

def get_best_matches(_result_dict):
    mean = np.mean([val for key,val in _result_dict.items()])

    positive = {}
    negative = {}

    for key,val in _result_dict.items() :
        res = (val - mean)
        if  res > mean:
            positive[key] = val
        else:
            negative[key] = val

    return positive

if __name__ == "__main__":
    sift = cv2.xfeatures2d.SIFT_create()

    #lokasi
    target_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/target/*.*"
    #query_path = "/Users/Antonie/Project/logo-det/Dataset/logo/img_logo/*/*.png"
    #query_path = "/Users/Antonie/Project/Skripsi/myWork/Code/Source/DB/query/*/*.png"
    query_path = "/Users/Antonie/Project/Skripsi/myWork/Code/dataset_img4/Process2/Process2/*.png"

    query_db = create_query_database(query_path)

    for files in glob(target_path, recursive=True):
        results = {}
        kb1, des1 = get_sift_features(files)
        print(os.path.basename(files), "\n")
        for keys, values in query_db.items():
            kb2 = values["keypoint"]
            des2 = values["descriptors"]
            good, percentage = compare_features_flann(kb1, des1, kb2, des2)

            results[keys] = percentage

        #final_result = get_best_matches(results)
        final_result = sorted(results.items(), key=lambda x: x[1], reverse=True)[:4]
        sortdict = dict(final_result)
        #print(sortdict)

    out_list = []
    for i in sortdict.keys():
        out_list.append(i)

    nama_file = out_list
    print("ini daftar retrieve :  ",out_list)

    #print("ini hanya 1 : ", nama_file)

    for i in range(0, len(nama_file)):
        print(nama_file[i])

    # document_path = "/Users/Antonie/Project/Skripsi/myWork/Code/dataset_img4/firstPage/"
    # for root, dir, files in os.walk(query_path):
    #     if nama_file in files:
    #         print(os.path.join(root, nama_file))

    # #img_path= os.path.join(document_path, str(a))
    # img_path = document_path + str(out_list[1])
    # #print(a)
    # #bimg = cv2.imread(img_path)
    # #b = cv2.resize(bimg, (450,600))
    # #cv2.imshow("result", b)
    # #cv2.waitKey(0)

    #words = nama_file[0].split('_')
    #print(words)

    for j in nama_file:
        wordss = j.split('_')
        #wordss.append(j)
        print(str(wordss[0]) + '.pdf')

    #tugas next : split filename : PemkabBuleleng_1 (for logo)

        #print(final_result)

        #plt.figure()
        #plt.imshow(final_result[1])
        #plt.show()

    print("-----------------")

Traceback (most recent call last):   File
"/Users/Antonie/Project/Skripsi/myWork/Code/siftFindDescriptor.py",
line 127, in
good, percentage = compare_features_flann(kb1, des1, kb2, des2)   File
"/Users/Antonie/Project/Skripsi/myWork/Code/siftFindDescriptor.py",
line 40, in compare_features_flann
matches = flann.knnMatch(_dsc1, dsc2, k=2) cv2.error: OpenCV(3.4.2)
/Users/travis/build/skvark/opencv-python/opencv/modules/flann/src/miniflann.cpp:315:
error: (-210:Unsupported format or combination of formats) in function
'buildIndex'

type=0

How can I fix it?


问:
tablerow seem not working. is there other example?
```<code><TableBody>
    {(() => {
        var result = [];
        let genericKey = Object.keys(genericResultList)[1];
        var list = genericResultList[genericKey];
        for (var i = 0; i < list.length; i++) {
            result.push(
                <TableRow>
                    {
                        Object.keys(list[i]).forEach(key => {
                            var val = list[i][key];
                            if (key != 'EDITED' && key != 'CHECKED' && key != 'DELETED') {
                                result.push(
                                    <TableCell>
                                        {val}
                                    </TableCell>
                                );
                            }
                        } )
                    }
                </TableRow>
            );

        }
        return (result);
    })()}
</TableBody>
</code>```

<TableRow> can't work. I console.log. I seem like not in place.

Am I doing wrong? Are there other way that work?

Body:
<TableBody>
    {(() => {
        var result = [];
        let genericKey = Object.keys(genericResultList)[1];
        var list = genericResultList[genericKey];
        for (var i = 0; i < list.length; i++) {
            result.push(
                <TableRow>
                    {
                        Object.keys(list[i]).forEach(key => {
                            var val = list[i][key];
                            if (key != 'EDITED' && key != 'CHECKED' && key != 'DELETED') {
                                result.push(
                                    <TableCell>
                                        {val}
                                    </TableCell>
                                );
                            }
                        } )
                    }
                </TableRow>
            );

        }
        return (result);
    })()}
</TableBody>

<TableRow> can't work. I console.log. I seem like not in place.

Am I doing wrong? Are there other way that work?


问:
Change file format to upload document
I am beginner and trying to learn on uploading file. I want to change code for image file mimetype to file like pdf, doc and pdf. But when I try to look for example for this filetype, I cannot find it. Usually it is for image type.

```<code>const fileFilter = (req, file, cb) => {
    if(file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg')
    cb(null, true)
    } else {
        cb(null, false)
    }
</code>```

I know it is silly question but to change the mimetype to  format file  like pdf, doc, pptx. It is correct to do like this?

```<code>const fileFilter = (req, file, cb) => {
    if(file.mimetype === 'application/msword' || file.mimetype === 'application/pdf' || file.mimetype === 'application/vnd.openxmlformats-officedocument.presentationml.presentation')
    cb(null, true)
    } else {
        cb(null, false)
    }
</code>```

I really appreciate if you can help me. Thank you.

Title: Change file format to upload document

Body:
I am beginner and trying to learn on uploading file. I want to change code for image file mimetype to file like pdf, doc and pdf. But when I try to look for example for this filetype, I cannot find it. Usually it is for image type.

const fileFilter = (req, file, cb) => {
    if(file.mimetype === 'image/png' || file.mimetype === 'image/jpg' || file.mimetype === 'image/jpeg')
    cb(null, true)
    } else {
        cb(null, false)
    }

I know it is silly question but to change the mimetype to  format file  like pdf, doc, pptx. It is correct to do like this?

const fileFilter = (req, file, cb) => {
    if(file.mimetype === 'application/msword' || file.mimetype === 'application/pdf' || file.mimetype === 'application/vnd.openxmlformats-officedocument.presentationml.presentation')
    cb(null, true)
    } else {
        cb(null, false)
    }

I really appreciate if you can help me. Thank you.


问:
error after deployement of the wordpress site
I want to deploy the wordpress site. The site is working properly on localhost but when I deploy it on server it shows an error

Your PHP installation appears to be missing the MySQL extension which
is required by WordPress.

It's my first time to deploy an wordpress app on server.


问:
Single select property in Notion API
How do I access single select options in using the JavaScript SDK for Notion API?

I tried the method of multi_select by WebDevSimplified, but it didn't work, don't know why.

Title: Single select property in Notion API


问:
Blur (Hide) content of app when it goes to the recents
In application I need to Blur content when it goes to the 'recents' and also to make screenshot when user work with the app (this is optional, but high needed feature).
I see a few questions (question 1, question 2 ) and answers about this - but none of them are work!

But users dont't bring me - one of them send my screenshot from his phone (Oneplus with Android 13) - when all secure apps hide its content with this screen and blur screenshot of app -

Does anyone know - what is it? Can it be some system GUI part of Oneplus? Or maybe at this moment there is some lib, that CAN hide content? Or maybe something else?

Also Same apps on another devices with same Android OS version doesn't hide content.

So, I have 2 questions -

How to not only hide (with white screen as default), but also BLUR content when the app goes to the recents?

Can solution on screenshot be specific part of phone GUI?


问:
Error with library libgtk-x11-2.0.so.0 on UNIX
When launching a JavaFX application, the following error occurs:

GraphicsPipeline.createPipeline failed for com.sun.prism.es2.ES2Pipeline
java.lang.UnsatisfiedLinkError: /opt/jdk/jdk1.8.0_181/jre/lib/amd64/libprism_es2.so: libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory

But at the same time, I have the libgtk-x11-2.0.so.0 library installed.

find / -name "libgdk-x11*" 2> /dev/null:

result

ldd /opt/jdk/jdk1.8.0_181/jre/lib/amd64/libprism_es2.so:

result

java version "1.8.0_181"

I don't know what should I do. I'm new to Linux


问:
To create automatic datewise folder and move the file in it
I am stuck in a situation where I would like to create an automatic date-wise folder on the FTP account. Also, it requires moving one to two files in an updated folder every day. i.e. If it is 28-Dec-22 then the automatic folder with the mentioned format below should be created and the file then should be moved to the updated date folder.

the format of the date will be like this

2023/01/01

This means on the FTP and on the root directory there will be a year folder then in the year folder there will be a month folder and in the month folder, there will be date-wise folders (month and date will folder will be two digits only.

At the start of next month, it requires creating an automatic month folder (within the year folder) and then the normal date folders will be created. that will be 2023/02/01 and so on.

I am using the code mentioned below to move the file from source to destination and it also creates the date-wise folder but in this code, it can only send the file to one selected destination and this cannot be moved into the updated date-wise folder.

```<code>Sub moveAllFilesInDateFolderIfNotExist()
 Dim DateFold As String, fileName As String, objFSO As Object
 Const sFolderPath As String = "E:\Uploading\Source"
 Const dFolderPath As String = "E:\Uploading\Destination"
 DateFold = dFolderPath & "\" & Format(Date, "ddmmyyyy") ' create the folder if it does not exist
 If Dir(DateFold, vbDirectory) = "" Then MkDir DateFold
 fileName = Dir(sFolderPath & "\*.*")
 Set objFSO = CreateObject("Scripting.FileSystemObject")

 Do While fileName <> ""
    If Not objFSO.FileExists(DateFold & "\" & fileName) Then
        Name sFolderPath & "\" & fileName As DateFold & "\" & fileName

    End If
    fileName = Dir
 Loop
End Sub
</code>```

Can anyone please help me in this situation?

Body:
I am stuck in a situation where I would like to create an automatic date-wise folder on the FTP account. Also, it requires moving one to two files in an updated folder every day. i.e. If it is 28-Dec-22 then the automatic folder with the mentioned format below should be created and the file then should be moved to the updated date folder.

the format of the date will be like this

2023/01/01

This means on the FTP and on the root directory there will be a year folder then in the year folder there will be a month folder and in the month folder, there will be date-wise folders (month and date will folder will be two digits only.

At the start of next month, it requires creating an automatic month folder (within the year folder) and then the normal date folders will be created. that will be 2023/02/01 and so on.

I am using the code mentioned below to move the file from source to destination and it also creates the date-wise folder but in this code, it can only send the file to one selected destination and this cannot be moved into the updated date-wise folder.

Sub moveAllFilesInDateFolderIfNotExist()
 Dim DateFold As String, fileName As String, objFSO As Object
 Const sFolderPath As String = "E:\Uploading\Source"
 Const dFolderPath As String = "E:\Uploading\Destination"
 DateFold = dFolderPath & "\" & Format(Date, "ddmmyyyy") ' create the folder if it does not exist
 If Dir(DateFold, vbDirectory) = "" Then MkDir DateFold
 fileName = Dir(sFolderPath & "\*.*")
 Set objFSO = CreateObject("Scripting.FileSystemObject")

 Do While fileName <> ""
    If Not objFSO.FileExists(DateFold & "\" & fileName) Then
        Name sFolderPath & "\" & fileName As DateFold & "\" & fileName

    End If
    fileName = Dir
 Loop
End Sub

Can anyone please help me in this situation?


问:
nginx + apache, redirect from a non-existent subdomain to a specific subdomain
Nginx + apache is running. One subdomain was liquidated and its articles moved to the same addresses, but a new subdomain.

In the .conf of the old subdomain, I have prescribed the following settings, they work fine.

```<code>server
{
    listen 80;
    root /var/www/old.site.ru;
    server_name old.site.ru www.old.site.ru;
    return 301 https://new.site.ru$request_uri;
}

server
{
    listen 443;

    ssl on;
    ssl_certificate /etc/ssl/wildcard.crt;
    ssl_certificate_key /etc/ssl/wildcard.key;

    server_name old.site.ru www.old.site.ru;

    return 301 https://new.site.ru$request_uri;
}
</code>```

Now it is planned to delete several more subdomains with the transfer of their articles to new ones, and I decided to delete unnecessary old subdomains. I want to redirect from specific (but already non-existent) subdomains to specific new ones in the general config. How can I do that?

I got into nginx.conf - something doesn't start in any way.

What do I need to do? Thanks!

Body:
Nginx + apache is running. One subdomain was liquidated and its articles moved to the same addresses, but a new subdomain.

In the .conf of the old subdomain, I have prescribed the following settings, they work fine.

server
{
    listen 80;
    root /var/www/old.site.ru;
    server_name old.site.ru www.old.site.ru;
    return 301 https://new.site.ru$request_uri;
}

server
{
    listen 443;

    ssl on;
    ssl_certificate /etc/ssl/wildcard.crt;
    ssl_certificate_key /etc/ssl/wildcard.key;

    server_name old.site.ru www.old.site.ru;

    return 301 https://new.site.ru$request_uri;
}

Now it is planned to delete several more subdomains with the transfer of their articles to new ones, and I decided to delete unnecessary old subdomains. I want to redirect from specific (but already non-existent) subdomains to specific new ones in the general config. How can I do that?

I got into nginx.conf - something doesn't start in any way.

What do I need to do? Thanks!


问:
Sep ; inside the value in pyspark dataframe
I am trying to save my dataframe in CSV format with sep=';', but some values of dataframe include this symbol ; and pyspark considers it as a sep too.

For example, if the value is "something;then something", it will be splitted and the resulting CSV file will corrupt.

Maybe I miss parameters which can handle this situation, I am using this syntax to save CSV file.

```<code>df.write.csv('test_csv',
              header=True,
              mode='overwrite',
              quote='\"',
              quoteAll=True,
              encoding='utf-8',
              sep=';')
</code>```

Body:
I am trying to save my dataframe in CSV format with sep=';', but some values of dataframe include this symbol ; and pyspark considers it as a sep too.

For example, if the value is "something;then something", it will be splitted and the resulting CSV file will corrupt.

Maybe I miss parameters which can handle this situation, I am using this syntax to save CSV file.

df.write.csv('test_csv',
              header=True,
              mode='overwrite',
              quote='\"',
              quoteAll=True,
              encoding='utf-8',
              sep=';')


问:
Not able to pipe through a inputpassword in python
I am trying to pass this pipe stnd input from a script password.py. this script excepts a password from user. but it is not allowing me to see by piping the input through a screen from subprocess.

I want to use subprocess to automate the process because I don't want to enter the password/key every time.

password.py

```<code>import getpass

password = getpass.getpass("Enter your password: ")
if password != "test":
    print("wrong password")
else:
    print("correct password")

</code>```

main.py

```<code>import subprocess as sp

# Start the "password.py" script as a subprocess
proc = sp.Popen(["python", "password.py"], stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)

# Read the process's standard output and error streams
stdout, stderr = proc.communicate()

# Print the output
print(stdout)
print(stderr)

# Wait for the process to complete and get its return code
returncode = proc.wait()

# Check the return code
if returncode == 0:
    print("Command successful")
else:
    print("Command failed")
</code>```

Error:

```<code>b'/usr/lib/python3.8/getpass.py:91: GetPassWarning: Can not control echo on the terminal.\n

passwd = fallback_getpass(prompt, stream)\nWarning: Password input may be echoed.\nEnter your password: Traceback (most recent call last):\n

File "/usr/lib/python3.8/getpass.py", line 69, in unix_getpass\n
  old = termios.tcgetattr(fd)     # a copy to save\ntermios.error: (25, \'Inappropriate ioctl for device\')\n\n

During handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n

File "password.py", line 3, in <module>\n    password = getpass.getpass("Enter your password: ")\n

File "/usr/lib/python3.8/getpass.py", line 91, in unix_getpass\n    passwd = fallback_getpass(prompt, stream)\n

File "/usr/lib/python3.8/getpass.py", line 126, in fallback_getpass\n    return _raw_input(prompt, stream)\n

File "/usr/lib/python3.8/getpass.py", line 148, in _raw_input\n    raise EOFError\nEOFError\n'
Command failed
</code>```

Body:
I am trying to pass this pipe stnd input from a script password.py. this script excepts a password from user. but it is not allowing me to see by piping the input through a screen from subprocess.

I want to use subprocess to automate the process because I don't want to enter the password/key every time.

password.py

import getpass

password = getpass.getpass("Enter your password: ")
if password != "test":
    print("wrong password")
else:
    print("correct password")

main.py

import subprocess as sp

# Start the "password.py" script as a subprocess
proc = sp.Popen(["python", "password.py"], stdin=sp.PIPE, stdout=sp.PIPE, stderr=sp.PIPE)

# Read the process's standard output and error streams
stdout, stderr = proc.communicate()

# Print the output
print(stdout)
print(stderr)

# Wait for the process to complete and get its return code
returncode = proc.wait()

# Check the return code
if returncode == 0:
    print("Command successful")
else:
    print("Command failed")

Error:

b'/usr/lib/python3.8/getpass.py:91: GetPassWarning: Can not control echo on the terminal.\n

passwd = fallback_getpass(prompt, stream)\nWarning: Password input may be echoed.\nEnter your password: Traceback (most recent call last):\n

File "/usr/lib/python3.8/getpass.py", line 69, in unix_getpass\n
  old = termios.tcgetattr(fd)     # a copy to save\ntermios.error: (25, \'Inappropriate ioctl for device\')\n\n

During handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n

File "password.py", line 3, in <module>\n    password = getpass.getpass("Enter your password: ")\n

File "/usr/lib/python3.8/getpass.py", line 91, in unix_getpass\n    passwd = fallback_getpass(prompt, stream)\n

File "/usr/lib/python3.8/getpass.py", line 126, in fallback_getpass\n    return _raw_input(prompt, stream)\n

File "/usr/lib/python3.8/getpass.py", line 148, in _raw_input\n    raise EOFError\nEOFError\n'
Command failed


问:
Would iframe in React cause memory leak?
Well, this might be a strange question, but there are some differences about the behavior of iframes between a native h5 page and a React page.

Native h5 Page

Here is a native h5 page with an iFrame. The iframe will create a WebSocket connection.
We can see the value of Time is Pending while the connection is still active.

![Image here](https://i.stack.imgur.com/UDWz3.png)

Then after I removed this iframe as a child from document, the value of Time became the time the connection lasted.

![Image here](https://i.stack.imgur.com/7milk.png)

However, in a React Page, something strange happens.

React Page

Every added iframe would create a WebSocket connection in Pending status.

![Image here](https://i.stack.imgur.com/fgY3K.png)

But when I remove them, the value of Time wouldn't change into the time they lasted, but still in Pending status.

![Image here](https://i.stack.imgur.com/lCLkY.png)

Here is my code:

```<code>function App() {
  const [frames, setFrames] = useState([]);

  const onAdd = useCallback(() => {
    const iFrame = (
      <iframe src='http://127.0.0.1:8080/iframe.html' />
    );

    setFrames((frames) => [
      ...frames,
      iFrame,
    ]);
  }, []);

  const onDel = useCallback(() => {
    setFrames((frames) => [
      ...frames.slice(0, frames.length - 1),
    ]);
  }, []);

  return (
    <div className="App">
      <div>
        <button onClick={onAdd}>+1</button>
        <button onClick={onDel}>-1</button>
      </div>
      <div>
        {
          frames.map((frame, index) => {
            return (
              <React.Fragment key={index}>
                {frame}
              </React.Fragment>
            )
          })
        }
      </div>
    </div>
  );
}
</code>```

I tried to make some logs in my WebSocket Server, and it seemed that the connections have been disconnected already.

I'm a freshman in frontend development, so this is a strange behavior as for me. I wonder if this caused by memory leak or something else.

Sincerely waiting for your answer.

Body:
Well, this might be a strange question, but there are some differences about the behavior of iframes between a native h5 page and a React page.

Native h5 Page

Here is a native h5 page with an iFrame. The iframe will create a WebSocket connection.
We can see the value of Time is Pending while the connection is still active.

![Image here](https://i.stack.imgur.com/UDWz3.png)

Then after I removed this iframe as a child from document, the value of Time became the time the connection lasted.

![Image here](https://i.stack.imgur.com/7milk.png)

However, in a React Page, something strange happens.

React Page

Every added iframe would create a WebSocket connection in Pending status.

![Image here](https://i.stack.imgur.com/fgY3K.png)

But when I remove them, the value of Time wouldn't change into the time they lasted, but still in Pending status.

![Image here](https://i.stack.imgur.com/lCLkY.png)

Here is my code:

function App() {
  const [frames, setFrames] = useState([]);

  const onAdd = useCallback(() => {
    const iFrame = (

    );

    setFrames((frames) => [
      ...frames,
      iFrame,
    ]);
  }, []);

  const onDel = useCallback(() => {
    setFrames((frames) => [
      ...frames.slice(0, frames.length - 1),
    ]);
  }, []);

  return (

        <button onClick={onAdd}>+1</button>
        <button onClick={onDel}>-1</button>

        {
          frames.map((frame, index) => {
            return (
              <React.Fragment key={index}>
                {frame}
              </React.Fragment>
            )
          })
        }

  );
}

I tried to make some logs in my WebSocket Server, and it seemed that the connections have been disconnected already.

I'm a freshman in frontend development, so this is a strange behavior as for me. I wonder if this caused by memory leak or something else.

Sincerely waiting for your answer.


问:
SSIS package deployment failure after SQL server default TCP port change + original package execution pending
I have a case that SQL server is running remotely and recently the SQL server TCP port is changed from 1433 to 61433. After service reboot, I can connect to the server by (server name, port number) but cannot deploy packages from VS2019 to the server remotely.

I tried to query with operation_id provided but I couldn't find the id specified. Also, when I try to run old SSIS package deployed on SQL server, it will show 'pending execution' and the execution never stops.
Have I missed any steps of SSIS package or SSISDB setting after port change? Thanks for help.

Symptom:

Deploy result failure message
(https://i.stack.imgur.com/ESDVh.png)

Details
(https://i.stack.imgur.com/HR2WP.png)

Ongoing Pending packages
(https://i.stack.imgur.com/6WGsB.png)

Port number changed to 61433
(https://i.stack.imgur.com/J37xo.png)


问:
MOJavaScriptException: TypeError: undefined is not an object (evaluating 'exports.Headers = global.Headers')
I've encounted an error of MOJavaScriptException: TypeError: undefined is not an object (evaluating 'exports.Headers = global.Headers') while trying to import discord-rpc to my Sketch Plugin project, couldn't Googled anything related online.

Full code

```<code>import sketch from 'sketch'
const { Client } = require("discord-rpc");

export default function() {
}
</code>```

Full Error Message

```<code>MOJavaScriptException: TypeError: undefined is not an object (evaluating 'exports.Headers = global.Headers')
./node_modules/node-fetch/browser.js browser.js:23:0
__webpack_require__ bootstrap:19:0
client.js:5:22
./node_modules/discord-rpc/src/client.js __my-command.js:1047:34
__webpack_require__ bootstrap:19:0
./node_modules/discord-rpc/src/index.js index.js:6:18
__webpack_require__ bootstrap:19:0
./src/my-command.js my-command.js:2:27
__webpack_require__ bootstrap:19:0
bootstrap:83:0
</code>```

I've tried to move the const { Client } = require("discord-rpc");  inside of export default function() {}, but no luck. changed my code to const discord = require("discord-rpc") is also tried.

Body:
I've encounted an error of MOJavaScriptException: TypeError: undefined is not an object (evaluating 'exports.Headers = global.Headers') while trying to import discord-rpc to my Sketch Plugin project, couldn't Googled anything related online.

Full code

import sketch from 'sketch'
const { Client } = require("discord-rpc");

export default function() {
}

Full Error Message

MOJavaScriptException: TypeError: undefined is not an object (evaluating 'exports.Headers = global.Headers')
./node_modules/node-fetch/browser.js browser.js:23:0
__webpack_require__ bootstrap:19:0
client.js:5:22
./node_modules/discord-rpc/src/client.js __my-command.js:1047:34
__webpack_require__ bootstrap:19:0
./node_modules/discord-rpc/src/index.js index.js:6:18
__webpack_require__ bootstrap:19:0
./src/my-command.js my-command.js:2:27
__webpack_require__ bootstrap:19:0
bootstrap:83:0

I've tried to move the const { Client } = require("discord-rpc");  inside of export default function() {}, but no luck. changed my code to const discord = require("discord-rpc") is also tried.


问:
Objective-C conversion of hex characters and Java convert hex characters are not the same?
Objective-C, convert NSData hexadecimal characters and Java byte array into a hexadecimal character is not the same, what this approach into the same?

Java code:

```<code>public static String convertByteToHexString(byte[] bytes){
          StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(String.format("%02X", b));
        }
       return builder.toString().toUpperCase();
 }

public static byte[] convertHexString(String ss) {
            int length = ss.length() / 2;
    byte digest[] = new byte[length];
    for (int i = 0; i < length; i++) {
        String byteString = ss.substring(2 * i, 2 * i + 2);
        int byteValue = Integer.parseInt(byteString, 16);
        digest[i] = (byte) byteValue;
    }
    return digest;
}
</code>```

Objective-C code:

```<code>+(NSString*)hexStringForData:(NSData*)data{
if (data == nil) {
    return nil;
}

NSMutableString* hexString = [NSMutableString string];

const unsigned char *p = [data bytes];

for (int i=0; i < [data length]; i++) {
    [hexString appendFormat:@"%02x", *p++];
}
return hexString;
</code>```

}

```<code>+ (NSData*)dataForHexString:(NSString*)hexString{
if (hexString == nil) {
    return nil;
}

const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
NSMutableData* data = [NSMutableData data];
while (*ch) {
    char byte = 0;
    if ('0' <= *ch && *ch <= '9') {
        byte = *ch - '0';
    } else if ('a' <= *ch && *ch <= 'f') {
        byte = *ch - 'a' + 10;
    }
    ch++;
    byte = byte << 4;
    if (*ch) {
        if ('0' <= *ch && *ch <= '9') {
            byte += *ch - '0';
        } else if ('a' <= *ch && *ch <= 'f') {
            byte += *ch - 'a' + 10;
        }
        ch++;
    }
    [data appendBytes:&byte length:1];
}
return data;
</code>```

}

c# code:

```<code>public static string convertByteArrayToHex(byte[] byte){

        StringBuilder builder = new StringBuilder();
        foreach (byte num in byte)
        {
            builder.AppendFormat("{0:X2}", num);
        }
        stream.Close();
        return builder.ToString();
</code>```

}

```<code>public static byte[] convertHexToByteArray(string str){
  int length = str.Length/2;
  byte[] buffer = new byte[length];
        for (int i = 0; i < length; i++)
        {
            int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
            buffer[i] = (byte)num2;
        }
 return buffer;
</code>```

}

=========================
Java c # the same, only the Objective-C。。。

ContentLicense: CC BY-SA 3.0

Body:
Objective-C, convert NSData hexadecimal characters and Java byte array into a hexadecimal character is not the same, what this approach into the same?

Java code:

public static String convertByteToHexString(byte[] bytes){
          StringBuilder builder = new StringBuilder();
        for (byte b : bytes) {
            builder.append(String.format("%02X", b));
        }
       return builder.toString().toUpperCase();
 }

public static byte[] convertHexString(String ss) {
            int length = ss.length() / 2;
    byte digest[] = new byte[length];
    for (int i = 0; i < length; i++) {
        String byteString = ss.substring(2 * i, 2 * i + 2);
        int byteValue = Integer.parseInt(byteString, 16);
        digest[i] = (byte) byteValue;
    }
    return digest;
}

Objective-C code:

+(NSString*)hexStringForData:(NSData*)data{
if (data == nil) {
    return nil;
}

NSMutableString* hexString = [NSMutableString string];

const unsigned char *p = [data bytes];

for (int i=0; i < [data length]; i++) {
    [hexString appendFormat:@"%02x", *p++];
}
return hexString;

}

+ (NSData*)dataForHexString:(NSString*)hexString{
if (hexString == nil) {
    return nil;
}

const char* ch = [[hexString lowercaseString] cStringUsingEncoding:NSUTF8StringEncoding];
NSMutableData* data = [NSMutableData data];
while (*ch) {
    char byte = 0;
    if ('0' <= *ch && *ch <= '9') {
        byte = *ch - '0';
    } else if ('a' <= *ch && *ch <= 'f') {
        byte = *ch - 'a' + 10;
    }
    ch++;
    byte = byte << 4;
    if (*ch) {
        if ('0' <= *ch && *ch <= '9') {
            byte += *ch - '0';
        } else if ('a' <= *ch && *ch <= 'f') {
            byte += *ch - 'a' + 10;
        }
        ch++;
    }
    [data appendBytes:&byte length:1];
}
return data;

}

c# code:

public static string convertByteArrayToHex(byte[] byte){

        StringBuilder builder = new StringBuilder();
        foreach (byte num in byte)
        {
            builder.AppendFormat("{0:X2}", num);
        }
        stream.Close();
        return builder.ToString();

}

public static byte[] convertHexToByteArray(string str){
  int length = str.Length/2;
  byte[] buffer = new byte[length];
        for (int i = 0; i < length; i++)
        {
            int num2 = Convert.ToInt32(str.Substring(i * 2, 2), 0x10);
            buffer[i] = (byte)num2;
        }
 return buffer;

}

=========================
Java c # the same, only the Objective-C。。。


问:
should I create multiple websocket instance or using noserver mode when I want to separate websocket cononections?
as a node express backend. I need a websocket of real-time chat, and a websocket of go game for multiple players. I use https://github.com/websockets/ws  library.
there are two solutions:

1.create multiple websocket server instances by passing different port.for example:

```<code>let chatServer = new WebsocketServer({port:8081})
let goServer = new WebsocketServer({port:8082})
</code>```

from front end, different page useEffect connect to different websocket server.

2.Multiple servers sharing a single HTTP/S server as ws documentation suggested.

```<code>const server = createServer();
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });

wss1.on('connection', function connection(ws) {
  // ...
});

wss2.on('connection', function connection(ws) {
  // ...
});
</code>```

from front end, connect to different server by pathname.

My question is, which one I should choose, and what is the difference? I really really want to know, what does "noServer" mode mean. thanks.

Body:
as a node express backend. I need a websocket of real-time chat, and a websocket of go game for multiple players. I use https://github.com/websockets/ws  library.
there are two solutions:

1.create multiple websocket server instances by passing different port.for example:

let chatServer = new WebsocketServer({port:8081})
let goServer = new WebsocketServer({port:8082})

from front end, different page useEffect connect to different websocket server.

2.Multiple servers sharing a single HTTP/S server as ws documentation suggested.

const server = createServer();
const wss1 = new WebSocketServer({ noServer: true });
const wss2 = new WebSocketServer({ noServer: true });

wss1.on('connection', function connection(ws) {
  // ...
});

wss2.on('connection', function connection(ws) {
  // ...
});

from front end, connect to different server by pathname.

My question is, which one I should choose, and what is the difference? I really really want to know, what does "noServer" mode mean. thanks.


问:
Add image in Readme.md for VS-code extension
I am Creating snippet extention of react-native for VS-code. In that I want to add some images into README.md file, which finally show images on marketplace inside description tab of my extention.

I have tried below things in README.md but it gives me error:

```<code>![feature X](/images/SnippetDemo1.png)
</code>```

ERROR  Couldn't detect the repository where this extension is published. The image '/images/SnippetDemo1.png' will be broken in README.md. GitHub/GitLab repositories will be automatically detected. Otherwise, please provide the repository URL in package.json or use the --baseContentUrl and --baseImagesUrl options.

Body:
I am Creating snippet extention of react-native for VS-code. In that I want to add some images into README.md file, which finally show images on marketplace inside description tab of my extention.

I have tried below things in README.md but it gives me error:

![feature X](/images/SnippetDemo1.png)

ERROR  Couldn't detect the repository where this extension is published. The image '/images/SnippetDemo1.png' will be broken in README.md. GitHub/GitLab repositories will be automatically detected. Otherwise, please provide the repository URL in package.json or use the --baseContentUrl and --baseImagesUrl options.


问:
Reducing Item by -10 in Class Based View
I have a button when clicked should reduce an Item by 10, it is possible to achieve using a function not as_view, please help on reproducing the same effect on a ListView

Views.py:

```<code>  def subs(request, pk):
    sw = get_object_or_404(Swimmers,id=pk)
    c_s = sw.sessions - 10
    sw.sessions = c_s
    sw.save()
    return render(request, 'accounts/modals/swimming/_vw_table.html', {'sw': sw})
</code>```

URL:

```<code>path('subt/<int:pk>/', views.subs, name='subt'),
</code>```

Template:

```<code>  <form id="post-form">
   <div class="col float-right">
   <button type="submit"  class="float-right btn btn-primary" id="saveBtn" name="button">REDUCE SESSION</a>
   </div>
  </form>
</code>```

Body:
I have a button when clicked should reduce an Item by 10, it is possible to achieve using a function not as_view, please help on reproducing the same effect on a ListView

Views.py:

  def subs(request, pk):
    sw = get_object_or_404(Swimmers,id=pk)
    c_s = sw.sessions - 10
    sw.sessions = c_s
    sw.save()
    return render(request, 'accounts/modals/swimming/_vw_table.html', {'sw': sw})

URL:

path('subt/<int:pk>/', views.subs, name='subt'),

Template:

  <form id="post-form">

   <button type="submit"  class="float-right btn btn-primary" id="saveBtn" name="button">REDUCE SESSION

  </form>