问:
How to upload multiple image to s3 in react-native?
I got bucket name, accesskey, region from my colleauge.

I want to upload image to s3 bucket.

How can I do this?

Thanks!

答:
Hey GWANHUI KIM

You can use react-native-s3-upload package to upload images to s3 bucket.

```<code>   import { RNS3 } from 'react-native-s3-upload';

     constructor(props) {
    super(props)

    this.state = {
      amazonData: [],
      pictures:''
    }
  }
takePics = () => {

    ImagePicker.openPicker({
      multiple: true,
      maxFiles: 3
    }).then(response => {
      store.amazonData = [];
      let tempArray = []
      response.forEach((item) => {
        let image = {
          uri: item.path,
          width: item.width,
          height: item.height,
          name: item.filename,
          type: 'image/png'
        }
        const config = {
          bucket: 'goodvet',
          region: 'ap-northeast-2',
          accessKey: 'AKIAIJ4ZNXCKL6CIYIXQ',
          secretKey: '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',
          successActionStatus: 201
        }
        tempArray.push(image)

        RNS3.put(image, config)
          .then(responseFromS3 => {
            this.setState({ amazonData: [...this.state.amazonData, responseFromS3.body.postResponse.location] })

          })
      })
      this.setState({ pictures: tempArray })
      { this.hideIcons() }

    })
  }

takePicHandler() {
    return (
      <View>
          <SwiperFlatList
            showPagination={this.state.showsPagination}
            data={this.state.pictures}
            renderItem={({ item }) =>
              <View style={styles.uploadedImageView}>
                <Image
                  style={{ width: "100%", height: "100%" }}
                  source={item} />
      </View>
    )
  }
</code>```

I hope that will work for you! :)

Thanks!

Body:
Hey GWANHUI KIM

You can use react-native-s3-upload package to upload images to s3 bucket.

   import { RNS3 } from 'react-native-s3-upload';

     constructor(props) {
    super(props)

    this.state = {
      amazonData: [],
      pictures:''
    }
  }
takePics = () => {

    ImagePicker.openPicker({
      multiple: true,
      maxFiles: 3
    }).then(response => {
      store.amazonData = [];
      let tempArray = []
      response.forEach((item) => {
        let image = {
          uri: item.path,
          width: item.width,
          height: item.height,
          name: item.filename,
          type: 'image/png'
        }
        const config = {
          bucket: 'goodvet',
          region: 'ap-northeast-2',
          accessKey: 'AKIAIJ4ZNXCKL6CIYIXQ',
          secretKey: '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',
          successActionStatus: 201
        }
        tempArray.push(image)

        RNS3.put(image, config)
          .then(responseFromS3 => {
            this.setState({ amazonData: [...this.state.amazonData, responseFromS3.body.postResponse.location] })

          })
      })
      this.setState({ pictures: tempArray })
      { this.hideIcons() }

    })
  }

takePicHandler() {
    return (
      <View>
          <SwiperFlatList
            showPagination={this.state.showsPagination}
            data={this.state.pictures}
            renderItem={({ item }) =>
              <View style={styles.uploadedImageView}>
                <Image
                  style={{ width: "100%", height: "100%" }}
                  source={item} />
      </View>
    )
  }

I hope that will work for you! :)

Thanks!


来源: stackexchange

问:
How to read visible-only cells using Python?
I want to read and merge only visible cells in Excel, but I failed.

Also, I've tried openpyxl but didn't work. (Find my second code)

Is there any other ways to read only visible cells and paste on new excel?

I want to read only visible cells because sometimes they need to be filtered or hidden.

Please kindly advise me.

What kind of module should I put in?

If every excel module cannot do that, please also let me know.

My current code:

```<code>import os
import glob
import xlwings as xw
import xlrd
import xlsxwriter

xw.App().visible = False
path = os.getcwd()
x=input('name：') + '.xlsx'
target_xls = os.path.join(path,x)
data = []
for file in glob.glob(path+'\*.*'):
    if file.endswith((".xls", ".xlsm", ".xlsx")):

        wb = xlrd.open_workbook(file)
        for sheet in wb.sheets():
            for rownum in range(sheet.nrows):
                data.append(sheet.row_values(rownum))
        workbook = xlsxwriter.Workbook(target_xls)
        worksheet = workbook.add_worksheet()
        for i in range(len(data)):
            print(range(len(data)))
            for j in range(len(data[i])):
                worksheet.write(i, j, data[i][j])
        workbook.close()
</code>```

My openpyxl code:

```<code>import os
import glob
import xlwings as xw
import xlrd
import xlsxwriter

from openpyxl import load_workbook
xw.App().visible = False
path = os.getcwd()
x = input('name：') + '.xlsx'
target_xls = os.path.join(path, x)
data = []
wb = load_workbook('sample.xlsx')
ws = wb['Sheet1']

for row in ws:

    if ws.row_dimensions[row[0].row].hidden == False:
        for cell in row:
            data.append(cell.value)
    workbook = xlsxwriter.Workbook(target_xls)
    worksheet = workbook.add_worksheet()

    for i in range(len(data)):
        print(range(len(data)))
        for j in range(len(data[i])):
            worksheet.write(i, j, data[i][j])
    workbook.close()
</code>```

I want to read excel like below:

And output into:

答:
```<code>#Reference: xlrd manual: https://media.readthedocs.org/pdf/xlrd/latest/xlrd.pdf
#Python Forum Reference: https://python-forum.io/Thread-Identify-Hidden-rows-in-xls
import xlrd

print("Read the VALUE and ROW VISIBILITY from cells A1:A6 in a .xls file from 'Sheet2'.")
print()

######################################################
# Access .xls file (Excel 2003 and before)
excel_filename = "HiddenRow3OnSheet2.xls"

# Open the workbook
#NOTE: Traceback error if 'formatting_info=True' is NOT INCLUDED
xl_workbook = xlrd.open_workbook(excel_filename, formatting_info=True)

#Set the focus on 'Sheet2'
my_sheet_name = "Sheet2"
xl_sheet = xl_workbook.sheet_by_name(my_sheet_name)

print("File: {}".format(excel_filename))
for irow in range(xl_sheet.nrows):
    ihidden = xl_sheet.rowinfo_map[irow].hidden   #Row Visibility 0=Visible 1=Hidden
    if ihidden == True:
        shidden = "VISIBLE"
    else:
        shidden = "HIDDEN"

    svalue = xl_sheet.cell(irow,0).value
    print("Value: {}        Row Visibility: {}".format(svalue, shidden))

######################################################
# Access .xlsx file (Excel 2007 and later)
excel_filename = "HiddenRow3OnSheet2.xlsx"

# Open the workbook
#NOTE: 'formatting_info=True' is NOT SUPPORTED for .xlsx files
xl_workbook = xlrd.open_workbook(excel_filename)

#Set the focus on 'Sheet2'
my_sheet_name = "Sheet2"
xl_sheet = xl_workbook.sheet_by_name(my_sheet_name)

print()
print("File: {}".format(excel_filename))
for irow in range(xl_sheet.nrows):
    svalue = xl_sheet.cell(irow,0).value
    print("Value: {}       Row Visibility: {}".format(svalue, "Not Available for .xlsx files"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to read and merge only visible cells in Excel, but I failed.

Also, I've tried openpyxl but didn't work. (Find my second code)

Is there any other ways to read only visible cells and paste on new excel?

I want to read only visible cells because sometimes they need to be filtered or hidden.

Please kindly advise me.

What kind of module should I put in?

If every excel module cannot do that, please also let me know.

My current code:

import os
import glob
import xlwings as xw
import xlrd
import xlsxwriter

xw.App().visible = False
path = os.getcwd()
x=input('name：') + '.xlsx'
target_xls = os.path.join(path,x)
data = []
for file in glob.glob(path+'\*.*'):
    if file.endswith((".xls", ".xlsm", ".xlsx")):

        wb = xlrd.open_workbook(file)
        for sheet in wb.sheets():
            for rownum in range(sheet.nrows):
                data.append(sheet.row_values(rownum))
        workbook = xlsxwriter.Workbook(target_xls)
        worksheet = workbook.add_worksheet()
        for i in range(len(data)):
            print(range(len(data)))
            for j in range(len(data[i])):
                worksheet.write(i, j, data[i][j])
        workbook.close()

My openpyxl code:

import os
import glob
import xlwings as xw
import xlrd
import xlsxwriter

from openpyxl import load_workbook
xw.App().visible = False
path = os.getcwd()
x = input('name：') + '.xlsx'
target_xls = os.path.join(path, x)
data = []
wb = load_workbook('sample.xlsx')
ws = wb['Sheet1']

for row in ws:

    if ws.row_dimensions[row[0].row].hidden == False:
        for cell in row:
            data.append(cell.value)
    workbook = xlsxwriter.Workbook(target_xls)
    worksheet = workbook.add_worksheet()

    for i in range(len(data)):
        print(range(len(data)))
        for j in range(len(data[i])):
            worksheet.write(i, j, data[i][j])
    workbook.close()

I want to read excel like below:

And output into:


问:
How to supply snakemake options within the Snakefile itself?
I would like to specify singularity bind paths inside the snakefile (ie. snakemake script) and not via command line. I believe this could be done somehow via their api by from snakemake import something, etc. How do I achieve this?

Broadly speaking, how do we supply options/arguments to snakemake via their api within a Snakefile?

答:
I made a pipeline that does a couple things, and one of those things is download samples. Starting 30 downloads at the same time is a waste of resources so I wanted to limit the number of parallel downloads, and I don't want to always pass --resources parallel_resources=1 to the command. I noticed that the snakemake.workflow exists when a Snakefile is executed, and here I added this as a resource:

```<code>workflow.global_resources.update({'parallel_downloads': 1})
</code>```

I have no experience with singularity, so I don't fully understand what you want. But my guess is that this is somewhere stored in the workflow and you can change it there.

p.s. this is not at all through an API, or guaranteed to work between versions

Body:
I made a pipeline that does a couple things, and one of those things is download samples. Starting 30 downloads at the same time is a waste of resources so I wanted to limit the number of parallel downloads, and I don't want to always pass --resources parallel_resources=1 to the command. I noticed that the snakemake.workflow exists when a Snakefile is executed, and here I added this as a resource:

workflow.global_resources.update({'parallel_downloads': 1})

I have no experience with singularity, so I don't fully understand what you want. But my guess is that this is somewhere stored in the workflow and you can change it there.

p.s. this is not at all through an API, or guaranteed to work between versions


问:
Laravel 5 Override Login Function
I'm working on my Laravel Project and trying to override the  default postLogin() from AuthenticatesAndRegistersUsers . So I have updated my AuthController and added this to override the built-in login,

```<code>public function postLogin(Request $request)
{

    $this->validate($request, [
        'email' => 'required|email', 'password' => 'required',
    ]);

    $credentials = $request->only('email', 'password');

    if ($this->auth->attempt($credentials, $request->has('remember')))
    {
        /* Check if the user is Activated */
        $userID = \Auth::user()->id;
        $user = new \App\User;
        $result = $user->isUserActivated($userID);

        if($result[0]->status == 1)
        {
            return redirect()->intended($this->redirectPath());
        }
        else if($result[0]->status == 0)
        {
            Session::flash('alert-danger', 'Your account is not yet Activated.');
            return Redirect::to('auth/login');
        }

    }

    return redirect($this->loginPath())
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'email' => $this->getFailedLoginMessage(),
                ]);
}
</code>```

As you can see I have $result[0]->status which tells if the user is activated, if not then I will redirect them back to auth/login. I tried to var_dump($result[0]->status);  and it is working fine and also means I override that it coz it's displaying it but my problem is instead of redirecting it to auth/login it is still going thru home and can login even if the status is 0. Seems I'm it's my override doesn't work, but when I var_dump $result[0]->status, it shows. Did i missed something?

答:
Try following this discussion at laracasts.

Here is a solution

```<code>if ($this->guard()->validate($this->credentials($request))) {
        $user = $this->guard()->getLastAttempted();
        if ($user->is_activated && $this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        } else {
            $this->incrementLoginAttempts($request);
            if ($request->ajax()) {
                return response()->json([
                    'error' => 'This account is not activated.'
                ], 401);
            }
        }
    }
</code>```

It provided a crucial update for a do my homework service at Top Homework Expert

ContentLicense: CC BY-SA 3.0

Title: Laravel 5 Override Login Function

Body:
I'm working on my Laravel Project and trying to override the  default postLogin() from AuthenticatesAndRegistersUsers . So I have updated my AuthController and added this to override the built-in login,

public function postLogin(Request $request)
{

    $this->validate($request, [
        'email' => 'required|email', 'password' => 'required',
    ]);

    $credentials = $request->only('email', 'password');

    if ($this->auth->attempt($credentials, $request->has('remember')))
    {
        /* Check if the user is Activated */
        $userID = \Auth::user()->id;
        $user = new \App\User;
        $result = $user->isUserActivated($userID);

        if($result[0]->status == 1)
        {
            return redirect()->intended($this->redirectPath());
        }
        else if($result[0]->status == 0)
        {
            Session::flash('alert-danger', 'Your account is not yet Activated.');
            return Redirect::to('auth/login');
        }

    }

    return redirect($this->loginPath())
                ->withInput($request->only('email', 'remember'))
                ->withErrors([
                    'email' => $this->getFailedLoginMessage(),
                ]);
}

As you can see I have $result[0]->status which tells if the user is activated, if not then I will redirect them back to auth/login. I tried to var_dump($result[0]->status);  and it is working fine and also means I override that it coz it's displaying it but my problem is instead of redirecting it to auth/login it is still going thru home and can login even if the status is 0. Seems I'm it's my override doesn't work, but when I var_dump $result[0]->status, it shows. Did i missed something?

Body:
Try following this discussion at laracasts.

Here is a solution

if ($this->guard()->validate($this->credentials($request))) {
        $user = $this->guard()->getLastAttempted();
        if ($user->is_activated && $this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        } else {
            $this->incrementLoginAttempts($request);
            if ($request->ajax()) {
                return response()->json([
                    'error' => 'This account is not activated.'
                ], 401);
            }
        }
    }

It provided a crucial update for a do my homework service at Top Homework Expert


问:
How do I pass a file into a Docker container to be used with the container?
I would like to pass a file from the host system to a container at runtime. I want to run a CLI tool within a container and use the file as an argument to the CLI tool. Is it possible to modify the following command: docker run -it --rm --name <container-name> to achieve what I want to do. The docker cp command doesn’t work for what I need since it doesn’t run from within the container and I need to pass the file name as an argument.

答:
I usually use the -v "$PWD:$PWD" -w "$PWD" trick. Run container and volume mount the current host working directory into the container at the same path and set working directory to same path.

So for example if I want to transcode a wav file on the host to a mp3 file usig ffmpeg running in a container I would do:

docker run --rm -v "$PWD:$PWD" -w "$PWD" mwader/static-ffmpeg:4.2.2 -i file.wav file.mp3

```

You can also add -u $UID:$GROUPS if your unsure what default user the image runs as.

Body:
I usually use the -v "$PWD:$PWD" -w "$PWD" trick. Run container and volume mount the current host working directory into the container at the same path and set working directory to same path.

So for example if I want to transcode a wav file on the host to a mp3 file usig ffmpeg running in a container I would do:

docker run --rm -v "$PWD:$PWD" -w "$PWD" mwader/static-ffmpeg:4.2.2 -i file.wav file.mp3

You can also add -u $UID:$GROUPS if your unsure what default user the image runs as.


问:
Bootstrap modal and jQuery: form inputs are empty
I'm using form inside a modal window in my application which uses Bootstrap.
Form looks like this:

```<code><div class="modal fade" id="my_modal">
    <div class="modal-dialog modal-lg">
        <div class="form-group">
            <form class="form-horizontal" id="my_form">
                <div class="form-group">
                    <div class="col-sm-10">
                        <input type="file" name="file" id="my_file">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-10">
                        <input type="text" name="my_text" id="my_text" class="form-control select-resource-form-control">
                    </div>
                </div>
                <button id="my_button" type="button" class="btn btn-primary btn-send">Send</button>
            </form>
        </div>
    </div>
</div>
</code>```

When I'm trying to send form data of this form, both file and text fields are empty at the recieveing part, and following commands in console also confirm that the form is empty:

when I use modal fade

If I replace the modal fade attribute in the root tag,for example, with modal-body, everything works just fine, but I need a modal window for my purposes, which shows up, sends the response and closes.
when I use modal-body

Would appreciate any ideas/workarounds about this

UPDATE:
ajax for the query is:

```<code>let form = $("#my_form").get(0);
$.ajax({
        url: "some/url/Im/sending/data/to",
        method: "POST",
        data: new FormData(form),
        cache: false,
        contentType: false,
        processData: false,
    }
}
</code>```

答:
The problem has been solved. When the modal window was instantiated, the page also instantiated a second one with class in. So I changed the selector for the window to the following and everything worked
"#my_modal.in #my_form"

Body:
I'm using form inside a modal window in my application which uses Bootstrap.
Form looks like this:

            <form class="form-horizontal" id="my_form">

                        <input type="file" name="file" id="my_file">

                        <input type="text" name="my_text" id="my_text" class="form-control select-resource-form-control">

                <button id="my_button" type="button" class="btn btn-primary btn-send">Send</button>
            </form>

When I'm trying to send form data of this form, both file and text fields are empty at the recieveing part, and following commands in console also confirm that the form is empty:

when I use modal fade

If I replace the modal fade attribute in the root tag,for example, with modal-body, everything works just fine, but I need a modal window for my purposes, which shows up, sends the response and closes.
when I use modal-body

Would appreciate any ideas/workarounds about this

UPDATE:
ajax for the query is:

let form = $("#my_form").get(0);
$.ajax({
        url: "some/url/Im/sending/data/to",
        method: "POST",
        data: new FormData(form),
        cache: false,
        contentType: false,
        processData: false,
    }
}


问:
list operations in python to combine
I have a scenario where I have two lists l1 & l2 as mentioned below:

```<code>l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]

l2 = [{'app_id': 9833, 'name': ABC}, {'app_id': 1036, 'name': CDE}, {'app_id': 1039, 'name': XYZ},{'app_id': 1030, 'name': JKL}]
</code>```

I am trying to check in this two list whether the app_id is common in both the lists if common then add the name value as well in the third list, so the desired output should be something like this.

```<code>l3 = [{'app_id': 9833, 'name': ABC, 'state': 0}, {'app_id': 1036, 'name': CDE, 'state': 1}, {'app_id': 1039, 'name': XYZ, 'state': 0},{'app_id': 1030, 'name': JKL, 'state': 0}]
</code>```

This is what I have tried and looks like the approach is wrong.

```<code>for key in l1:
    temp=key['app_id']
    for keynd in l2:
        if keynd[app_id]==temp:
            l3.append(keynd['name'])
</code>```

Can someone help me here on how to achieve this ?

答:
Your question is currently ambiguous:

what to do with elements of l1 not present in l2? I shall assume ignore them

what to do with elements of l2 not present in l1? I shall assume ignore them

what to do if an app_id from l1 is present more than once in l2? I shall assume use any and shall use last

Searching a dict is generally faster than iterating a list, so I shall build an auxilliary mapping app_id=>name from l2, and build a copy of l1 containing only app_id present in l2, and then append the name from the auxilliary mapping:

```<code>aux = {it['app_id']: it['name'] for it in l2}
l3 = [it.copy() for it in l1 if it['app_id'] in aux]
for it in l3:
    it['name'] = aux[it['app_id']]
</code>```

it gives for l3: [{'app_id': 9833, 'state': 0, 'name': 'ABC'}, {'app_id': 1036, 'state': 1, 'name': 'CDE'}, {'app_id': 1039, 'state': 0, 'name': 'XYZ'}, {'app_id': 1030, 'state': 0, 'name': 'JKL'}] without needing nested loops.

Title: list operations in python to combine

Body:
I have a scenario where I have two lists l1 & l2 as mentioned below:

l1 = [{'app_id': 9833, 'state': 0}, {'app_id': 1036, 'state': 1}, {'app_id': 1039, 'state': 0},{'app_id': 1030, 'state': 0}]

l2 = [{'app_id': 9833, 'name': ABC}, {'app_id': 1036, 'name': CDE}, {'app_id': 1039, 'name': XYZ},{'app_id': 1030, 'name': JKL}]

I am trying to check in this two list whether the app_id is common in both the lists if common then add the name value as well in the third list, so the desired output should be something like this.

l3 = [{'app_id': 9833, 'name': ABC, 'state': 0}, {'app_id': 1036, 'name': CDE, 'state': 1}, {'app_id': 1039, 'name': XYZ, 'state': 0},{'app_id': 1030, 'name': JKL, 'state': 0}]

This is what I have tried and looks like the approach is wrong.

for key in l1:
    temp=key['app_id']
    for keynd in l2:
        if keynd[app_id]==temp:
            l3.append(keynd['name'])

Can someone help me here on how to achieve this ?

Body:
Your question is currently ambiguous:

what to do with elements of l1 not present in l2? I shall assume ignore them

what to do with elements of l2 not present in l1? I shall assume ignore them

what to do if an app_id from l1 is present more than once in l2? I shall assume use any and shall use last

Searching a dict is generally faster than iterating a list, so I shall build an auxilliary mapping app_id=>name from l2, and build a copy of l1 containing only app_id present in l2, and then append the name from the auxilliary mapping:

aux = {it['app_id']: it['name'] for it in l2}
l3 = [it.copy() for it in l1 if it['app_id'] in aux]
for it in l3:
    it['name'] = aux[it['app_id']]

it gives for l3: [{'app_id': 9833, 'state': 0, 'name': 'ABC'}, {'app_id': 1036, 'state': 1, 'name': 'CDE'}, {'app_id': 1039, 'state': 0, 'name': 'XYZ'}, {'app_id': 1030, 'state': 0, 'name': 'JKL'}] without needing nested loops.


问:
Linux Pipe viewer, how to split the pipe
I'm trying to extract large .tar file using pv.

```<code>pv large_file.tar.gz | tar -xcf /../MyFolder.
</code>```

The pv command works like expected,showing the progress in the console.

I'm trying to split the stdout, to show the progress both in the console and save the same standout, to a file.

I tried doing so with tee, but couldn't make it work.

```<code>pv large_file.tar.gz | tee /tmp/strout.log | tar -xcf /../MyFolder
</code>```

Any suggestions how can i display the progress to the console an in the same time save it to a file?

Thanks!

答:
PV progress is sent to stderr, can you try this?:
pv large_file.tar.gz > >(tar -xz -C ./MyFolder/) | echo you might need to edit the tar command as i couldnt get yours to work for me

Body:
I'm trying to extract large .tar file using pv.

pv large_file.tar.gz | tar -xcf /../MyFolder.

The pv command works like expected,showing the progress in the console.

I'm trying to split the stdout, to show the progress both in the console and save the same standout, to a file.

I tried doing so with tee, but couldn't make it work.

pv large_file.tar.gz | tee /tmp/strout.log | tar -xcf /../MyFolder

Any suggestions how can i display the progress to the console an in the same time save it to a file?

Thanks!


问:
Get transformation from node in d3
Is it possible to obtain the current transformation (translate in particular, i.e. set by .attr('transform', 'translate(20, 10)')) from an svg group element using d3 in transform form (from d3-transform)? I manage to get the attribute (select('g').attr('transform')), but need to convert this somehow into a transform object/function to chain more transformations and reapply it to the node.

I try to translate the g element as part of the dragging. It does not contain an x/y attribute (as with many other drag examples). Instead, it specifies those transform() attributes for correct placement.

My current approach is $g.node().transform.baseVal[0].matrix.e to get the x-value of the transformation, but I was hoping for a more "d3-integrated" approach.

答:
You can do it by requesting transformation matrix of the  element:

```<code>const matrix = select('g').node().transform.baseVal.consolidate().matrix
const translateX = matrix.e
const translateY = matrix.f
const scale = matrix.d
</code>```

Here is a more detailed explanation.

Title: Get transformation from node in d3

Body:
You can do it by requesting transformation matrix of the  element:

const matrix = select('g').node().transform.baseVal.consolidate().matrix
const translateX = matrix.e
const translateY = matrix.f
const scale = matrix.d

Here is a more detailed explanation.


问:
In NextJS, how to build when referencing external npm package that contains SVGs?
My nextjs project (let's call it TheHost) references another npm package (let's call it ThePackage).

SVGs load fine when defined within TheHost, but importing ThePackage fails because next tries to interpret the svg as javascript... so I get the following error when doing a next build:

```<code>SyntaxError: Unexpected token '<'
</code>```

To re-iterate, SVGs work fine when referencing an svg defined in TheHost itself. The problem seems to be importing npm packages that contain SVGs.

It doesn't matter if I import a component from ThePackage that uses an SVG or not, just the fact that somewhere in the npm package it contains an "import xxx from '../path/to/svg' is enough to break next build.

For what it's worth, the ThePackage's transpiled javascript reads the svg as follows:

```<code>var _mysvg = require("../path/to/the-svg.svg");
</code>```

Lots of details:

The next build stack trace is:

```<code>> Using external babel configuration
> Location: "/Users/w/dev/TheHost/.babelrc"
Creating an optimized production build

Compiled successfully.

> Build error occurred
/Users/w/dev/TheHost/node_modules/ThePackage/build/assets/card_background.svg:1
<svg viewBox="0 0 860 382" fill="none" xmlns="http://www.w3.org/2000/svg">
^

SyntaxError: Unexpected token '<'
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/Users/w/dev/TheHost/node_modules/TheProject/build/card/style.js:14:47)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32) {
  type: 'SyntaxError'
}
Automatically optimizing pages .%
</code>```

The .babelrc file:

```<code>{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    "babel-plugin-styled-components",
    "inline-react-svg"
  ]
}
</code>```

The next.config.js file:

```<code>const withSourceMaps = require("@zeit/next-source-maps");
const withImages = require("next-images");

module.exports = withImages(
  withSourceMaps({
    env: { *** redacted *** },
    publicRuntimeConfig: { *** redacted *** },
    webpack: (config, options) => {
      if (!options.isServer) {
        config.resolve.alias["@sentry/node"] = "@sentry/browser";
      }
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
  })
);
</code>```

The nextjs svgr package versions are as follows:

```<code>"next": "^9.2.1",
"next-images": "^1.3.0",
"@svgr/webpack": "^5.1.0",
"babel-eslint": "^10.0.3",
"babel-plugin-inline-react-svg": "^1.1.1",
</code>```

ThePackage is built with the following output configuration (webpack):

```<code>  entry: './src/index.js',
  output: {
    path: buildFolder,
    filename: 'ThePackage.js',
    library: 'ThePackage',
    libraryTarget: 'umd', /* Note: umd */
    umdNamedDefine: true
  },
</code>```

答:
NextJS ignores node_modules by default so you'd need to specifically allow your config to be able to transpile your package. Fortunately, someone has already created a NextJS plugin to allow this: https://github.com/martpie/next-transpile-modules

I'd also suggest using Next Compose Plugins to neaten up the config. In the end, your next.config.js will look something like this:

```<code>const withSourceMaps = require("@zeit/next-source-maps");
const withImages = require("next-images");
const withPlugins = require('next-compose-plugins');
const withTM = require('next-transpile-modules')(['ThePackage']);

module.exports = withPlugins([
    withTM,
    [
        withImages,
        {
            exclude: /\.svg$/
        }
    ],
    withSourceMaps
],
{
    env: { *** redacted *** },
    publicRuntimeConfig: { *** redacted *** },
    webpack: (config, options) => {
      if (!options.isServer) {
        config.resolve.alias["@sentry/node"] = "@sentry/browser";
      }
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
});
</code>```

I've also excluded SVGs from being processed by withImages.

Body:
My nextjs project (let's call it TheHost) references another npm package (let's call it ThePackage).

SVGs load fine when defined within TheHost, but importing ThePackage fails because next tries to interpret the svg as javascript... so I get the following error when doing a next build:

SyntaxError: Unexpected token '<'

To re-iterate, SVGs work fine when referencing an svg defined in TheHost itself. The problem seems to be importing npm packages that contain SVGs.

It doesn't matter if I import a component from ThePackage that uses an SVG or not, just the fact that somewhere in the npm package it contains an "import xxx from '../path/to/svg' is enough to break next build.

For what it's worth, the ThePackage's transpiled javascript reads the svg as follows:

var _mysvg = require("../path/to/the-svg.svg");

Lots of details:

The next build stack trace is:

> Using external babel configuration
> Location: "/Users/w/dev/TheHost/.babelrc"
Creating an optimized production build

Compiled successfully.

> Build error occurred
/Users/w/dev/TheHost/node_modules/ThePackage/build/assets/card_background.svg:1
<svg viewBox="0 0 860 382" fill="none" xmlns="http://www.w3.org/2000/svg">
^

SyntaxError: Unexpected token '<'
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Function.Module._load (internal/modules/cjs/loader.js:727:14)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at Object.<anonymous> (/Users/w/dev/TheHost/node_modules/TheProject/build/card/style.js:14:47)
    at Module._compile (internal/modules/cjs/loader.js:959:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)
    at Module.load (internal/modules/cjs/loader.js:815:32) {
  type: 'SyntaxError'
}
Automatically optimizing pages .%

The .babelrc file:

{
  "presets": [
    "next/babel"
  ],
  "plugins": [
    "babel-plugin-styled-components",
    "inline-react-svg"
  ]
}

The next.config.js file:

const withSourceMaps = require("@zeit/next-source-maps");
const withImages = require("next-images");

module.exports = withImages(
  withSourceMaps({
    env: { *** redacted *** },
    publicRuntimeConfig: { *** redacted *** },
    webpack: (config, options) => {
      if (!options.isServer) {
        config.resolve.alias["@sentry/node"] = "@sentry/browser";
      }
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
  })
);

The nextjs svgr package versions are as follows:

"next": "^9.2.1",
"next-images": "^1.3.0",
"@svgr/webpack": "^5.1.0",
"babel-eslint": "^10.0.3",
"babel-plugin-inline-react-svg": "^1.1.1",

ThePackage is built with the following output configuration (webpack):

  entry: './src/index.js',
  output: {
    path: buildFolder,
    filename: 'ThePackage.js',
    library: 'ThePackage',
    libraryTarget: 'umd', /* Note: umd */
    umdNamedDefine: true
  },

Body:
NextJS ignores node_modules by default so you'd need to specifically allow your config to be able to transpile your package. Fortunately, someone has already created a NextJS plugin to allow this: https://github.com/martpie/next-transpile-modules

I'd also suggest using Next Compose Plugins to neaten up the config. In the end, your next.config.js will look something like this:

const withSourceMaps = require("@zeit/next-source-maps");
const withImages = require("next-images");
const withPlugins = require('next-compose-plugins');
const withTM = require('next-transpile-modules')(['ThePackage']);

module.exports = withPlugins([
    withTM,
    [
        withImages,
        {
            exclude: /\.svg$/
        }
    ],
    withSourceMaps
],
{
    env: { *** redacted *** },
    publicRuntimeConfig: { *** redacted *** },
    webpack: (config, options) => {
      if (!options.isServer) {
        config.resolve.alias["@sentry/node"] = "@sentry/browser";
      }
      config.module.rules.push({
        test: /\.svg$/,
        use: ["@svgr/webpack"]
      });
      return config;
    }
});

I've also excluded SVGs from being processed by withImages.


问:
OpenCV Python what's an appropriate map from a full color space to a reduced color palette?
Assume we have a priorly known set of n colors C. We are given a list of colors l.

The goal is for every color l, match it to a color in C such that it minimizes a distance function D.

The most straightforward approach is to use the euclidean distance, however that's not a good idea because of the following example:

Assume the input color is (0.1, 0, 0) so very dark red. Assume that brown (0,5, 0.5, 0) and pure red (1,0,0) are both in C.

The euclidean distance gives:

distance to brown = (0.4^2 + 0.5^2) = 0.41

distance to red = (0.9^2) = 0.81

Thus dark red is mapped to brown instead of red, which visually doesn't really make sense.

We could try the chebychev distance:

distance to brown = max(0.4, 0.5, 0) = 0.5

distance to red = max(0.9, 0, 0) = 0.9

Or the manhattan distance:

distance to brown = max(0.4 + 0.5) = 0.9

distance to red = max(0.9 + 0 + 0) = 0.9

The first still chooses brown over red, where the second picks both as equally valid choices. Although an improvement, it's not the ideal.

I however am not sure how to measure "visual distance", i.e if a color would "look green" to a human, how to map said color to green for example.

I am using opencv, and I have searched the documentation but I don''t seem to find if this problem is already solved.

答:
Welcome to the world of Colors! If you're using RGB, the mentioned distance metrics are unlikely to work because RGB is not a perceptually uniform color space (distances between vectors in the color space do not resemble the human perceived changes). CIELAB color space is supposedly a perceptually uniform one.

A popular color distance metric that was subjected to a few revisions over the time is CIELAB \deltaE*

These distance metrics are available in the colormath package.

from docs:

```<code>from colormath.color_objects import LabColor
from colormath.color_diff import delta_e_cie1976

# Reference color.
color1 = LabColor(lab_l=0.9, lab_a=16.3, lab_b=-2.22)
# Color to be compared to the reference.
color2 = LabColor(lab_l=0.7, lab_a=14.2, lab_b=-1.80)
# This is your delta E value as a float.
delta_e = delta_e_cie1976(color1, color2)
</code>```

In your problem, if the size of your known set of colors (C) is small (say 10), even the delta_E might not work as expected. A more reliable way would be to collect a new set S that has a lot of shades of each color in C (You can use Color Dictionaries) and map each color in l to it's closet in S and then to C. You can speed up your search by using a data structure like kd-tree by pre-computing your distance metrics.

Body:
Welcome to the world of Colors! If you're using RGB, the mentioned distance metrics are unlikely to work because RGB is not a perceptually uniform color space (distances between vectors in the color space do not resemble the human perceived changes). CIELAB color space is supposedly a perceptually uniform one.

A popular color distance metric that was subjected to a few revisions over the time is CIELAB \deltaE*

These distance metrics are available in the colormath package.

from docs:

from colormath.color_objects import LabColor
from colormath.color_diff import delta_e_cie1976

# Reference color.
color1 = LabColor(lab_l=0.9, lab_a=16.3, lab_b=-2.22)
# Color to be compared to the reference.
color2 = LabColor(lab_l=0.7, lab_a=14.2, lab_b=-1.80)
# This is your delta E value as a float.
delta_e = delta_e_cie1976(color1, color2)

In your problem, if the size of your known set of colors (C) is small (say 10), even the delta_E might not work as expected. A more reliable way would be to collect a new set S that has a lot of shades of each color in C (You can use Color Dictionaries) and map each color in l to it's closet in S and then to C. You can speed up your search by using a data structure like kd-tree by pre-computing your distance metrics.


问:
Contact form 7 input box not clickable
I have one site developed in wordpress and One of my contact form is not working while clicking on input box i am not able to enter any deatils in that can any body check and suggest me solution I have tried many related to CSS but none of them are working.

Link of form https://kulorgroup.com/contact-us/

Thank you,

答: this "jquery.touchSwipe.min.js" jquery on your page not let you click text box, remove "jquery.touchSwipe.min.js" from your contact page and check</p>

Title: Contact form 7 input box not clickable


问:
DatePicker dialog is not showing on single tap
Expectation:

When user will tap on MaterialTextView component, DatePickerDialog should open.

Whats happening:

User needs to tap twice on MaterialTextView component for opening DatePickerDialog.

MainActivity

```<code>protected void onCreate(Bundle SavedInstanceState){
MaterialTextView issueDate = findViewById(R.id.edIssueDate);
 issueDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            hideKeyboard(AddNewCoupon.this);
            DatePickerDialog datePickerDialog = new DatePickerDialog(AddNewCoupon.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    issueDate.setText(String.valueOf(dayOfMonth)+"/"+String.valueOf(month)+"/"+String.valueOf(year));
                    //newCustomer.hideKeyboard(AddNewCoupon.this);
                }
            }, year, month, day);
            datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            datePickerDialog.show();
        }
    });
}
</code>```

hideKeyboard() method:

```<code>public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    View view = activity.getCurrentFocus();
    if (view == null) {
        view = new View(activity);
    }

    if (imm != null)
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
</code>```

Layout:

```<code><com.google.android.material.textview.MaterialTextView
                        android:id="@+id/edIssueDate"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:ems="10"
                        android:focusable="auto"
                        android:focusableInTouchMode="true"
                        android:hint="@string/txtVIssueingDtHint"
                        android:nextFocusDown="@id/edExpDate"
                        android:onClick="showDatePickerDialogForIssue"
                        android:paddingLeft="4dp"
                        android:textColor="@color/design_default_color_on_secondary"
                        android:textSize="18sp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/textView2" />
</code>```

Dependencies:

```<code>dependencies {
...

implementation 'com.google.android.material:material:1.2.0-alpha04'

...
}
</code>```

Code runs perfectly as DatePickerDialog opens but the problem is user needs to tap twice for opeining it. Where I've made mistake? How can I fix the code?

答:
Remove this option unless it is a required option.</p>

```<code>android:focusable="auto"
android:focusableInTouchMode="true"
</code>```

Body:
Expectation:

When user will tap on MaterialTextView component, DatePickerDialog should open.

Whats happening:

User needs to tap twice on MaterialTextView component for opening DatePickerDialog.

MainActivity

protected void onCreate(Bundle SavedInstanceState){
MaterialTextView issueDate = findViewById(R.id.edIssueDate);
 issueDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Calendar c = Calendar.getInstance();
            int year = c.get(Calendar.YEAR);
            int month = c.get(Calendar.MONTH);
            int day = c.get(Calendar.DAY_OF_MONTH);

            hideKeyboard(AddNewCoupon.this);
            DatePickerDialog datePickerDialog = new DatePickerDialog(AddNewCoupon.this, new DatePickerDialog.OnDateSetListener() {
                @Override
                public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                    issueDate.setText(String.valueOf(dayOfMonth)+"/"+String.valueOf(month)+"/"+String.valueOf(year));
                    //newCustomer.hideKeyboard(AddNewCoupon.this);
                }
            }, year, month, day);
            datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis() - 1000);
            datePickerDialog.show();
        }
    });
}

hideKeyboard() method:

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    View view = activity.getCurrentFocus();
    if (view == null) {
        view = new View(activity);
    }

    if (imm != null)
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

Layout:

<com.google.android.material.textview.MaterialTextView
                        android:id="@+id/edIssueDate"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="4dp"
                        android:ems="10"
                        android:focusable="auto"
                        android:focusableInTouchMode="true"
                        android:hint="@string/txtVIssueingDtHint"
                        android:nextFocusDown="@id/edExpDate"
                        android:onClick="showDatePickerDialogForIssue"
                        android:paddingLeft="4dp"
                        android:textColor="@color/design_default_color_on_secondary"
                        android:textSize="18sp"
                        app:layout_constraintEnd_toEndOf="parent"
                        app:layout_constraintStart_toStartOf="parent"
                        app:layout_constraintTop_toBottomOf="@+id/textView2" />

Dependencies:

dependencies {
...

implementation 'com.google.android.material:material:1.2.0-alpha04'

...
}

Code runs perfectly as DatePickerDialog opens but the problem is user needs to tap twice for opeining it. Where I've made mistake? How can I fix the code?

Body:
Remove this option unless it is a required option.

android:focusable="auto"
android:focusableInTouchMode="true"


问:
How to pass variable to later in program / Inputting double to dialog box
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

```<code>void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}
</code>```

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.

答:
Call your function with the address of the variable that will hold the value until you want to use it

```<code>void function(double *variable) {
    /* ... */
    *variable = 42;
}
</code>```

and use the function like this

```<code>someotherfunction() {
    double variable;
    function(&variable);
    /* ... lots of code ... */
    /* ... and much later ... */
    use(variable);
}
</code>```

Or, make function return the value rather than void and saving it through a pointer

```<code>double function(void) {
    return 42;
}

someotherfunction() {
    double variable;
    variable = function();
    /* ... lots of code ... */
    /* ... and much later ... */
    use(variable);
}
</code>```

Body:
I'm trying to create a dialog box at the start of my program that allows the user to input a number that is then used in another function (actually in another C file) much later on in the program.

void function()
{
double variable;
char buf[256] = "400";
sprintf( buf, "%d", variable);
#ifdef WIN32
edit_dialog(NULL,"Enter variable", "Please enter the variable:", buf,260);
#endif
variable = atof(buf);
}

I'd like to pass 'variable' into another function later on in the program. The problem is, I don't need the variable until much later. I don't want to pass it between each and every function until it gets to the right part of the program. How do I do this?

Also when I launch this, I get the dialog box as I'd expect but the number in the box is not 400, as I would expect. Instead it is 2089881670(!) I assume I am handling memory incorrectly but don't understand why.

Body:
Call your function with the address of the variable that will hold the value until you want to use it

void function(double *variable) {
    /* ... */
    *variable = 42;
}

and use the function like this

someotherfunction() {
    double variable;
    function(&variable);
    /* ... lots of code ... */
    /* ... and much later ... */
    use(variable);
}

Or, make function return the value rather than void and saving it through a pointer

double function(void) {
    return 42;
}

someotherfunction() {
    double variable;
    variable = function();
    /* ... lots of code ... */
    /* ... and much later ... */
    use(variable);
}


问:
How can we delete one value only from the array of localStorage?
For example LocalStorage with  Key: watchlist, value: [5632, 5421, 2964]

```<code>const dataId = 5421;
const existingUnWatchlist = JSON.parse(localStorage.getItem('watchlist') || '[]');

if (existingUnWatchlist.includes(dataId)) {

        let index = existingUnWatchlist.indexOf(dataId);
        existingUnWatchlist.splice(index, dataId);
        localStorage.setItem('watchlist', JSON.stringify(existingUnWatchlist));

}
</code>```

Those above code delete array [1 : 5421] and whole rest part of all array below. I just want to delete a single array value can it be possible?

答:
Change

```<code> existingUnWatchlist.splice(index, dataId);
</code>```

to

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

The second argument of splice is how many elements to delete, anything after the second argument will be added

```<code>let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
</code>```

Body:
For example LocalStorage with  Key: watchlist, value: [5632, 5421, 2964]

const dataId = 5421;
const existingUnWatchlist = JSON.parse(localStorage.getItem('watchlist') || '[]');

if (existingUnWatchlist.includes(dataId)) {

        let index = existingUnWatchlist.indexOf(dataId);
        existingUnWatchlist.splice(index, dataId);
        localStorage.setItem('watchlist', JSON.stringify(existingUnWatchlist));

}

Those above code delete array [1 : 5421] and whole rest part of all array below. I just want to delete a single array value can it be possible?

Body:
Change

 existingUnWatchlist.splice(index, dataId);

to

 existingUnWatchlist.splice(index, 1);

The second argument of splice is how many elements to delete, anything after the second argument will be added

let arrDeletedItems = array.splice(start[, deleteCount[, item1[, item2[, ...]]]])


问:
ASP.NET MVC 5 Core Identity CompanyID foreign key on dbo.AspNetUsers table
I've got an MVC 5 app that uses Core Identity on a SQL server database. On the user registration view, I want to add a foreign key dropdown for the Company that the user is assigned to. It is a required field and a user can only be assigned to one company.

AspNetUsers

Company Table

```<code>public class ApplicationUser : IdentityUser
{
    ....
    public int? CompanyID { get; set; }

  //  [ForeignKey("CompanyId")]
  //  public virtual Company UserCompany { get; set; }
}
</code>```

I have added the CompanyID to the RegisterViewModel under the AccountViewModels.cs

```<code>public class RegisterViewModel
{
    ....

    [Required]
    [Display(Name = "Company")]
    public int CompanyID { get; set; }
</code>```

Then I have added the following to the AccountController:

```<code>    using System;
    using System.Globalization;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using EMS.Models;

    namespace EMS.Controllers
    {
       // [Authorize]
        public class AccountController : Controller
        {
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private ApplicationDbContext context;
    **private EMSEntities db = new EMSEntities();**

    public AccountController()
    {
        context = new ApplicationDbContext();
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName");**
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model, ApplicationUser applicationUser)
    {
        if (ModelState.IsValid)
        {
            **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName", model.CompanyID);**
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, **CompanyID = model.CompanyID** };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    // New Methods

        [AllowAnonymous]
        [HttpGet]
        public ActionResult RegisterRole()
    {
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        ViewBag.UserName = new SelectList(context.Users.ToList(), "UserName", "UserName");
        return View();
    }
</code>```

And then finally I have added the dropdown to the Register view:

```<code><div class="form-group">
    @Html.Label("Company", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("CompanyID", null, htmlAttributes: new { @class = "form-control" })
    </div>
</div>
</code>```

When running the app and trying to register a new user, I get the following error:

Register user issue

When trying to login, I get the same error on a different line:

Server Error in '/' Application. The model backing the
  'ApplicationDbContext' context has changed since the database was
  created. Consider using Code First Migrations to update the database
  (http://go.microsoft.com/fwlink/?LinkId=238269).

What is the problem?

答:
Thank you Jansen, your answer put me on the right track but did not solve the issue completely. What solved the issue was to add the following to the Global.asax file under Application_Start:</p>

```<code>    Database.SetInitializer<ApplicationDbContext>(null);
</code>```

Body:
I've got an MVC 5 app that uses Core Identity on a SQL server database. On the user registration view, I want to add a foreign key dropdown for the Company that the user is assigned to. It is a required field and a user can only be assigned to one company.

AspNetUsers

Company Table

public class ApplicationUser : IdentityUser
{
    ....
    public int? CompanyID { get; set; }

  //  [ForeignKey("CompanyId")]
  //  public virtual Company UserCompany { get; set; }
}

I have added the CompanyID to the RegisterViewModel under the AccountViewModels.cs

public class RegisterViewModel
{
    ....

    [Required]
    [Display(Name = "Company")]
    public int CompanyID { get; set; }

Then I have added the following to the AccountController:

    using System;
    using System.Globalization;
    using System.Linq;
    using System.Security.Claims;
    using System.Threading.Tasks;
    using System.Web;
    using System.Web.Mvc;
    using Microsoft.AspNet.Identity;
    using Microsoft.AspNet.Identity.Owin;
    using Microsoft.Owin.Security;
    using EMS.Models;

    namespace EMS.Controllers
    {
       // [Authorize]
        public class AccountController : Controller
        {
    private ApplicationSignInManager _signInManager;
    private ApplicationUserManager _userManager;
    private ApplicationDbContext context;
    **private EMSEntities db = new EMSEntities();**

    public AccountController()
    {
        context = new ApplicationDbContext();
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName");**
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(RegisterViewModel model, ApplicationUser applicationUser)
    {
        if (ModelState.IsValid)
        {
            **ViewBag.Company = new SelectList(db.Companies.ToList(), "ID", "CompanyName", model.CompanyID);**
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email, **CompanyID = model.CompanyID** };
            var result = await UserManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
                // Send an email with this link
                // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
                await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                return RedirectToAction("Index", "Home");
            }
            AddErrors(result);
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    // New Methods

        [AllowAnonymous]
        [HttpGet]
        public ActionResult RegisterRole()
    {
        ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
        ViewBag.UserName = new SelectList(context.Users.ToList(), "UserName", "UserName");
        return View();
    }

And then finally I have added the dropdown to the Register view:

    @Html.Label("Company", new { @class = "col-md-2 control-label" })

        @Html.DropDownList("CompanyID", null, htmlAttributes: new { @class = "form-control" })

When running the app and trying to register a new user, I get the following error:

Register user issue

When trying to login, I get the same error on a different line:

Server Error in '/' Application. The model backing the
  'ApplicationDbContext' context has changed since the database was
  created. Consider using Code First Migrations to update the database
  (http://go.microsoft.com/fwlink/?LinkId=238269).

What is the problem?

Body:
Thank you Jansen, your answer put me on the right track but did not solve the issue completely. What solved the issue was to add the following to the Global.asax file under Application_Start:

    Database.SetInitializer<ApplicationDbContext>(null);