问:
if else in loop bringing up errors in typescript
I have this function that is supposed to get referral codes from users. User gives a code and the referral code checked if it exists in the database then evaluated if

it does not match the current user, so that one should not refer himself and

it is a match with one of the codes in the database

This code however just does not find a match even if the code given is in the database. If the referral code matches the one of the current user, it works correctly and points that out i.e one cannot refer themselves.

But if the referral code is a match to that of another user which is how a referral system should work, it still says no match.

How can I remove this error

```<code>export const getID = functions.https.onCall(async(data, context) => {
  const db = admin.firestore();
  const usersSnapshot = await db.collection("user").get();
  const allUIDs = usersSnapshot.docs.map(doc => doc.data().userID);

  const userID = context.auth.uid;
  const providedID = "cNx7IuY6rZlR9mYSfb1hY7ROFY2";

 //db.collection("user").doc(providedID).collection("referrals").doc(userID);

  await check();

  function check() {
    let result;
    allUIDs.forEach(idFromDb => {
      if (providedID === idFromDb && (idFromDb === userID)) {
        result = "ownmatch";
      } else if (providedID === idFromDb && (idFromDb !== userID)) {
        result = "match";
      } else {
        result = "nomatch";
      }
    });
    return result;
  }

  if (check() === "match") {
    return {
      message: `Match Found`,
    };
  } else if (check() === "ownmatch") {
    return {
      message: `Sorry, you can't use your own invite code`,
    };
  } else {
    return {
      message: `No User with that ID`
    };
  }
});
</code>```

答:
(This is not an answer, but a simple refactoring.)

This is what your code is currently doing (roughly, I didn't run it):

```<code>const resultMsgs = {
  nomatch:  'No User With That ID',
  ownmatch: 'Sorry, you can\'t use your own invite code',
  match:    'Match Found',
}

function check(uids, providedId, userId) {
  let result

  uids.forEach(idFromDb => {
    if (providedId !== idFromDb) {
      result = 'nomatch'
      return
    }

    if (userID === idFromDb) {
      result = 'ownmatch'
      return
    }

    result = 'match'
  })

  return result
}

export const getID = functions
  .https
  .onCall(async (data, context) => {
    const userId     = context.auth.uid
    const providedId = 'cNx7IuY6rZlR9mYSfb1hY7ROFY2'

    const db   = admin.firestore()
    const user = await db.collection('user').get()
    const uids = user.docs.map(doc => doc.data().userId)

    const checkResult = check(uids, providedId, userId)
    return { message: resultMsgs[checkResult] }
  })
</code>```

(I removed the seemingly-spurious db collection operation.)

Your forEach is iterating over all of the uuids, but result will be set to whatever the last comparison was. Perhaps this is correct, but:

If you're looking for any match, this is not what you want.

If you're looking for all matches, this is not what you want.

If you're looking to match the last UUID, it's what you want, but an odd way to go about it.

So:

If you want any matches, use... ahem any form of an any function.

If you want all matches, use any form of an all function.

If you want the first match, then just check the first element.

If you want the complete set of comparisons then you'll need to use map instead of forEach, and handle each result appropriately, whatever that means in your case.

In any event, I'd recommend breaking up your code more cleanly. It'll be much easier to reason about, and fix.

Body:
I have this function that is supposed to get referral codes from users. User gives a code and the referral code checked if it exists in the database then evaluated if

it does not match the current user, so that one should not refer himself and

it is a match with one of the codes in the database

This code however just does not find a match even if the code given is in the database. If the referral code matches the one of the current user, it works correctly and points that out i.e one cannot refer themselves.

But if the referral code is a match to that of another user which is how a referral system should work, it still says no match.

How can I remove this error

export const getID = functions.https.onCall(async(data, context) => {
  const db = admin.firestore();
  const usersSnapshot = await db.collection("user").get();
  const allUIDs = usersSnapshot.docs.map(doc => doc.data().userID);

  const userID = context.auth.uid;
  const providedID = "cNx7IuY6rZlR9mYSfb1hY7ROFY2";

 //db.collection("user").doc(providedID).collection("referrals").doc(userID);

  await check();

  function check() {
    let result;
    allUIDs.forEach(idFromDb => {
      if (providedID === idFromDb && (idFromDb === userID)) {
        result = "ownmatch";
      } else if (providedID === idFromDb && (idFromDb !== userID)) {
        result = "match";
      } else {
        result = "nomatch";
      }
    });
    return result;
  }

  if (check() === "match") {
    return {
      message: `Match Found`,
    };
  } else if (check() === "ownmatch") {
    return {
      message: `Sorry, you can't use your own invite code`,
    };
  } else {
    return {
      message: `No User with that ID`
    };
  }
});

Body:
(This is not an answer, but a simple refactoring.)

This is what your code is currently doing (roughly, I didn't run it):

const resultMsgs = {
  nomatch:  'No User With That ID',
  ownmatch: 'Sorry, you can\'t use your own invite code',
  match:    'Match Found',
}

function check(uids, providedId, userId) {
  let result

  uids.forEach(idFromDb => {
    if (providedId !== idFromDb) {
      result = 'nomatch'
      return
    }

    if (userID === idFromDb) {
      result = 'ownmatch'
      return
    }

    result = 'match'
  })

  return result
}

export const getID = functions
  .https
  .onCall(async (data, context) => {
    const userId     = context.auth.uid
    const providedId = 'cNx7IuY6rZlR9mYSfb1hY7ROFY2'

    const db   = admin.firestore()
    const user = await db.collection('user').get()
    const uids = user.docs.map(doc => doc.data().userId)

    const checkResult = check(uids, providedId, userId)
    return { message: resultMsgs[checkResult] }
  })

(I removed the seemingly-spurious db collection operation.)

Your forEach is iterating over all of the uuids, but result will be set to whatever the last comparison was. Perhaps this is correct, but:

If you're looking for any match, this is not what you want.

If you're looking for all matches, this is not what you want.

If you're looking to match the last UUID, it's what you want, but an odd way to go about it.

So:

If you want any matches, use... ahem any form of an any function.

If you want all matches, use any form of an all function.

If you want the first match, then just check the first element.

If you want the complete set of comparisons then you'll need to use map instead of forEach, and handle each result appropriately, whatever that means in your case.

In any event, I'd recommend breaking up your code more cleanly. It'll be much easier to reason about, and fix.


来源: stackexchange

问:
problem with managed query
I'm trying to write application, which lists all mp3 files from sd card.

```<code>String[] columns = new String[] {
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.TITLE_KEY,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ARTIST_ID,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.TRACK
    };

    String uristr_t = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.getPath();
    Cursor musicCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                columns, null, null, null);

    if(musicCursor != null){
        mSongs = new ArrayList<SongInfo>( musicCursor.getCount());
        boolean isMediaFilesExist = musicCursor.moveToFirst();
                ...
</code>```

There are some mp3-files on the sd card but musicCursor.GetCount() returns 0. I suppose that path is incorrect. EXTERNAL_CONTENT_URI is content://media/external/audio/media and its path is:

```<code>/external/audio/media
</code>```

but my sd card's path is:

```<code> /mnt/sdcard
</code>```

And I've tried to set Uri manually:

```<code>String uriStr = "content://" + Environment.getExternalStorageDirectory().getPath();
Uri sdCardUri = Uri.parse(uriStr);
Cursor musicCursor = managedQuery(sdCardUri, columns, null, null, null);
</code>```

In that case Uri is content:///mnt/sdcard, but musicCursor is null after managedQuery. Maybe format of uriStr is incorrect and Uri initialization is wrong?
Thanks!

答:
Your code is correct. The path /external/audio/media is the content provider path not the path int the actual filesystem.
Are you sure you have MP3 files on the card? Check in the music app you can see files. If you can't in there, I sometimes find (especially on the emulator) that the indexing doesn't always run. Force the SD to get reindexed of all media by unmounting the SD card and remounting (Settings/SD card & phone storage/Unmount SD card).</p>

ContentLicense: CC BY-SA 3.0

Title: problem with managed query

Body:
I'm trying to write application, which lists all mp3 files from sd card.

String[] columns = new String[] {
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.TITLE_KEY,
            MediaStore.Audio.Media.DATA,
            MediaStore.Audio.Media.ALBUM,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.ARTIST_ID,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.TRACK
    };

    String uristr_t = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI.getPath();
    Cursor musicCursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                columns, null, null, null);

    if(musicCursor != null){
        mSongs = new ArrayList<SongInfo>( musicCursor.getCount());
        boolean isMediaFilesExist = musicCursor.moveToFirst();
                ...

There are some mp3-files on the sd card but musicCursor.GetCount() returns 0. I suppose that path is incorrect. EXTERNAL_CONTENT_URI is content://media/external/audio/media and its path is:

/external/audio/media

but my sd card's path is:

 /mnt/sdcard

And I've tried to set Uri manually:

String uriStr = "content://" + Environment.getExternalStorageDirectory().getPath();
Uri sdCardUri = Uri.parse(uriStr);
Cursor musicCursor = managedQuery(sdCardUri, columns, null, null, null);

In that case Uri is content:///mnt/sdcard, but musicCursor is null after managedQuery. Maybe format of uriStr is incorrect and Uri initialization is wrong?
Thanks!


问:
Function "fread()" not reading specific file types?
I have this snip of code in order to load some files into memory, into data .

There are three files in the same path that I would like to read: an XML, a PNG and a TTF font file. All three are successfully open and its size shown in size. Unfortunatelly, only the XML and PNG are read into data.

The TTF file gets the correct size, the equally proper result of fread, but an empty (not null) data and empty fp->_base.

```<code>  char* data;
  size_t size = 0;
  FILE *fp = fopen(completeFilePath, "rb");
  if (fp != NULL) {
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    data = new char[size];
    size_t result = fread(data, sizeof(char), size, fp);
    fclose(fp);
  }
</code>```

Could you bring some light into this problem?

Greatly appreciated.

答: The null byte doesn't magically mean the end of anything it's found in. It's just a convention used by a lot of C standard library functions. It's perfectly valid for a file to contain a null byte and then have more characters after. This is exactly what's in your data: a null byte and then more characters. So it's not actually empty; you're just incorrectly assuming that it is.

ContentLicense: CC BY-SA 4.0

Body:
I have this snip of code in order to load some files into memory, into data .

There are three files in the same path that I would like to read: an XML, a PNG and a TTF font file. All three are successfully open and its size shown in size. Unfortunatelly, only the XML and PNG are read into data.

The TTF file gets the correct size, the equally proper result of fread, but an empty (not null) data and empty fp->_base.

  char* data;
  size_t size = 0;
  FILE *fp = fopen(completeFilePath, "rb");
  if (fp != NULL) {
    fseek(fp, 0, SEEK_END);
    size = ftell(fp);
    fseek(fp, 0, SEEK_SET);
    data = new char[size];
    size_t result = fread(data, sizeof(char), size, fp);
    fclose(fp);
  }

Could you bring some light into this problem?

Greatly appreciated.


问:
Matplotlib savefig cuts off pyplot table
I want to make some summarizing visualization + statistics of a data column.
I want to combine two or more subplots with a descriptive table and save the figure locally.
However, when saving the plot, a part of the table gets cropped.

When I do the following

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

column=np.random.normal(size=10000)
df=pd.DataFrame(column, columns=["Price"])

summary = (
        df.describe()
        .append((df.isnull().sum()/len(df)*100)
        .rename('nans %'))
        .iloc[:,0].to_frame()
        )
fig, (ax_distplot) = plt.subplots(1, 1, figsize=(25, 12))

#Distplot with summarizing table
sns.distplot(df.loc[:,"Price"], hist=True, bins=30, kde=False, ax=ax_distplot)
ax_distplot.set(ylabel='Count')
tab = ax_distplot.table(cellText=np.around(summary.values, decimals=2),
                        rowLabels=summary.index,
                        colLabels=summary.columns, loc="right",
                        bbox=[1.15, .2, 0.25, 0.8])

</code>```

I get:

When saving it locally with the following command

```<code>plt.savefig("Price.pdf", bbox_inches="tight")
</code>```

Yields:

I have tried

```<code>plt.subplots_adjust(right=0.85)
</code>```

without any luck.

答:
One workaround is to add some pad around the figure. I tried and pad_inches=1 works well in your example

```<code>plt.savefig("Price.pdf", bbox_inches="tight", pad_inches=1)
</code>```

Body:
I want to make some summarizing visualization + statistics of a data column.
I want to combine two or more subplots with a descriptive table and save the figure locally.
However, when saving the plot, a part of the table gets cropped.

When I do the following

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

column=np.random.normal(size=10000)
df=pd.DataFrame(column, columns=["Price"])

summary = (
        df.describe()
        .append((df.isnull().sum()/len(df)*100)
        .rename('nans %'))
        .iloc[:,0].to_frame()
        )
fig, (ax_distplot) = plt.subplots(1, 1, figsize=(25, 12))

#Distplot with summarizing table
sns.distplot(df.loc[:,"Price"], hist=True, bins=30, kde=False, ax=ax_distplot)
ax_distplot.set(ylabel='Count')
tab = ax_distplot.table(cellText=np.around(summary.values, decimals=2),
                        rowLabels=summary.index,
                        colLabels=summary.columns, loc="right",
                        bbox=[1.15, .2, 0.25, 0.8])

I get:

When saving it locally with the following command

plt.savefig("Price.pdf", bbox_inches="tight")

Yields:

I have tried

plt.subplots_adjust(right=0.85)

without any luck.

Body:
One workaround is to add some pad around the figure. I tried and pad_inches=1 works well in your example

plt.savefig("Price.pdf", bbox_inches="tight", pad_inches=1)


问:
Does 'SELECT FOR UPDATE' work in pg-promise task?
I want to do SELECT .. FOR UPDATE  to lock a row in a table so it can be updated in a atomic way, as concurrent request of the same type could happen.

I've been doing some testing but its not clear FOR UPDATE works in a pg-promise.task. I'm trying to avoid using a pg-promise.tx as that would require more logic and possibly recursion, both of which I want to avoid as the use case will be high throughput.

Update:
After more research and testing, I've found that using a task with SELECT .. FOR UPDATE is giving me an unexpected result. Explanation of code below.

```<code>submitUserOnline:(pgdb, u_uuid, socketConnectionList, user_websock) =>{
  return new Promise((resolve,reject) =>{
// pgdb.tx({mode} t => {
   pgdb.task( t => {
    return t.one('SELECT * FROM users WHERE user_uuid = $1', [u_uuid]
    .then(user =>{
// nothing happens here right now, but may in future, including for completeness. May cancel request based off some comparisons.
     return t.any('SELECT * FROM users_online WHERE user_uuid = $1 FOR UPDATE',[u_uuid]
     .then(result =>{
      if(result.length > 0){
        console.error('duplicate connection found ' + user_websock.uuid);
        if(socketConnectionList[result[0].web_sock_uuid] !== undefined){
          console.error('drop connection' + result[0].web_sock_uuid);
          socketConnectionList[result[0].web_sock_uuid].wsc.close(4020, 'USER_RECONN');
        }
        console.error('duplicate connection found - update next ' + user_websock.uuid);
        return t.none('UPDATE users_online SET web_sock_uuid = $1 WHERE user_uuid = $2', [user_websock, u_uuid])
        .then(res =>{
          console.error('UPDATE res: ' + res);
        })
        .catch(err =>{
          console.error('UPDATE err: ' + err);});

       }else{
         // not reached in test case
         console.error('no duplicate found ' + user_websock.uuid);
         return t.none(INSERT INTO  users_online.....ect ect
       }
      });
   })
   .then(res =>{
     console.error('>>>task/tx res: ' + res);
     resolve({msg: "OK"});
   })
   .catch(err =>{
     console.error('>>>task/tx err: ' + err);
     if(err.code ==== '40001'){// recursion for when called as 'tx'
       console.error('>>>task/tx err - call recurse');
       module.exports.submitUserOnline(pgdb, u_uuid, socketConnectionList, user_websock)
       .then(res =>{
         console.error('>>>task/tx err - call recurse - res ' + res);
         resolve({msg: "OK"});
        })
        .catch( err =>{
          console.error('>>>task/tx err - call recurse - err: ' + err);
          reject({msg:"FAILED"});
        });
     }
    });
  });
}
</code>```

```<code>const mode = new TransactionMode({
    tiLevel: isolationLevel.serializable,
    readOnly: false,
    deferrable: true
});
</code>```

submitUserOnline is called by a websocket handler. In my test case I have an 10 element array(same user_uuid) which triggers all client connections in a for loop. Basically its making the connections to the server websocket, that socket checks the users_online table for the specific user, if that user is already in the table, kill the stale connection and update the web_sock_uuid in the table, this is where the issues comes in(sometimes it works sometimes not, one run of 10 concurrent connections shows the issue). When the user row web_sock_uuid is UPDATE'ed, the other concurrent connections seem to block properly on the SELECT .. FOR UPDATE(SLFU), when the UPDATE executes, then() doesnt always run before the next SLFU is released. This seems to present it self in the form of the pending SLFU returning the old web_sock_uuid of the row before the prior UPDATE. In one instance the same stale 'web_sock_uuid' was returned 4 times in a row.

If I switch from the task method to the tx method, which requires the recursive calling, the above code works as expected, although it does require many recersions.

答:
The pg-promise tasks are simply shared connections. They do not create transactions implicitly.

To use locks in Postgres, you need to create transactions, since all locks created in a transaction are released at the end of the transaction. If you do not create transactions explicitly, each query will be its own separate transaction.

Of course, you do not have to use the tx method. You could use task, and manage the transaction yourself.

Body:
I want to do SELECT .. FOR UPDATE  to lock a row in a table so it can be updated in a atomic way, as concurrent request of the same type could happen.

I've been doing some testing but its not clear FOR UPDATE works in a pg-promise.task. I'm trying to avoid using a pg-promise.tx as that would require more logic and possibly recursion, both of which I want to avoid as the use case will be high throughput.

Update:
After more research and testing, I've found that using a task with SELECT .. FOR UPDATE is giving me an unexpected result. Explanation of code below.

submitUserOnline:(pgdb, u_uuid, socketConnectionList, user_websock) =>{
  return new Promise((resolve,reject) =>{
// pgdb.tx({mode} t => {
   pgdb.task( t => {
    return t.one('SELECT * FROM users WHERE user_uuid = $1', [u_uuid]
    .then(user =>{
// nothing happens here right now, but may in future, including for completeness. May cancel request based off some comparisons.
     return t.any('SELECT * FROM users_online WHERE user_uuid = $1 FOR UPDATE',[u_uuid]
     .then(result =>{
      if(result.length > 0){
        console.error('duplicate connection found ' + user_websock.uuid);
        if(socketConnectionList[result[0].web_sock_uuid] !== undefined){
          console.error('drop connection' + result[0].web_sock_uuid);
          socketConnectionList[result[0].web_sock_uuid].wsc.close(4020, 'USER_RECONN');
        }
        console.error('duplicate connection found - update next ' + user_websock.uuid);
        return t.none('UPDATE users_online SET web_sock_uuid = $1 WHERE user_uuid = $2', [user_websock, u_uuid])
        .then(res =>{
          console.error('UPDATE res: ' + res);
        })
        .catch(err =>{
          console.error('UPDATE err: ' + err);});

       }else{
         // not reached in test case
         console.error('no duplicate found ' + user_websock.uuid);
         return t.none(INSERT INTO  users_online.....ect ect
       }
      });
   })
   .then(res =>{
     console.error('>>>task/tx res: ' + res);
     resolve({msg: "OK"});
   })
   .catch(err =>{
     console.error('>>>task/tx err: ' + err);
     if(err.code ==== '40001'){// recursion for when called as 'tx'
       console.error('>>>task/tx err - call recurse');
       module.exports.submitUserOnline(pgdb, u_uuid, socketConnectionList, user_websock)
       .then(res =>{
         console.error('>>>task/tx err - call recurse - res ' + res);
         resolve({msg: "OK"});
        })
        .catch( err =>{
          console.error('>>>task/tx err - call recurse - err: ' + err);
          reject({msg:"FAILED"});
        });
     }
    });
  });
}

const mode = new TransactionMode({
    tiLevel: isolationLevel.serializable,
    readOnly: false,
    deferrable: true
});

submitUserOnline is called by a websocket handler. In my test case I have an 10 element array(same user_uuid) which triggers all client connections in a for loop. Basically its making the connections to the server websocket, that socket checks the users_online table for the specific user, if that user is already in the table, kill the stale connection and update the web_sock_uuid in the table, this is where the issues comes in(sometimes it works sometimes not, one run of 10 concurrent connections shows the issue). When the user row web_sock_uuid is UPDATE'ed, the other concurrent connections seem to block properly on the SELECT .. FOR UPDATE(SLFU), when the UPDATE executes, then() doesnt always run before the next SLFU is released. This seems to present it self in the form of the pending SLFU returning the old web_sock_uuid of the row before the prior UPDATE. In one instance the same stale 'web_sock_uuid' was returned 4 times in a row.

If I switch from the task method to the tx method, which requires the recursive calling, the above code works as expected, although it does require many recersions.


问:
dynamically loading django apps at runtime
Is it possible to dynamically load Django apps at runtime? Usually, apps are loaded at initialization, using the INSTALLED_APPS tuple in settings.py. However, is it possible to load additional apps at runtime? I am encountering this issue in different situations. One situation, for example, arises during testing, when I would like to dynamically load or unload apps.

In order to make the problem more concrete, imagine I have a directory called apps where I put my apps and I would like to automatically install any new app that goes in there without manually editing the settings.py.

This is easy enough. Following the example code in

Django: Dynamically add apps as plugin, building urls and other settings automatically

we put the following code in settings.py to could loop over the names of all sub-directories in the app directory and increment the INSTALLED_APPS tuple in settings.py like this:

```<code>APPS_DIR = '/path_to/apps/'

for item in os.listdir(APPS_DIR):
    if os.path.isdir(os.path.join(APPS_DIR, item)):
        app_name = 'apps.%s' % item
    if app_name not in INSTALLED_APPS:
        INSTALLED_APPS += (app_name, )
</code>```

After that, if I was in a Django shell, I could something like

```<code>from django.conf import settings
</code>```

and the apps would be listed in settings.INSTALLED_APPS. And if I did

```<code>from django.core import management
management.call_command('syncdb', interactive=False)
</code>```

that would create the necessary DB tables for the apps.

However, if I were to now add some more apps to the apps/ directory, without re-starting, these would not be listed in settings.INSTALLED_APPS, and so a subsequent call to the syncdb would have no effect.

What I would like to know is if there is something I could do --- without restarting --- to reload the settings and load/install new apps.

I have tried to directly import my settings.py, i.e.
from myproject import settings

and then reload that settings using the python builtin after any app directory changes. Although settings.INSTALLED_APPS is now changed to include the newly added apps, this ultimately makes no difference. For example,

```<code>from django.db import models
models.get_apps()
</code>```

shows only the original apps in apps and not the newly added ones and likewise

```<code>management.call_command('syncdb', interactive=False)
</code>```

will not see the newly added apps.

As I stated above, I am thinking about this situation particularly in the context of testings where I dynamically would add or remove apps.

Ps. I working with Django 1.6, but on the advice of @RickyA, I see that there are some substantial changes to Django's treatment of applications in 1.7

https://docs.djangoproject.com/en/1.7/ref/applications/

I'm still not sure what this might mean for the problem I am facing.

答:
Yes! Anything (or almost everything) in Python is possible. You should use os.walk() in order to get all folders, subfolders and files within your apps path in order to get all of your apps including the nested ones.</p>

```<code>def get_installed_apps():
    from os import walk, chdir, getcwd
    previous_path = getcwd()
    master = []
    APPS_ROOT_PATH = '/my/project/apps/folder'
    chdir(APPS_ROOT_PATH)
    for root, directories, files in walk(top=getcwd(), topdown=False):
        for file in files:
            if 'apps.py' in file:
                app_path = f"{root.replace(BASE_DIR + '/', '').replace('/', '.')}.apps"
                print(app_path)
                master.append(app_path)
    chdir(previous_path)
    return master

print(get_installed_apps())
</code>```

Body:
Is it possible to dynamically load Django apps at runtime? Usually, apps are loaded at initialization, using the INSTALLED_APPS tuple in settings.py. However, is it possible to load additional apps at runtime? I am encountering this issue in different situations. One situation, for example, arises during testing, when I would like to dynamically load or unload apps.

In order to make the problem more concrete, imagine I have a directory called apps where I put my apps and I would like to automatically install any new app that goes in there without manually editing the settings.py.

This is easy enough. Following the example code in

Django: Dynamically add apps as plugin, building urls and other settings automatically

we put the following code in settings.py to could loop over the names of all sub-directories in the app directory and increment the INSTALLED_APPS tuple in settings.py like this:

APPS_DIR = '/path_to/apps/'

for item in os.listdir(APPS_DIR):
    if os.path.isdir(os.path.join(APPS_DIR, item)):
        app_name = 'apps.%s' % item
    if app_name not in INSTALLED_APPS:
        INSTALLED_APPS += (app_name, )

After that, if I was in a Django shell, I could something like

from django.conf import settings

and the apps would be listed in settings.INSTALLED_APPS. And if I did

from django.core import management
management.call_command('syncdb', interactive=False)

that would create the necessary DB tables for the apps.

However, if I were to now add some more apps to the apps/ directory, without re-starting, these would not be listed in settings.INSTALLED_APPS, and so a subsequent call to the syncdb would have no effect.

What I would like to know is if there is something I could do --- without restarting --- to reload the settings and load/install new apps.

I have tried to directly import my settings.py, i.e.
from myproject import settings

and then reload that settings using the python builtin after any app directory changes. Although settings.INSTALLED_APPS is now changed to include the newly added apps, this ultimately makes no difference. For example,

from django.db import models
models.get_apps()

shows only the original apps in apps and not the newly added ones and likewise

management.call_command('syncdb', interactive=False)

will not see the newly added apps.

As I stated above, I am thinking about this situation particularly in the context of testings where I dynamically would add or remove apps.

Ps. I working with Django 1.6, but on the advice of @RickyA, I see that there are some substantial changes to Django's treatment of applications in 1.7

https://docs.djangoproject.com/en/1.7/ref/applications/

I'm still not sure what this might mean for the problem I am facing.

Body:
Yes! Anything (or almost everything) in Python is possible. You should use os.walk() in order to get all folders, subfolders and files within your apps path in order to get all of your apps including the nested ones.

def get_installed_apps():
    from os import walk, chdir, getcwd
    previous_path = getcwd()
    master = []
    APPS_ROOT_PATH = '/my/project/apps/folder'
    chdir(APPS_ROOT_PATH)
    for root, directories, files in walk(top=getcwd(), topdown=False):
        for file in files:
            if 'apps.py' in file:
                app_path = f"{root.replace(BASE_DIR + '/', '').replace('/', '.')}.apps"
                print(app_path)
                master.append(app_path)
    chdir(previous_path)
    return master

print(get_installed_apps())


问:
Struggling with input validation/check constraint
I'm trying to create a table with an email address column and want to make sure that only addresses in the correct format (contains "@") are allowed. I know how to use the LIKE operator in queries but not how to put a value constraint on a column.

答:
You can add the check constraint like this  For your basic example:

```<code>alter table t add contraint chk_email
    (check (email like '%@%') );
</code>```

Of course, that is really only a betting.  Perhaps something more like this:

```<code>alter table t add contraint chk_email
    (check (email like '%_@[^.]%' and               -- one @ and something before and after
            email not like '%@%@%' and         -- not more than one @
            email not like '%[^-.a-zA-Z0-9_]%'  -- valid characters)
    );
</code>```

This still will allow invalid emails, but it is at least closer.

Body:
You can add the check constraint like this  For your basic example:

alter table t add contraint chk_email
    (check (email like '%@%') );

Of course, that is really only a betting.  Perhaps something more like this:

alter table t add contraint chk_email
    (check (email like '%_@[^.]%' and               -- one @ and something before and after
            email not like '%@%@%' and         -- not more than one @
            email not like '%[^-.a-zA-Z0-9_]%'  -- valid characters)
    );

This still will allow invalid emails, but it is at least closer.


问:
Ordering a bar chart labels in dc.js (again)
I know there are a lot of questions on that specific subject on SO but none of the solutions seem to work in my case.

This is my data :

```<code>var theData = [{
  "value": "190.79",
  "age_days": "22",
  "criteria": "FX"
}, {
  "value": "18.43",
  "age_days": "22",
  "criteria": "FX"
}, {...}]
</code>```

I put the data into buckets as such :

```<code>var getAge = (d) => {
  if ((d.age_days) <= 7) {
    return (["1w", "2w", "1m", "3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 14) {
    return (["2w", "1m", "3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 30) {
    return (["1m", "3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 90) {
    return (["3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 180) {
    return (["6m", "1y", "All"]);
  } else if ((d.age_days) <= 360) {
    return (["1y", "All"]);
  } else {
    return (["All"]);
  }
};

var ndx = crossfilter(theData);
var dims = {};
var groups = {};

dims.age = ndx.dimension(getAge,true);
groups.age = {};
groups.age.valueSum = dims.age.group().reduceSum((d) => d.value);
</code>```

I then try to order the group using the fake group approach :

```<code>var sort_group = (source_group, order) => {
    return {
        all: () => {
            let g = source_group.all();
            let map = {};
            g.forEach(function (kv) {
                map[kv.key] = kv.value;
            });
            return order
                .filter((k) => map.hasOwnProperty(k))
                .map((k) => {
                    return {key: k, value: map[k]}
                });
        }
    };
};
var the_order = ["1w", "2w", "1m", "3m", "6m", "1y", "All"];
var the_sorted_age_group = sort_group(groups.age.valueSum, the_order);
</code>```

then I create the barChart using

```<code>theAgeChart
  .height(200)
  .width(400)
  .dimension(dims.age)
  .group(the_sorted_age_group)
  .valueAccessor((d) => d.value)
  .x(d3.scaleBand())
  .xUnits(dc.units.ordinal);
</code>```

But it still comes out using the default sort :

I've created a jsFiddle here which contains everything.

How can I get my bars sorted as I want them to be sorted ?

答:
When elasticX is true or the x scale domain is not set, the coordinate grid mixin will generate the X domain

```<code>        if (_chart.elasticX() || _x.domain().length === 0) {
            _x.domain(_chart._ordinalXDomain());
        }
</code>```

(source)

That totally makes sense, but it always sorts the domain when it generates it:

```<code>_chart._ordinalXDomain = function () {
    var groups = _chart._computeOrderedGroups(_chart.data());
    return groups.map(_chart.keyAccessor());
};
</code>```

(source)

I guess we could consider not sorting the domain when ordering is null.

Anyway, one workaround is to set the domain yourself:

```<code>.x(d3.scaleBand().domain(the_order))
</code>```

You don't need to sort the group for a bar chart. (For a line chart, the group order must agree with the scale domain, but it doesn't matter for the bar chart.)

With the domain set, this also works:

```<code>.group(groups.age.valueSum)
</code>```

Fork of your fiddle.

I guess the moral of the story is that it's complicated to generate charts automatically. Most of the time one does want the X domain sorted, but what's the best way to allow the user to provide their own sort?

I would not say this is the best way, but there is a way to make it work.

Body:
I know there are a lot of questions on that specific subject on SO but none of the solutions seem to work in my case.

This is my data :

var theData = [{
  "value": "190.79",
  "age_days": "22",
  "criteria": "FX"
}, {
  "value": "18.43",
  "age_days": "22",
  "criteria": "FX"
}, {...}]

I put the data into buckets as such :

var getAge = (d) => {
  if ((d.age_days) <= 7) {
    return (["1w", "2w", "1m", "3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 14) {
    return (["2w", "1m", "3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 30) {
    return (["1m", "3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 90) {
    return (["3m", "6m", "1y", "All"]);
  } else if ((d.age_days) <= 180) {
    return (["6m", "1y", "All"]);
  } else if ((d.age_days) <= 360) {
    return (["1y", "All"]);
  } else {
    return (["All"]);
  }
};

var ndx = crossfilter(theData);
var dims = {};
var groups = {};

dims.age = ndx.dimension(getAge,true);
groups.age = {};
groups.age.valueSum = dims.age.group().reduceSum((d) => d.value);

I then try to order the group using the fake group approach :

var sort_group = (source_group, order) => {
    return {
        all: () => {
            let g = source_group.all();
            let map = {};
            g.forEach(function (kv) {
                map[kv.key] = kv.value;
            });
            return order
                .filter((k) => map.hasOwnProperty(k))
                .map((k) => {
                    return {key: k, value: map[k]}
                });
        }
    };
};
var the_order = ["1w", "2w", "1m", "3m", "6m", "1y", "All"];
var the_sorted_age_group = sort_group(groups.age.valueSum, the_order);

then I create the barChart using

theAgeChart
  .height(200)
  .width(400)
  .dimension(dims.age)
  .group(the_sorted_age_group)
  .valueAccessor((d) => d.value)
  .x(d3.scaleBand())
  .xUnits(dc.units.ordinal);

But it still comes out using the default sort :

I've created a jsFiddle here which contains everything.

How can I get my bars sorted as I want them to be sorted ?

Body:
When elasticX is true or the x scale domain is not set, the coordinate grid mixin will generate the X domain

        if (_chart.elasticX() || _x.domain().length === 0) {
            _x.domain(_chart._ordinalXDomain());
        }

(source)

That totally makes sense, but it always sorts the domain when it generates it:

_chart._ordinalXDomain = function () {
    var groups = _chart._computeOrderedGroups(_chart.data());
    return groups.map(_chart.keyAccessor());
};

(source)

I guess we could consider not sorting the domain when ordering is null.

Anyway, one workaround is to set the domain yourself:

.x(d3.scaleBand().domain(the_order))

You don't need to sort the group for a bar chart. (For a line chart, the group order must agree with the scale domain, but it doesn't matter for the bar chart.)

With the domain set, this also works:

.group(groups.age.valueSum)

Fork of your fiddle.

I guess the moral of the story is that it's complicated to generate charts automatically. Most of the time one does want the X domain sorted, but what's the best way to allow the user to provide their own sort?

I would not say this is the best way, but there is a way to make it work.


问:
Register Application With Zapier
I am developing an application from where users can create zaps and later those zaps can be searched in Zapier if I will connect my application from Zapier.

Now question is how to get the  Integration Key that can be used when connecting to Zapier  by clicking "Connect an Account"

after this how I can search for the zaps that I created in my application?
do I need to use any api to create those zaps in zapier?

答:
David here, from the Zapier Platform team.

If you add a private app to Zapier, you'll be able to use it for your zaps immediately. If you want others to use it, you'll want to go through the process describe here, where you invite users, submit for activation, etc.

We have a few guides to get you going:

UI Quickstart

CLI Quickstart

Title: Register Application With Zapier


问:
Program not working as well - C
The following code gives me a zero value for 'count' all the time...

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}
</code>```

Thanks !

答:
Replace

```<code>int const count = 0;
</code>```

with

```<code>int count = 0;
</code>```

Your are trying to change a variable (count++) declared const which, obviously, is not allowed.

EDIT: The answer to your updated question is that you should change the loop condition from string[i] == '\0' to string[i] != '\0'. This is because the loop runs while the condition is true. string[i] != '\0' is true for the whole string except the terminating null byte while the opposite is true for string[i] == '\0'. Therefore, your original loop didn't run a single time.

Title: Program not working as well - C

Body:
The following code gives me a zero value for 'count' all the time...

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZE 128

int main ()

{
    char mychar , string [SIZE];
    int i;
    int count =0 ;

    printf ("Please enter your string: \n\n");
    fgets (string, SIZE, stdin);

    printf ("Please enter char to find: ");
    mychar = getchar();

    for (i=0 ; (string[i] == '\0') ; i++ )
        if ( string[i]  == mychar )
            count++;

    printf ("The char %c appears %d times" ,mychar ,count);

    return 0;
}

Thanks !

Body:
Replace

int const count = 0;

with

int count = 0;

Your are trying to change a variable (count++) declared const which, obviously, is not allowed.

EDIT: The answer to your updated question is that you should change the loop condition from string[i] == '\0' to string[i] != '\0'. This is because the loop runs while the condition is true. string[i] != '\0' is true for the whole string except the terminating null byte while the opposite is true for string[i] == '\0'. Therefore, your original loop didn't run a single time.


问:
How to apply a method to a Pandas Dataframe
I have this dataframe

```<code>   Col1              Col2

0  A (1000 EUR)  C ( 3000 USD)

1  B (2000 CHF)  D ( 4000 GBP)
</code>```

I would like to convert it to

```<code>   Col1  Col2

0  1000  3000

1  2000  4000
</code>```

I know how to create a dataframe (with indexes) for 1 column, but not for multiple columns

This code produces this result

```<code>   Col1

0  1000

1  2000

a = z['Col1'].str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce')
</code>```

how can I amend the code above to also add col2 (ideally using vectorisation rather than iteration) (so ideally I wouln't want to have to enter the same code for every column)

答:
You could use str.extract on each column and use pd.concat to build a new dataframe from the result:

```<code>x = np.concatenate([df[col].str.extract(r'(?<=\()\s*(\d+)') for col in df], axis=1)
pd.DataFrame(x, columns=df.columns)

   Col1  Col2
0  1000  3000
1  2000  4000
</code>```

Body:
I have this dataframe

   Col1              Col2

0  A (1000 EUR)  C ( 3000 USD)

1  B (2000 CHF)  D ( 4000 GBP)

I would like to convert it to

   Col1  Col2

0  1000  3000

1  2000  4000

I know how to create a dataframe (with indexes) for 1 column, but not for multiple columns

This code produces this result

   Col1

0  1000

1  2000

a = z['Col1'].str.split('(').str[-1].str.split().str[0].apply(pd.to_numeric,errors='coerce')

how can I amend the code above to also add col2 (ideally using vectorisation rather than iteration) (so ideally I wouln't want to have to enter the same code for every column)

Body:
You could use str.extract on each column and use pd.concat to build a new dataframe from the result:

x = np.concatenate([df[col].str.extract(r'(?<=\()\s*(\d+)') for col in df], axis=1)
pd.DataFrame(x, columns=df.columns)

   Col1  Col2
0  1000  3000
1  2000  4000


问:
How can I stop input with newline character
I am reading a list of numbers separated by spaces. Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\n') character. </p>

```<code>    int numArrayCount = 0;
    int num, count = 0;
    int binaryArray[CAPACITY];
    int numArray[CAPACITY];

    //takes in positive numbers higher than zero and less than 64.
    //End output with Ctrl+Z

    while (scanf_s( "%d", &num ) == 1) {
        if (num < 64 && num > 0) {
            binaryArray[ count++ ] = base10ToBinary(num);
            numArray[ numArrayCount++ ] = num;
        }
    }
</code>```

答:
```<code>while (scanf_s(" %d", &num) == 1) {
</code>```

Insert a space before the %d as  it will make the scanf function disregard the input that was leftover from whatever was left in stdin and you won't need that getchar() anymore.

Body:
I am reading a list of numbers separated by spaces. Currently the loop stops when I press Ctrl + Z. I just need to know how to modify the loop to terminate when I hit enter or if it meets the newline('\n') character.

    int numArrayCount = 0;
    int num, count = 0;
    int binaryArray[CAPACITY];
    int numArray[CAPACITY];

    //takes in positive numbers higher than zero and less than 64.
    //End output with Ctrl+Z

    while (scanf_s( "%d", &num ) == 1) {
        if (num < 64 && num > 0) {
            binaryArray[ count++ ] = base10ToBinary(num);
            numArray[ numArrayCount++ ] = num;
        }
    }

Body:
while (scanf_s(" %d", &num) == 1) {

Insert a space before the %d as  it will make the scanf function disregard the input that was leftover from whatever was left in stdin and you won't need that getchar() anymore.


问:
Could not load type Castle.Proxies.IReadinessProxy when running xUnit integration tests in parallel with Autofac
I am having an issue that I've been many days unable to resolve.
I use xUnit with a given-then-when abstraction to make tests more readable.

I am using a wrapper over EventStore and running some integration tests. They all go well.. except one that fails when running all in parallel (and xUnit runs in parallel), but if I run them all sequentially they all succeed.

I cannot understand why this would be an issue because every single fact is supposed to run the constructor (the given) and the functionality to test (the when). And in each fact I instantiate an Autofac ContainerBuilder, build the container and resolve its IComponentContext, so in theory every test should be isoalted and idempotent as intended.

This is the exception I keep receiving:

```<code>Autofac.Core.DependencyResolutionException : An exception was thrown while activating SalesOrder.EventStore.Infra.EventStore.EventStore -> SalesOrder.EventStore.Infra.EventStore.DomainEventsRetriever -> SalesOrder.EventStore.Infra.EventStore.Factories.DomainEventFactory -> λ:SalesOrder.EventStore.Infra.EventStore.EventTypeResolver.
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Castle.Proxies.IReadinessProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 136
   at Autofac.Core.Resolving.InstanceLookup.Execute() in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 85
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 130
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 83
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 1041
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 871
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 300
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore.When() in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests\EventStoreExtensionsTests\ResolveTests.cs:line 53
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore..ctor()
----- Inner Stack Trace -----
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeModule.GetTypes()
   at System.Reflection.Assembly.GetTypes()
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c.<RegisterResolvers>b__6_2(Assembly s) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 174
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at SalesOrder.EventStore.Infra.EventStore.Factories.EventTypeResolverFactory.Create(IEnumerable`1 existingTypes, IReadOnlyDictionary`2 domainEventSerializerDeserializers) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore\Factories\EventTypeResolverFactory.cs:line 16
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c__DisplayClass6_0.<RegisterResolvers>b__1(IComponentContext context) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 180
   at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass0_0`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p) in C:\projects\autofac\src\Autofac\Builder\RegistrationBuilder.cs:line 62
   at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Activators\Delegate\DelegateActivator.cs:line 71
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 118
</code>```

This is the test with only one Fact that fails when running in parallel with others:

```<code>public class Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore
    : Given_When_Then_Test
{
    private IEventStore _sut;
    private IComponentContext _componentContext;

    protected override void Given()
    {
        var builder = new ContainerBuilder();
        builder
            .RegisterEventStore(
                ctx =>
                {
                    var eventStoreOptions =
                        new EventStoreOptions
                        {
                            Url = EventStoreTestConstants.TestUrl,
                            Port = EventStoreTestConstants.TestPort
                        };
                    return eventStoreOptions;
                },
                ctx =>
                {
                    var readinessOptions =
                        new ReadinessOptions
                        {
                            Timeout = EventStoreTestConstants.TestTimeout
                        };
                    return readinessOptions;
                });

        var container = builder.Build();
        _componentContext = container.Resolve<IComponentContext>();
    }

    protected override void When()
    {
        _sut = _componentContext.Resolve<IEventStore>();
    }

    [Fact]
    public void Then_It_Should_Not_Be_Null()
    {
        _sut.Should().NotBeNull();
    }
}
</code>```

Any clue what may be happening here?
I've had a look at Autofac's guidelines on concurrency: https://autofaccn.readthedocs.io/en/latest/advanced/concurrency.html but I think I am already using properly the component context.

UPDATE 1: FYI this is the GivenThenWhen template I use. But nothing very special here (I think!)

```<code>namespace ToolBelt.TestSupport
{
    public abstract class Given_When_Then_Test
        : IDisposable
    {
        protected Given_When_Then_Test()
        {
            Setup();
        }

        private void Setup()
        {
            Given();
            When();
        }

        protected abstract void Given();

        protected abstract void When();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }

    public abstract class Given_WhenAsync_Then_Test
        : IDisposable
    {
        protected Given_WhenAsync_Then_Test()
        {
            Task.Run(async () => { await SetupAsync(); }).GetAwaiter().GetResult();
        }

        private async Task SetupAsync()
        {
            Given();
            await WhenAsync();
        }

        protected abstract void Given();

        protected abstract Task WhenAsync();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }
}
</code>```

UPDATE 2: And this is the IoCC Autofac registration's method I am using for my implementation and all the tests. A bit complex because I use reflection to keep the EventStore wrapper fully generic, but just in case somebody sees something funky there that might affect the tests..

```<code>public static class EventStoreExtensions
{
    public static void RegisterEventStore(
        this ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever = null)
    {
        RegisterEventStoreConnection(builder, optionsRetriever);
        RegisterFactories(builder);
        RegisterEventStoreManager(builder);
        RegisterConverters(builder);
        RegisterResolvers(builder, customDomainEventMappersOptionsRetriever);
        RegisterEventStoreServices(builder);
        RegisterEventStoreReadinessCheck(builder, readinessOptionsRetriever);
    }

    private static void RegisterEventStoreReadinessCheck(
        ContainerBuilder builder,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var readinessOptions = readinessOptionsRetriever.Invoke(ctx);

                var timeout = readinessOptions.Timeout;
                var eventStoreConnection = context.Resolve<IEventStoreConnection>();

                var eventStoreReadiness =
                    new EventStoreReadiness(
                        eventStoreConnection,
                        timeout);

                return eventStoreReadiness;

            })
            .As<IEventStoreReadiness>()
            .As<IReadiness>()
            .SingleInstance();
    }

    private static void RegisterEventStoreConnection(
        ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var eventStoreOptions = optionsRetriever.Invoke(ctx);

                ConnectionSettings connectionSetting =
                    ConnectionSettings
                        .Create()
                        .KeepReconnecting();

                var urlString = eventStoreOptions.Url;
                var port = eventStoreOptions.Port;
                var ipAddress = IPAddress.Parse(urlString);
                var tcpEndPoint = new IPEndPoint(ipAddress, port);

                var eventStoreConnection = EventStoreConnection.Create(connectionSetting, tcpEndPoint);
                return eventStoreConnection;
            })
            .As<IEventStoreConnection>()
            .SingleInstance();
    }

    private static void RegisterFactories(
        ContainerBuilder builder)
    {
        builder
            .RegisterType<DomainEventFactory>()
            .As<IDomainEventFactory>()
            .SingleInstance();

        builder
            .RegisterType<EventDataFactory>()
            .As<IEventDataFactory>()
            .SingleInstance();

        builder
            .RegisterType<ExpectedVersionFactory>()
            .As<IExpectedVersionFactory>()
            .SingleInstance();

        builder
            .RegisterType<IdFactory>()
            .As<IIdFactory>()
            .SingleInstance();

        builder
            .RegisterType<StreamNameFactory>()
            .As<IStreamNameFactory>()
            .SingleInstance();

        builder
            .RegisterType<RetrievedEventFactory>()
            .As<IRetrievedEventFactory>()
            .SingleInstance();
    }

    private static void RegisterEventStoreManager(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreManager>()
            .As<IEventStoreManager>()
            .SingleInstance();
    }

    private static void RegisterConverters(ContainerBuilder builder)
    {
        builder
            .Register(context =>
            {
                var utf8Encoding = new BytesConverter(Encoding.UTF8);
                return utf8Encoding;
            })
            .As<IBytesConverter>()
            .SingleInstance();

        builder
            .RegisterType<NewtonsoftConverter>()
            .As<IJsonConverter>()
            .SingleInstance();
    }

    private static void RegisterResolvers(
        ContainerBuilder builder,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var mapperResolver = MapperResolverFactory.Create(domainEventSerializerDeserializers);
                return mapperResolver;
            })
            .As<IMapperResolver>()
            .SingleInstance();

        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();

                var assembliesLoaded = AppDomain.CurrentDomain.GetAssemblies();
                var domainEventTypes =
                    assembliesLoaded
                        .SelectMany(s => s.GetTypes())
                        .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                    && x.IsClass);
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var typeResolver =
                    EventTypeResolverFactory.Create(
                        domainEventTypes,
                        domainEventSerializerDeserializers);
                return typeResolver;
            })
            .As<IEventTypeResolver>()
            .SingleInstance();
    }

    private static void RegisterEventStoreServices(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreRepository>()
            .As<IEventStoreRepository>();

        builder
            .RegisterType<DomainEventsPersister>()
            .As<IDomainEventsPersister>();

        builder
            .RegisterType<DomainEventsRetriever>()
            .As<IDomainEventsRetriever>();

        builder
            .RegisterType<EventStore>()
            .As<IEventStore>();
    }
}
</code>```

UPDATE 3: This is the whole repository in case somebody is bored and wants to try to reproduce it. It is a generic event store wrapper used for event sourcing implemented for Greg Young's Event Store product using the official C# driver.

https://gitlab.com/DiegoDrivenDesign/DiDrDe.EventStore

Funnily enough, this issue seems to disappear every once in a while. In fact, often, after restarting the PC all the tests pass properly. Other times it doesn't so I suspect it has something to do with the fact that I'm loading assemblies at runtime and something gets out of whack :(

UPDATE 9 Sep 2021
The async execution I was doing is not entirely correct. There is a way to embrace async execution with xUnit that may have been playing a role in this race condition. This is a better implementation of the given-when-then pattern all my tests inherit from. Thanks to IAsyncLifetime I am able to asynchronously (and await) the preconditions and the action itself.

```<code>using System.Threading.Tasks;
using Xunit;

namespace Rubiko.TestSupport.XUnit
{
    public abstract class Given_When_Then_Test_Async
        : IAsyncLifetime
    {
        public async Task InitializeAsync()
        {
            await Given();
            await When();
        }

        public async Task DisposeAsync()
        {
            await Cleanup();
        }

        protected virtual Task Cleanup()
        {
            return Task.CompletedTask;
        }

        protected abstract Task Given();

        protected abstract Task When();
    }
}
</code>```

答:
The inner exeption indicates that a type could not be loaded

Could not load type 'Castle.Proxies.IReadinessProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

and it came from this line :

```<code>at System.Reflection.Assembly.GetTypes()
at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c <RegisterResolvers>b__6_2(Assembly s) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 174
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
</code>```

which corresponds to this line in your code

```<code>var domainEventTypes = assembliesLoaded
                          .SelectMany(s => s.GetTypes())
                          .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                      && x.IsClass);
</code>```

It means that one of the assembly contains a type that contains a reference to another assembly which is not loaded. Based on the name of the type in error it seems to be related with castle auto generated type.

You can subscribe to the static AppDomain.CurrentDomain.AssemblyResolve and AppDomain.CurrentDomain.TypeResolve events to better understand why the assembly is not loaded and maybe load it manually. See Assembly.GetTypes() - ReflectionTypeLoadException for more information.

In some case the exception is "normal" and could be ignored with a code like this :

```<code>public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
    // TODO: Argument validation
    try
    {
        return assembly.GetTypes();
    }
    catch (ReflectionTypeLoadException e)
    {
        return e.Types.Where(t => t != null);
    }
}
</code>```

Code from How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes()

And you can use this here :

```<code>var domainEventTypes = assembliesLoaded
                          .SelectMany(s => s.GetLoadableTypes())
                          .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                      && x.IsClass);
</code>```

Body:
I am having an issue that I've been many days unable to resolve.
I use xUnit with a given-then-when abstraction to make tests more readable.

I am using a wrapper over EventStore and running some integration tests. They all go well.. except one that fails when running all in parallel (and xUnit runs in parallel), but if I run them all sequentially they all succeed.

I cannot understand why this would be an issue because every single fact is supposed to run the constructor (the given) and the functionality to test (the when). And in each fact I instantiate an Autofac ContainerBuilder, build the container and resolve its IComponentContext, so in theory every test should be isoalted and idempotent as intended.

This is the exception I keep receiving:

Autofac.Core.DependencyResolutionException : An exception was thrown while activating SalesOrder.EventStore.Infra.EventStore.EventStore -> SalesOrder.EventStore.Infra.EventStore.DomainEventsRetriever -> SalesOrder.EventStore.Infra.EventStore.Factories.DomainEventFactory -> λ:SalesOrder.EventStore.Infra.EventStore.EventTypeResolver.
---- System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Castle.Proxies.IReadinessProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 136
   at Autofac.Core.Resolving.InstanceLookup.Execute() in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 85
   at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 130
   at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Resolving\ResolveOperation.cs:line 83
   at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 1041
   at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 871
   at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\ResolutionExtensions.cs:line 300
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore.When() in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests\EventStoreExtensionsTests\ResolveTests.cs:line 53
   at SalesOrder.EventStore.Infra.EventStore.Autofac.IntegrationTests.EventStoreExtensionsTests.ResolveTests.Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore..ctor()
----- Inner Stack Trace -----
   at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeModule.GetTypes()
   at System.Reflection.Assembly.GetTypes()
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c.<RegisterResolvers>b__6_2(Assembly s) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 174
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
   at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
   at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
   at SalesOrder.EventStore.Infra.EventStore.Factories.EventTypeResolverFactory.Create(IEnumerable`1 existingTypes, IReadOnlyDictionary`2 domainEventSerializerDeserializers) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore\Factories\EventTypeResolverFactory.cs:line 16
   at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c__DisplayClass6_0.<RegisterResolvers>b__1(IComponentContext context) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 180
   at Autofac.Builder.RegistrationBuilder.<>c__DisplayClass0_0`1.<ForDelegate>b__0(IComponentContext c, IEnumerable`1 p) in C:\projects\autofac\src\Autofac\Builder\RegistrationBuilder.cs:line 62
   at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) in C:\projects\autofac\src\Autofac\Core\Activators\Delegate\DelegateActivator.cs:line 71
   at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters, Object& decoratorTarget) in C:\projects\autofac\src\Autofac\Core\Resolving\InstanceLookup.cs:line 118

This is the test with only one Fact that fails when running in parallel with others:

public class Given_A_Container_With_Event_Store_Registered_When_Resolving_An_IEventStore
    : Given_When_Then_Test
{
    private IEventStore _sut;
    private IComponentContext _componentContext;

    protected override void Given()
    {
        var builder = new ContainerBuilder();
        builder
            .RegisterEventStore(
                ctx =>
                {
                    var eventStoreOptions =
                        new EventStoreOptions
                        {
                            Url = EventStoreTestConstants.TestUrl,
                            Port = EventStoreTestConstants.TestPort
                        };
                    return eventStoreOptions;
                },
                ctx =>
                {
                    var readinessOptions =
                        new ReadinessOptions
                        {
                            Timeout = EventStoreTestConstants.TestTimeout
                        };
                    return readinessOptions;
                });

        var container = builder.Build();
        _componentContext = container.Resolve<IComponentContext>();
    }

    protected override void When()
    {
        _sut = _componentContext.Resolve<IEventStore>();
    }

    [Fact]
    public void Then_It_Should_Not_Be_Null()
    {
        _sut.Should().NotBeNull();
    }
}

Any clue what may be happening here?
I've had a look at Autofac's guidelines on concurrency: https://autofaccn.readthedocs.io/en/latest/advanced/concurrency.html but I think I am already using properly the component context.

UPDATE 1: FYI this is the GivenThenWhen template I use. But nothing very special here (I think!)

namespace ToolBelt.TestSupport
{
    public abstract class Given_When_Then_Test
        : IDisposable
    {
        protected Given_When_Then_Test()
        {
            Setup();
        }

        private void Setup()
        {
            Given();
            When();
        }

        protected abstract void Given();

        protected abstract void When();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }

    public abstract class Given_WhenAsync_Then_Test
        : IDisposable
    {
        protected Given_WhenAsync_Then_Test()
        {
            Task.Run(async () => { await SetupAsync(); }).GetAwaiter().GetResult();
        }

        private async Task SetupAsync()
        {
            Given();
            await WhenAsync();
        }

        protected abstract void Given();

        protected abstract Task WhenAsync();

        public void Dispose()
        {
            Cleanup();
        }

        protected virtual void Cleanup()
        {
        }
    }
}

UPDATE 2: And this is the IoCC Autofac registration's method I am using for my implementation and all the tests. A bit complex because I use reflection to keep the EventStore wrapper fully generic, but just in case somebody sees something funky there that might affect the tests..

public static class EventStoreExtensions
{
    public static void RegisterEventStore(
        this ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever = null)
    {
        RegisterEventStoreConnection(builder, optionsRetriever);
        RegisterFactories(builder);
        RegisterEventStoreManager(builder);
        RegisterConverters(builder);
        RegisterResolvers(builder, customDomainEventMappersOptionsRetriever);
        RegisterEventStoreServices(builder);
        RegisterEventStoreReadinessCheck(builder, readinessOptionsRetriever);
    }

    private static void RegisterEventStoreReadinessCheck(
        ContainerBuilder builder,
        Func<IComponentContext, ReadinessOptions> readinessOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var readinessOptions = readinessOptionsRetriever.Invoke(ctx);

                var timeout = readinessOptions.Timeout;
                var eventStoreConnection = context.Resolve<IEventStoreConnection>();

                var eventStoreReadiness =
                    new EventStoreReadiness(
                        eventStoreConnection,
                        timeout);

                return eventStoreReadiness;

            })
            .As<IEventStoreReadiness>()
            .As<IReadiness>()
            .SingleInstance();
    }

    private static void RegisterEventStoreConnection(
        ContainerBuilder builder,
        Func<IComponentContext, EventStoreOptions> optionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var eventStoreOptions = optionsRetriever.Invoke(ctx);

                ConnectionSettings connectionSetting =
                    ConnectionSettings
                        .Create()
                        .KeepReconnecting();

                var urlString = eventStoreOptions.Url;
                var port = eventStoreOptions.Port;
                var ipAddress = IPAddress.Parse(urlString);
                var tcpEndPoint = new IPEndPoint(ipAddress, port);

                var eventStoreConnection = EventStoreConnection.Create(connectionSetting, tcpEndPoint);
                return eventStoreConnection;
            })
            .As<IEventStoreConnection>()
            .SingleInstance();
    }

    private static void RegisterFactories(
        ContainerBuilder builder)
    {
        builder
            .RegisterType<DomainEventFactory>()
            .As<IDomainEventFactory>()
            .SingleInstance();

        builder
            .RegisterType<EventDataFactory>()
            .As<IEventDataFactory>()
            .SingleInstance();

        builder
            .RegisterType<ExpectedVersionFactory>()
            .As<IExpectedVersionFactory>()
            .SingleInstance();

        builder
            .RegisterType<IdFactory>()
            .As<IIdFactory>()
            .SingleInstance();

        builder
            .RegisterType<StreamNameFactory>()
            .As<IStreamNameFactory>()
            .SingleInstance();

        builder
            .RegisterType<RetrievedEventFactory>()
            .As<IRetrievedEventFactory>()
            .SingleInstance();
    }

    private static void RegisterEventStoreManager(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreManager>()
            .As<IEventStoreManager>()
            .SingleInstance();
    }

    private static void RegisterConverters(ContainerBuilder builder)
    {
        builder
            .Register(context =>
            {
                var utf8Encoding = new BytesConverter(Encoding.UTF8);
                return utf8Encoding;
            })
            .As<IBytesConverter>()
            .SingleInstance();

        builder
            .RegisterType<NewtonsoftConverter>()
            .As<IJsonConverter>()
            .SingleInstance();
    }

    private static void RegisterResolvers(
        ContainerBuilder builder,
        Func<IComponentContext, CustomDomainEventMappersOptions> customDomainEventMappersOptionsRetriever)
    {
        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var mapperResolver = MapperResolverFactory.Create(domainEventSerializerDeserializers);
                return mapperResolver;
            })
            .As<IMapperResolver>()
            .SingleInstance();

        builder
            .Register(context =>
            {
                var ctx = context.Resolve<IComponentContext>();

                var assembliesLoaded = AppDomain.CurrentDomain.GetAssemblies();
                var domainEventTypes =
                    assembliesLoaded
                        .SelectMany(s => s.GetTypes())
                        .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                    && x.IsClass);
                var customDomainEventMappersOptions = customDomainEventMappersOptionsRetriever?.Invoke(ctx);
                var domainEventSerializerDeserializers =
                    customDomainEventMappersOptions?.DomainEventSerializerDeserializers;
                var typeResolver =
                    EventTypeResolverFactory.Create(
                        domainEventTypes,
                        domainEventSerializerDeserializers);
                return typeResolver;
            })
            .As<IEventTypeResolver>()
            .SingleInstance();
    }

    private static void RegisterEventStoreServices(ContainerBuilder builder)
    {
        builder
            .RegisterType<EventStoreRepository>()
            .As<IEventStoreRepository>();

        builder
            .RegisterType<DomainEventsPersister>()
            .As<IDomainEventsPersister>();

        builder
            .RegisterType<DomainEventsRetriever>()
            .As<IDomainEventsRetriever>();

        builder
            .RegisterType<EventStore>()
            .As<IEventStore>();
    }
}

UPDATE 3: This is the whole repository in case somebody is bored and wants to try to reproduce it. It is a generic event store wrapper used for event sourcing implemented for Greg Young's Event Store product using the official C# driver.

https://gitlab.com/DiegoDrivenDesign/DiDrDe.EventStore

Funnily enough, this issue seems to disappear every once in a while. In fact, often, after restarting the PC all the tests pass properly. Other times it doesn't so I suspect it has something to do with the fact that I'm loading assemblies at runtime and something gets out of whack :(

UPDATE 9 Sep 2021
The async execution I was doing is not entirely correct. There is a way to embrace async execution with xUnit that may have been playing a role in this race condition. This is a better implementation of the given-when-then pattern all my tests inherit from. Thanks to IAsyncLifetime I am able to asynchronously (and await) the preconditions and the action itself.

using System.Threading.Tasks;
using Xunit;

namespace Rubiko.TestSupport.XUnit
{
    public abstract class Given_When_Then_Test_Async
        : IAsyncLifetime
    {
        public async Task InitializeAsync()
        {
            await Given();
            await When();
        }

        public async Task DisposeAsync()
        {
            await Cleanup();
        }

        protected virtual Task Cleanup()
        {
            return Task.CompletedTask;
        }

        protected abstract Task Given();

        protected abstract Task When();
    }
}

Body:
The inner exeption indicates that a type could not be loaded

Could not load type 'Castle.Proxies.IReadinessProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

and it came from this line :

at System.Reflection.Assembly.GetTypes()
at SalesOrder.EventStore.Infra.EventStore.Autofac.EventStoreExtensions.<>c <RegisterResolvers>b__6_2(Assembly s) in C:\src\SalesOrder.EventStore\SalesOrder.EventStore.Infra.EventStore.Autofac\EventStoreExtensions.cs:line 174
at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()

which corresponds to this line in your code

var domainEventTypes = assembliesLoaded
                          .SelectMany(s => s.GetTypes())
                          .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                      && x.IsClass);

It means that one of the assembly contains a type that contains a reference to another assembly which is not loaded. Based on the name of the type in error it seems to be related with castle auto generated type.

You can subscribe to the static AppDomain.CurrentDomain.AssemblyResolve and AppDomain.CurrentDomain.TypeResolve events to better understand why the assembly is not loaded and maybe load it manually. See Assembly.GetTypes() - ReflectionTypeLoadException for more information.

In some case the exception is "normal" and could be ignored with a code like this :

public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly)
{
    // TODO: Argument validation
    try
    {
        return assembly.GetTypes();
    }
    catch (ReflectionTypeLoadException e)
    {
        return e.Types.Where(t => t != null);
    }
}

Code from How to prevent ReflectionTypeLoadException when calling Assembly.GetTypes()

And you can use this here :

var domainEventTypes = assembliesLoaded
                          .SelectMany(s => s.GetLoadableTypes())
                          .Where(x => typeof(IDomainEvent).IsAssignableFrom(x)
                                      && x.IsClass);


问:
List-items automatically update while they're in an Object and they shouldn't
I started to make a football game app in C#. I should make 15 Matchdays. Every matchday has a number, date and two lists with teams in it. In every MatchDay the teams with the same index in the lists play against eachother. (TeamList1[0] plays against TeamList2[0], ...). I make 15 matchdays with a for loop and switch the teams in the lists with the SwitchTeams() method. First i make a matchday-object with the two lists in it, then I put this matchday in a MatchDayList  and then i change the lists and make the next matchday object. But when i switch the teams in the list in the normal code, the list in my MatchDay object changes as well.
I don't know how this is possible and how to make the normal lists change and the lists that are in the MatchDay object remain the same. Does anyone have a solution for this? Thank you

```<code>//variables
List<Team> teamList1 = new List<Team>();
List<Team> teamList2 = new List<Team>();
List<MatchDay> matchDayList = new List<MatchDay>();

//Making the 15 Matchdays
private void ComposeGamesMenuItem_Click(object sender, RoutedEventArgs e)
        {
            DateTime date = new DateTime(DateTime.Now.Year, 7, 31);
            while (date.DayOfWeek != DayOfWeek.Saturday)
            {
                date = date.AddDays(-1);
            }
            for (int i = 1; i <= 15; i++) {
                List<Team> helpList1 = teamList1;
                List<Team> helpList2 = teamList2;
                MatchDay helpMatchDay = new MatchDay(i, helpList1, helpList2, date);
                matchDayList.Add(helpMatchDay);
                SwitchTeams();
                date = date.AddDays(7);
            }
        }

// Switching teams in original lists
 private void SwitchTeams()
        {
            teamList2.Insert(0, teamList1[1]);
            teamList1.RemoveAt(1);
            teamList1.Add(teamList2[8]);
            teamList2.RemoveAt(8);
        }

//Matchday class
public class MatchDay
    {
        private int DayNumber;
        private List<Team> TeamsList1;
        private List<Team> TeamsList2;
        private List<int> ScoresList1;
        private List<int> ScoresList2;
        private DateTime Date;

public MatchDay(int dayNumber, List<Team> teamsList1, List<Team> teamsList2, DateTime date)
        {
            DayNumber = dayNumber;
            TeamsList1 = teamsList1;
            TeamsList2 = teamsList2;
            Date = date;
        }
    }

</code>```

I expect the List in TeamList1 and TeamList2 in the Matchday Class not the change after the SwitchTeams() method. Only the TeamList1 and TeamList2 that are variables should change and put in the new Matchday Object and also not change ofcourse.

答:
Because it's the same list.  In your program you have exactly two lists of teams:

```<code>List<Team> teamList1 = new List<Team>();
List<Team> teamList2 = new List<Team>();
</code>```

You never create any more.  When you use them to construct your MatchDay object:

```<code>new MatchDay(i, helpList1, helpList2, date)
</code>```

That object now has a reference to each list.  Any changes made to a list will be visible by all references to that list.  They haven't been copied.

You can create new lists with the .ToList() extension method.  For example:

```<code>new MatchDay(i, helpList1.ToList(), helpList2.ToList(), date)
</code>```

This would create new lists, but they would of course still have references to the same objects.  So you can modify one list, and it won't modify the other one.  But if you modify a property on one of the objects in that list it will modify the object in the original list as well, and all for the same reason as the original problem you described.

In general, assigning a reference-type object (anything other than primitive types like int, bool, double, etc.) to a variable does not create a copy of that object, it just sets that variable as a reference to that same object.

Body:
I started to make a football game app in C#. I should make 15 Matchdays. Every matchday has a number, date and two lists with teams in it. In every MatchDay the teams with the same index in the lists play against eachother. (TeamList1[0] plays against TeamList2[0], ...). I make 15 matchdays with a for loop and switch the teams in the lists with the SwitchTeams() method. First i make a matchday-object with the two lists in it, then I put this matchday in a MatchDayList  and then i change the lists and make the next matchday object. But when i switch the teams in the list in the normal code, the list in my MatchDay object changes as well.
I don't know how this is possible and how to make the normal lists change and the lists that are in the MatchDay object remain the same. Does anyone have a solution for this? Thank you

//variables
List<Team> teamList1 = new List<Team>();
List<Team> teamList2 = new List<Team>();
List<MatchDay> matchDayList = new List<MatchDay>();

//Making the 15 Matchdays
private void ComposeGamesMenuItem_Click(object sender, RoutedEventArgs e)
        {
            DateTime date = new DateTime(DateTime.Now.Year, 7, 31);
            while (date.DayOfWeek != DayOfWeek.Saturday)
            {
                date = date.AddDays(-1);
            }
            for (int i = 1; i <= 15; i++) {
                List<Team> helpList1 = teamList1;
                List<Team> helpList2 = teamList2;
                MatchDay helpMatchDay = new MatchDay(i, helpList1, helpList2, date);
                matchDayList.Add(helpMatchDay);
                SwitchTeams();
                date = date.AddDays(7);
            }
        }

// Switching teams in original lists
 private void SwitchTeams()
        {
            teamList2.Insert(0, teamList1[1]);
            teamList1.RemoveAt(1);
            teamList1.Add(teamList2[8]);
            teamList2.RemoveAt(8);
        }

//Matchday class
public class MatchDay
    {
        private int DayNumber;
        private List<Team> TeamsList1;
        private List<Team> TeamsList2;
        private List<int> ScoresList1;
        private List<int> ScoresList2;
        private DateTime Date;

public MatchDay(int dayNumber, List<Team> teamsList1, List<Team> teamsList2, DateTime date)
        {
            DayNumber = dayNumber;
            TeamsList1 = teamsList1;
            TeamsList2 = teamsList2;
            Date = date;
        }
    }

I expect the List in TeamList1 and TeamList2 in the Matchday Class not the change after the SwitchTeams() method. Only the TeamList1 and TeamList2 that are variables should change and put in the new Matchday Object and also not change ofcourse.

Body:
Because it's the same list.  In your program you have exactly two lists of teams:

List<Team> teamList1 = new List<Team>();
List<Team> teamList2 = new List<Team>();

You never create any more.  When you use them to construct your MatchDay object:

new MatchDay(i, helpList1, helpList2, date)

That object now has a reference to each list.  Any changes made to a list will be visible by all references to that list.  They haven't been copied.

You can create new lists with the .ToList() extension method.  For example:

new MatchDay(i, helpList1.ToList(), helpList2.ToList(), date)

This would create new lists, but they would of course still have references to the same objects.  So you can modify one list, and it won't modify the other one.  But if you modify a property on one of the objects in that list it will modify the object in the original list as well, and all for the same reason as the original problem you described.

In general, assigning a reference-type object (anything other than primitive types like int, bool, double, etc.) to a variable does not create a copy of that object, it just sets that variable as a reference to that same object.


问:
How to create a custom ListView with "extends Activity"?
I am learning android programming, I was able to create a custom ListView
with:

```<code>public class project1 extends ListActivity
{
....
}
</code>```

With a xml file for the custom layout.
i would like to know how to do the same thing but with

```<code>public class project1 extends Activity

    {
    ....
    }
</code>```

All the tutorials I looked at use extends ListActivity, I know that its there to
make things simpler, but for the sake of learning how to do it the hard way???

答:
It is not really anything harder when extending Activity.

The only thing that changes is that you first have to grab a reference to your ListView defined in your XML layout file using the findViewById() method.

```<code>ListView mListView = (ListView)findViewById(R.id.my_listview);
</code>```

Defining a custom Adapter works the same. Just create it and assign your ListView that adapter.

```<code>mListView.setAdapter(mAdapter);
</code>```

Thats it. Nothing special about it.

Body:
I am learning android programming, I was able to create a custom ListView
with:

public class project1 extends ListActivity
{
....
}

With a xml file for the custom layout.
i would like to know how to do the same thing but with

public class project1 extends Activity

    {
    ....
    }

All the tutorials I looked at use extends ListActivity, I know that its there to
make things simpler, but for the sake of learning how to do it the hard way???

Body:
It is not really anything harder when extending Activity.

The only thing that changes is that you first have to grab a reference to your ListView defined in your XML layout file using the findViewById() method.

ListView mListView = (ListView)findViewById(R.id.my_listview);

Defining a custom Adapter works the same. Just create it and assign your ListView that adapter.

mListView.setAdapter(mAdapter);

Thats it. Nothing special about it.


问:
How I Can Use For Loop With Array And Get value One By One By Clicking
Please, I want some help.
I want to use for-loop with array and i want to get values one by one using button.

I want on click and get --> "A",

when i click again and get --> "B",

when i click again and get --> "C"

...

When i use for loop i get only the last value
you can see and edit the code here.

How can I use for-loop with an array and get value one by one by clicking:

```<code>var myArray = ["A", "B", "C", "D", "E", "F"];

var display = document.getElementById("display");
var x = 0;

function oneByOne() {
    for (i = 0; i < myArray.length; i++) {
    display.innerHTML = myArray[i]; // Result => "F"
 }
}
</code>```

Like the following code:

```<code>display.innerHTML = myArray[0];

function oneByOne() {
 x++;
 if (x < myArray.length) {
   display.innerHTML = myArray[x];

} else {
   display.innerHTML = "End";
 }
}
</code>```

HTML code:

```<code><h1 id="display"></h1>
<button onclick="oneByOne()"> One By One </button>
</code>```

答:
A while loop is easier to use for a "one-by-one" operation than a for loop. Either way loops continue to iterate through the array until the end -- so you need to pause or stop the loop so you when you click it shows only one iteration. You also have to remember where you are in the loop by having the increment declared outside the loop (or your case outside the function) so it doesn't get reset back to 0. BTW you declared x=0 outside the function (good) but then you have global i variable (no var) inside loop instead (bad).

The first example is a while loop. Note the break breaks the loop allowing the callback function to catch each loop. The second example is a for loop. Instead of a break returning whatever is in the loop stops it. The way it's remembering where it is in the loop is by incrementing the index within the brackets of the array as it is being returned.

const array = ["A", "B", "C", "D", "E", "F"];

////////////  X1 BY WHILE LOOP //////////////
const button1 = document.querySelector('.button1');
const display1 = document.querySelector(".display1");

let x1 = 0;

function oneByOne1(e) {
  while (x1 < array.length) {
    display1.innerHTML = array[x1];
    break;
  }
  x1++
}

button1.onclick = oneByOne1;

////////////  X1 BY FOR LOOP ////////////////
const button2 = document.querySelector('.button2');
const display2 = document.querySelector(".display2");

let x2 = 0;

function oneByOne2(e) {
  for (x2; x2 < array.length; x2++) {
    return display2.innerHTML = array[x2++];
  }
}

button2.onclick = oneByOne2;```
<pre class="snippet-code-css lang-css prettyprint-override"><code>:root {
  font-family: Consolas
}</code>```

<button class='button1'>X1</button> while loop...X1: <output class='display1'></output>

<button class='button2'>X2</button> for loop.....X2: <output class='display2'></output>```

Body:
Please, I want some help.
I want to use for-loop with array and i want to get values one by one using button.

I want on click and get --> "A",

when i click again and get --> "B",

when i click again and get --> "C"

...

When i use for loop i get only the last value
you can see and edit the code here.

How can I use for-loop with an array and get value one by one by clicking:

var myArray = ["A", "B", "C", "D", "E", "F"];

var display = document.getElementById("display");
var x = 0;

function oneByOne() {
    for (i = 0; i < myArray.length; i++) {
    display.innerHTML = myArray[i]; // Result => "F"
 }
}

Like the following code:

display.innerHTML = myArray[0];

function oneByOne() {
 x++;
 if (x < myArray.length) {
   display.innerHTML = myArray[x];

} else {
   display.innerHTML = "End";
 }
}

HTML code:

<button onclick="oneByOne()"> One By One </button>

Body:
A while loop is easier to use for a "one-by-one" operation than a for loop. Either way loops continue to iterate through the array until the end -- so you need to pause or stop the loop so you when you click it shows only one iteration. You also have to remember where you are in the loop by having the increment declared outside the loop (or your case outside the function) so it doesn't get reset back to 0. BTW you declared x=0 outside the function (good) but then you have global i variable (no var) inside loop instead (bad).

The first example is a while loop. Note the break breaks the loop allowing the callback function to catch each loop. The second example is a for loop. Instead of a break returning whatever is in the loop stops it. The way it's remembering where it is in the loop is by incrementing the index within the brackets of the array as it is being returned.

const array = ["A", "B", "C", "D", "E", "F"];

////////////  X1 BY WHILE LOOP //////////////
const button1 = document.querySelector('.button1');
const display1 = document.querySelector(".display1");

let x1 = 0;

function oneByOne1(e) {
  while (x1 < array.length) {
    display1.innerHTML = array[x1];
    break;
  }
  x1++
}

button1.onclick = oneByOne1;

////////////  X1 BY FOR LOOP ////////////////
const button2 = document.querySelector('.button2');
const display2 = document.querySelector(".display2");

let x2 = 0;

function oneByOne2(e) {
  for (x2; x2 < array.length; x2++) {
    return display2.innerHTML = array[x2++];
  }
}

button2.onclick = oneByOne2;

:root {
  font-family: Consolas
}

<button class='button1'>X1</button> while loop...X1: <output class='display1'></output><br>
<button class='button2'>X2</button> for loop.....X2: <output class='display2'></output>