问:
Share a TXT file between two android application Android 11 and Android 12
I developed two application, one is a LAUNCHER the other one is the MAIN-APP.
I my MAIN-APP the user can choose the language.
I would like to change automatically the language also in my LAUNCHER.
I would like to create a txt file in Documents folder from my MAIN-APP, so the LAUNCHER can read this file and set the same language.
But now in Android 11 seems impossible to create a file TXT in the Documents folder and read this file from another application.

I tried with MediaStore:

MAIN APP :

```<code>private static void saveLanguageOnFile(String lang, String country){

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            File folderDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
            boolean success;

            if (!folderDocuments.exists()) {
                try {
                    folderDocuments.mkdir();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            success = folderDocuments.exists();

            if (success) {
                try {
                    FileOutputStream fos = new FileOutputStream(new File(folderDocuments, "language.txt"));
                    fos.write((lang + "-" + country).getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

            Uri contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
            ContentResolver contentResolver = ActivitiesManager.getInstance().getTopActivity().getApplication().getApplicationContext().getContentResolver();

            String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
            String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS+"/"};
            Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);

            long idFile = -1;
            if (cursor != null && cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    int columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
                    int columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
                    if (columnIndexDisplayName > 0 && columnIndexId > 0) {
                        String fileName = cursor.getString(columnIndexDisplayName);
                        if (fileName.equals("language.txt")) {
                            idFile = cursor.getLong(columnIndexId);
                            break;
                        }
                    }
                }
                cursor.close();
            }

            Uri uriFile;
            if (idFile > -1) {
                uriFile = ContentUris.withAppendedId(contentUri, idFile);
            } else {
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DISPLAY_NAME, "language.txt");   // file name
                values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
                uriFile = contentResolver.insert(contentUri, values);
            }
            try {
                if (uriFile != null) {
                    OutputStream outputStream = contentResolver.openOutputStream(uriFile, "rwt");
                    if (outputStream != null) {
                        outputStream.write((lang + "-" + country).getBytes());
                        outputStream.close();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
}
</code>```

ANDROID LAUNCHER APP :

```<code>private fun setLanguage() {
    var lang = Locale.getDefault().language
    var country = Locale.getDefault().country
    val previousLang = lang
    val previousCountry = country

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        val language = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"language.txt")
        if (language.exists()) {
            try {
                val br = BufferedReader(FileReader(language))
                var st: StringTokenizer
                var line: String?

                while (br.readLine().also { line = it } != null) {
                    st = StringTokenizer(line, "-")
                    lang = st.nextToken()
                    country = st.nextToken()
                }

                br.close()
            } catch (e: IOException) {
                Log.e("LauncherDMD", ".loadFile: err: " + e.message)
            }
        }
    } else {
        val contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        val contentResolver: ContentResolver = application.applicationContext.contentResolver

        val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
        val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS+"/")
        val orderBy = MediaStore.MediaColumns.DATE_ADDED + " DESC"
        val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, orderBy)

        var idFile: Long = -1

        if (cursor != null && cursor.count > 0) {
            while (cursor.moveToNext()) {
                val columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                val columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
                if (columnIndexDisplayName > 0 && columnIndexId > 0) {
                    val fileName = cursor.getString(columnIndexDisplayName)
                    if (fileName.contains("language")) {
                        idFile = cursor.getLong(columnIndexId)
                        break
                    }
                }
            }

            cursor.close()
        }

        val uriFile: Uri
        if (idFile > -1) {
            uriFile = ContentUris.withAppendedId(contentUri, idFile)
            try {
                val br = BufferedReader(InputStreamReader(getContentResolver().openInputStream(uriFile), "UTF-8"))
                var st: StringTokenizer
                var line: String?

                while (br.readLine().also { line = it } != null) {
                    st = StringTokenizer(line, "-")
                    lang = st.nextToken()
                    country = st.nextToken()
                }

                br.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    val locale = Locale(lang,country)
    Lingver.getInstance().setLocale(this.applicationContext, locale)

    if(!previousCountry.equals(country) && !previousLang.equals(lang)){
        recreate()
    }

    Log.i("LauncherDMD", "Utility: Nuova lingua impostata: $lang")
    Log.i("LauncherDMD", "Utility: Nuova nazione impostata: $country")
}
</code>```

This solution works BUT the problem is that every time the MAIN-APP is uninstalled and installed again (sometimes it happens), it cannot access to the language file previously created by itself and instead it create a duplicate.
I obviously I cannot delete the old language file before creating new ones.
I also know that I cannot use the special permission "MANAGE_EXTERNAL_STORAGE" because I have to publish the app on the play store.

Thanks in advance!

Body:
I developed two application, one is a LAUNCHER the other one is the MAIN-APP.
I my MAIN-APP the user can choose the language.
I would like to change automatically the language also in my LAUNCHER.
I would like to create a txt file in Documents folder from my MAIN-APP, so the LAUNCHER can read this file and set the same language.
But now in Android 11 seems impossible to create a file TXT in the Documents folder and read this file from another application.

I tried with MediaStore:

MAIN APP :

private static void saveLanguageOnFile(String lang, String country){

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            File folderDocuments = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
            boolean success;

            if (!folderDocuments.exists()) {
                try {
                    folderDocuments.mkdir();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }

            success = folderDocuments.exists();

            if (success) {
                try {
                    FileOutputStream fos = new FileOutputStream(new File(folderDocuments, "language.txt"));
                    fos.write((lang + "-" + country).getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {

            Uri contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
            ContentResolver contentResolver = ActivitiesManager.getInstance().getTopActivity().getApplication().getApplicationContext().getContentResolver();

            String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
            String[] selectionArgs = new String[]{Environment.DIRECTORY_DOCUMENTS+"/"};
            Cursor cursor = contentResolver.query(contentUri, null, selection, selectionArgs, null);

            long idFile = -1;
            if (cursor != null && cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    int columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
                    int columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID);
                    if (columnIndexDisplayName > 0 && columnIndexId > 0) {
                        String fileName = cursor.getString(columnIndexDisplayName);
                        if (fileName.equals("language.txt")) {
                            idFile = cursor.getLong(columnIndexId);
                            break;
                        }
                    }
                }
                cursor.close();
            }

            Uri uriFile;
            if (idFile > -1) {
                uriFile = ContentUris.withAppendedId(contentUri, idFile);
            } else {
                ContentValues values = new ContentValues();
                values.put(MediaStore.MediaColumns.DISPLAY_NAME, "language.txt");   // file name
                values.put(MediaStore.MediaColumns.MIME_TYPE, "text/plain");
                values.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOCUMENTS);
                uriFile = contentResolver.insert(contentUri, values);
            }
            try {
                if (uriFile != null) {
                    OutputStream outputStream = contentResolver.openOutputStream(uriFile, "rwt");
                    if (outputStream != null) {
                        outputStream.write((lang + "-" + country).getBytes());
                        outputStream.close();
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            }

        }
}

ANDROID LAUNCHER APP :

private fun setLanguage() {
    var lang = Locale.getDefault().language
    var country = Locale.getDefault().country
    val previousLang = lang
    val previousCountry = country

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
        val language = File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS),"language.txt")
        if (language.exists()) {
            try {
                val br = BufferedReader(FileReader(language))
                var st: StringTokenizer
                var line: String?

                while (br.readLine().also { line = it } != null) {
                    st = StringTokenizer(line, "-")
                    lang = st.nextToken()
                    country = st.nextToken()
                }

                br.close()
            } catch (e: IOException) {
                Log.e("LauncherDMD", ".loadFile: err: " + e.message)
            }
        }
    } else {
        val contentUri = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
        val contentResolver: ContentResolver = application.applicationContext.contentResolver

        val selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?"
        val selectionArgs = arrayOf(Environment.DIRECTORY_DOCUMENTS+"/")
        val orderBy = MediaStore.MediaColumns.DATE_ADDED + " DESC"
        val cursor = contentResolver.query(contentUri, null, selection, selectionArgs, orderBy)

        var idFile: Long = -1

        if (cursor != null && cursor.count > 0) {
            while (cursor.moveToNext()) {
                val columnIndexDisplayName = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)
                val columnIndexId = cursor.getColumnIndex(MediaStore.MediaColumns._ID)
                if (columnIndexDisplayName > 0 && columnIndexId > 0) {
                    val fileName = cursor.getString(columnIndexDisplayName)
                    if (fileName.contains("language")) {
                        idFile = cursor.getLong(columnIndexId)
                        break
                    }
                }
            }

            cursor.close()
        }

        val uriFile: Uri
        if (idFile > -1) {
            uriFile = ContentUris.withAppendedId(contentUri, idFile)
            try {
                val br = BufferedReader(InputStreamReader(getContentResolver().openInputStream(uriFile), "UTF-8"))
                var st: StringTokenizer
                var line: String?

                while (br.readLine().also { line = it } != null) {
                    st = StringTokenizer(line, "-")
                    lang = st.nextToken()
                    country = st.nextToken()
                }

                br.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

    val locale = Locale(lang,country)
    Lingver.getInstance().setLocale(this.applicationContext, locale)

    if(!previousCountry.equals(country) && !previousLang.equals(lang)){
        recreate()
    }

    Log.i("LauncherDMD", "Utility: Nuova lingua impostata: $lang")
    Log.i("LauncherDMD", "Utility: Nuova nazione impostata: $country")
}

This solution works BUT the problem is that every time the MAIN-APP is uninstalled and installed again (sometimes it happens), it cannot access to the language file previously created by itself and instead it create a duplicate.
I obviously I cannot delete the old language file before creating new ones.
I also know that I cannot use the special permission "MANAGE_EXTERNAL_STORAGE" because I have to publish the app on the play store.

Thanks in advance!


来源: stackexchange

问:
Asynchronous requests using proxy with Guzzle 7
Im trying create a PHP script that uses proxy and asynchronous requests with Guzzle but Im not reaching the success.

On the Guzzle 7 docs, we can see this example below:

```<code>use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

$client = new Client();

$requests = function ($total) {
    $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
    for ($i = 0; $i < $total; $i++) {
        yield new Request('GET', $uri);
    }
};

$pool = new Pool($client, $requests(100), [
    'concurrency' => 5,
    'fulfilled' => function (Response $response, $index) {
        // this is delivered each successful response
    },
    'rejected' => function (RequestException $reason, $index) {
        // this is delivered each failed request
    },
]);

// Initiate the transfers and create a promise
$promise = $pool->promise();

// Force the pool of requests to complete.
$promise->wait();
</code>```

And with my low knowledge on Guzzle, I think that we can apply proxies only on Client not on Request class, so what I've to do to make it happens?

I've been created this example how it will works using simple cURL;

```<code>$mh = curl_multi_init();

$ch = [];

$headers = array(
    'Host: example.com',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language: en-US,en;q=0.5',
    'DNT: 1',
    'Connection: keep-alive'
);

$timeout = 7;

$chunked = array_chunk($proxies, 1000);

foreach($chunked as $proxies) {
    foreach($proxies as $i => $proxy) {
        $ch[$i] = curl_init();

        curl_setopt($ch[$i], CURLOPT_AUTOREFERER, true);
        curl_setopt($ch[$i], CURLOPT_COOKIESESSION, true);
        curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch[$i], CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch[$i], CURLOPT_HTTPPROXYTUNNEL, true);
        curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYSTATUS, false);
        curl_setopt($ch[$i], CURLOPT_PROXY_SSL_VERIFYPEER, false);
        curl_setopt($ch[$i], CURLOPT_CONNECTTIMEOUT_MS, $timeout * 1000);
        curl_setopt($ch[$i], CURLOPT_MAXREDIRS, -1);
        curl_setopt($ch[$i], CURLOPT_SOCKS5_AUTH, CURLAUTH_NONE);
        curl_setopt($ch[$i], CURLOPT_SSL_OPTIONS,  CURLSSLOPT_NO_REVOKE);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch[$i], CURLOPT_PROXY_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
        curl_setopt($ch[$i], CURLOPT_PROXY_SSL_VERIFYHOST, 0);
        curl_setopt($ch[$i], CURLOPT_TIMEOUT_MS, $timeout * 1000);
        curl_setopt($ch[$i], CURLOPT_ENCODING, 'gzip, deflate, br');
        curl_setopt($ch[$i], CURLOPT_PROXY, $proxy);
        curl_setopt($ch[$i], CURLOPT_URL, 'https://example.com');
        curl_setopt($ch[$i], CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0');
        curl_setopt($ch[$i], CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);

        curl_multi_add_handle($mh, $ch[$i]);
    }

    do {
        curl_multi_exec($mh, $running);

        curl_multi_select($mh);
    } while ($running > 0);

    foreach($ch as $key => $handle) {
        $content = curl_multi_getcontent($handle);

        if (strstr($content, 'Example')) {
            file_put_contents('proxies.txt', $proxies[$key].PHP_EOL , FILE_APPEND | LOCK_EX);
        }

        curl_multi_remove_handle($mh, $ch[$key]);
    }

    curl_multi_close($mh);
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Im trying create a PHP script that uses proxy and asynchronous requests with Guzzle but Im not reaching the success.

On the Guzzle 7 docs, we can see this example below:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Pool;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;

$client = new Client();

$requests = function ($total) {
    $uri = 'http://127.0.0.1:8126/guzzle-server/perf';
    for ($i = 0; $i < $total; $i++) {
        yield new Request('GET', $uri);
    }
};

$pool = new Pool($client, $requests(100), [
    'concurrency' => 5,
    'fulfilled' => function (Response $response, $index) {
        // this is delivered each successful response
    },
    'rejected' => function (RequestException $reason, $index) {
        // this is delivered each failed request
    },
]);

// Initiate the transfers and create a promise
$promise = $pool->promise();

// Force the pool of requests to complete.
$promise->wait();

And with my low knowledge on Guzzle, I think that we can apply proxies only on Client not on Request class, so what I've to do to make it happens?

I've been created this example how it will works using simple cURL;

$mh = curl_multi_init();

$ch = [];

$headers = array(
    'Host: example.com',
    'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8',
    'Accept-Language: en-US,en;q=0.5',
    'DNT: 1',
    'Connection: keep-alive'
);

$timeout = 7;

$chunked = array_chunk($proxies, 1000);

foreach($chunked as $proxies) {
    foreach($proxies as $i => $proxy) {
        $ch[$i] = curl_init();

        curl_setopt($ch[$i], CURLOPT_AUTOREFERER, true);
        curl_setopt($ch[$i], CURLOPT_COOKIESESSION, true);
        curl_setopt($ch[$i], CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch[$i], CURLOPT_FRESH_CONNECT, true);
        curl_setopt($ch[$i], CURLOPT_HTTPPROXYTUNNEL, true);
        curl_setopt($ch[$i], CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYSTATUS, false);
        curl_setopt($ch[$i], CURLOPT_PROXY_SSL_VERIFYPEER, false);
        curl_setopt($ch[$i], CURLOPT_CONNECTTIMEOUT_MS, $timeout * 1000);
        curl_setopt($ch[$i], CURLOPT_MAXREDIRS, -1);
        curl_setopt($ch[$i], CURLOPT_SOCKS5_AUTH, CURLAUTH_NONE);
        curl_setopt($ch[$i], CURLOPT_SSL_OPTIONS,  CURLSSLOPT_NO_REVOKE);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch[$i], CURLOPT_PROXY_SSL_OPTIONS, CURLSSLOPT_NO_REVOKE);
        curl_setopt($ch[$i], CURLOPT_PROXY_SSL_VERIFYHOST, 0);
        curl_setopt($ch[$i], CURLOPT_TIMEOUT_MS, $timeout * 1000);
        curl_setopt($ch[$i], CURLOPT_ENCODING, 'gzip, deflate, br');
        curl_setopt($ch[$i], CURLOPT_PROXY, $proxy);
        curl_setopt($ch[$i], CURLOPT_URL, 'https://example.com');
        curl_setopt($ch[$i], CURLOPT_USERAGENT, 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:108.0) Gecko/20100101 Firefox/108.0');
        curl_setopt($ch[$i], CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch[$i], CURLOPT_SSL_VERIFYHOST, 0);

        curl_multi_add_handle($mh, $ch[$i]);
    }

    do {
        curl_multi_exec($mh, $running);

        curl_multi_select($mh);
    } while ($running > 0);

    foreach($ch as $key => $handle) {
        $content = curl_multi_getcontent($handle);

        if (strstr($content, 'Example')) {
            file_put_contents('proxies.txt', $proxies[$key].PHP_EOL , FILE_APPEND | LOCK_EX);
        }

        curl_multi_remove_handle($mh, $ch[$key]);
    }

    curl_multi_close($mh);
}


问:
connecting to mikrotik using routeros api
I am automating WiFi payments, so my code is able to ask for payments and a callback is sent. I get the information and save it, generate a user, send an sms to the client and create the generated user in mikrotik all at the same time.
Below is my code:

'''

```<code>def confirmation(request):
    print("Start Mpesa")
    global profile

    mpesa_body = request.body.decode('utf-8')
    mpesa_body = json.loads(mpesa_body)
    print(mpesa_body)
    print("Mpesa Body")

    merchant_requestID = mpesa_body["Body"]["stkCallback"]["MerchantRequestID"]
    print('merchant_requestID: ', merchant_requestID)
    checkout_requestID = mpesa_body["Body"]["stkCallback"]["CheckoutRequestID"]
    print('checkout_requestID: ', checkout_requestID)
    result_code = mpesa_body["Body"]["stkCallback"]["ResultCode"]
    print('result_code: ', result_code)
    result_desc = mpesa_body["Body"]["stkCallback"]["ResultDesc"]
    print('result_desc: ', result_desc)
    metadata = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"]
    for item in metadata:
        title = item["Name"]
        if title == "Amount":
            amount = item["Value"]
            print('Amount: ', amount)
        elif title == "MpesaReceiptNumber":
            mpesa_receipt_number = item["Value"]
            print('Mpesa Reference No: ', mpesa_receipt_number)
        elif title == "TransactionDate":
            transaction_date = item["Value"]
            print('Transaction date: ', transaction_date)
        elif title == "PhoneNumber":
            phone_number = item["Value"]
            print('Phone Number: ', phone_number)

    str_transaction_date = str(transaction_date)
    trans_datetime = datetime.strptime(str_transaction_date, "%Y%m%d%H%M%S")
    tz_trans_datetime = pytz.utc.localize(trans_datetime)

    payment = MpesaPayment.objects.create(
        MerchantRequestID=merchant_requestID,
        CheckoutRequestID=checkout_requestID,
        ResultCode=result_code,
        ResultDesc=result_desc,
        Amount=amount,
        MpesaReceiptNumber=mpesa_receipt_number,
        TransactionDate=tz_trans_datetime,
        PhoneNumber=phone_number,
    )
    if result_code == 0:
        payment.save()
        print("Successfully saved")

        password_length = 5
        password = secrets.token_urlsafe(password_length)
        print(password)

        headers = {
            'Content-Type': 'application/json',
            'h_api_key': os.getenv("SMS_Token"),
            'Accept': 'application/json'
        }
        payload = {
            "mobile": phone_number,
            "response_type": "json",
            "sender_name": "23107",
            "service_id": 0,
            "message": "Your WiFi Voucher is " + password + ".\nAirRumi."
        }
        response = requests.request("POST", 'https://api.mobitechtechnologies.com/sms/sendsms', headers=headers,
                                    json=payload)
        r = response.json()
        print(r)
        print("SMS Sent")

        print(amount)

        if amount == 1:
            profile = 'one_hour'
        elif amount == 50:
            profile = 'one_day'
        elif amount == 300:
            profile = 'one_week'
        elif amount == 1000:
            profile = 'one_month'
        else:
            print('Incorrect Amount')

        print(profile)

        connection = routeros_api.RouterOsApiPool(
            host=os.getenv("ip"),
            username=os.getenv("usernamee"),
            password=os.getenv("password"),
            port=8728,
            use_ssl=False,
            ssl_verify=False,
            ssl_verify_hostname=True,
            ssl_context=None,
            plaintext_login=True
        )
        api = connection.get_api()

        user = api.get_resource('/ip/hotspot/user')
        user.add(name=password, server="hotspot1", password='1234', profile=profile)

        print("User " + password + " created.")

    else:
        print("Payment was not successful")

    context = {
        "resultcode": result_code,
        "resultdesc": result_desc
    }

    if context['resultcode'] == 0:
        return JsonResponse(dict(context))
</code>```

'''

I  keep getting this error:

```<code>2023-01-03T13:37:23.849348+00:00 app[web.1]: Internal Server Error: /confirm
2023-01-03T13:37:23.849349+00:00 app[web.1]: Traceback (most recent call last):
2023-01-03T13:37:23.849350+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
2023-01-03T13:37:23.849350+00:00 app[web.1]:     response = get_response(request)
2023-01-03T13:37:23.849353+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
2023-01-03T13:37:23.849353+00:00 app[web.1]:     response = wrapped_callback(request, *callback_args, **callback_kwargs)
2023-01-03T13:37:23.849354+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
2023-01-03T13:37:23.849354+00:00 app[web.1]:     return view_func(*args, **kwargs)
2023-01-03T13:37:23.849354+00:00 app[web.1]:   File "/app/Splash/views.py", line 184, in confirmation
2023-01-03T13:37:23.849355+00:00 app[web.1]:     api = connection.get_api()
2023-01-03T13:37:23.849355+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/routeros_api/api.py", line 45, in get_api
2023-01-03T13:37:23.849355+00:00 app[web.1]:     self.socket = api_socket.get_socket(self.host, self.port,
2023-01-03T13:37:23.849355+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/routeros_api/api_socket.py", line 16, in get_socket
2023-01-03T13:37:23.849356+00:00 app[web.1]:     api_socket.connect((hostname, port))
2023-01-03T13:37:23.849356+00:00 app[web.1]: TypeError: str, bytes or bytearray expected, not NoneType
2023-01-03T13:37:23.849807+00:00 app[web.1]: 10.1.14.110 - - [03/Jan/2023:13:37:23 +0000] "POST /confirm HTTP/1.1" 500 75776 "-" "Apache-HttpClient/4.5.5 (Java/1.8.0_251)"
2023-01-03T13:37:23.849768+00:00 heroku[router]: at=info method=POST path="/confirm" host=airrumi.herokuapp.com request_id=2cb1aad4-7a83-43ce-a942-005d2cf64be9 fwd="10.184.18.139,196.201.214.200" dyno=web.1 connect=0ms service=454ms status=500 bytes=76092 protocol=https
</code>```

I have no idea where am messing up, because my test page is connecting perfectly and creating the user in mikrotik. Below is my test.py
'''

```<code># generate usernames
import secrets
import os
import routeros_api
from dotenv import load_dotenv

load_dotenv()

password_length = 5
password = secrets.token_urlsafe(password_length)
print(password)

amount = 1

if amount == 1:
    profile = 'one_hour'
elif amount == 50:
    profile = 'one_day'
elif amount == 300:
    profile = 'one_week'
elif amount == 1000:
    profile = 'one_month'
else:
    print('Incorrect Amount')

print(profile)

connection = routeros_api.RouterOsApiPool(
    host=os.getenv("ip"),
    username=os.getenv("usernamee"),
    password=os.getenv("password"),
    port=8728,
    use_ssl=False,
    ssl_verify=False,
    ssl_verify_hostname=True,
    ssl_context=None,
    plaintext_login=True
)
api = connection.get_api()

user = api.get_resource('/ip/hotspot/user')
user.add(name=password, server="hotspot1", password='1234', profile=profile)

print("User " + password + " Created.")
</code>```

'''

Body:
I am automating WiFi payments, so my code is able to ask for payments and a callback is sent. I get the information and save it, generate a user, send an sms to the client and create the generated user in mikrotik all at the same time.
Below is my code:

'''

def confirmation(request):
    print("Start Mpesa")
    global profile

    mpesa_body = request.body.decode('utf-8')
    mpesa_body = json.loads(mpesa_body)
    print(mpesa_body)
    print("Mpesa Body")

    merchant_requestID = mpesa_body["Body"]["stkCallback"]["MerchantRequestID"]
    print('merchant_requestID: ', merchant_requestID)
    checkout_requestID = mpesa_body["Body"]["stkCallback"]["CheckoutRequestID"]
    print('checkout_requestID: ', checkout_requestID)
    result_code = mpesa_body["Body"]["stkCallback"]["ResultCode"]
    print('result_code: ', result_code)
    result_desc = mpesa_body["Body"]["stkCallback"]["ResultDesc"]
    print('result_desc: ', result_desc)
    metadata = mpesa_body["Body"]["stkCallback"]["CallbackMetadata"]["Item"]
    for item in metadata:
        title = item["Name"]
        if title == "Amount":
            amount = item["Value"]
            print('Amount: ', amount)
        elif title == "MpesaReceiptNumber":
            mpesa_receipt_number = item["Value"]
            print('Mpesa Reference No: ', mpesa_receipt_number)
        elif title == "TransactionDate":
            transaction_date = item["Value"]
            print('Transaction date: ', transaction_date)
        elif title == "PhoneNumber":
            phone_number = item["Value"]
            print('Phone Number: ', phone_number)

    str_transaction_date = str(transaction_date)
    trans_datetime = datetime.strptime(str_transaction_date, "%Y%m%d%H%M%S")
    tz_trans_datetime = pytz.utc.localize(trans_datetime)

    payment = MpesaPayment.objects.create(
        MerchantRequestID=merchant_requestID,
        CheckoutRequestID=checkout_requestID,
        ResultCode=result_code,
        ResultDesc=result_desc,
        Amount=amount,
        MpesaReceiptNumber=mpesa_receipt_number,
        TransactionDate=tz_trans_datetime,
        PhoneNumber=phone_number,
    )
    if result_code == 0:
        payment.save()
        print("Successfully saved")

        password_length = 5
        password = secrets.token_urlsafe(password_length)
        print(password)

        headers = {
            'Content-Type': 'application/json',
            'h_api_key': os.getenv("SMS_Token"),
            'Accept': 'application/json'
        }
        payload = {
            "mobile": phone_number,
            "response_type": "json",
            "sender_name": "23107",
            "service_id": 0,
            "message": "Your WiFi Voucher is " + password + ".\nAirRumi."
        }
        response = requests.request("POST", 'https://api.mobitechtechnologies.com/sms/sendsms', headers=headers,
                                    json=payload)
        r = response.json()
        print(r)
        print("SMS Sent")

        print(amount)

        if amount == 1:
            profile = 'one_hour'
        elif amount == 50:
            profile = 'one_day'
        elif amount == 300:
            profile = 'one_week'
        elif amount == 1000:
            profile = 'one_month'
        else:
            print('Incorrect Amount')

        print(profile)

        connection = routeros_api.RouterOsApiPool(
            host=os.getenv("ip"),
            username=os.getenv("usernamee"),
            password=os.getenv("password"),
            port=8728,
            use_ssl=False,
            ssl_verify=False,
            ssl_verify_hostname=True,
            ssl_context=None,
            plaintext_login=True
        )
        api = connection.get_api()

        user = api.get_resource('/ip/hotspot/user')
        user.add(name=password, server="hotspot1", password='1234', profile=profile)

        print("User " + password + " created.")

    else:
        print("Payment was not successful")

    context = {
        "resultcode": result_code,
        "resultdesc": result_desc
    }

    if context['resultcode'] == 0:
        return JsonResponse(dict(context))

'''

I  keep getting this error:

2023-01-03T13:37:23.849348+00:00 app[web.1]: Internal Server Error: /confirm
2023-01-03T13:37:23.849349+00:00 app[web.1]: Traceback (most recent call last):
2023-01-03T13:37:23.849350+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/exception.py", line 55, in inner
2023-01-03T13:37:23.849350+00:00 app[web.1]:     response = get_response(request)
2023-01-03T13:37:23.849353+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/django/core/handlers/base.py", line 197, in _get_response
2023-01-03T13:37:23.849353+00:00 app[web.1]:     response = wrapped_callback(request, *callback_args, **callback_kwargs)
2023-01-03T13:37:23.849354+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
2023-01-03T13:37:23.849354+00:00 app[web.1]:     return view_func(*args, **kwargs)
2023-01-03T13:37:23.849354+00:00 app[web.1]:   File "/app/Splash/views.py", line 184, in confirmation
2023-01-03T13:37:23.849355+00:00 app[web.1]:     api = connection.get_api()
2023-01-03T13:37:23.849355+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/routeros_api/api.py", line 45, in get_api
2023-01-03T13:37:23.849355+00:00 app[web.1]:     self.socket = api_socket.get_socket(self.host, self.port,
2023-01-03T13:37:23.849355+00:00 app[web.1]:   File "/app/.heroku/python/lib/python3.10/site-packages/routeros_api/api_socket.py", line 16, in get_socket
2023-01-03T13:37:23.849356+00:00 app[web.1]:     api_socket.connect((hostname, port))
2023-01-03T13:37:23.849356+00:00 app[web.1]: TypeError: str, bytes or bytearray expected, not NoneType
2023-01-03T13:37:23.849807+00:00 app[web.1]: 10.1.14.110 - - [03/Jan/2023:13:37:23 +0000] "POST /confirm HTTP/1.1" 500 75776 "-" "Apache-HttpClient/4.5.5 (Java/1.8.0_251)"
2023-01-03T13:37:23.849768+00:00 heroku[router]: at=info method=POST path="/confirm" host=airrumi.herokuapp.com request_id=2cb1aad4-7a83-43ce-a942-005d2cf64be9 fwd="10.184.18.139,196.201.214.200" dyno=web.1 connect=0ms service=454ms status=500 bytes=76092 protocol=https

I have no idea where am messing up, because my test page is connecting perfectly and creating the user in mikrotik. Below is my test.py
'''

# generate usernames
import secrets
import os
import routeros_api
from dotenv import load_dotenv

load_dotenv()

password_length = 5
password = secrets.token_urlsafe(password_length)
print(password)

amount = 1

if amount == 1:
    profile = 'one_hour'
elif amount == 50:
    profile = 'one_day'
elif amount == 300:
    profile = 'one_week'
elif amount == 1000:
    profile = 'one_month'
else:
    print('Incorrect Amount')

print(profile)

connection = routeros_api.RouterOsApiPool(
    host=os.getenv("ip"),
    username=os.getenv("usernamee"),
    password=os.getenv("password"),
    port=8728,
    use_ssl=False,
    ssl_verify=False,
    ssl_verify_hostname=True,
    ssl_context=None,
    plaintext_login=True
)
api = connection.get_api()

user = api.get_resource('/ip/hotspot/user')
user.add(name=password, server="hotspot1", password='1234', profile=profile)

print("User " + password + " Created.")

'''


问:
how to do unity multi object selection drag and drop and dropped object merge
I want to equate every object I touched with the mouse to the position of the object at the point where I left the mouse.
For example, I want to select three sixteen and collect all three in a single square.

The object should be equal to the position of the object at that point, not at the point where I left the mouse.


问:
T-SQL OUTPUT clause to update a temp table
I have a utility script that is used to insert data into tables in my database. The script has a number of temp table in it that stores the new data to be inserted and a lot of it is related.

So, for example I have tables like so

```<code>DECLARE @Table1 TABLE
(
Table1ID INT
Table1Description VARCHAR(50)
Table1Code VARCHAR(5)
)

DECLARE @Table2 TABLE
(
Table2ID INT
Table2Description VARCHAR(50)
Table2Code VARCHAR(5)
)

DECLARE @Relationships TABLE
(
Table1Code VARCHAR(5)
Table2Code VARCHAR(5)
)
</code>```

So the script populates the data in @Table1 and @Table2, but doesn't populate the ID fields. Once the data has been MERGEd into the database tables, I update the Table1ID and Table2ID fields in a separate statement as they are auto incrementing fields. Then when I use the @Relationships table to populate the database table, I can join to @Table1 and @Table2 to get the actual ID values.

I'm updating the script and I'm wondering if I can MERGE the data from @Table1/@Table2 into the database and update the ID fields in the temp table as part of the MERGE statement using the OUTPUT clause all in one statement?

I think the answer is no as I can't find anything mentioning updating an existing table with the OUTPUT clause, only inserting into a table.

I am still able to do what I need to do, so I'm not after alternatives. I just wondering if it is possible using the OUTPUT Clause

Thanks in advance

Body:
I have a utility script that is used to insert data into tables in my database. The script has a number of temp table in it that stores the new data to be inserted and a lot of it is related.

So, for example I have tables like so

DECLARE @Table1 TABLE
(
Table1ID INT
Table1Description VARCHAR(50)
Table1Code VARCHAR(5)
)

DECLARE @Table2 TABLE
(
Table2ID INT
Table2Description VARCHAR(50)
Table2Code VARCHAR(5)
)

DECLARE @Relationships TABLE
(
Table1Code VARCHAR(5)
Table2Code VARCHAR(5)
)

So the script populates the data in @Table1 and @Table2, but doesn't populate the ID fields. Once the data has been MERGEd into the database tables, I update the Table1ID and Table2ID fields in a separate statement as they are auto incrementing fields. Then when I use the @Relationships table to populate the database table, I can join to @Table1 and @Table2 to get the actual ID values.

I'm updating the script and I'm wondering if I can MERGE the data from @Table1/@Table2 into the database and update the ID fields in the temp table as part of the MERGE statement using the OUTPUT clause all in one statement?

I think the answer is no as I can't find anything mentioning updating an existing table with the OUTPUT clause, only inserting into a table.

I am still able to do what I need to do, so I'm not after alternatives. I just wondering if it is possible using the OUTPUT Clause

Thanks in advance


问:
Remove duplicate couple values
I have a dataframe such as

```<code>COL1         COL2
Homo_sapiens Mus_musculus
Mus_musculus Homo_sapiens
Droso_A      Droso_b
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus
</code>```

How can I remove duplicated values within COL1 and COL2 not matter where the values are, wich mean that I want to remove duplicate couple values. Here is an example:

For instance, Homo_sapiens is present in COL1 AND Mus_musculus is in COL2

But since Homo_sapiens is present in COL2 AND Mus_musculus is in COL1 as well,
I only keep the first one :

```<code>COL1         COL2
Homo_sapiens Mus_musculus
Droso_A      Droso_b
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus
</code>```

Then for Droso_A and Droso_b it is a classic duplicate that can be achieved using :

```<code>df = df.drop_duplicates(subset = ["COL1","COL2"])

COL1         COL2
Homo_sapiens Mus_musculus
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus
</code>```

Then Betta_spe and Rattus_rattus and Rattus_norvegicus does not have any duplicate :

```<code>COL1         COL2
Homo_sapiens Mus_musculus
Droso_A      Droso_b
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus
</code>```

Title: Remove duplicate couple values

Body:
I have a dataframe such as

COL1         COL2
Homo_sapiens Mus_musculus
Mus_musculus Homo_sapiens
Droso_A      Droso_b
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus

How can I remove duplicated values within COL1 and COL2 not matter where the values are, wich mean that I want to remove duplicate couple values. Here is an example:

For instance, Homo_sapiens is present in COL1 AND Mus_musculus is in COL2

But since Homo_sapiens is present in COL2 AND Mus_musculus is in COL1 as well,
I only keep the first one :

COL1         COL2
Homo_sapiens Mus_musculus
Droso_A      Droso_b
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus

Then for Droso_A and Droso_b it is a classic duplicate that can be achieved using :

df = df.drop_duplicates(subset = ["COL1","COL2"])

COL1         COL2
Homo_sapiens Mus_musculus
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus

Then Betta_spe and Rattus_rattus and Rattus_norvegicus does not have any duplicate :

COL1         COL2
Homo_sapiens Mus_musculus
Droso_A      Droso_b
Droso_A      Droso_b
Betta_spe    Rattus_rattus
Betta_spe    Rattus_norvegirus


问:
Typegoose and TypeGraphQL - @FieldResolver not working
I have try to get the user by the userid which stored in the notice, but I get undefined in the FieldResolver.

Notice Schema

@ObjectType({description: "Notice Schema"})
export class Notice extends Base{
    @NField() @prop() userId: string;
    @NField((type: any) => User) @prop({ref: () => User,require: true}) user: Ref<User>;
    @NField() @prop() title: string;
    @NField() @prop() type: string;
    @NField() @prop() lostDate: Date;
    @NField({nullable: true}) @prop({default: null}) foundDate: Date;
    @NField({nullable: true}) @prop({default: null}) found_user_id: string;
    @NField() @prop() description: string;
    @NField() @prop() venue: string;
    @NField() @prop() contact: string;
    @NField({nullable: true}) @prop() imageDir: string;
}
```
<p>Notice Resolver</p>
<pre class="lang-js prettyprint-override"><code>@Resolver((of) => Notice)
export class NoticeResolver{
    constructor() {}

    @FieldResolver()
    async user(@Root() notice: Notice){
        console.log(notice.userId)
        return await UserModel.findById(notice.userId)
    }

    @Mutation(() => Notice)
    async createNotice(
        @Arg("noticeInfo") noticeInfo: NoticeInput
    ) {
        let notice = new NoticeModel()
        for (let key in noticeInfo){
            notice[key] = noticeInfo[key]
        }
        return (await NoticeModel.create(notice)).save()
    }

    @Query(() => [Notice])
    async findNoticeByUserId(
        @Arg("user_id") user_id: string
    ) {
        let result:any = await NoticeModel.find({userId: user_id})
        return result
    }

    @Query(() => [Notice])
    async findNoticeById(
        @Arg("notice_id") notice_id: string
    ) {
        return NoticeModel.aggregate([
            {
                $match: { _id: notice_id },
            },
        ])
    }

    @Query(() => [Notice])
    async allNotice() {
        return await NoticeModel.find({})
    }

}
</code>```

And the query

```<code>query{
    allNotice{
      _id
      userId
      title
      type
      lostDate
      foundDate
      found_user_id
      description
      venue
      contact
      imageDir
      user{
        name
        phone
        email
        country
      }
    }
}
</code>```

When a run the query the console.log in the Field Resolver shown "undefined"

I do not really know what happen, I am also follow the docmentation in the type-graphql
and the version is ^1.1.1

Body:
I have try to get the user by the userid which stored in the notice, but I get undefined in the FieldResolver.

Notice Schema

@ObjectType({description: "Notice Schema"})
export class Notice extends Base{
    @NField() @prop() userId: string;
    @NField((type: any) => User) @prop({ref: () => User,require: true}) user: Ref<User>;
    @NField() @prop() title: string;
    @NField() @prop() type: string;
    @NField() @prop() lostDate: Date;
    @NField({nullable: true}) @prop({default: null}) foundDate: Date;
    @NField({nullable: true}) @prop({default: null}) found_user_id: string;
    @NField() @prop() description: string;
    @NField() @prop() venue: string;
    @NField() @prop() contact: string;
    @NField({nullable: true}) @prop() imageDir: string;
}

Notice Resolver

@Resolver((of) => Notice)
export class NoticeResolver{
    constructor() {}

    @FieldResolver()
    async user(@Root() notice: Notice){
        console.log(notice.userId)
        return await UserModel.findById(notice.userId)
    }

    @Mutation(() => Notice)
    async createNotice(
        @Arg("noticeInfo") noticeInfo: NoticeInput
    ) {
        let notice = new NoticeModel()
        for (let key in noticeInfo){
            notice[key] = noticeInfo[key]
        }
        return (await NoticeModel.create(notice)).save()
    }

    @Query(() => [Notice])
    async findNoticeByUserId(
        @Arg("user_id") user_id: string
    ) {
        let result:any = await NoticeModel.find({userId: user_id})
        return result
    }

    @Query(() => [Notice])
    async findNoticeById(
        @Arg("notice_id") notice_id: string
    ) {
        return NoticeModel.aggregate([
            {
                $match: { _id: notice_id },
            },
        ])
    }

    @Query(() => [Notice])
    async allNotice() {
        return await NoticeModel.find({})
    }

}

And the query

query{
    allNotice{
      _id
      userId
      title
      type
      lostDate
      foundDate
      found_user_id
      description
      venue
      contact
      imageDir
      user{
        name
        phone
        email
        country
      }
    }
}

When a run the query the console.log in the Field Resolver shown "undefined"

I do not really know what happen, I am also follow the docmentation in the type-graphql
and the version is ^1.1.1


问:
Enumerating 3-connected quadrangulations in sage
I am not familiar at all yet with Sage, and was wondering how could I enumerate all 3-connected quadrangulations on 8,9,10 etc vertices? Is there a way to do this?

I searched quadrangulations on Sage and came across this:

quadrangulations(order, minimum_degree=None, minimum_connectivity=None, no_nonfacial_quadrangles=False, dual=False)

I also noticed that one can generate the cube graph (the only 3-connected quadrangulation on 8 vertices) as: graphs.quadrangulations(8, minimum_connectivity=3) (this gives 0x7fd3c2f9a260 but since I am not familiar with sage, I am not sure how would I go about plotting / visualizing this graph to see that it is in fact the cube, so I would like a clarification on this).

So I assume that I could go through larger quadrangulations by graphs.quadrangulations(9, minimum_connectivity=3) and graphs.quadrangulations(10, minimum_connectivity=3) etc.


问:
Jest not generating values correctly using crypto
I made a function to generate a complex password using window.crypto lib, this work perfectly and return values like jQzPN%c@tr71ie6Dt^C8.
Here is my function :

```<code>const genPwd = (length: number): string => {
  const regex = /^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*[0-9]).{8,}$/;
  const charset =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_-+={[}]|:;<,>.?/';
  let result = '';
  let values = new Uint32Array(length);
  window.crypto.getRandomValues(values);
  for (let i = 0; i < length; i++) {
    result += charset[values[i] % charset.length];
  }
  if (!regex.test(result)) {
    console.log('result', result);
    return genPwd(length);
  } else {
    return result;
  }
};
</code>```

But when I try to test this function using Jest, it falls everytime in the last condition because it doesn't match the regex, the console.log shows "AAAAAAAAAAAAAAAAAAAA", like nothing is generating correctly, so it doesn't match the regex and looping.

Here is my test :

```<code>it('should generate a x length password', () => {
  const mGetRandomValues = jest.fn().mockReturnValueOnce(new Uint32Array(20));
  Object.defineProperty(globalThis, 'crypto', {
    value: { getRandomValues: mGetRandomValues },
  });
  const valueToConvert = utils.genPwd(20);
  const valueToFind = 20;
  expect(valueToConvert).toHaveLength(valueToFind);
  expect(mGetRandomValues).toBeCalledWith(new Uint32Array(valueToFind));
});

</code>```

Does anyone have a solution ?

I have no idea about this issue

Body:
I made a function to generate a complex password using window.crypto lib, this work perfectly and return values like jQzPN%c@tr71ie6Dt^C8.
Here is my function :

const genPwd = (length: number): string => {
  const regex = /^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*[0-9]).{8,}$/;
  const charset =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_-+={[}]|:;<,>.?/';
  let result = '';
  let values = new Uint32Array(length);
  window.crypto.getRandomValues(values);
  for (let i = 0; i < length; i++) {
    result += charset[values[i] % charset.length];
  }
  if (!regex.test(result)) {
    console.log('result', result);
    return genPwd(length);
  } else {
    return result;
  }
};

But when I try to test this function using Jest, it falls everytime in the last condition because it doesn't match the regex, the console.log shows "AAAAAAAAAAAAAAAAAAAA", like nothing is generating correctly, so it doesn't match the regex and looping.

Here is my test :

it('should generate a x length password', () => {
  const mGetRandomValues = jest.fn().mockReturnValueOnce(new Uint32Array(20));
  Object.defineProperty(globalThis, 'crypto', {
    value: { getRandomValues: mGetRandomValues },
  });
  const valueToConvert = utils.genPwd(20);
  const valueToFind = 20;
  expect(valueToConvert).toHaveLength(valueToFind);
  expect(mGetRandomValues).toBeCalledWith(new Uint32Array(valueToFind));
});

Does anyone have a solution ?

I have no idea about this issue


问:
TCP Keepalive Problems in Virtual Box
I ran into issues with TCP Keep Alives in Virtual Box maybe someone can help me out here.
Our software runs inside a Linux VM running with Virtual Box on Windows.
From there a TCP connection is established where we try to check broken connections by enabeling TCP Keep Alives.
Since we want to detect broken connections fast we changed the defaults of those on OS level (since thats where you're supposed do this) and thats where we keep running into issues with Virtual Box.
I did a little investigation with a simple python script and wireshark and got some strange results.

The python script looks like this:

```<code>import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE)) # seconds
print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL)) # seconds
print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT))

s.connect(("10.33.42.0", 2112))

s.recv(16)
</code>```

Pretty basic. I establish a tcp connection and block with the recv call. The other side never sends anything (I just use netcat) so that the keepalive would apply after the TCP_KEEPIDLE intervall.
Also I print out the keepalive settings to see if they were picked up correctly.

So now I ran this script in different environments and got pretty different results with it.
Running it on Plain Linux works. I can set the TCP_KEEPIDLE to 10 sec and wireshark shows that every 10 sec an TCP Keep Alive is sent.

Next I ran it inside WSL (Windows-Subsystem Linux) I use for development purposes and there the first thing came up that was strange:

The settings seemed to be picked up correctly (since the prints of script) resembeled the settings I did on OS level which had a TCP_KEEPIDLE of 10 sec, but when I looked into Wireshark i saw that a keepalive was sent every minute (no matter what I configured). I can't explain where this 10 sec intervall comes from (I assumed that it could be from the windows settings, but they were on default which would be a KEEPIDLE of 2 hours).

Then I ran it on our actual deployment (VM running Linux on Windows). The output of the scripted looked good again. Picked up the 10 sec of TCP_KEEPIDLE, but I never saw a single Keepalive message.

My first guess here again maybe the windows settings are used even though the script prints the Linux settings. The intervall would be 2 hours there by default, which would explain why I don't see any message in the 10 minutes I tested.

So I changed the settings on the Windows host which did not make a difference for the VM setup.

But what I did notice when running the python script directly on Windows it still printed the default settings even though when looking at Wireshark the keepalive worked as configured. So it seems that python does not always get the right settings when getting them with getsockopt.

I'm pretty much in a dead end here. Since I don't know what settings are applied in my two VM setups (WSL and Virtual Box).
Is there someone here that has a little more insight on what happens with Keepalive settings in VM Scenarios and where the settings come from there?

Title: TCP Keepalive Problems in Virtual Box

Body:
I ran into issues with TCP Keep Alives in Virtual Box maybe someone can help me out here.
Our software runs inside a Linux VM running with Virtual Box on Windows.
From there a TCP connection is established where we try to check broken connections by enabeling TCP Keep Alives.
Since we want to detect broken connections fast we changed the defaults of those on OS level (since thats where you're supposed do this) and thats where we keep running into issues with Virtual Box.
I did a little investigation with a simple python script and wireshark and got some strange results.

The python script looks like this:

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE)) # seconds
print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL)) # seconds
print(s.getsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT))

s.connect(("10.33.42.0", 2112))

s.recv(16)

Pretty basic. I establish a tcp connection and block with the recv call. The other side never sends anything (I just use netcat) so that the keepalive would apply after the TCP_KEEPIDLE intervall.
Also I print out the keepalive settings to see if they were picked up correctly.

So now I ran this script in different environments and got pretty different results with it.
Running it on Plain Linux works. I can set the TCP_KEEPIDLE to 10 sec and wireshark shows that every 10 sec an TCP Keep Alive is sent.

Next I ran it inside WSL (Windows-Subsystem Linux) I use for development purposes and there the first thing came up that was strange:

The settings seemed to be picked up correctly (since the prints of script) resembeled the settings I did on OS level which had a TCP_KEEPIDLE of 10 sec, but when I looked into Wireshark i saw that a keepalive was sent every minute (no matter what I configured). I can't explain where this 10 sec intervall comes from (I assumed that it could be from the windows settings, but they were on default which would be a KEEPIDLE of 2 hours).

Then I ran it on our actual deployment (VM running Linux on Windows). The output of the scripted looked good again. Picked up the 10 sec of TCP_KEEPIDLE, but I never saw a single Keepalive message.

My first guess here again maybe the windows settings are used even though the script prints the Linux settings. The intervall would be 2 hours there by default, which would explain why I don't see any message in the 10 minutes I tested.

So I changed the settings on the Windows host which did not make a difference for the VM setup.

But what I did notice when running the python script directly on Windows it still printed the default settings even though when looking at Wireshark the keepalive worked as configured. So it seems that python does not always get the right settings when getting them with getsockopt.

I'm pretty much in a dead end here. Since I don't know what settings are applied in my two VM setups (WSL and Virtual Box).
Is there someone here that has a little more insight on what happens with Keepalive settings in VM Scenarios and where the settings come from there?


问:
Is there any data structure that behaves like both a Set and Map in OOP?
Considering the following example:

```<code>class Person {
    int citizenNumber; // key
    int age;
    string name;
    constructor(citizenNumber, age, name);
}

Map<int, Person> personsMap = {};
//Map allows the inconsistency fault: key != citizenNumber (object key)
personsMap.put(1, new Person(2, 18, "John"));

// Set would allow this if search by a key was possible
Set<Person> personsSet = { new Person(1, 20, "Paul") };
int searchableCitizenNumber = 1;

// Person should implement/extend some key like `key => citizenNumber`
Person person = personsSet.get(searchableCitizenNumber);
</code>```

Is there any data strucuture that:

Does not allow duplicates

Allow queries from a given key stored in the object itself

Body:
Considering the following example:

class Person {
    int citizenNumber; // key
    int age;
    string name;
    constructor(citizenNumber, age, name);
}

Map<int, Person> personsMap = {};
//Map allows the inconsistency fault: key != citizenNumber (object key)
personsMap.put(1, new Person(2, 18, "John"));

// Set would allow this if search by a key was possible
Set<Person> personsSet = { new Person(1, 20, "Paul") };
int searchableCitizenNumber = 1;

// Person should implement/extend some key like `key => citizenNumber`
Person person = personsSet.get(searchableCitizenNumber);

Is there any data strucuture that:

Does not allow duplicates

Allow queries from a given key stored in the object itself


问:
Is there an option to minify CSS and JS in PhpStorm only if minified file already exists?
On Visual Studio Code, there is an option to trigger the minify extension only if the minified file already exists (extension JS & CSS Minifier).

But in PhpStorm I couldn't find something like this using the File Watchers UglifyJS and CSSO.

Is there something I can do in these options below to emulate the same VS Code behavior?


问:
Reflected XSS and Stored XSS Vulnerability in asp.net mvc application (checkmarx platform)
This is the Checkmarx explanation for the code below. It's under XSS Vulnarability.

The application's EditToolMovementModel embeds untrusted data in the generated output with SubTitle, at line 12 of Project\Views\ToolMovement\Edit.cshtml. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.

The attacker would be able to alter the returned web page by simply providing modified data in the user input MovementName, which is read by the EditToolMovementModel method at line 12 of Project\Views\ToolMovement\Edit.cshtml. This input then flows through the code straight to the output web page, without sanitization.

This can enable a Reflected Cross-Site Scripting (XSS) attack.

```<code>@{
    ViewBag.Title = "Inventory";
    ViewBag.SubTitle = Model.MovementName;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

</code>```

Please suggest the alternative for @Html.Raw() functionality in ASP.NET MVC.

Suggest me any useful links to resolve Reflected XSS, Stored XSS vulnerabilities in asp.net mvc application.

Body:
This is the Checkmarx explanation for the code below. It's under XSS Vulnarability.

The application's EditToolMovementModel embeds untrusted data in the generated output with SubTitle, at line 12 of Project\Views\ToolMovement\Edit.cshtml. This untrusted data is embedded straight into the output without proper sanitization or encoding, enabling an attacker to inject malicious code into the output.

The attacker would be able to alter the returned web page by simply providing modified data in the user input MovementName, which is read by the EditToolMovementModel method at line 12 of Project\Views\ToolMovement\Edit.cshtml. This input then flows through the code straight to the output web page, without sanitization.

This can enable a Reflected Cross-Site Scripting (XSS) attack.

@{
    ViewBag.Title = "Inventory";
    ViewBag.SubTitle = Model.MovementName;
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Please suggest the alternative for @Html.Raw() functionality in ASP.NET MVC.

Suggest me any useful links to resolve Reflected XSS, Stored XSS vulnerabilities in asp.net mvc application.


问:
Pass extra data as a variable from controller to API Resource (Collection Resource) in Laravel
i'm trying to pass a variable that has region name as a string from a json file from controller to API resource but, instead of getting region name for example "Riyadh Region" i'm getting "0" I dont know why. Here is my code [API resource code]
[Post controller]

Here is my output:

Output

i'm getting region name as 0 and 1 instead of Riyadh Region why?


问:
When are environment variables available in flutter app?
I'm using Flutter 3.3.10, on macOS 11.6, and I am trying to use env vars at runtime. For the sake of the test I have 2 prints, one in main() and 1 in the build() function, like so:
print(const String.fromEnvironment('APPNAME'));

When I run the app from terminal on an iOS simulator like so: flutter run --dart-define=APPNAME=TEST_APP I get 2 blank prints:

```<code>Xcode build done.                                           10.8s
flutter:
flutter:
</code>```

It is only after I do a hot restart ('R') that it prints:

```<code>Performing hot restart...
Restarted application in 378ms.
flutter: TEST_APP
flutter: TEST_APP
</code>```

Why are the env vars not available on the first run?

EDIT: Interestingly, I don't get that problem when I run the exact same app on an Android emulator.

Body:
I'm using Flutter 3.3.10, on macOS 11.6, and I am trying to use env vars at runtime. For the sake of the test I have 2 prints, one in main() and 1 in the build() function, like so:
print(const String.fromEnvironment('APPNAME'));

When I run the app from terminal on an iOS simulator like so: flutter run --dart-define=APPNAME=TEST_APP I get 2 blank prints:

Xcode build done.                                           10.8s
flutter:
flutter:

It is only after I do a hot restart ('R') that it prints:

Performing hot restart...
Restarted application in 378ms.
flutter: TEST_APP
flutter: TEST_APP

Why are the env vars not available on the first run?

EDIT: Interestingly, I don't get that problem when I run the exact same app on an Android emulator.


问:
Why is RabbitMQ throwing exeption: Received a MESSAGE frame with unexpected subscription id?
RabbitMQ is integrated with our application for a few years, but on a recent client side implementation, the RabbitMQ receive fails (once in a while) with error:

Received a MESSAGE frame with unexpected subscription id. Received "{8D3575DC-2049-4C9C-94CD-E8C019E555CD}" but expected "{19EFC409-28D1-4CBB-8CE2-B84DB35B954F}"

The receive is done on a single thread that does nothing else. A similar implementation at the server side is fine and does not result in any receive error. Any suggestions to why this might be happening? This is on RabbitMQ client/server version 3.10.6, with publisher/subscriber model.


问:
How to safely use SAML RelayState
My team is having a hard time to come up with a completely safe solution to transfer critical information through SAML RelayState. I hope you can give us some advice.

To give you a little bit of context, we are a Service Provider working with ~200 IdP and with the following specificity:

our system has many 'organization'

an account is defined by a pair of organization + credentials. Meaning a user can have an account on 'Organization A' and another account on 'Organization B'. It can be the same user, even using the same email address, but for our system, it's 2 completely different accounts

a single organization can connect to multiple IdP. For example we allow an organization to have an IdP for their employee and another IdP for their external consultants or whatever

we often have a single IdP shared by multiple Organization

Our problem: during the callback phase, how to know which Organization the user is trying to log into?

Until now, whenever we add a new IdP on our system, we would first generate a unique Service Provider for this IdP and add the SP's UID in its EntityID + Metadata URL + consumer service url.

By doing so, during the callback phase, we can easily find the IdP from the SP, and finally the Organization related to this IdP.

Obviously, this is not a sustainable solution. We had many (justified) complaints, mostly from Organization sharing the same IdP and Federations.

Our problem with RelayState: we have an Organization + IdP discovery system on our application. Meaning anyone can start an authentication flow with any IdP. Anyone could just start a flow with Organization A, copy the RelayState, start a flow with Organization B using an IdP they do have access, replace the RelayState with the one from Organization A and gain access to Organization A.

Do you think our system is deeply flawed? We thought about using the Issuer to verify the RelayState and we are making some tests, but I believe someone else has a similar experience and can lead us on the right way !

I know it's a lot of information, please let me know if anything is unclear.

Thank you!

Title: How to safely use SAML RelayState


问:
NGX - loader rotate logo
I am trying to add an animation to the custom logos property.

However, the effects only apply to fgs.

Is there a way to add animation effects to the logo or add custom css classes to make it rotate?

This is my configuration, but only rotates the shape (rotating plane) not the imagen (isotipo.png)

```<code>const ngxUiLoaderConfig: NgxUiLoaderConfig = {
  bgsColor: '#1b4962',
  bgsOpacity: 0.5,
  bgsPosition: 'bottom-right',
  bgsSize: 60,
  bgsType: 'rotating-plane',
  blur: 5,
  delay: 0,
  fastFadeOut: true,
  fgsColor: '#1b4962',
  fgsPosition: 'center-center',
  fgsSize: 70,
  fgsType: 'rotating-plane',
  gap: 24,
  logoUrl: '../../assets/img/isotipo2.png',
  logoPosition: 'center-center',
  logoSize: 120,
  masterLoaderId: 'master',
  overlayBorderRadius: '0',
  overlayColor: 'rgba(40,40,40,0.2)',
  pbColor: '#eb5353',
  pbDirection: 'ltr',
  pbThickness: 3,
  hasProgressBar: true,
  textColor: '#FFFFFF',
  textPosition: 'center-center',
  maxTime: -1,
  minTime: 300
};
</code>```

Title: NGX - loader rotate logo

Body:
I am trying to add an animation to the custom logos property.

However, the effects only apply to fgs.

Is there a way to add animation effects to the logo or add custom css classes to make it rotate?

This is my configuration, but only rotates the shape (rotating plane) not the imagen (isotipo.png)

const ngxUiLoaderConfig: NgxUiLoaderConfig = {
  bgsColor: '#1b4962',
  bgsOpacity: 0.5,
  bgsPosition: 'bottom-right',
  bgsSize: 60,
  bgsType: 'rotating-plane',
  blur: 5,
  delay: 0,
  fastFadeOut: true,
  fgsColor: '#1b4962',
  fgsPosition: 'center-center',
  fgsSize: 70,
  fgsType: 'rotating-plane',
  gap: 24,
  logoUrl: '../../assets/img/isotipo2.png',
  logoPosition: 'center-center',
  logoSize: 120,
  masterLoaderId: 'master',
  overlayBorderRadius: '0',
  overlayColor: 'rgba(40,40,40,0.2)',
  pbColor: '#eb5353',
  pbDirection: 'ltr',
  pbThickness: 3,
  hasProgressBar: true,
  textColor: '#FFFFFF',
  textPosition: 'center-center',
  maxTime: -1,
  minTime: 300
};


问:
Unnesting arrays of different dimensions
I am trying to use the unnest optimisation to bundle rows into a single insert and reduce the number of RTTs to the database.

My basic insert query looks like so:

```<code>INSERT INTO table (fielda, fieldb, fieldc)
SELECT fielda, fieldb, fieldc
    FROM unnest($1, $2, $3)) as a (fielda, fieldb, fieldc)
</code>```

And this works beautifully, so long as fieldc is a scalar value.

If fieldc happens to be a real[] for example, and thus $3 is a real[][], this no longer works because unnest unnests to reals, not real[]s.

Somehow I need to get unnest to produce rows, only unnested by 1 level. There is a very helpful existing answer here: https://stackoverflow.com/a/8142998/15531756 which implements a function for unnesting a single array, but this creates a set of values, rather than a set of rows containing everything I need. As far as I am aware I can't join this array onto the normal unnest for the other parameters.

So how would one insert bundled data like this where a column has an array value type?

At the moment I have resorted to dynamically generating a query

```<code>INSERT INTO table (fielda, fieldb, fieldc)
VALUES
($1, $2, $3),
($4, $5, $6)
... and so on
</code>```

but this is markedly slower, even re-using the same statement.

Body:
I am trying to use the unnest optimisation to bundle rows into a single insert and reduce the number of RTTs to the database.

My basic insert query looks like so:

INSERT INTO table (fielda, fieldb, fieldc)
SELECT fielda, fieldb, fieldc
    FROM unnest($1, $2, $3)) as a (fielda, fieldb, fieldc)

And this works beautifully, so long as fieldc is a scalar value.

If fieldc happens to be a real[] for example, and thus $3 is a real[][], this no longer works because unnest unnests to reals, not real[]s.

Somehow I need to get unnest to produce rows, only unnested by 1 level. There is a very helpful existing answer here: https://stackoverflow.com/a/8142998/15531756 which implements a function for unnesting a single array, but this creates a set of values, rather than a set of rows containing everything I need. As far as I am aware I can't join this array onto the normal unnest for the other parameters.

So how would one insert bundled data like this where a column has an array value type?

At the moment I have resorted to dynamically generating a query

INSERT INTO table (fielda, fieldb, fieldc)
VALUES
($1, $2, $3),
($4, $5, $6)
... and so on

but this is markedly slower, even re-using the same statement.


问:
how to send a file to an external api in laravel job?
I want to upload an image from a mobile app and send that file to Laravel API then, I want to send that image to an external API for getting information from pictures. In the controller I have the following code:

```<code>public function processImage(Request $request): JsonResponse
    {
        $request->validate([
            'image' => 'image|mimes:jpeg,jpg,png,gif'
        ]);
        $file = $request->file('image');
        $filePath = $file->store('temp');
        ProcessImageJob::dispatch($filePath);

        $jobStatusId = 1;

        return response()->json(compact('jobStatusId'));
    }
</code>```

In ProcessImageJob I call the API like this:

```<code>$client = new Client();
        $response = $client
            ->post($uploadUrl, [
                'headers' => $this->authHeaders,
                'multipart' => [
                    [
                        'name'     => 'files',
                        'contents' => fopen($this->image, 'r'),
                        'headers'  => [ 'Content-Type' => 'image/jpeg']
                    ],
                ]
            ]);
        $response = json_decode($response->getBody()->getContents(), true);
</code>```

when I request, it gives in the queue terminal this error: fopen(temp/XLCeHZJqkmwtyIhJ75rgDNTbXIhrlmncsvqTvvkD.jpg): Failed to open stream: No such file or directory  how to fix this error? I appreciate any help.

P.S: For Laravel app, I use sail for docker.

Body:
I want to upload an image from a mobile app and send that file to Laravel API then, I want to send that image to an external API for getting information from pictures. In the controller I have the following code:

public function processImage(Request $request): JsonResponse
    {
        $request->validate([
            'image' => 'image|mimes:jpeg,jpg,png,gif'
        ]);
        $file = $request->file('image');
        $filePath = $file->store('temp');
        ProcessImageJob::dispatch($filePath);

        $jobStatusId = 1;

        return response()->json(compact('jobStatusId'));
    }

In ProcessImageJob I call the API like this:

$client = new Client();
        $response = $client
            ->post($uploadUrl, [
                'headers' => $this->authHeaders,
                'multipart' => [
                    [
                        'name'     => 'files',
                        'contents' => fopen($this->image, 'r'),
                        'headers'  => [ 'Content-Type' => 'image/jpeg']
                    ],
                ]
            ]);
        $response = json_decode($response->getBody()->getContents(), true);

when I request, it gives in the queue terminal this error: fopen(temp/XLCeHZJqkmwtyIhJ75rgDNTbXIhrlmncsvqTvvkD.jpg): Failed to open stream: No such file or directory  how to fix this error? I appreciate any help.

P.S: For Laravel app, I use sail for docker.


问:
Align button horizontally in top of frame and table bottom vertically
I get in trouble with the fact of after clicking on a button : I would like my table is set at bottom of my button but it's not that

I've managed to get it without after clicking a button but without, I've tested many things and nothing.

Here is the code :

```<code>contents = new BoxPanel(Orientation.Horizontal) {
      contents += Button("Top 10 most commun runways latitude") {
        val headers = Array.tabulate(10) {"Col-" + _}.toSeq
        val rowData = Array.tabulate[Any](10, 10) {"" + _ + ":" + _}
        contents += new ScrollPane(new Table(rowData, headers))
      }
      contents += Button("10 highest and lowest number of countries") {
        }

      contents += Button("Type of runways per country") {}
  }
</code>```

What I get

What I would like

Body:
I get in trouble with the fact of after clicking on a button : I would like my table is set at bottom of my button but it's not that

I've managed to get it without after clicking a button but without, I've tested many things and nothing.

Here is the code :

contents = new BoxPanel(Orientation.Horizontal) {
      contents += Button("Top 10 most commun runways latitude") {
        val headers = Array.tabulate(10) {"Col-" + _}.toSeq
        val rowData = Array.tabulate[Any](10, 10) {"" + _ + ":" + _}
        contents += new ScrollPane(new Table(rowData, headers))
      }
      contents += Button("10 highest and lowest number of countries") {
        }

      contents += Button("Type of runways per country") {}
  }

What I get

What I would like


问:
Androidx classes in pyjnius
i want to access Androidx classes with pyjnius but I don't know how to access them.

I have already tried using autoclass for accessing Androidx classes but this gives me error saying no class found. any help is greatly appreciated, thanks in advance.

Title: Androidx classes in pyjnius


问:
Handling audio source errors (404) with Icecast on Safari
I have Icecast broadcast live streams that can return a 404 until the stream is properly mounted/connected. In this scenario I use the onerror from the source element to do an initial reconnect loop until the URL is ready. An example below...

```<code><audio onerror="handleAudioError();">
    <source onerror="handleSourceError();" src="https://listen.site.com/3472397749832" type="audio/mpeg">
</audio>
</code>```

This works fine in Chrome & Firefox, yet Safari never gets to the source error and returns a 404 early. The only way around this seems to be an initial fetch, handle the 404 then do the reconnect and set the source src. But this totally goes against trying to use native audio HTML error handling. Has anyone seen this or any insight on what might be happening? I'm assuming it's something to do with the Icecast setup but not sure what. Here are the headers that are returned...

Safari

This returns a 206 partial content initially, then the 404

Chrome / Firefox

Body:
I have Icecast broadcast live streams that can return a 404 until the stream is properly mounted/connected. In this scenario I use the onerror from the source element to do an initial reconnect loop until the URL is ready. An example below...

<audio onerror="handleAudioError();">
    <source onerror="handleSourceError();" src="https://listen.site.com/3472397749832" type="audio/mpeg">
</audio>

This works fine in Chrome & Firefox, yet Safari never gets to the source error and returns a 404 early. The only way around this seems to be an initial fetch, handle the 404 then do the reconnect and set the source src. But this totally goes against trying to use native audio HTML error handling. Has anyone seen this or any insight on what might be happening? I'm assuming it's something to do with the Icecast setup but not sure what. Here are the headers that are returned...

Safari

This returns a 206 partial content initially, then the 404

Chrome / Firefox


问:
An analogue of the Stylus for html tags
Tell me, is there a solution similar to Stylus - embedding css in downloadable pages - but for embedding the tags I need in html before and after the tags that I specify? For example, to embed the  tag before the
 and the corresponding  after the closing
. And of course  before
 and closing tags respectively.

I tried the css setting in Styles, but in order to remove the hiding again, I have to disable/enable the Stylus, and I would like to leave it on all the time and collapse/expand the groups I need.

```<code>div.someclass {
cursor: pointer;
}

.o-hide {
visibility: hidden;
transition: all ease 0.8s;
}

.o-hide:hover {
visibility: visible;
}

.o-hide p {
visibility: visible;
margin: 0;
padding: 0;
}
</code>```
```<code>
div.someclass {
cursor: pointer;
}

.o-hide:hover {
display: block;
}

.o-hide p {
display: block;
margin: 0;
padding: 0;
}
</code>```
```<code>
div.someclass {
cursor: pointer;
}

.o-hide {
position: absolute;
top: -9999px;
left: -9999px;
}

.o-hide:hover {
position: static;
}
</code>```

etc

Title: An analogue of the Stylus for html tags

Body:
Tell me, is there a solution similar to Stylus - embedding css in downloadable pages - but for embedding the tags I need in html before and after the tags that I specify? For example, to embed the  tag before the
 and the corresponding  after the closing
. And of course  before
 and closing tags respectively.

I tried the css setting in Styles, but in order to remove the hiding again, I have to disable/enable the Stylus, and I would like to leave it on all the time and collapse/expand the groups I need.

div.someclass {
cursor: pointer;
}

.o-hide {
visibility: hidden;
transition: all ease 0.8s;
}

.o-hide:hover {
visibility: visible;
}

.o-hide p {
visibility: visible;
margin: 0;
padding: 0;
}

div.someclass {
cursor: pointer;
}

.o-hide:hover {
display: block;
}

.o-hide p {
display: block;
margin: 0;
padding: 0;
}

div.someclass {
cursor: pointer;
}

.o-hide {
position: absolute;
top: -9999px;
left: -9999px;
}

.o-hide:hover {
position: static;
}

etc


问:
Docker-stack. Forcing docker stack services to use ipv4
I would like to have a service being deployed as part of a docker stack to listen on ipv4.
Currently the docker stack deployed service (rabbitmq) is listening on ipv6, I would like to have it listen via ipv4.
The section of docker compose .yaml file that I using to deploy the docker stack as the following yaml section.

```<code>    rabbitmq-3-11-0:
      #image: rabbitmq:3.11.0-management
      image: "127.0.0.1:5000/bcl-sdv-rabbitmq-3-11-0:v0.1"
      ports:
        -
          "0.0.0.0:5672:5672/tcp"
        -
          "0.0.0.0:15672:15672/tcp" #15672: HTTP API clients, management UI and rabbitmqadmin (only if the management plugin is enabled)
</code>```

On deployment of the docker stack, the "rabbitmq-3-11-0" service is deployed successfully.

To test IP connectivity I issue the following commands on the docker node.

```<code>ncat -w 2 -v ::1 5672 </dev/null; echo $?
</code>```

yields

```<code>Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to ::1:5672.
</code>```

While the command

```<code>ncat -w 2 -v 0.0.0.0 5672 </dev/null; echo $?
</code>```

yields

```<code>Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 0.0.0.0:5672.
Ncat: Connection reset by peer.
1
</code>```

The command

```<code>ncat -w 2 -v 127.0.0.1 5672 </dev/null; echo $?
</code>```

produces

```<code>Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 127.0.0.1:5672.
Ncat: Connection reset by peer.
1
</code>```

The netstat command below

```<code>sudo netstat -tulnp|grep 5672
</code>```

shows that the ports 5672 and 15672 are listening on ipv6.

```<code>tcp6       4      0 :::5672                 :::*                    LISTEN      2527/dockerd
tcp6       0      0 :::15672                :::*                    LISTEN      2527/dockerd
</code>```

The command to determine the docker version below

```<code>docker info|grep Version
</code>```

Outputs

```<code> Server Version: 20.10.20
 Cgroup Version: 1
 Kernel Version: 3.10.0-1160.76.1.el7.x86_64
</code>```

The Linux version command below

```<code>lsb_release
</code>```

prints

```<code>LSB Version:    :core-4.1-amd64:core-4.1-noarch
</code>```

Body:
I would like to have a service being deployed as part of a docker stack to listen on ipv4.
Currently the docker stack deployed service (rabbitmq) is listening on ipv6, I would like to have it listen via ipv4.
The section of docker compose .yaml file that I using to deploy the docker stack as the following yaml section.

    rabbitmq-3-11-0:
      #image: rabbitmq:3.11.0-management
      image: "127.0.0.1:5000/bcl-sdv-rabbitmq-3-11-0:v0.1"
      ports:
        -
          "0.0.0.0:5672:5672/tcp"
        -
          "0.0.0.0:15672:15672/tcp" #15672: HTTP API clients, management UI and rabbitmqadmin (only if the management plugin is enabled)

On deployment of the docker stack, the "rabbitmq-3-11-0" service is deployed successfully.

To test IP connectivity I issue the following commands on the docker node.

ncat -w 2 -v ::1 5672 </dev/null; echo $?

yields

Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to ::1:5672.

While the command

ncat -w 2 -v 0.0.0.0 5672 </dev/null; echo $?

yields

Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 0.0.0.0:5672.
Ncat: Connection reset by peer.
1

The command

ncat -w 2 -v 127.0.0.1 5672 </dev/null; echo $?

produces

Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Connected to 127.0.0.1:5672.
Ncat: Connection reset by peer.
1

The netstat command below

sudo netstat -tulnp|grep 5672

shows that the ports 5672 and 15672 are listening on ipv6.

tcp6       4      0 :::5672                 :::*                    LISTEN      2527/dockerd
tcp6       0      0 :::15672                :::*                    LISTEN      2527/dockerd

The command to determine the docker version below

docker info|grep Version

Outputs

 Server Version: 20.10.20
 Cgroup Version: 1
 Kernel Version: 3.10.0-1160.76.1.el7.x86_64

The Linux version command below

lsb_release

prints

LSB Version:    :core-4.1-amd64:core-4.1-noarch


问:
How to resolve a proxy object without the extra call to handler.get?
I want to create a proxy object that has a set of keys defined in typescript and the returned type is related to the key.

But when I try to resolve this object, it comes an extra call to get with key 'then' (as Promise wants to check if it's a thenable object)

If I test it explicit, I cannot mark the return type.

        get<M extends ServiceKeys<T>>(
          target: {
            [ClientSymbol]: WsRpcClient<T>
          },
          key: M
        ): (
          payload: ServiceRequest<T, M>
        ) => PromiseResult<ServiceRespond<T, M>, ServiceError<T, M>> {
          if (key === 'then') {
            return undefined // I cannot mark this type!
          }
          return payload => {
            return MakeWrapExt(target[ClientSymbol].request(key, payload))
          }
        }
```


问:
Some advice about REST endpoints design
Currently we have some endpoints which are essentialy a PATCH but the request is to not leverage on JSONPatch o JSONMergePatch objects because endpoints must have specific DTOs as body.
My idea is to have the same @PATCH endpoint consumes different types:

```<code>@Path("path/to/resource")
@PATCH
@Consumes(???)
void modificationOne(DTO#1 modifications) {
}

@Path("path/to/resource")
@PATCH
@Consumes(???)
void modificationTwo(DTO#2 modifications) {
}
</code>```

I'm struggle about @Consumes() media type:

application/vnd.patch.modificationOne+json, application/vnd.patch.modificationTwo+json

application/json-patch+json; type=DTO#1, application/json-patch+json; type=DTO#2

Anyone with some advices for a better and/or more pratical solution?

Title: Some advice about REST endpoints design

Body:
Currently we have some endpoints which are essentialy a PATCH but the request is to not leverage on JSONPatch o JSONMergePatch objects because endpoints must have specific DTOs as body.
My idea is to have the same @PATCH endpoint consumes different types:

@Path("path/to/resource")
@PATCH
@Consumes(???)
void modificationOne(DTO#1 modifications) {
}

@Path("path/to/resource")
@PATCH
@Consumes(???)
void modificationTwo(DTO#2 modifications) {
}

I'm struggle about @Consumes() media type:

application/vnd.patch.modificationOne+json, application/vnd.patch.modificationTwo+json

application/json-patch+json; type=DTO#1, application/json-patch+json; type=DTO#2

Anyone with some advices for a better and/or more pratical solution?


问:
Create a private room in socket io
I have a node js server witch is for a chat page. Now I want to make a private messiging part of the server. Currently i have the following code:
Client:

```<code>    rooms.addEventListener('submit', function(e){
        e.preventDefault();
        if(roomName.value){
          socket.emit('Join-Room', roomName.value);
          roomName.value = '';
        }
      });

</code>```

Server:

```<code>socket.on('Join-Room', (roomName) => {
    socket.join(roomName);
  });

</code>```

When I try to join one room nothing happens and i am still in the main chat.

Title: Create a private room in socket io

Body:
I have a node js server witch is for a chat page. Now I want to make a private messiging part of the server. Currently i have the following code:
Client:

    rooms.addEventListener('submit', function(e){
        e.preventDefault();
        if(roomName.value){
          socket.emit('Join-Room', roomName.value);
          roomName.value = '';
        }
      });

Server:

socket.on('Join-Room', (roomName) => {
    socket.join(roomName);
  });

When I try to join one room nothing happens and i am still in the main chat.


问:
Is gojs-angular v2.0.6 is not compatible with angular v11?
Im using angular version 11, but when i install gojs(v2.2.21) & gojs-angular(2.0.6) packages, i got this error.

Error: ./node_modules/gojs-angular/fesm2015/gojs-angular.mjs 487:0-27 Can't import the named export 'ɵɵngDeclareClassMetadata' from non EcmaScript module (only default export is available)

gojs-angular error

But when i downgraded the packages like this, it works

gojs => 1.8.34
gojs-angular => 1.0.20

Is latest gojs-angular is not compatible with angular v11 ?


问:
Getting Null UserAttributes in Cognito CustomMessage_ForgotPassword event in Go
I am sending password reset link to my users using cognito CustomMessage_ForgotPassword event. Here is my handler code.

```<code>func handler(ctx context.Context, event *events.CognitoEventUserPoolsCustomMessage) (*events.CognitoEventUserPoolsCustomMessage,error)
{
resetURL := fmt.Sprintf("%s/login/recover", os.Getenv("DOMAIN_URL"))
var customMessageForgotPassword = fmt.Sprintf(
    `<style>
    p {
    display: block;
    }
    </style>

    <div tabindex="-1"><p>Hello,</p>
    <p> Click on link below to reset your password.</p>
    <p><a href="%s?code=%s&email=%s"> Reset Password </a></p>
    <p>Thanks</p>
    </div>`,
    resetURL,
    event.Request.CodeParameter, event.Request.UserAttributes["Email"])

if event.TriggerSource == "CustomMessage_ForgotPassword" {
    event.Response.EmailMessage = customMessageForgotPassword
    event.Response.EmailSubject = "Reset Your Password"
}

return event, nil

}
</code>```

Here is the definition of CognitoEventUserPoolsCustomMessageRequest in cognito.go file.

```<code>type CognitoEventUserPoolsCustomMessage struct {
CognitoEventUserPoolsHeader
Request  CognitoEventUserPoolsCustomMessageRequest  `json:"request"`
Response CognitoEventUserPoolsCustomMessageResponse `json:"response"`
}

type CognitoEventUserPoolsCustomMessageRequest struct {
UserAttributes    map[string]interface{} `json:"userAttributes"`
CodeParameter     string                 `json:"codeParameter"`
UsernameParameter string                 `json:"usernameParameter"`
ClientMetadata    map[string]string      `json:"clientMetadata"`
}
</code>```

In email I am getting Reset password url parameters like Domain_URL/login/recover?code=13578&email=%!s()

Tried with parameters like UsernameParameter and some other solutions. But always getting nil here.
Any solution to this problem?

Body:
I am sending password reset link to my users using cognito CustomMessage_ForgotPassword event. Here is my handler code.

func handler(ctx context.Context, event *events.CognitoEventUserPoolsCustomMessage) (*events.CognitoEventUserPoolsCustomMessage,error)
{
resetURL := fmt.Sprintf("%s/login/recover", os.Getenv("DOMAIN_URL"))
var customMessageForgotPassword = fmt.Sprintf(
    `

Hello,

 Click on link below to reset your password.

 Reset Password

Thanks

`,
    resetURL,
    event.Request.CodeParameter, event.Request.UserAttributes["Email"])

if event.TriggerSource == "CustomMessage_ForgotPassword" {
    event.Response.EmailMessage = customMessageForgotPassword
    event.Response.EmailSubject = "Reset Your Password"
}

return event, nil

}

Here is the definition of CognitoEventUserPoolsCustomMessageRequest in cognito.go file.

type CognitoEventUserPoolsCustomMessage struct {
CognitoEventUserPoolsHeader
Request  CognitoEventUserPoolsCustomMessageRequest  `json:"request"`
Response CognitoEventUserPoolsCustomMessageResponse `json:"response"`
}

type CognitoEventUserPoolsCustomMessageRequest struct {
UserAttributes    map[string]interface{} `json:"userAttributes"`
CodeParameter     string                 `json:"codeParameter"`
UsernameParameter string                 `json:"usernameParameter"`
ClientMetadata    map[string]string      `json:"clientMetadata"`
}

In email I am getting Reset password url parameters like Domain_URL/login/recover?code=13578&email=%!s()

Tried with parameters like UsernameParameter and some other solutions. But always getting nil here.
Any solution to this problem?


问:
How to exclude transitive jar from assembly file in assembly maven plugin
hello folks I am trying to exclude a jar from assembly file which is a transitive dependency of the main jar.

I have already excluded the dependency from my pom.xml and
I need to exclude hive-storage-api from following hive-exec jar

```<code><moduleSet>
  <useAllReactorProjects>true</useAllReactorProjects>
  <includes>
    <include>org.apache.ranger:ranger-hive-plugin</include>
  </includes>
  <binaries>
    <outputDirectory>ews/webapp/WEB-INF/classes/ranger-plugins/hive</outputDirectory>
    <includeDependencies>true</includeDependencies>
    <unpack>false</unpack>
    <directoryMode>755</directoryMode>
    <fileMode>644</fileMode>
    <includes>
      <include>org.apache.hive:hive-common:jar:${hive.version}</include>
      <include>org.apache.hive:hive-service:jar:${hive.version}</include>
      <include>org.apache.hive:hive-exec:jar:${hive.version}</include>
      <include>org.apache.hive:hive-jdbc:jar:${hive.version}</include>
      <include>org.apache.hive:hive-metastore:jar:${hive.version}</include>
      <include>org.apache.thrift:libfb303:jar:${libfb303.version}</include>
      <include>org.apache.thrift:libthrift:jar:${libthrift.version}</include>
    </includes>
  </binaries>
</moduleSet>
</code>```

I am getting hive-storage-api inside this location ews/webapp/WEB-INF/classes/ranger-plugins/hive/META-INF/maven/org.apache.hive/hive-storage-api
even after adding exlude tag as below after  above.

```<code>    <excludes>
      <exclude>org.apache.hive:hive-storage-api</exclude>
    </excludes>
</code>```

after building my project I still get this jar and its not getting excluded from ews/webapp/WEB-INF/classes/ranger-plugins/hive location?

I searched existing questions but the answers are not relevant for this?

Thanks in advance.

Body:
hello folks I am trying to exclude a jar from assembly file which is a transitive dependency of the main jar.

I have already excluded the dependency from my pom.xml and
I need to exclude hive-storage-api from following hive-exec jar

<moduleSet>
  <useAllReactorProjects>true</useAllReactorProjects>
  <includes>
    <include>org.apache.ranger:ranger-hive-plugin</include>
  </includes>
  <binaries>
    <outputDirectory>ews/webapp/WEB-INF/classes/ranger-plugins/hive</outputDirectory>
    <includeDependencies>true</includeDependencies>
    <unpack>false</unpack>
    <directoryMode>755</directoryMode>
    <fileMode>644</fileMode>
    <includes>
      <include>org.apache.hive:hive-common:jar:${hive.version}</include>
      <include>org.apache.hive:hive-service:jar:${hive.version}</include>
      <include>org.apache.hive:hive-exec:jar:${hive.version}</include>
      <include>org.apache.hive:hive-jdbc:jar:${hive.version}</include>
      <include>org.apache.hive:hive-metastore:jar:${hive.version}</include>
      <include>org.apache.thrift:libfb303:jar:${libfb303.version}</include>
      <include>org.apache.thrift:libthrift:jar:${libthrift.version}</include>
    </includes>
  </binaries>
</moduleSet>

I am getting hive-storage-api inside this location ews/webapp/WEB-INF/classes/ranger-plugins/hive/META-INF/maven/org.apache.hive/hive-storage-api
even after adding exlude tag as below after  above.

    <excludes>
      <exclude>org.apache.hive:hive-storage-api</exclude>
    </excludes>

after building my project I still get this jar and its not getting excluded from ews/webapp/WEB-INF/classes/ranger-plugins/hive location?

I searched existing questions but the answers are not relevant for this?

Thanks in advance.


问:
Find matching entries and display attached row
I have used QGIS to create statistics by categories-excel-documents. Those documents contain tables (within the same sheet) with IDs, representing buffers of specific places, function-labels, representing the function of the buildings within the buffer of those specific places (ID), and a count for each function-label for each buffer of a specific place(ID).

I did this for two counties which happen to have overlapping buffers, which means I had to combine those tables to get a complete picture of how many buildings of certain functions are within each buffer.

For this, I used a Pivot-Table in Excel. So far so good.
excerpt from excel, showing the original tables used for the pivot-table, the pivot-table and a column containing the relevant IDs

Now, my original tables as well as my Pivot-Table contain IDs (buffer of specific places) that are irrelevant and make the list really long.
Additionally, I have a list / table containing the IDs of buffers that are relevant and will be used for further processing.

How can I either filter my Pivot-Table (or original sources) or rather match entries with the list of IDs that are of relevance, so that I get a list of the needed IDs AND the attached information belonging to the ID (function-label and count per function-label)?

I came across a VLOOKUP-post VLOOKUP-Post on Stack overflow but it stated that this would ignore repeated values. As my IDs are repeated for each function-label, this would be a problem.

I tried to find a filter function in the Pivot-Table but was only able to hand select the IDs that I want displayed in the Pivot-Table. As that's roughly 180 IDs, I don't want to do it manually. I've also seen videos that used the filter or match-function, but this was only used to show  matching numbers between two columns of numbers, not the corresponding data that's attached. A similar question on StackOverflow was answered and suggested VLOOKUP, but it also stated that this would be problematic, if the column contained repeated values. As the ID is repeated multiple times for the different function-labels, this seems unfit for my problem.