问:
RSA/ECB/PKCS1Padding Decryption in Python3
Here's java code

z.java

```<code>import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import java.util.Base64;

public class z {
    public static void main(String []args) {
        try
        {
            String public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC32VkPYUKYszF665DH0jRuCuyKPqf4pkmcUWXOp8CZkNriew18iLiNGBAtDXhmtdzj6bEaBbxkNixzLfNMtNQw53bfW5lgRC91nG4fiK085sJ8CkdL22PIhRWO75x2pwk+Wqlx5N3OxVV0oS76dI7/pCqTCfqJec7BMH820Im5AwIDAQAB";
            String encrpted_data_base64 = "qKVan83WWFmVRVASPZ2Io8iM1qs/rowwHH4zh7NNcrh8544hhJr1fKE2PkogAKZWD8mjoO1x4AhRSkrLMsTB0m6V+ZsayLOLiIpCh5hsybaH3NdPKPhMyIqAUdw3au2Zcl76b/4FeNvP9ay/S0niXzQMVBTgHcHhrfjquqQnoXc=";

            PublicKey generatePublic = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(public_key.getBytes())));
            Cipher instance = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            instance.init(2, generatePublic);
            byte[] decode = Base64.getDecoder().decode(encrpted_data_base64.getBytes());
            byte[] bArr = instance.doFinal(decode);
            String s = new String(bArr);
            System.out.println(s);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}
</code>```

run it and it will output the result "rtmp://wfjsh.sryhm.cn/5showcam/7362473_1636710891?auth_key=1636719851-0-0-85e0853c941754dff7809599215a6076"

But how can I decrypt this enceypted data in Python3?
Here's my python3 code:

```<code>from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
from base64 import b64encode

public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC32VkPYUKYszF665DH0jRuCuyKPqf4pkmcUWXOp8CZkNriew18iLiNGBAtDXhmtdzj6bEaBbxkNixzLfNMtNQw53bfW5lgRC91nG4fiK085sJ8CkdL22PIhRWO75x2pwk+Wqlx5N3OxVV0oS76dI7/pCqTCfqJec7BMH820Im5AwIDAQAB"
encrpted_data_base64 = "qKVan83WWFmVRVASPZ2Io8iM1qs/rowwHH4zh7NNcrh8544hhJr1fKE2PkogAKZWD8mjoO1x4AhRSkrLMsTB0m6V+ZsayLOLiIpCh5hsybaH3NdPKPhMyIqAUdw3au2Zcl76b/4FeNvP9ay/S0niXzQMVBTgHcHhrfjquqQnoXc="

public_key = b64decode(public_key)
public_key = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(public_key)
plaintext = cipher.decrypt(b64decode(encrpted_data_base64), "Error while decrypting")
print(plaintext)
</code>```

Run it and it throws these:

```<code>    plaintext = cipher.decrypt(b64decode(encrpted_data_base64), "Error while decrypting")
  File "C:\Python39\lib\site-packages\Crypto\Cipher\PKCS1_v1_5.py", line 169, in decrypt
    m_int = self._key._decrypt(ct_int)
  File "C:\Python39\lib\site-packages\Crypto\PublicKey\RSA.py", line 156, in _decrypt
    raise TypeError("This is not a private key")
TypeError: This is not a private key
</code>```

I am not sure what's wrong

答: You Can't Decrypt using the public key.</p>

Body:
Here's java code

z.java

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;
import java.util.Base64;

public class z {
    public static void main(String []args) {
        try
        {
            String public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC32VkPYUKYszF665DH0jRuCuyKPqf4pkmcUWXOp8CZkNriew18iLiNGBAtDXhmtdzj6bEaBbxkNixzLfNMtNQw53bfW5lgRC91nG4fiK085sJ8CkdL22PIhRWO75x2pwk+Wqlx5N3OxVV0oS76dI7/pCqTCfqJec7BMH820Im5AwIDAQAB";
            String encrpted_data_base64 = "qKVan83WWFmVRVASPZ2Io8iM1qs/rowwHH4zh7NNcrh8544hhJr1fKE2PkogAKZWD8mjoO1x4AhRSkrLMsTB0m6V+ZsayLOLiIpCh5hsybaH3NdPKPhMyIqAUdw3au2Zcl76b/4FeNvP9ay/S0niXzQMVBTgHcHhrfjquqQnoXc=";

            PublicKey generatePublic = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(Base64.getDecoder().decode(public_key.getBytes())));
            Cipher instance = Cipher.getInstance("RSA/ECB/PKCS1Padding");
            instance.init(2, generatePublic);
            byte[] decode = Base64.getDecoder().decode(encrpted_data_base64.getBytes());
            byte[] bArr = instance.doFinal(decode);
            String s = new String(bArr);
            System.out.println(s);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

run it and it will output the result "rtmp://wfjsh.sryhm.cn/5showcam/7362473_1636710891?auth_key=1636719851-0-0-85e0853c941754dff7809599215a6076"

But how can I decrypt this enceypted data in Python3?
Here's my python3 code:

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from base64 import b64decode
from base64 import b64encode

public_key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC32VkPYUKYszF665DH0jRuCuyKPqf4pkmcUWXOp8CZkNriew18iLiNGBAtDXhmtdzj6bEaBbxkNixzLfNMtNQw53bfW5lgRC91nG4fiK085sJ8CkdL22PIhRWO75x2pwk+Wqlx5N3OxVV0oS76dI7/pCqTCfqJec7BMH820Im5AwIDAQAB"
encrpted_data_base64 = "qKVan83WWFmVRVASPZ2Io8iM1qs/rowwHH4zh7NNcrh8544hhJr1fKE2PkogAKZWD8mjoO1x4AhRSkrLMsTB0m6V+ZsayLOLiIpCh5hsybaH3NdPKPhMyIqAUdw3au2Zcl76b/4FeNvP9ay/S0niXzQMVBTgHcHhrfjquqQnoXc="

public_key = b64decode(public_key)
public_key = RSA.importKey(public_key)
cipher = PKCS1_v1_5.new(public_key)
plaintext = cipher.decrypt(b64decode(encrpted_data_base64), "Error while decrypting")
print(plaintext)

Run it and it throws these:

    plaintext = cipher.decrypt(b64decode(encrpted_data_base64), "Error while decrypting")
  File "C:\Python39\lib\site-packages\Crypto\Cipher\PKCS1_v1_5.py", line 169, in decrypt
    m_int = self._key._decrypt(ct_int)
  File "C:\Python39\lib\site-packages\Crypto\PublicKey\RSA.py", line 156, in _decrypt
    raise TypeError("This is not a private key")
TypeError: This is not a private key

I am not sure what's wrong

Body: You Can't Decrypt using the public key.


来源: stackexchange

问:
using random_split() in python to split the Trainset to train and validation
```<code>train_dataset = torchvision.datasets.FashionMNIST(data_dir, train=True, download=True)
test_dataset  = torchvision.datasets.FashionMNIST(data_dir, train=False, download=True)
</code>```

using two above lines I load the Mnist dataset and then transfered them to Tensor and Dataloader using below lines of code

```<code>tr =transforms.Compose([transforms.ToTensor(),])
train_dataset.transform = tr
test_dataset.transform = tr
train_dataloader = DataLoader(train_dataset, batch_size=256, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=256, shuffle=False)
</code>```

and then by using the for loop such as bellow I iterate over the data and do training model in pytorch.

```<code>for i in train_dataloader:
</code>```

But when I split the training data into two parts using random_split I get error using the for loop

```<code>train_dataset, val_dataset = random_split(train_dataset, (50000, 10000))

train_dataset.transform = tr
test_dataset.transform = tr
val_dataset.transform = tr

train_dataloader = DataLoader(train_dataset, batch_size=256, shuffle=True)
validation_dataloader = DataLoader(val_dataset, batch_size=256, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=256, shuffle=False)
</code>```

The error is:

```<code>default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found <class 'PIL.Image.Image'>
</code>```

How can solve the issue?

答:
You should pass transform to your FashionMNIST dataset's constructor directly.

```<code>train_dataset = torchvision.datasets.FashionMNIST(data_dir, train=True, download=True, transform=tr)
test_dataset  = torchvision.datasets.FashionMNIST(data_dir, train=False, download=True, transform=tr)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
train_dataset = torchvision.datasets.FashionMNIST(data_dir, train=True, download=True)
test_dataset  = torchvision.datasets.FashionMNIST(data_dir, train=False, download=True)

using two above lines I load the Mnist dataset and then transfered them to Tensor and Dataloader using below lines of code

tr =transforms.Compose([transforms.ToTensor(),])
train_dataset.transform = tr
test_dataset.transform = tr
train_dataloader = DataLoader(train_dataset, batch_size=256, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=256, shuffle=False)

and then by using the for loop such as bellow I iterate over the data and do training model in pytorch.

for i in train_dataloader:

But when I split the training data into two parts using random_split I get error using the for loop

train_dataset, val_dataset = random_split(train_dataset, (50000, 10000))

train_dataset.transform = tr
test_dataset.transform = tr
val_dataset.transform = tr

train_dataloader = DataLoader(train_dataset, batch_size=256, shuffle=True)
validation_dataloader = DataLoader(val_dataset, batch_size=256, shuffle=True)
test_dataloader = DataLoader(test_dataset, batch_size=256, shuffle=False)

The error is:

default_collate: batch must contain tensors, numpy arrays, numbers, dicts or lists; found <class 'PIL.Image.Image'>

How can solve the issue?

Body:
You should pass transform to your FashionMNIST dataset's constructor directly.

train_dataset = torchvision.datasets.FashionMNIST(data_dir, train=True, download=True, transform=tr)
test_dataset  = torchvision.datasets.FashionMNIST(data_dir, train=False, download=True, transform=tr)


问:
How to optimize mesh normals calculation?
I am making an application for real time mesh deformation and I need to calculate normals a huge number of times. Now the problem is I found with some profiling this bit of code is taking largest cpu time so how can I possibly optimize this?

```<code>void Mesh::RecalculateNormals()
{
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            const glm::vec3 no = cross(e1, e2);

            vert[ia].normal += glm::vec4(no, 0.0);
            vert[ib].normal += glm::vec4(no, 0.0);
            vert[ic].normal += glm::vec4(no, 0.0);
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}
</code>```

Also before this function is called I must loop through all vertices and clewr the previous normals by setting normals to vec3(0).

How can I speed this up? Could there be a better algorithm? Or is GLM slow?

答:
Though what  Jérôme Richard suggested is way better, implementing all that is way to complex for me as of now. So i tried some basic optimization and now the code is about 5 to 6 times faster !

Here is the new code:

```<code>#define VEC3_SUB(a, b, out) out.x = a.x - b.x; \
                out.y = a.y - b.y; \
                out.z = a.z - b.z;

#define VEC3_ADD(a, b, out) out.x = a.x + b.x; \
                out.y = a.y + b.y; \
                out.z = a.z + b.z;

float inline __declspec (naked) __fastcall asm_sqrt(float n)
{
    _asm fld dword ptr [esp+4]
    _asm fsqrt
    _asm ret 4
}

#define VEC3_NORMALIZE(v, out)  \
{               \
                                 \
    float tempLength = ( (v.x) * (v.x) ) + ( (v.y) * (v.y) ) +( (v.z) * (v.z) ); \
    float lengthSqrauedI = 1.0f / asm_sqrt(tempLength); \
    out.x = (v.x) * lengthSqrauedI;              \
    out.y = (v.y) * lengthSqrauedI;              \
    out.z = (v.z) * lengthSqrauedI;              \
}

#define VEC3_CROSS(a, b, out) \
{                             \
    out.x = ( (a.y) * (b.z) ) - ( (a.z) * (b.y) ); \
    out.y = ( (a.z) * (b.x) ) - ( (a.x) * (b.z) ); \
    out.z = ( (a.x) * (b.y) ) - ( (a.y) * (b.x) ); \
}

void Mesh::RecalculateNormals()
{
        glm::vec3 e1;
        glm::vec3 e2;
        glm::vec3 no;

        int iabc[3];
        for (int i = 0; i < indexCount; i += 3)
        {
            iabc[0] = indices[i];
            iabc[1] = indices[i + 1];
            iabc[2] = indices[i + 2];

            glm::vec4& tmp4a = vert[iabc[0]].position;
            glm::vec4& tmp4b = vert[iabc[1]].position;
            glm::vec4& tmp4c = vert[iabc[2]].position;

            VEC3_SUB(tmp4a, tmp4b, e1);
            VEC3_SUB(tmp4c, tmp4b, e2);

            VEC3_CROSS(e1, e2, no);

            VEC3_ADD(vert[iabc[0]].normal, no, vert[iabc[0]].normal);
            VEC3_ADD(vert[iabc[1]].normal, no, vert[iabc[1]].normal);
            VEC3_ADD(vert[iabc[2]].normal, no, vert[iabc[2]].normal);
        }

        for (int i = 0; i < vertexCount; i++)
        {
            VEC3_NORMALIZE(vert[i].normal, vert[i].normal);
        }

}
</code>```

Body:
I am making an application for real time mesh deformation and I need to calculate normals a huge number of times. Now the problem is I found with some profiling this bit of code is taking largest cpu time so how can I possibly optimize this?

void Mesh::RecalculateNormals()
{
        for (int i = 0; i < indexCount; i += 3)
        {
            const int ia = indices[i];
            const int ib = indices[i + 1];
            const int ic = indices[i + 2];

            const glm::vec3 e1 = glm::vec3(vert[ia].position) - glm::vec3(vert[ib].position);
            const glm::vec3 e2 = glm::vec3(vert[ic].position) - glm::vec3(vert[ib].position);
            const glm::vec3 no = cross(e1, e2);

            vert[ia].normal += glm::vec4(no, 0.0);
            vert[ib].normal += glm::vec4(no, 0.0);
            vert[ic].normal += glm::vec4(no, 0.0);
        }

        for (int i = 0; i < vertexCount; i++)
            vert[i].normal = glm::vec4(glm::normalize(glm::vec3(vert[i].normal)), 0.0f);

}

Also before this function is called I must loop through all vertices and clewr the previous normals by setting normals to vec3(0).

How can I speed this up? Could there be a better algorithm? Or is GLM slow?

Body:
Though what  Jérôme Richard suggested is way better, implementing all that is way to complex for me as of now. So i tried some basic optimization and now the code is about 5 to 6 times faster !

Here is the new code:

#define VEC3_SUB(a, b, out) out.x = a.x - b.x; \
                out.y = a.y - b.y; \
                out.z = a.z - b.z;

#define VEC3_ADD(a, b, out) out.x = a.x + b.x; \
                out.y = a.y + b.y; \
                out.z = a.z + b.z;

float inline __declspec (naked) __fastcall asm_sqrt(float n)
{
    _asm fld dword ptr [esp+4]
    _asm fsqrt
    _asm ret 4
}

#define VEC3_NORMALIZE(v, out)  \
{               \
                                 \
    float tempLength = ( (v.x) * (v.x) ) + ( (v.y) * (v.y) ) +( (v.z) * (v.z) ); \
    float lengthSqrauedI = 1.0f / asm_sqrt(tempLength); \
    out.x = (v.x) * lengthSqrauedI;              \
    out.y = (v.y) * lengthSqrauedI;              \
    out.z = (v.z) * lengthSqrauedI;              \
}

#define VEC3_CROSS(a, b, out) \
{                             \
    out.x = ( (a.y) * (b.z) ) - ( (a.z) * (b.y) ); \
    out.y = ( (a.z) * (b.x) ) - ( (a.x) * (b.z) ); \
    out.z = ( (a.x) * (b.y) ) - ( (a.y) * (b.x) ); \
}

void Mesh::RecalculateNormals()
{
        glm::vec3 e1;
        glm::vec3 e2;
        glm::vec3 no;

        int iabc[3];
        for (int i = 0; i < indexCount; i += 3)
        {
            iabc[0] = indices[i];
            iabc[1] = indices[i + 1];
            iabc[2] = indices[i + 2];

            glm::vec4& tmp4a = vert[iabc[0]].position;
            glm::vec4& tmp4b = vert[iabc[1]].position;
            glm::vec4& tmp4c = vert[iabc[2]].position;

            VEC3_SUB(tmp4a, tmp4b, e1);
            VEC3_SUB(tmp4c, tmp4b, e2);

            VEC3_CROSS(e1, e2, no);

            VEC3_ADD(vert[iabc[0]].normal, no, vert[iabc[0]].normal);
            VEC3_ADD(vert[iabc[1]].normal, no, vert[iabc[1]].normal);
            VEC3_ADD(vert[iabc[2]].normal, no, vert[iabc[2]].normal);
        }

        for (int i = 0; i < vertexCount; i++)
        {
            VEC3_NORMALIZE(vert[i].normal, vert[i].normal);
        }

}


问:
fclose(): Argument #1 ($stream) must be of type resource, bool given
I just restart my laravel 8.0 project and I got this below error, please what could be wrong, this happens anytime I run "PHP artisan serve"</p>
```<code>   TypeError

  fclose(): Argument #1 ($stream) must be of type resource, bool given

  at C:\Users\owner\Laravel-App\test-app\vendor\symfony\process\Pipes\WindowsPip
es.php:74
     70▕                         fclose($this->lockHandles[$pipe]);
     71▕                     }
     72▕                     $this->lockHandles[$pipe] = $h;
     73▕
  ➜  74▕                     if (!fclose(fopen($file, 'w')) || !$h = fopen($file
, 'r')) {
     75▕                         flock($this->lockHandles[$pipe], \LOCK_UN);
     76▕                         fclose($this->lockHandles[$pipe]);
     77▕                         unset($this->lockHandles[$pipe]);
     78▕                         continue 2;
       continue 2;

  1   C:\Users\owner\Laravel-App\test-app\vendor\symfony\process\Pipes\WindowsPi
pes.php:74
      fclose()

  2   C:\Users\owner\Laravel-App\test-app\vendor\symfony\process\Process.php:130
4
      Symfony\Component\Process\Pipes\WindowsPipes::__construct()
</code>```

答:
Don't restart, don't uninstall, don't panic !

If you are on Windows Machine then follow these below step :

Click the Start charm.

Type cmd, right-click the Command Prompt tile, and then click Run as administrator.

Type tasklist /v | find "php" press enter and find the PID of php.exe

Kill the process by taskkill /PID <PID> /F

You are done.

Body:
I just restart my laravel 8.0 project and I got this below error, please what could be wrong, this happens anytime I run "PHP artisan serve"

   TypeError

  fclose(): Argument #1 ($stream) must be of type resource, bool given

  at C:\Users\owner\Laravel-App\test-app\vendor\symfony\process\Pipes\WindowsPip
es.php:74
     70▕                         fclose($this->lockHandles[$pipe]);
     71▕                     }
     72▕                     $this->lockHandles[$pipe] = $h;
     73▕
  ➜  74▕                     if (!fclose(fopen($file, 'w')) || !$h = fopen($file
, 'r')) {
     75▕                         flock($this->lockHandles[$pipe], \LOCK_UN);
     76▕                         fclose($this->lockHandles[$pipe]);
     77▕                         unset($this->lockHandles[$pipe]);
     78▕                         continue 2;
       continue 2;

  1   C:\Users\owner\Laravel-App\test-app\vendor\symfony\process\Pipes\WindowsPi
pes.php:74
      fclose()

  2   C:\Users\owner\Laravel-App\test-app\vendor\symfony\process\Process.php:130
4
      Symfony\Component\Process\Pipes\WindowsPipes::__construct()


问:
Load nib from file path
We might have a need for loading a nib using the results of

```<code>[NSBundle -pathForResource:ofType:inDirectory:forLocalization:]
</code>```

I thought this would be possible, but all the methods I can find only want the name not leading path info.

We are exploring a way to provide both fr-Fr and fr-CA through one code base.  Our client wants a fr-CA translation and we're afraid we might have another customer that wants a fr-Fr translation. I was thinking we could path to correct nib based on the selected language.

Thanks

答:
The path lookup takes into account the user's locale preferences. If you provide the proper localization directories (.lproj), the right nib should be loaded by the system.

Per Apple's documentation:

The method first looks for a matching resource file in the non-localized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics.

Unfortunately, Apple's documentation is self-contradictory and incomplete. If you look at "Internationalization and Programming Topics", section "Language and Locale Designations", you will find under "Language and Locale IDs" this gem:

Important: In iOS, the bundle interfaces do not take dialect or script information into account when looking for localized resources; only the language designator code is considered. Therefore if your project includes language-specific project directories with both a language and region designator, those directories are ignored. The bundle interfaces in Mac OS X do support region designators in language-specific project directories.

This is not entirely true. If you look at Apple's own applications, you will see that iOS does support some region designations, but only the ones Apple cares about. See for example the list of .lproj directories in a recent Mobile Safari:

```<code>$ ls -d *.lproj
Dutch.lproj/    el.lproj/       pt_PT.lproj/
English.lproj/  en_GB.lproj/    ro.lproj/
French.lproj/   fi.lproj/       ru.lproj/
German.lproj/   he.lproj/       sk.lproj/
Italian.lproj/  hr.lproj/       sv.lproj/
Japanese.lproj/ hu.lproj/       th.lproj/
Spanish.lproj/  id.lproj/       tr.lproj/
ar.lproj/       ko.lproj/       uk.lproj/
ca.lproj/       no.lproj/       vi.lproj/
cs.lproj/       pl.lproj/       zh_CN.lproj/
da.lproj/       pt.lproj/       zh_TW.lproj/
</code>```

Notice that two Chinese regions, a British English region, and a Portugal Portuguese region are supported. But none of these solves the problem of fr_CA versus fr_FR.

For that, let's look at MobileSafari again. It must implement its own smart lookup, because it has plenty of more finely distinguished StaticBookmarks-xx_YY.plist files.

So, that's the solution: Use the locale functions that are still available, and do your own lookup accordingly.

ContentLicense: CC BY-SA 3.0

Title: Load nib from file path

Body:
We might have a need for loading a nib using the results of

[NSBundle -pathForResource:ofType:inDirectory:forLocalization:]

I thought this would be possible, but all the methods I can find only want the name not leading path info.

We are exploring a way to provide both fr-Fr and fr-CA through one code base.  Our client wants a fr-CA translation and we're afraid we might have another customer that wants a fr-Fr translation. I was thinking we could path to correct nib based on the selected language.

Thanks

Body:
The path lookup takes into account the user's locale preferences. If you provide the proper localization directories (.lproj), the right nib should be loaded by the system.

Per Apple's documentation:

The method first looks for a matching resource file in the non-localized resource directory of the specified bundle. (In Mac OS X, this directory is typically called Resources but in iOS, it is the main bundle directory.) If a matching resource file is not found, it then looks in the top level of any available language-specific “.lproj” directories. (The search order for the language-specific directories corresponds to the user’s preferences.) It does not recurse through other subdirectories at any of these locations. For more details see Internationalization Programming Topics.

Unfortunately, Apple's documentation is self-contradictory and incomplete. If you look at "Internationalization and Programming Topics", section "Language and Locale Designations", you will find under "Language and Locale IDs" this gem:

Important: In iOS, the bundle interfaces do not take dialect or script information into account when looking for localized resources; only the language designator code is considered. Therefore if your project includes language-specific project directories with both a language and region designator, those directories are ignored. The bundle interfaces in Mac OS X do support region designators in language-specific project directories.

This is not entirely true. If you look at Apple's own applications, you will see that iOS does support some region designations, but only the ones Apple cares about. See for example the list of .lproj directories in a recent Mobile Safari:

$ ls -d *.lproj
Dutch.lproj/    el.lproj/       pt_PT.lproj/
English.lproj/  en_GB.lproj/    ro.lproj/
French.lproj/   fi.lproj/       ru.lproj/
German.lproj/   he.lproj/       sk.lproj/
Italian.lproj/  hr.lproj/       sv.lproj/
Japanese.lproj/ hu.lproj/       th.lproj/
Spanish.lproj/  id.lproj/       tr.lproj/
ar.lproj/       ko.lproj/       uk.lproj/
ca.lproj/       no.lproj/       vi.lproj/
cs.lproj/       pl.lproj/       zh_CN.lproj/
da.lproj/       pt.lproj/       zh_TW.lproj/

Notice that two Chinese regions, a British English region, and a Portugal Portuguese region are supported. But none of these solves the problem of fr_CA versus fr_FR.

For that, let's look at MobileSafari again. It must implement its own smart lookup, because it has plenty of more finely distinguished StaticBookmarks-xx_YY.plist files.

So, that's the solution: Use the locale functions that are still available, and do your own lookup accordingly.


问:
TestFlight React Native Expo crashes on startup
I'm disappointed because I work on an react native application managed with Expo. Up to here, all works fine. My releases with TestFlight works fine but today I face to a new problem. All my builds on TestFlight crashes on startup. At the beginning, I was thinking about an error from me, but when I try to reinstall my old builds (I'm sure they works because I tested it) the application face to the same bug. So, my theory is, my TestFlight release is going to fetch an Apple Server and he can't maybe.. So it crashes... DO you have an idea or do you think Apple is the problem ?

There is my crashes log, I verified it it's the same crashes on my old builds than on my last builds.

```<code>Thread 0 name:
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x00000001b8003334 __pthread_kill + 8
1   libsystem_pthread.dylib         0x00000001d5a89a9c pthread_kill + 272 (pthread.c:1582)
2   libsystem_c.dylib               0x00000001930c5c10 __abort + 128 (abort.c:155)
3   libsystem_c.dylib               0x00000001930c5b90 abort + 136 (abort.c:126)
4   libc++abi.dylib                 0x000000019e8e9bb8 abort_message + 132 (abort_message.cpp:78)
5   libc++abi.dylib                 0x000000019e8daec8 demangling_terminate_handler() + 308 (cxa_default_handlers.cpp:67)
6   libobjc.A.dylib                 0x000000019e7e705c _objc_terminate() + 144 (objc-exception.mm:701)
7   libc++abi.dylib                 0x000000019e8e8fa0 std::__terminate(void (*)()) + 20 (cxa_handlers.cpp:59)
8   libc++abi.dylib                 0x000000019e8e8f2c std::terminate() + 48 (cxa_handlers.cpp:88)
9   libdispatch.dylib               0x00000001898eb830 _dispatch_client_callout + 40 (object.m:562)
10  libdispatch.dylib               0x00000001898fa9ec _dispatch_async_and_wait_invoke + 96 (queue.c:1545)
11  libdispatch.dylib               0x00000001898eb81c _dispatch_client_callout + 20 (object.m:559)
12  libdispatch.dylib               0x00000001898f9c70 _dispatch_main_queue_callback_4CF + 884 (inline_internal.h:2557)
13  CoreFoundation                  0x0000000189c78340 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1790)
14  CoreFoundation                  0x0000000189c72218 __CFRunLoopRun + 2524 (CFRunLoop.c:3118)
15  CoreFoundation                  0x0000000189c71308 CFRunLoopRunSpecific + 600 (CFRunLoop.c:3242)
16  GraphicsServices                0x00000001a12f4734 GSEventRunModal + 164 (GSEvent.c:2259)
17  UIKitCore                       0x000000018c6ef75c -[UIApplication _run] + 1072 (UIApplication.m:3269)
18  UIKitCore                       0x000000018c6f4fcc UIApplicationMain + 168 (UIApplication.m:4740)
19  ComMlDevSpiritApp               0x0000000100259e78 main + 88 (main.m:8)
20  libdyld.dylib                   0x000000018992dcf8 start + 4
</code>```

https://pastebin.com/JbyrRwQQ

答: Run expo build:android or expo build:ios instead of using eas. You can still use eas submit.

Body:
I'm disappointed because I work on an react native application managed with Expo. Up to here, all works fine. My releases with TestFlight works fine but today I face to a new problem. All my builds on TestFlight crashes on startup. At the beginning, I was thinking about an error from me, but when I try to reinstall my old builds (I'm sure they works because I tested it) the application face to the same bug. So, my theory is, my TestFlight release is going to fetch an Apple Server and he can't maybe.. So it crashes... DO you have an idea or do you think Apple is the problem ?

There is my crashes log, I verified it it's the same crashes on my old builds than on my last builds.

Thread 0 name:
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x00000001b8003334 __pthread_kill + 8
1   libsystem_pthread.dylib         0x00000001d5a89a9c pthread_kill + 272 (pthread.c:1582)
2   libsystem_c.dylib               0x00000001930c5c10 __abort + 128 (abort.c:155)
3   libsystem_c.dylib               0x00000001930c5b90 abort + 136 (abort.c:126)
4   libc++abi.dylib                 0x000000019e8e9bb8 abort_message + 132 (abort_message.cpp:78)
5   libc++abi.dylib                 0x000000019e8daec8 demangling_terminate_handler() + 308 (cxa_default_handlers.cpp:67)
6   libobjc.A.dylib                 0x000000019e7e705c _objc_terminate() + 144 (objc-exception.mm:701)
7   libc++abi.dylib                 0x000000019e8e8fa0 std::__terminate(void (*)()) + 20 (cxa_handlers.cpp:59)
8   libc++abi.dylib                 0x000000019e8e8f2c std::terminate() + 48 (cxa_handlers.cpp:88)
9   libdispatch.dylib               0x00000001898eb830 _dispatch_client_callout + 40 (object.m:562)
10  libdispatch.dylib               0x00000001898fa9ec _dispatch_async_and_wait_invoke + 96 (queue.c:1545)
11  libdispatch.dylib               0x00000001898eb81c _dispatch_client_callout + 20 (object.m:559)
12  libdispatch.dylib               0x00000001898f9c70 _dispatch_main_queue_callback_4CF + 884 (inline_internal.h:2557)
13  CoreFoundation                  0x0000000189c78340 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 (CFRunLoop.c:1790)
14  CoreFoundation                  0x0000000189c72218 __CFRunLoopRun + 2524 (CFRunLoop.c:3118)
15  CoreFoundation                  0x0000000189c71308 CFRunLoopRunSpecific + 600 (CFRunLoop.c:3242)
16  GraphicsServices                0x00000001a12f4734 GSEventRunModal + 164 (GSEvent.c:2259)
17  UIKitCore                       0x000000018c6ef75c -[UIApplication _run] + 1072 (UIApplication.m:3269)
18  UIKitCore                       0x000000018c6f4fcc UIApplicationMain + 168 (UIApplication.m:4740)
19  ComMlDevSpiritApp               0x0000000100259e78 main + 88 (main.m:8)
20  libdyld.dylib                   0x000000018992dcf8 start + 4

https://pastebin.com/JbyrRwQQ


问:
Subsetting a dataframe in R by retaining first occurrences of unique elements from all columns
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

```<code>df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))
</code>```

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this

答:
Another possible solution, based on dplyr and purrr::map_dfc:

library(tidyverse)

df <- data.frame(
  Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
  category1 = c("a", "", "b", "a", ""),
  category2 = c("c", "", "", "d", "c"),
  category3 = c("", "", "e", "f", "f"),
  category4 = c("", "", "", "", ""),
  category5 = c("i", "", "i", "j", ""))

df %>%
  map_dfc(~ if_else(duplicated(.x), "", .x)) %>%
  filter(rowSums(. == "") != 5)

#> # A tibble: 3 × 6
#>   Hits  category1 category2 category3 category4 category5
#>   <chr> <chr>     <chr>     <chr>     <chr>     <chr>
#> 1 Hit1  "a"       "c"       ""        ""        "i"
#> 2 Hit3  "b"       ""        "e"       ""        ""
#> 3 Hit4  ""        "d"       "f"       ""        "j"
```

Body:
df is a test dataframe which has 5 rows and 6 columns and it is a subset of a much larger dataframe (dimensions: 1000000 X 30).

df <- data.frame(
 Hits = c("Hit1", "Hit2", "Hit3", "Hit4", "Hit5"),
 category1 = c("a", "", "b", "a", ""),
 category2 = c("c", "", "", "d", "c"),
 category3 = c("", "", "e", "f", "f"),
 category4 = c("", "", "", "", ""),
 category5 = c("i", "", "i", "j", ""))

df looks like this

For each column from category1 to category5 I need to retain only the first occurrences of all the unique elements. e.g. For category1, the unique elements are a and b and their first occurrences are in rows 1 and 3 respectively. So rows 1 and 3 should be retained, and so on. The output should look something like this


问:
XLWings Throwing Error on quit after a copy
When running xlwings 0.26.1 (latest for Anaconda 3.83) or 0.10.0 (using for compatibility reasons) with the latest version of Office 365 Excel, I get an error after moving a sheet when running app.quit():

```<code>import xlwings as xw
import pythoncom

pythoncom.CoInitialize()
app = xw.apps.add()
app.display_alerts = False
app.screen_updating = False

wbSource = app.books.open('pathSourceTemp')
wsSource = wbSource.sheets['sourceSheet']
wbDestination = app.books.open('pathDestinationTemp')
wsDestination = None

#Grabs first sheet in destination
wsDestination = wbDestination.sheets[0]

#Copy sheet "before" destination sheet (which should be 1 sheet after the destination sheet)
wsSource.api.Copy(Before=wsDestination.api)
wbDestination.save()

#Close workbooks and app
wbDestination.close()
wbSource.close()
app.screen_updating = True
app.quit()
</code>```

The final line causes Excel to throw an error that I have to click out of for the process to continue.

答:
Since version 0.24.3, the idiomatic way is using with xw.App() as app.
The advantage of this is that there won't be any hidden excel processes left over in the background, if you use a hidden instance (visible=False) and your code fails.

```<code>import xlwings as xw

# You could also omit .screen_updating (and .display_alerts)
# and use xw.App(visible=False) instead, if appropriate.
with xw.App() as app:
    app.display_alerts = False
    app.screen_updating = False

    wbSource = xw.Book()
    wbDestination = xw.Book()

    # Do your stuff here.

    app.screen_updating = True
    # Save as needed, for example: wbDestination.save()
    wbSource.close()
    wbDestination.close()
</code>```

Body:
When running xlwings 0.26.1 (latest for Anaconda 3.83) or 0.10.0 (using for compatibility reasons) with the latest version of Office 365 Excel, I get an error after moving a sheet when running app.quit():

import xlwings as xw
import pythoncom

pythoncom.CoInitialize()
app = xw.apps.add()
app.display_alerts = False
app.screen_updating = False

wbSource = app.books.open('pathSourceTemp')
wsSource = wbSource.sheets['sourceSheet']
wbDestination = app.books.open('pathDestinationTemp')
wsDestination = None

#Grabs first sheet in destination
wsDestination = wbDestination.sheets[0]

#Copy sheet "before" destination sheet (which should be 1 sheet after the destination sheet)
wsSource.api.Copy(Before=wsDestination.api)
wbDestination.save()

#Close workbooks and app
wbDestination.close()
wbSource.close()
app.screen_updating = True
app.quit()

The final line causes Excel to throw an error that I have to click out of for the process to continue.

Body:
Since version 0.24.3, the idiomatic way is using with xw.App() as app.
The advantage of this is that there won't be any hidden excel processes left over in the background, if you use a hidden instance (visible=False) and your code fails.

import xlwings as xw

# You could also omit .screen_updating (and .display_alerts)
# and use xw.App(visible=False) instead, if appropriate.
with xw.App() as app:
    app.display_alerts = False
    app.screen_updating = False

    wbSource = xw.Book()
    wbDestination = xw.Book()

    # Do your stuff here.

    app.screen_updating = True
    # Save as needed, for example: wbDestination.save()
    wbSource.close()
    wbDestination.close()


问:
Creating vector based on whether dataframe values are divisible by ten
```<code>library(babynames)
</code>```

I am looking to make a vector of all decade marker years AKA years in the babynames package that are divisible by 10.

```<code>range(babynames$year)
</code>```

told me the years in the set are 1880-2017 and I made the following solution

```<code>c(seq(from=1880,to=2017,10))
</code>```

However if the range of babynames did not begin on a number that ended with 10 this example would not work. So now I am looking to find a solution that finds all the decade markers (1890,1900,1910...) between numbers if the first is for ex. 1881

I expect this is possible by checking whether the year between 1881-2017 is divisible by 10 resulting in an integer, and if it is, listing it. How do I do this?

Something like this pseudo code

```<code>for (i in 1881:2017) {
  if (is.integer(i/10)==TRUE)
  c(i)

</code>```

答:
Using the modulo operator %% which gives the remainder of a division you could do:

library(babynames)

years <- sort(unique(babynames$year))
years[years %% 10 == 0]
#>  [1] 1880 1890 1900 1910 1920 1930 1940 1950 1960 1970 1980 1990 2000 2010
```

Body:
library(babynames)

I am looking to make a vector of all decade marker years AKA years in the babynames package that are divisible by 10.

range(babynames$year)

told me the years in the set are 1880-2017 and I made the following solution

c(seq(from=1880,to=2017,10))

However if the range of babynames did not begin on a number that ended with 10 this example would not work. So now I am looking to find a solution that finds all the decade markers (1890,1900,1910...) between numbers if the first is for ex. 1881

I expect this is possible by checking whether the year between 1881-2017 is divisible by 10 resulting in an integer, and if it is, listing it. How do I do this?

Something like this pseudo code

for (i in 1881:2017) {
  if (is.integer(i/10)==TRUE)
  c(i)


问:
Text won't start in the top left of Text Box
I have an input description box with a fixed height and width and its own style. The text is centred but I want it to start in the top left.

HTML

```<code><input id="eventDescriptionInput" placeholder="Description" />
</code>```

CSS

```<code>#eventDescriptionInput {
padding: 10px;
width: 100%;
height: 200px;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;[enter image description here][1]
box-shadow: 0px 0px 3px gray;
}
</code>```

答:
I am not sure if you only wanted it to be done with input tag or any other tag is acceptable as long as the style is remained.

I would suggest to use  to make things more simple.

#eventDescriptionInput {
padding: 10px;
width: 100%;
height: 200px;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;
box-shadow: 0px 0px 3px gray;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
</head>
<body>
<textarea id="eventDescriptionInput" placeholder="Description"></textarea>
</body>
</html></code>```

Body:
I have an input description box with a fixed height and width and its own style. The text is centred but I want it to start in the top left.

HTML

<input id="eventDescriptionInput" placeholder="Description" />

CSS

#eventDescriptionInput {
padding: 10px;
width: 100%;
height: 200px;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;[enter image description here][1]
box-shadow: 0px 0px 3px gray;
}

Body:
I am not sure if you only wanted it to be done with input tag or any other tag is acceptable as long as the style is remained.

I would suggest to use  to make things more simple.

#eventDescriptionInput {
padding: 10px;
width: 100%;
height: 200px;
box-sizing: border-box;
margin-bottom: 25px;
border-radius: 3px;
outline: none;
border: none;
box-shadow: 0px 0px 3px gray;
}

<html>
<head>
</head>
<body>
<textarea id="eventDescriptionInput" placeholder="Description"></textarea>
</body>
</html>


问:
What is the point of itertools.count and itertools.islice?
I've looked at a online courses, and they have examples like the following:

```<code>from itertools import count

# creates a count iterator object
iterator =(count(start = 0, step = 2))

# prints an even list of integers
print("Even list:",
      list(next(iterator) for _ in range(5)))
</code>```

... which you could write using range or np.arange. Here's another example:

```<code># list containing some strings
my_list =["x", "y", "z"]

# count spits out integers for
# each value in my list
for i in zip(count(start = 1, step = 1), my_list):
    print(i)
</code>```

... which is basically just enumerate. So my question is: can you give an example of itertools.count and itertools.islice that can't be done (or has to be done much more clunkily) using range?

答:
Here's a situation where the count instance is used sporadically, not immediately in a single loop.

```<code>class Foo:
    _x = count()  # Infinite supply of unique integer values

    def __init__(self):
        self._id = f'Foo #{next(self._x)}'
</code>```

Here's a case where islice is used to prevent O(n) memory usage:

```<code>def is_sorted(some_list):
    return all(i <= j for i, j in zip(some_list, islice(some_list, 1, None)))
</code>```

If you had written that instead as

```<code>def is_sorted(some_list):
    return all(i <= j for i, j in zip(some_list, some_list[1:]))
</code>```

you would have had to make nearly a full copy of some_list before even testing the first pair, which is a huge waste with a large list like [2, 1] + [3] * 10000.

Neither one is necessary, in the sense that each is trivially definable:

```<code>def count(start=0, step=1):
    while True:
        yield start
        start += step

# A more accurate translation would be more complicated than necessary for our purposes here.
# The real version would have to be able to handle stop=None
# and choose 1 and -1 as default values for step, depending
# on whether stop is less than or greater than start.
def islice(itr, start, stop, step):
    for _ in range(start):
        next(itr)

    while start < stop:
        yield next(itr)
        start += step
</code>```

Body:
I've looked at a online courses, and they have examples like the following:

from itertools import count

# creates a count iterator object
iterator =(count(start = 0, step = 2))

# prints an even list of integers
print("Even list:",
      list(next(iterator) for _ in range(5)))

... which you could write using range or np.arange. Here's another example:

# list containing some strings
my_list =["x", "y", "z"]

# count spits out integers for
# each value in my list
for i in zip(count(start = 1, step = 1), my_list):
    print(i)

... which is basically just enumerate. So my question is: can you give an example of itertools.count and itertools.islice that can't be done (or has to be done much more clunkily) using range?

Body:
Here's a situation where the count instance is used sporadically, not immediately in a single loop.

class Foo:
    _x = count()  # Infinite supply of unique integer values

    def __init__(self):
        self._id = f'Foo #{next(self._x)}'

Here's a case where islice is used to prevent O(n) memory usage:

def is_sorted(some_list):
    return all(i <= j for i, j in zip(some_list, islice(some_list, 1, None)))

If you had written that instead as

def is_sorted(some_list):
    return all(i <= j for i, j in zip(some_list, some_list[1:]))

you would have had to make nearly a full copy of some_list before even testing the first pair, which is a huge waste with a large list like [2, 1] + [3] * 10000.

Neither one is necessary, in the sense that each is trivially definable:

def count(start=0, step=1):
    while True:
        yield start
        start += step

# A more accurate translation would be more complicated than necessary for our purposes here.
# The real version would have to be able to handle stop=None
# and choose 1 and -1 as default values for step, depending
# on whether stop is less than or greater than start.
def islice(itr, start, stop, step):
    for _ in range(start):
        next(itr)

    while start < stop:
        yield next(itr)
        start += step


问:
Is "for each" Microsoft specific?
Visual C++ 2010 accepts:

```<code>std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for each (auto i in v)
    std::cout << i << std::endl;
</code>```

Is this a C++11 feature or a Microsoft extension? According to Wikipedia, the syntax of C++11's for-each loop different:

```<code>int myint[] = {1,2,3,4,5};
for (int& i: myint)
{
    std::cout << i;
}
</code>```

答:
I'd also like to note a caveat of Microsoft's "for each" loop; using STL containers such as std::vector, you cannot pass variables by reference, only by value and const reference. For example:

```<code>int myarr [] = {4, 6, 8, 10, 12, 15};
std::vector<int> mvt (myarr, myarr+6);

for each (int & x in mvt) //will not compile for reasons unbeknownst to those outside MS
   x+= 4;
</code>```

If your compiler supports C++0x range-based for I'd use that instead.  If not, I would use BOOST_FOREACH or std::for_each with a function object or lambda as these are portable. Whatever you do, stay clear from Microsoft's "for each".

Title: Is "for each" Microsoft specific?

Body:
Visual C++ 2010 accepts:

std::vector<int> v;
v.push_back(1);
v.push_back(2);
v.push_back(3);
for each (auto i in v)
    std::cout << i << std::endl;

Is this a C++11 feature or a Microsoft extension? According to Wikipedia, the syntax of C++11's for-each loop different:

int myint[] = {1,2,3,4,5};
for (int& i: myint)
{
    std::cout << i;
}

LastEditorDisplayName: Roger Pate

Body:
I'd also like to note a caveat of Microsoft's "for each" loop; using STL containers such as std::vector, you cannot pass variables by reference, only by value and const reference. For example:

int myarr [] = {4, 6, 8, 10, 12, 15};
std::vector<int> mvt (myarr, myarr+6);

for each (int & x in mvt) //will not compile for reasons unbeknownst to those outside MS
   x+= 4;

If your compiler supports C++0x range-based for I'd use that instead.  If not, I would use BOOST_FOREACH or std::for_each with a function object or lambda as these are portable. Whatever you do, stay clear from Microsoft's "for each".


问:
How to disable default error response for Api Versioning
Good evening, everybody. Trying to implement Api Versioning for my project. Faced with the problem that receiving default errors template response for request. Look code 1

```<code>{
    "error": {
        "code": "UnsupportedApiVersion",
        "message": "The HTTP resource that matches the request URI 'https://localhost:5003/v2.3' does not support the API version '2.3'.",
        "innerError": null
    }
}
</code>```

But I have my own error response template that want to receive.

```<code>{
"traceId": "0HMF1NONVN8SF:00000002",
    "errors": [
        {
            "message": "",
            "source": ""
        }
    ]
}
</code>```

As I understand I could implement my own ErrorResponseProvider, but could I avoid doing that?

How could I can disable ErrorResponse for ApiVersionOptions?
My api version configuration:

```<code> services
   .AddApiVersioning(opt =>
                {
                    opt.ApiVersionReader = new UrlSegmentApiVersionReader();
                    opt.UseApiBehavior = false;
                    opt.DefaultApiVersion = ApiVersion.Default;
                    opt.AssumeDefaultVersionWhenUnspecified = true;
                })
                .AddVersionedApiExplorer(opt =>
                {
                    opt.GroupNameFormat = "'v'VV";
                    opt.SubstituteApiVersionInUrl = true;
                });
</code>```

Versions:

.NET 6

ASP.NET Core 6

Microsoft.AspNetCore.Mvc.Versioning 5

答:
Actually I didn't find the way to disable it. However, I found the solution for my case. First of all, I implemented my CustomErrorResponseProvider for ErrorResponses.

```<code> public class CustomErrorResponseProvider : DefaultErrorResponseProvider
    {
        public override IActionResult CreateResponse(ErrorResponseContext context)
        {
            switch (context.ErrorCode)
            {
                case "UnsupportedApiVersion":
                    throw new UnsupportedApiVersionException("Url", context.Message);
            }

            return base.CreateResponse(context);
        }
    }
</code>```

Than started throw necessary exception from it. And that's all!

As my middleware looks like this(img below), my ErrorHandlingMiddleware didn't catch an exception, because it was generated by default api versioning error handler.

Body:
Good evening, everybody. Trying to implement Api Versioning for my project. Faced with the problem that receiving default errors template response for request. Look code 1

{
    "error": {
        "code": "UnsupportedApiVersion",
        "message": "The HTTP resource that matches the request URI 'https://localhost:5003/v2.3' does not support the API version '2.3'.",
        "innerError": null
    }
}

But I have my own error response template that want to receive.

{
"traceId": "0HMF1NONVN8SF:00000002",
    "errors": [
        {
            "message": "",
            "source": ""
        }
    ]
}

As I understand I could implement my own ErrorResponseProvider, but could I avoid doing that?

How could I can disable ErrorResponse for ApiVersionOptions?
My api version configuration:

 services
   .AddApiVersioning(opt =>
                {
                    opt.ApiVersionReader = new UrlSegmentApiVersionReader();
                    opt.UseApiBehavior = false;
                    opt.DefaultApiVersion = ApiVersion.Default;
                    opt.AssumeDefaultVersionWhenUnspecified = true;
                })
                .AddVersionedApiExplorer(opt =>
                {
                    opt.GroupNameFormat = "'v'VV";
                    opt.SubstituteApiVersionInUrl = true;
                });

Versions:

.NET 6

ASP.NET Core 6

Microsoft.AspNetCore.Mvc.Versioning 5

Body:
Actually I didn't find the way to disable it. However, I found the solution for my case. First of all, I implemented my CustomErrorResponseProvider for ErrorResponses.

 public class CustomErrorResponseProvider : DefaultErrorResponseProvider
    {
        public override IActionResult CreateResponse(ErrorResponseContext context)
        {
            switch (context.ErrorCode)
            {
                case "UnsupportedApiVersion":
                    throw new UnsupportedApiVersionException("Url", context.Message);
            }

            return base.CreateResponse(context);
        }
    }

Than started throw necessary exception from it. And that's all!

As my middleware looks like this(img below), my ErrorHandlingMiddleware didn't catch an exception, because it was generated by default api versioning error handler.