问:
strtod accepts "e" but also "d" -- why?
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

```<code>#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}
</code>```

答:
What do you mean by "accepts"? This is the output I'm getting

```<code>::: [1.000000] [10.000000] [1.000000] [1.000000]
</code>```

strtod (as all other conversion routines in C) parses the string until it finds the character that "doesn't belong". That character is not considered an error, it is simply treated as a terminator character. In case of "1d1" only the first "1" is parsed and the parsing stops at 'd'. The result of conversion is 1.0 (as it should be).

If you asked strtod to return the "end pointer" from each call, you'd see that the pointer points to character 'd' for the input string with 'd' in it (the same applies to 'a' and 'f' as well).

If you are getting a different result, it must be a quirk of the implementation you are using.

Title: strtod accepts "e" but also "d" -- why?

Body:
I find this strange.

While it makes sense that strtod accepts 'e' as one of the characters (exactly one to be precise) in the input string I find that it also accepts 'd'.

Can someone please explain?

#include < stdio.h >
#include < stdlib.h >
int main ()
{
char *s[] = {"1a1", "1e1", "1d1", "1f1"};
char * pEnd;
double d0, d1, d2, d3;
d0 = strtod (s[0],&pEnd);
d1 = strtod (s[1],NULL);
d2 = strtod (s[2],NULL);
d3 = strtod (s[3],NULL);
printf ("::: [%f] [%f] [%f] [%f] \n", d0, d1, d2, d3);
return 0;
}

Body:
What do you mean by "accepts"? This is the output I'm getting

::: [1.000000] [10.000000] [1.000000] [1.000000]

strtod (as all other conversion routines in C) parses the string until it finds the character that "doesn't belong". That character is not considered an error, it is simply treated as a terminator character. In case of "1d1" only the first "1" is parsed and the parsing stops at 'd'. The result of conversion is 1.0 (as it should be).

If you asked strtod to return the "end pointer" from each call, you'd see that the pointer points to character 'd' for the input string with 'd' in it (the same applies to 'a' and 'f' as well).

If you are getting a different result, it must be a quirk of the implementation you are using.


来源: stackexchange

问:
ImportError: cannot import name 'GceClusterResolver'
I am following the guide for installing TensorFlow Slim, and I faced this error.

```<code>ImportError: cannot import name 'GceClusterResolver'
</code>```

I searched online and found some questions on Stack Overflow regarding "import error cannot import name xxx", but none of them is the same as mine. I've tried their solutions too but they didn't work.

This is the complete error message. Any help is greatly appreciated.

```<code>python -c "import tensorflow.contrib.slim as slim; eval = slim.evaluation.evaluate_once"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/__init__.py", line 31, in <module>
    from tensorflow.contrib import cluster_resolver
  File "/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/cluster_resolver/__init__.py", line 26, in <module>
    from tensorflow.python.distribute.cluster_resolver.gce_cluster_resolver import GceClusterResolver
ImportError: cannot import name 'GceClusterResolver'
</code>```

答:
I found out that i was using tflearn with tensorflow 2 but tflearn is not compatible with tensorflow 2. I just falled back to a tensorflow 1 version.

```<code># uninstall both libs
pip uninstall tensorflow
pip uninstall tflearn

# install the compatible version
pip install tflearn
pip install tensorflow==1.15
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am following the guide for installing TensorFlow Slim, and I faced this error.

ImportError: cannot import name 'GceClusterResolver'

I searched online and found some questions on Stack Overflow regarding "import error cannot import name xxx", but none of them is the same as mine. I've tried their solutions too but they didn't work.

This is the complete error message. Any help is greatly appreciated.

python -c "import tensorflow.contrib.slim as slim; eval = slim.evaluation.evaluate_once"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/__init__.py", line 31, in <module>
    from tensorflow.contrib import cluster_resolver
  File "/anaconda3/lib/python3.6/site-packages/tensorflow/contrib/cluster_resolver/__init__.py", line 26, in <module>
    from tensorflow.python.distribute.cluster_resolver.gce_cluster_resolver import GceClusterResolver
ImportError: cannot import name 'GceClusterResolver'

Body:
I found out that i was using tflearn with tensorflow 2 but tflearn is not compatible with tensorflow 2. I just falled back to a tensorflow 1 version.

# uninstall both libs
pip uninstall tensorflow
pip uninstall tflearn

# install the compatible version
pip install tflearn
pip install tensorflow==1.15


问:
Perfect forwarding with multiple passes over input arguments
Consider the following function accept that takes a "universal reference" of type T and forwards that to a parse<T>() function object with an overload for lvalues and one for rvalues:

```<code>template<class T>
void accept(T&& arg)
{
    parse<T>()(std::forward<T>(arg), 0); // copy or move, depending on rvaluedness of arg
}

template<class T>
class parse
{
    // parse will modify a local copy or move of its input parameter
    void operator()(T const& arg, int n) const { /* optimized for lvalues */ }
    void operator()(T&& arg)    , int n) const { /* optimized for rvalues */ }
};
</code>```

Since perfect forwarding leaves the source object in a valid but undefined state, it is impossible to perfectly forward again within the same scope. Below my attempt to have as few copies as possible in a hypothetical split() function that takes an int representing the number passes that have to be made over the input data:

```<code>template<class T>
void split(T&& arg, int n)
{
    for (auto i = 0; i < n - 1; ++i)
        parse<T>()(arg , i);                 // copy n-1 times
    parse<T>()(std::forward<T>(arg), n - 1); // possibly move the n-th time
}
</code>```

Question: is this the recommended way to apply perfect forwarding for multiple passes over the same data? If not, what is a more idiomatic way to minimize the number of copies?

答:
(I know, it is an old thread)

As stated in the comments, the data is a large array or vector of uint64_t. A better optimization than parameter passing to prevent a final copy would probably be to optimize the many copy operations to

read once

write many times (for each intended pass)

in one step instead of many independent copies.

A starting point could be this faster alternative to memcpy? which has answers that include memcpy-like code. You would have to multiply the code line that writes to the destination to write several copies of the data instead.

You can also combine memset, which is optimized for writing the same value to memory over and over again, and memcpy, which is optimized for reading and writing blocks of memory once for each block. You could look into optimized source code here: https://github.com/KNNSpeed/AVX-Memmove

The best code will be specific to the architecture and processor used. So you would have to test and compare your achieved speed.

ContentLicense: CC BY-SA 3.0

Body:
Consider the following function accept that takes a "universal reference" of type T and forwards that to a parse<T>() function object with an overload for lvalues and one for rvalues:

template<class T>
void accept(T&& arg)
{
    parse<T>()(std::forward<T>(arg), 0); // copy or move, depending on rvaluedness of arg
}

template<class T>
class parse
{
    // parse will modify a local copy or move of its input parameter
    void operator()(T const& arg, int n) const { /* optimized for lvalues */ }
    void operator()(T&& arg)    , int n) const { /* optimized for rvalues */ }
};

Since perfect forwarding leaves the source object in a valid but undefined state, it is impossible to perfectly forward again within the same scope. Below my attempt to have as few copies as possible in a hypothetical split() function that takes an int representing the number passes that have to be made over the input data:

template<class T>
void split(T&& arg, int n)
{
    for (auto i = 0; i < n - 1; ++i)
        parse<T>()(arg , i);                 // copy n-1 times
    parse<T>()(std::forward<T>(arg), n - 1); // possibly move the n-th time
}

Question: is this the recommended way to apply perfect forwarding for multiple passes over the same data? If not, what is a more idiomatic way to minimize the number of copies?


问:
How do I know if I need Full IIS in my Azure web role?
I need to migrate an ASP.NET application to Azure. The application needs database access and access to temporary files and also using out-proc COM objects. Turns out there's "Full IIS" mode that offers some rather vaguely phrased advantages (from here):

However there are a number of useful capabilities that only exist in IIS, including support for multiple sites or virtual applications and activation of WCF services over non-HTTP transports through Windows Activation Services.

Now obviously using Full IIS forces me to deal with the ASP.NET part and role part working in different processes and that's a big deal so I need to know whether I need Full IIS mode in the first place.

How do I decide if I need Full IIS mode? Is there a full checklist?

答:
I think your default answer should be use Full IIS in Windows Azure capabilities.  The hosted web core offering is really there for backwards compatibility as it was the original model prior to 1.3 SDK.  Full IIS is the default and you must explicitly opt to go back to HWC.

The reasons that most people wanted full IIS were around a few, but important limitations:

Better support for IIS extensions (e.g. Smooth Streaming, Web Farm, ARR, etc.).  HWC did not always support the modules and combined with a missing admin permission, made it really hard if not impossible to use all the modules that folks wanted to use.

Support for multiple web sites, vdirs, and application pools.  HWC is a single app pool (the hosting process) and no way to support multiple web sites.  There was a serious concern about needing to dedicate 1 entire role to a single web site.  With Full IIS, you can have multiple sites and use host headers to get more bang for buck out of web role (especially with small web sites)

Support for standard tooling - Web Deploy, AppCmd, etc. don't work really well (if at all) with HWC.  Anything that modified the applicationHost.config usually had issues with HWC.

WAS support.  This allows you to use WCF with IIS as a host in non-HTTP transports.

In general, with Full IIS you have parity with what you do on-premises so it makes it much easier to configure and setup.

Regarding the RoleEntryPoint/HWC process model versus the RoleEntryPoint and separate Full IIS process, I am not sure that is really an issue.  There were a few quirks perhaps initially, but what concerns you the most about this?


问:
How to save the data gathered in the address book?
I am using a file in text edit ubuntu. I am trying to figure out a way to save it. When I close the python shell and rerun it, it deletes all past info. Would I have to make a new function?

```<code>AdressBook  = '/home/bookworm/AdressBook.txt'
contacts = {}

def write():
    Data = open(AdressBook,'w')
    for name, many in contacts.items():
        Data.write(name + ',' + many)
    Data.close()

def read():
    Data = open(AdressBook, 'r')
    stuff = Data.read()
    print(stuff)
    Data.close()

user = input('Would you like to acess your adress book?')
if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':
</code>```

It is only the deleted and added contacts to be saved

```<code>    while user != 5:
        user = input('''Select One:
Press 1 to update
Press 2 to display all contacts
Press 3 to search adress book
Press 4 to delete contacts
Press 5 to quit your adress book.''')

        if user == '1':
            name = input('Please enter the name of the contact that you would like to add.')
            contact = input('Please enter the contact information of %s.'%name)
            Name = '\n' + name
            contacts.update( {Name : contact} )
            print('')
            print('%s was added to your adress book!' %name)
            print('')
            write()

        elif user == '2':
            read()
</code>```

To call read function

```<code>        elif user == '3':
            name = input('What is the name of the person whose contacts you need?')
            print(contacts[name])
</code>```

To delete a contact

```<code>        elif user == '4':
            name = input('Type in the name of the contact that you would like to delete.')
            del contacts[name]
            print('Your contact List has sucessfully deleted %s' %name)
            write()

        elif user == '5':
            print('Thank you for acessing your adress book!')
            exit()

else:
    exit()
</code>```

答:
Your file becomes empty everytime because you are taking contacts = {} in the start of the program. So instead of creating an empty dictionary, you need to initialize the dictionary with the file contents in the starting.

```<code>
AdressBook  = '/home/bookworm/AdressBook.txt'
contacts = initialize_contacts()

def write():
    Data = open(AdressBook,'w')
    for name, many in contacts.items():
        Data.write(name + ',' + many + '\n')
    Data.close()

def read():
    Data = open(AdressBook, 'r')
    stuff = Data.read()
    print(stuff)
    Data.close()
    return stuff

def initialize_contacts():
    data = read()
    contact_list = data.split('\n')
    for contact in contact_list[:-1]:
        name,cont = contact.split(',')
        contacts[name] = cont

</code>```

Body:
I am using a file in text edit ubuntu. I am trying to figure out a way to save it. When I close the python shell and rerun it, it deletes all past info. Would I have to make a new function?

AdressBook  = '/home/bookworm/AdressBook.txt'
contacts = {}

def write():
    Data = open(AdressBook,'w')
    for name, many in contacts.items():
        Data.write(name + ',' + many)
    Data.close()

def read():
    Data = open(AdressBook, 'r')
    stuff = Data.read()
    print(stuff)
    Data.close()

user = input('Would you like to acess your adress book?')
if user == 'yes' or 'yep' or 'y' or 'Yes' or 'YES!' or 'YES' or 'Yurp' or 'Yeppers' or
'si'or'1':

It is only the deleted and added contacts to be saved

    while user != 5:
        user = input('''Select One:
Press 1 to update
Press 2 to display all contacts
Press 3 to search adress book
Press 4 to delete contacts
Press 5 to quit your adress book.''')

        if user == '1':
            name = input('Please enter the name of the contact that you would like to add.')
            contact = input('Please enter the contact information of %s.'%name)
            Name = '\n' + name
            contacts.update( {Name : contact} )
            print('')
            print('%s was added to your adress book!' %name)
            print('')
            write()

        elif user == '2':
            read()

To call read function

        elif user == '3':
            name = input('What is the name of the person whose contacts you need?')
            print(contacts[name])

To delete a contact

        elif user == '4':
            name = input('Type in the name of the contact that you would like to delete.')
            del contacts[name]
            print('Your contact List has sucessfully deleted %s' %name)
            write()

        elif user == '5':
            print('Thank you for acessing your adress book!')
            exit()

else:
    exit()

Body:
Your file becomes empty everytime because you are taking contacts = {} in the start of the program. So instead of creating an empty dictionary, you need to initialize the dictionary with the file contents in the starting.

AdressBook  = '/home/bookworm/AdressBook.txt'
contacts = initialize_contacts()

def write():
    Data = open(AdressBook,'w')
    for name, many in contacts.items():
        Data.write(name + ',' + many + '\n')
    Data.close()

def read():
    Data = open(AdressBook, 'r')
    stuff = Data.read()
    print(stuff)
    Data.close()
    return stuff

def initialize_contacts():
    data = read()
    contact_list = data.split('\n')
    for contact in contact_list[:-1]:
        name,cont = contact.split(',')
        contacts[name] = cont


问:
Ag grid header checkbox selection
I am using Ag-grid with server-side data

HTML code is:

<ag-grid-angular *ngIf="isShowProceedButton" #agGrid style="width: 100%; height: 70vh; float: left;" class="ag-theme-balham template-grid" [enableSorting]="true" [enableFilter]="true" [gridOptions]="gridOptions" (gridReady)="onGridReady($event)" rowSelection="multiple">
</ag-grid-angular>
```
<p>TS file code:</p>

<pre class="lang-js prettyprint-override"><code>this.columnDefs.push({
  // headerName: keyValues[j], field: this.headers[i],
  headerName: keyValues[j],
  field: this.headers[i],
  'isMapped': 0,
  'skipRow': this.rowHeader[i].skipRow,
  headerComponentFramework: AgGridCheckboxComponent,
  'isShowCheckBox': this.isShowProceedButton
})
</code>```

It will show me the grid with checkbox:

Why when I uncheck the checkbox e.g. uncheck FY2014E and scroll horizontally then again it shows the checkbox as selected?

答:
Hi Harshal you have to set suppressColumnVirtualisation property in your gridOptions like that:</p>

```<code>this.gridOptions.suppressColumnVirtualisation = true;
</code>```

Title: Ag grid header checkbox selection

Body:
I am using Ag-grid with server-side data

HTML code is:

<ag-grid-angular *ngIf="isShowProceedButton" #agGrid style="width: 100%; height: 70vh; float: left;" class="ag-theme-balham template-grid" [enableSorting]="true" [enableFilter]="true" [gridOptions]="gridOptions" (gridReady)="onGridReady($event)" rowSelection="multiple">
</ag-grid-angular>

TS file code:

this.columnDefs.push({
  // headerName: keyValues[j], field: this.headers[i],
  headerName: keyValues[j],
  field: this.headers[i],
  'isMapped': 0,
  'skipRow': this.rowHeader[i].skipRow,
  headerComponentFramework: AgGridCheckboxComponent,
  'isShowCheckBox': this.isShowProceedButton
})

It will show me the grid with checkbox:

Why when I uncheck the checkbox e.g. uncheck FY2014E and scroll horizontally then again it shows the checkbox as selected?

Body:
Hi Harshal you have to set suppressColumnVirtualisation property in your gridOptions like that:

this.gridOptions.suppressColumnVirtualisation = true;


问:
Calculating sum until the indexPath.row instead of total using tableView
I had a question about calculation functions and I cant seem to understand the logic behind it yet as I just started to do coding in iOS about 3 months ago.

Here's a screenshot in the link and please take a look at it.

I would like to achieve results as explained Below

Expected Results : there will be more than 10000 cell of rows eventually, so my sum Cell will required to calculate based on the first index of the data instead of cell, I tried enumerated, mapping, for in loops but to no success
.

PLEASE PROVIDE CODE ALONG WITH YOUR EXPLANATION SO I CAN UNDERSTAND AS I AM NOT AN EXPERIENCED CODER

Example

UIVIEW

TotalBalance = $ 28.00 << Achieve by updateTotal()

TableView

TransactionType : $ 10.00 ($10.00) < this will sum cell 1 only as it is the first cell

TransactionType : $ 5.00  ($15.00) < this will sum cell 1 - 2 only

TransactionType : $ 3.00  ($18.00) < this will sum cell 1 - 3 only

TransactionType : $ 10.00 ($28.00) < this will sum cell 1 -  4 only

```<code>class Account: Object {
    @objc dynamic var name : String = ""
    @objc dynamic var balance : Double = 0

    var ofTransaction = List<Transaction>()

}

class Transaction: Object {
    @objc dynamic var name : String = ""
    @objc dynamic var amount : Double = 0

    var parentAccount = LinkingObjects(fromType: Account.self, property: "ofTransaction")

}

class AccountCell: UITableViewCell {
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var amount: UILabel!
    @IBOutlet weak var sum: UILabel!

}

</code>```

```<code>    func updateTotal() {
        let total = getTransactions
            .map { $0.amount }
            .reduce(0, +)

        let totalFormatter = NumberFormatter()

        totallabel.text = totalFormatter.string(for: total)!
    }
</code>```

```<code>   override func viewDidLoad() {
       super.viewDidLoad()
       account = realm.objects(Account.self)
       getTransactions = realm.objects(Transaction.self)

   }
 // MARK: - Table view data source
   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AccountCell

       if let transCell = getTransactions?[indexPath.row] {
           cell.name.text = transCell.name
           cell.amount.text = "\(transCell.amount)"

           ///Wrong Logic : This logic updates the Sum to Total !
           let sumCell = getTransactions
               .map { $0.amount }
               .reduce(0, +)

           cell.sum.text = "\(sumCell)"

       }
       return cell
   }
</code>```

答:
Use it like below-</p>

```<code>override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AccountCell

    if let transCell = getTransactions?[indexPath.row] {
        cell.name.text = transCell.name
        cell.amount.text = "\(transCell.amount)"

        //Correct calculation in Loops
        var sumUp = 0.0
        for (index,trans) in getTransactions.enumerated() {
            if (index == indexPath.row) { break }
            sumUp += trans.amount
            cell.sum.text = "\(sumUp)"

        }
    }

    return cell
}
</code>```

Body:
I had a question about calculation functions and I cant seem to understand the logic behind it yet as I just started to do coding in iOS about 3 months ago.

Here's a screenshot in the link and please take a look at it.

I would like to achieve results as explained Below

Expected Results : there will be more than 10000 cell of rows eventually, so my sum Cell will required to calculate based on the first index of the data instead of cell, I tried enumerated, mapping, for in loops but to no success
.

PLEASE PROVIDE CODE ALONG WITH YOUR EXPLANATION SO I CAN UNDERSTAND AS I AM NOT AN EXPERIENCED CODER

Example

UIVIEW

TotalBalance = $ 28.00 << Achieve by updateTotal()

TableView

TransactionType : $ 10.00 ($10.00) < this will sum cell 1 only as it is the first cell

TransactionType : $ 5.00  ($15.00) < this will sum cell 1 - 2 only

TransactionType : $ 3.00  ($18.00) < this will sum cell 1 - 3 only

TransactionType : $ 10.00 ($28.00) < this will sum cell 1 -  4 only

class Account: Object {
    @objc dynamic var name : String = ""
    @objc dynamic var balance : Double = 0

    var ofTransaction = List<Transaction>()

}

class Transaction: Object {
    @objc dynamic var name : String = ""
    @objc dynamic var amount : Double = 0

    var parentAccount = LinkingObjects(fromType: Account.self, property: "ofTransaction")

}

class AccountCell: UITableViewCell {
    @IBOutlet weak var name: UILabel!
    @IBOutlet weak var amount: UILabel!
    @IBOutlet weak var sum: UILabel!

}

    func updateTotal() {
        let total = getTransactions
            .map { $0.amount }
            .reduce(0, +)

        let totalFormatter = NumberFormatter()

        totallabel.text = totalFormatter.string(for: total)!
    }

   override func viewDidLoad() {
       super.viewDidLoad()
       account = realm.objects(Account.self)
       getTransactions = realm.objects(Transaction.self)

   }
 // MARK: - Table view data source
   override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AccountCell

       if let transCell = getTransactions?[indexPath.row] {
           cell.name.text = transCell.name
           cell.amount.text = "\(transCell.amount)"

           ///Wrong Logic : This logic updates the Sum to Total !
           let sumCell = getTransactions
               .map { $0.amount }
               .reduce(0, +)

           cell.sum.text = "\(sumCell)"

       }
       return cell
   }

Body:
Use it like below-

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! AccountCell

    if let transCell = getTransactions?[indexPath.row] {
        cell.name.text = transCell.name
        cell.amount.text = "\(transCell.amount)"

        //Correct calculation in Loops
        var sumUp = 0.0
        for (index,trans) in getTransactions.enumerated() {
            if (index == indexPath.row) { break }
            sumUp += trans.amount
            cell.sum.text = "\(sumUp)"

        }
    }

    return cell
}


问:
Updating an Activity from an AsyncTask
So I'm an iOS developer learning android, and I'm having a difficult time understanding some things. Right now I have a datamanager class. In that class it has an AsyncTask to update the data. OnPreExecute I pop an activity to show it is updating. I understand I could use extras to pass initial information to the UpdateActivity. My problem is I'm not sure how to send new information in OnProgressUpdate. Here is my code widdled down:</p>

```<code>    private class myTask extends AsyncTask<Integer,String,Void>{

    @Override
    protected void onCancelled() {
        super.onCancelled();
        isUpdating = false;
    }

    @Override
    protected Void doInBackground(Integer... params) {
        //My BG Code
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Remove updating view
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Intent myIntent = new Intent(mContext,UpdateActivity.class);
        mContext.startActivity(myIntent);
    }
}
</code>```

答:
AsyncTask is designed to work best when nested in an Activity class.

What makes AsyncTask 'special' is that it isn't just a worker thread - instead it combines a worker thread which processes the code in doInBackground(...) with methods which run on the Activity's UI thread - onProgressUpdate(...) and onPostExecute(...) being the most commonly used.

By periodically calling updateProgress(...) from doInBackground(...), the onProgressUpdate(...) method is called allowing it to manipulate the Activity's UI elements (progress bar, text to show name of file being downloaded, etc etc).

In short, rather than firing your 'update' Activity from an AsyncTask, your update Activity itself should have a nested AsyncTask which it uses to process the update and publish progress to the UI.

Title: Updating an Activity from an AsyncTask

Body:
So I'm an iOS developer learning android, and I'm having a difficult time understanding some things. Right now I have a datamanager class. In that class it has an AsyncTask to update the data. OnPreExecute I pop an activity to show it is updating. I understand I could use extras to pass initial information to the UpdateActivity. My problem is I'm not sure how to send new information in OnProgressUpdate. Here is my code widdled down:

    private class myTask extends AsyncTask<Integer,String,Void>{

    @Override
    protected void onCancelled() {
        super.onCancelled();
        isUpdating = false;
    }

    @Override
    protected Void doInBackground(Integer... params) {
        //My BG Code
    }

    @Override
    protected void onPostExecute(Void result) {
        // TODO Remove updating view
        super.onPostExecute(result);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Intent myIntent = new Intent(mContext,UpdateActivity.class);
        mContext.startActivity(myIntent);
    }
}


问:
Boxplot and line with dual y-axis from two data frame using ggplot in R
I am using ggplot to put boxplot and line in the same plot. I have two data frames, here are snippets for these two DFs:

```<code> TMA.core variable    value
1      I-5      H&E 356642.6
2      B-1      H&E 490276.9
3      B-13      H&E 460831.8
4      L-11      H&E 551614.2
5      B-6      H&E 663711.8
6      F-10      H&E 596832.8
</code>```

(there are many variables.)

```<code>    TMA.core     Mean        CoV
   I-5 390829.7 0.15181577
   B-1 414909.9 0.21738852
   B-13 500829.8 0.39049256
   L-11 537229.7 0.07387486
   B-6 575698.9 0.44764127
   F-10 589245.2 0.15382864
</code>```

What I want to do is draw boxplot using the first data frame and then plot the CoV for the corresponding TMA core and connect using geom_line.
My codes are:

```<code>ggplot() +
geom_boxplot(data = Merge_stats_melt, aes(x = reorder(TMA.core, value, FUN = mean), y = value)) +
geom_line(data = Merge_stas_mean_order, aes(x = reorder(TMA.core, Mean), y = CoV, group = 1)) +
scale_y_continuous(
# Add a second axis and specify its features
sec.axis = sec_axis(~./1000000, name = 'CoV')
)
</code>```

Using these codes I can draw the boxplot but the line is always a horizontal line at y = 0.
How to solve this issue?

答:
Using one or two data frames doesn't really matter. Just remember to adjust the y aesthetic accordingly, which you forgot to do.

```<code>library(ggplot2)
library(scales)
</code>```

Find the ideal scaling factor for the dual axis

```<code>ratio <- max(Merge_stats_melt$value) / max(Merge_stas_mean_order$CoV)

ggplot() +
  geom_boxplot(data = Merge_stats_melt, aes(x = reorder(TMA.core, value, FUN = mean), y = value)) +
  geom_line(data = Merge_stas_mean_order, aes(x = reorder(TMA.core, Mean), y = CoV*ratio, group = 1)) +
  scale_y_continuous(labels=comma,
    sec.axis = sec_axis(~./ratio, name = 'CoV')
  )
</code>```

Body:
I am using ggplot to put boxplot and line in the same plot. I have two data frames, here are snippets for these two DFs:

 TMA.core variable    value
1      I-5      H&E 356642.6
2      B-1      H&E 490276.9
3      B-13      H&E 460831.8
4      L-11      H&E 551614.2
5      B-6      H&E 663711.8
6      F-10      H&E 596832.8

(there are many variables.)

    TMA.core     Mean        CoV
   I-5 390829.7 0.15181577
   B-1 414909.9 0.21738852
   B-13 500829.8 0.39049256
   L-11 537229.7 0.07387486
   B-6 575698.9 0.44764127
   F-10 589245.2 0.15382864

What I want to do is draw boxplot using the first data frame and then plot the CoV for the corresponding TMA core and connect using geom_line.
My codes are:

ggplot() +
geom_boxplot(data = Merge_stats_melt, aes(x = reorder(TMA.core, value, FUN = mean), y = value)) +
geom_line(data = Merge_stas_mean_order, aes(x = reorder(TMA.core, Mean), y = CoV, group = 1)) +
scale_y_continuous(
# Add a second axis and specify its features
sec.axis = sec_axis(~./1000000, name = 'CoV')
)

Using these codes I can draw the boxplot but the line is always a horizontal line at y = 0.
How to solve this issue?

Body:
Using one or two data frames doesn't really matter. Just remember to adjust the y aesthetic accordingly, which you forgot to do.

library(ggplot2)
library(scales)

Find the ideal scaling factor for the dual axis

ratio <- max(Merge_stats_melt$value) / max(Merge_stas_mean_order$CoV)

ggplot() +
  geom_boxplot(data = Merge_stats_melt, aes(x = reorder(TMA.core, value, FUN = mean), y = value)) +
  geom_line(data = Merge_stas_mean_order, aes(x = reorder(TMA.core, Mean), y = CoV*ratio, group = 1)) +
  scale_y_continuous(labels=comma,
    sec.axis = sec_axis(~./ratio, name = 'CoV')
  )


问:
Not Able To get the token Id in flutter
I am using below code to register new user in Flutter Application with Firebase as backend, but I am not able to retrieve the token id in my application, when I tried to save it the firestore database it is storing it as null.

```<code>FirebaseAuth.instance
                      .createUserWithEmailAndPassword(
                      email: emailInputController.text,
                      password: pwdInputController.text)
                      .then((currentUser) =>
                      Firestore.instance
                          .collection("users")
                          .document(currentUser.user.uid)
                          .setData({
                        "id": currentUser.user.uid,
                        "tokenId": currentUser.user.getIdToken(),
                        "fullname": fullNameInputController.text,
                      })
</code>```

I receive this in my logs about the tokenId

Invalid argument: Instance of 'Future<'IdTokenResult'>'

答:
As indicated in the official documentation getIdToken(), it actually returns a promise, so you won't be able to directly access the value. You will need to await the value to be loaded and them manage it. You will need to handle as in the below code sample:

```<code>FirebaseAuth.instance.currentUser().then(user => {
        if (user != null) {
           user.getIdToken().then(token => {
             //handle token
           }
        }
});
</code>```

In case you want a more direct way, the below line should work for you too.

```<code>var token = await FirebaseAuth.instance.currentUser().getIdToken();
</code>```

While this codes are untested,, I believe they should help you have handle the promise, you should have the value and saving it in your database should not face any more issues.

Let me know if the information helped you!

Title: Not Able To get the token Id in flutter

Body:
I am using below code to register new user in Flutter Application with Firebase as backend, but I am not able to retrieve the token id in my application, when I tried to save it the firestore database it is storing it as null.

FirebaseAuth.instance
                      .createUserWithEmailAndPassword(
                      email: emailInputController.text,
                      password: pwdInputController.text)
                      .then((currentUser) =>
                      Firestore.instance
                          .collection("users")
                          .document(currentUser.user.uid)
                          .setData({
                        "id": currentUser.user.uid,
                        "tokenId": currentUser.user.getIdToken(),
                        "fullname": fullNameInputController.text,
                      })

I receive this in my logs about the tokenId

Invalid argument: Instance of 'Future<'IdTokenResult'>'

Body:
As indicated in the official documentation getIdToken(), it actually returns a promise, so you won't be able to directly access the value. You will need to await the value to be loaded and them manage it. You will need to handle as in the below code sample:

FirebaseAuth.instance.currentUser().then(user => {
        if (user != null) {
           user.getIdToken().then(token => {
             //handle token
           }
        }
});

In case you want a more direct way, the below line should work for you too.

var token = await FirebaseAuth.instance.currentUser().getIdToken();

While this codes are untested,, I believe they should help you have handle the promise, you should have the value and saving it in your database should not face any more issues.

Let me know if the information helped you!


问:
Convert bigint value formatted as 20200321 to datetime formatted as '2020-03-21 00:00:00'
How do we convert the bigint value 20200321 which is a date(2020-03-21 i.e., 21st March, 2020) to datetime format '2020-03-21 00:00:00' so that we can map with other tables

答:
Cast your bigint to varchar first and then cast to datetime.

```<code>declare @a as bigint = 20200321;
select CAST(CAST(@A AS varchar) as datetime)
</code>```

Body:
Cast your bigint to varchar first and then cast to datetime.

declare @a as bigint = 20200321;
select CAST(CAST(@A AS varchar) as datetime)


问:
Why doesn't Symfony 5.1 recognize routes configured on a "routes.php" file?
I'm having a hard time trying to configure my routes using a config/routes.php file in Symfony 5.1.

As per the Symfony routing documentation, I should be able to configure my routes in a PHP file:

Instead of defining routes in the controller classes, you can define them in a separate YAML, XML or PHP file. The main advantage is that they don't require any extra dependency.

But in practice, Symfony only recognizes the routes if I put my routes in a file routes.yaml.

Routes configured inside a file routes.php result in the error "No route found for "GET /something" (404 Not Found)".   When running debug:router, these routes are not listed.

The same route works great when configured in routes.yaml.

In a different project using Symfony 5.0.8, route configuration via routes.php is working like a charm.

This is how I tested it:

Created a controller (omitted, since it's no relevant, any controller would do)

Created a routes.php file:

//config/routes.php example

use App\Controller;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

return function(RoutingConfigurator $routes)
{
    $routes->add('schools_list', '/schools')
        ->controller([Controller\SchoolController::class, 'list'])
        ->methods(['GET']);
};
```

<ol start="3">
<li>Running <code>debug:router</code> will result in:</li>
</ol>

``` ---------------- -------- -------- ------ --------------------------
  Name             Method   Scheme   Host   Path
 ---------------- -------- -------- ------ --------------------------
  _preview_error   ANY      ANY      ANY    /_error/{code}.{_format}
 ---------------- -------- -------- ------ --------------------------
```

<ol start="4">
<li>Configured the same route inside <code>routes.yaml</code>:</li>
</ol>

<pre class="lang-yaml prettyprint-override"><code>#config/routes.yaml
schools_list:
    path: /schools
    controller: App\Controller\SchoolController::list
    methods: GET
</code>```

Running debug:router will result in:

```<code> ---------------- -------- -------- ------ --------------------------
  Name             Method   Scheme   Host   Path
 ---------------- -------- -------- ------ --------------------------
  _preview_error   ANY      ANY      ANY    /_error/{code}.{_format}
  schools_list     GET      ANY      ANY    /schools
 ---------------- -------- -------- ------ --------------------------
</code>```

答:
On Symfony < 5.1, the default Kernel::configureRoutes() looked like this:

```<code>protected function configureRoutes(RouteCollectionBuilder $routes): void
{
    $confDir = $this->getProjectDir().'/config';

    $routes->import($confDir.'/{routes}/'.$this->environment.'/*'.self::CONFIG_EXTS, '/', 'glob');
    $routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob');
    $routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
}
</code>```

Notice specifically Kernel::CONFIG_EXTS, which is set to:

```<code>private const CONFIG_EXTS = '.{php,xml,yaml,yml}';
</code>```

So it will try loading routes from PHP, XML OR YAML files (it will even attempt to load YAML from files with the .yml extension).

But on Symfony 5.1+, this method has been changed to:

```<code>protected function configureRoutes(RoutingConfigurator $routes): void
{
    $routes->import('../config/{routes}/'.$this->environment.'/*.yaml');
    $routes->import('../config/{routes}/*.yaml');
    $routes->import('../config/{routes}.yaml');
}
</code>```

Now it only attempts to load YAML files by default. Yup, sad. But it has a very easy fix.

(Notice also that RouteCollectionBuilder has been replaced with RoutingConfigurator, since type-hinting the former has been deprecated on 5.1).

Just change your Kernel::configureRoutes() to account for your PHP files:

```<code>protected function configureRoutes(RoutingConfigurator $routes): void
{
    $extensions = '{php,yaml}';

    $routes->import('../config/{routes}/' . $this->environment . "/*.$extensions");
    $routes->import("../config/{routes}/*.$extensions");
    $routes->import("../config/{routes}.$extensions");
}
</code>```

And you will be ready to go.

Body:
I'm having a hard time trying to configure my routes using a config/routes.php file in Symfony 5.1.

As per the Symfony routing documentation, I should be able to configure my routes in a PHP file:

Instead of defining routes in the controller classes, you can define them in a separate YAML, XML or PHP file. The main advantage is that they don't require any extra dependency.

But in practice, Symfony only recognizes the routes if I put my routes in a file routes.yaml.

Routes configured inside a file routes.php result in the error "No route found for "GET /something" (404 Not Found)".   When running debug:router, these routes are not listed.

The same route works great when configured in routes.yaml.

In a different project using Symfony 5.0.8, route configuration via routes.php is working like a charm.

This is how I tested it:

Created a controller (omitted, since it's no relevant, any controller would do)

Created a routes.php file:

//config/routes.php example

use App\Controller;
use Symfony\Component\Routing\Loader\Configurator\RoutingConfigurator;

return function(RoutingConfigurator $routes)
{
    $routes->add('schools_list', '/schools')
        ->controller([Controller\SchoolController::class, 'list'])
        ->methods(['GET']);
};

Running debug:router will result in:

 ---------------- -------- -------- ------ --------------------------
  Name             Method   Scheme   Host   Path
 ---------------- -------- -------- ------ --------------------------
  _preview_error   ANY      ANY      ANY    /_error/{code}.{_format}
 ---------------- -------- -------- ------ --------------------------

Configured the same route inside routes.yaml:

#config/routes.yaml
schools_list:
    path: /schools
    controller: App\Controller\SchoolController::list
    methods: GET

Running debug:router will result in:

 ---------------- -------- -------- ------ --------------------------
  Name             Method   Scheme   Host   Path
 ---------------- -------- -------- ------ --------------------------
  _preview_error   ANY      ANY      ANY    /_error/{code}.{_format}
  schools_list     GET      ANY      ANY    /schools
 ---------------- -------- -------- ------ --------------------------

Body:
On Symfony < 5.1, the default Kernel::configureRoutes() looked like this:

protected function configureRoutes(RouteCollectionBuilder $routes): void
{
    $confDir = $this->getProjectDir().'/config';

    $routes->import($confDir.'/{routes}/'.$this->environment.'/*'.self::CONFIG_EXTS, '/', 'glob');
    $routes->import($confDir.'/{routes}/*'.self::CONFIG_EXTS, '/', 'glob');
    $routes->import($confDir.'/{routes}'.self::CONFIG_EXTS, '/', 'glob');
}

Notice specifically Kernel::CONFIG_EXTS, which is set to:

private const CONFIG_EXTS = '.{php,xml,yaml,yml}';

So it will try loading routes from PHP, XML OR YAML files (it will even attempt to load YAML from files with the .yml extension).

But on Symfony 5.1+, this method has been changed to:

protected function configureRoutes(RoutingConfigurator $routes): void
{
    $routes->import('../config/{routes}/'.$this->environment.'/*.yaml');
    $routes->import('../config/{routes}/*.yaml');
    $routes->import('../config/{routes}.yaml');
}

Now it only attempts to load YAML files by default. Yup, sad. But it has a very easy fix.

(Notice also that RouteCollectionBuilder has been replaced with RoutingConfigurator, since type-hinting the former has been deprecated on 5.1).

Just change your Kernel::configureRoutes() to account for your PHP files:

protected function configureRoutes(RoutingConfigurator $routes): void
{
    $extensions = '{php,yaml}';

    $routes->import('../config/{routes}/' . $this->environment . "/*.$extensions");
    $routes->import("../config/{routes}/*.$extensions");
    $routes->import("../config/{routes}.$extensions");
}

And you will be ready to go.


问:
Turbo Assembler 16 bit compiler on Windows 10
I just want to compile and debug my assembler projects easily and i downloaded Visual ASM programm for windows 10. Its runs and work on 32 bit TASM compiler, but i cant compile on 16 bit compiler. Before it i used dos-box for emulating dos to compile 16 bit commands. Now i want to know is  there possible way to compile some 16 bit commands on windows 10. Sorry for my english, thanks. </p>

答:
Of course you can write and compile 16bit realmode programs on 64bit windows, but you cannot run them, because the embedded DOS emulator NTVDM.EXE is available only on 32bit Windows.
We have to install 3rd party emulator, e.g. DosBox.

```<code>D:>ver
DOSBox version 0.74-2. Reported DOS version 5.00
D:>tasm.exe
Turbo Assembler Version 2.01 Copyright (c) 1988, 1990 Borland International
Syntax:  TASM [options] source [,object], [,listing] [,xref]
</code>```

Within DOSBox you can assemble, link, debug, execute with 16bit tools TASM.EXE, TLINK.EXE, TD.EXE.

Borland in 1993 released its 32bit compiler with built-in extender 32RTF which can run on 64bit Windows, your visual IDE probably uses that version:

```<code>C:\>ver
Microsoft Windows [Version 10.0.16299.15]
C:\>tasm.exe
Turbo Assembler  Version 4.0  Copyright (c) 1988, 1993 Borland International
Syntax:  TASM [options] source [,object] [,listing] [,xref]
</code>```

However, you still cannot execute 16bit programs written in it outside of DOSBox.
You should abandon the realm of 16 bits, as @PeterCordes told you.

Body:
Of course you can write and compile 16bit realmode programs on 64bit windows, but you cannot run them, because the embedded DOS emulator NTVDM.EXE is available only on 32bit Windows.
We have to install 3rd party emulator, e.g. DosBox.

D:>ver
DOSBox version 0.74-2. Reported DOS version 5.00
D:>tasm.exe
Turbo Assembler Version 2.01 Copyright (c) 1988, 1990 Borland International
Syntax:  TASM [options] source [,object], [,listing] [,xref]

Within DOSBox you can assemble, link, debug, execute with 16bit tools TASM.EXE, TLINK.EXE, TD.EXE.

Borland in 1993 released its 32bit compiler with built-in extender 32RTF which can run on 64bit Windows, your visual IDE probably uses that version:

C:\>ver
Microsoft Windows [Version 10.0.16299.15]
C:\>tasm.exe
Turbo Assembler  Version 4.0  Copyright (c) 1988, 1993 Borland International
Syntax:  TASM [options] source [,object] [,listing] [,xref]

However, you still cannot execute 16bit programs written in it outside of DOSBox.
You should abandon the realm of 16 bits, as @PeterCordes told you.


问:
Activate MVC Web site on IIS 7 Windows Server 2008 R2 Enterprise SP2
I have create a new ASP.NET Core 2.1 project empty on Visual Studio 2019

This is generated by a line in the Startup.cs file

```<code>public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}
</code>```

The application can serve static files HTML from the wwwroot folder.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <p>test</p>
</body>
</html>
</code>```

The project working on localhost

I need published it to a folder on remote server with SO Windows Server 2008 R2 Enterprise SP2.

I had IIS 7 installed on server.

I installed .Net 4.5.2 and asp.net 2.1 core runtime and asp.net core 3.1 runtime on the server 2008 R2 SP2

I copied the folder contiaining my published Web site to \inetpub\wwwroot on the server.

With this post I configured MVC website in IIS.

https://www.codeproject.com/Articles/1168712/How-to-Quickly-Configure-your-MVC-Website-in-IIS

But on the server the return is

When click on wwwroot project folder

What do I do to give the Web site a URL and otherwise make it active as a Web site?

Maybe I have to install more on the server?

update

Installed on the server

it finally worked thanks to everyone for the support and help

答:
We should use DotNet build, DotNet publish command to publish our website rather than copy the project file to the website directory.

https://learn.microsoft.com/en-us/aspnet/core/tutorials/publish-to-iis?view=aspnetcore-3.1&tabs=netcore-cli

In Visual studio, we just need to use the below menu to publish website since VS is a strong, powerful IDE.

Select folder and type the physical path of the website.

At last, we need to install the corresponding Asp.Net hosting bundles(2.1 version instead of 3.1) in order to host Asp.net core web application in IIS.

Result.

Feel free to let me know if the problem still exists.

Body:
I have create a new ASP.NET Core 2.1 project empty on Visual Studio 2019

This is generated by a line in the Startup.cs file

public class Startup
{
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

The application can serve static files HTML from the wwwroot folder.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title></title>

test

The project working on localhost

I need published it to a folder on remote server with SO Windows Server 2008 R2 Enterprise SP2.

I had IIS 7 installed on server.

I installed .Net 4.5.2 and asp.net 2.1 core runtime and asp.net core 3.1 runtime on the server 2008 R2 SP2

I copied the folder contiaining my published Web site to \inetpub\wwwroot on the server.

With this post I configured MVC website in IIS.

https://www.codeproject.com/Articles/1168712/How-to-Quickly-Configure-your-MVC-Website-in-IIS

But on the server the return is

When click on wwwroot project folder

What do I do to give the Web site a URL and otherwise make it active as a Web site?

Maybe I have to install more on the server?

update

Installed on the server

it finally worked thanks to everyone for the support and help


问:
Remove empty brackets ( ) from string
I had a problem in removing empty brackets from string, I tried few methods didn't work. kindly help

here is the dataframe

```<code>data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
print(df1)
</code>```

which have multiple occurrence of ( ) need to remove only empty brackets.

input:

```<code>      disc
0   ( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( ) ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-p
</code>```

output:

```<code>     disc
0   -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane boc-epoxideide
</code>```

using replace is not helping because it will remove all brackets there in the string.

答:
replace should work:

a="'( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol"

>>> a.replace("( )","")
>>> "' -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol"
```

Title: Remove empty brackets ( ) from string

Body:
I had a problem in removing empty brackets from string, I tried few methods didn't work. kindly help

here is the dataframe

data = {'disc': ['( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate','( ) ( s ) -isopropyl 2 ','( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane ( ) boc-epoxideide']}
df1 = pd.DataFrame(data)
print(df1)

which have multiple occurrence of ( ) need to remove only empty brackets.

input:

      disc
0   ( ) -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( ) ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-p

output:

     disc
0   -2,4-dichloro-a- ( chloromethyl ) -benzenemethanol methanesulfonate
1   ( s ) -isopropyl 2
2   ( 2s3s ) -12-epoxy-3- ( boc-amino ) -4-phenylbutane boc-epoxideide

using replace is not helping because it will remove all brackets there in the string.


问:
Kinesis vs KPL vs KCL
This is somewhat of a shallow-level question. However, I perplexed by this trio of services.

I understand that KPL produces fast data and KCL consumes fast data produced by Kinesis. However, what I fail to understand is the if KPL and KCL make up this pair, what do we need AWS Kinesis for?

Another way to look at it: If AWS Kinesis can produce the fast data and KCL can consume it, then what we need KPL for?

Any clarifying answer is greatly appreciated.

答:
AWS Kinesis is a very broad platform. Roughly , you can think of AWS Kinesis as:
Kinesis Data Streams + Kinesis Video Streams + Kinesis Firehose + Kinesis Analytics.
(Each one has its own purpose).

More detail here: https://aws.amazon.com/kinesis/

Now, lets take Kinesis Data Streams, for example:
What if you are a developer and you need feed data to a specific Kinesis Data Stream programatically (i.e. SDK)?
This is where KPL comes into play. You use KPL to feed data to THAT stream.

Similar Story with KCL:

If you are a developer and you want get data ("consume") from that DATA STREAM, you use KCL.

In short:
AWS Kinesis is huge platform, where KCL and KPL serve specific purposes.

Title: Kinesis vs KPL vs KCL


问:
Split screen in two
I am trying to split my layout into two halves.When I try layout_weight,in splits it into  two horizontal halves.How do i split the layout into two vertical halves.

```<code>          <?xml version="1.0" encoding="utf-8"?>
</code>```

```<code>android:id="@+id/linearLayout123" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_weight="1"
                 android:layout_gravity="top"
                 android:id="@+id/linearLayout12"
    android:layout_width="fill_parent"
                 android:layout_height="fill_parent">

 <Button android:id="@+id/button1"
               android:layout_width="wrap_content"

               android:layout_height="wrap_content"
                android:text="Hello, I am a Button" />

      </LinearLayout>

<LinearLayout android:layout_weight="1"
    android:layout_gravity="bottom" android:id="@+id/linearLayout1"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

           <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a TextView" />

       </LinearLayout>

      </LinearLayout>
</code>```

答:
Use 'orientation="vertical"' in the enclosing layout, and apply your weights to the children such as:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_gravity="fill"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:weightSum="1.0"
    android:orientation="vertical"
    android:padding="5dp">

<TopChildView android:layout_height="0dp"
    android:layout_weight="0.5"
    .../>

<BottomChildView android:layout_height="0dp"
    android:layout_weight="0.5"
    .../>
</code>```

Title: Split screen in two

Body:
I am trying to split my layout into two halves.When I try layout_weight,in splits it into  two horizontal halves.How do i split the layout into two vertical halves.

          <?xml version="1.0" encoding="utf-8"?>

android:id="@+id/linearLayout123" android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_weight="1"
                 android:layout_gravity="top"
                 android:id="@+id/linearLayout12"
    android:layout_width="fill_parent"
                 android:layout_height="fill_parent">

 <Button android:id="@+id/button1"
               android:layout_width="wrap_content"

               android:layout_height="wrap_content"
                android:text="Hello, I am a Button" />

      </LinearLayout>

<LinearLayout android:layout_weight="1"
    android:layout_gravity="bottom" android:id="@+id/linearLayout1"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

           <TextView
            android:id="@+id/text2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello, I am a TextView" />

       </LinearLayout>

      </LinearLayout>

Body:
Use 'orientation="vertical"' in the enclosing layout, and apply your weights to the children such as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_gravity="fill"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    android:weightSum="1.0"
    android:orientation="vertical"
    android:padding="5dp">

<TopChildView android:layout_height="0dp"
    android:layout_weight="0.5"
    .../>

<BottomChildView android:layout_height="0dp"
    android:layout_weight="0.5"
    .../>


问:
Python: modifying a value in one dictionary changes another dictionary
I'm making a chess program on Python by using dictionaries, and to set up my board I do:

```<code>EmptyBoard = {
    8:['☐','☒','☐','☒','☐','☒','☐','☒'],
    7:['☒','☐','☒','☐','☒','☐','☒','☐'],
    6:['☐','☒','☐','☒','☐','☒','☐','☒'],
    5:['☒','☐','☒','☐','☒','☐','☒','☐'],
    4:['☐','☒','☐','☒','☐','☒','☐','☒'],
    3:['☒','☐','☒','☐','☒','☐','☒','☐'],
    2:['☐','☒','☐','☒','☐','☒','☐','☒'],
    1:['☒','☐','☒','☐','☒','☐','☒','☐'],
    ' ':['⒜','⒝','⒞','⒟','⒠','⒡','⒢','⒣']
    }   #regular letters aren't wide enough

Default = {
    8:['♜','♞','♝','♛','♚','♝','♞','♜'],
    7:['♟','♟','♟','♟','♟','♟','♟','♟'],
    2:['♙','♙','♙','♙','♙','♙','♙','♙'],
    1:['♖','♘','♗','♕','♔','♗','♘','♖']
    }

Board = {}

def NewGame():
    Board.update(EmptyBoard)
    Board.update(Default)
    # some more code

NewGame()
</code>```

this is fine until I have to edit a block in Board like so:

```<code>Board[3][2] = "X"
print(EmptyBoard[3][2]) # ==> Results in 'X', should stay '☐' or '☒'
</code>```

this changes both Board[x][y] and whichever one of EmptyBoard and Default that [x][y] happens to be in.

This clones the pieces for every move after their first.

How do I make it so that only Board is edited?

答:
Both Default and EmptyBoard are dictionaries from something to list. When you call update in NewGame, you set Board[3] (for example) to refer to the exact same list as EmptyBoard[3]. Then, if you write something like:

```<code>Board[3][4] = X
</code>```

you change that list - which is shared between Board and EmptyBord (or Board and Default).

To fix it, use deepcopy:

```<code>import copy

def NewGame():
    Board.update(copy.deepcopy(EmptyBoard))
    Board.update(copy.deepcopy(Default))
    ...
</code>```

One more thing - the convention is to start variables in python with a small letter.

Body:
I'm making a chess program on Python by using dictionaries, and to set up my board I do:

EmptyBoard = {
    8:['☐','☒','☐','☒','☐','☒','☐','☒'],
    7:['☒','☐','☒','☐','☒','☐','☒','☐'],
    6:['☐','☒','☐','☒','☐','☒','☐','☒'],
    5:['☒','☐','☒','☐','☒','☐','☒','☐'],
    4:['☐','☒','☐','☒','☐','☒','☐','☒'],
    3:['☒','☐','☒','☐','☒','☐','☒','☐'],
    2:['☐','☒','☐','☒','☐','☒','☐','☒'],
    1:['☒','☐','☒','☐','☒','☐','☒','☐'],
    ' ':['⒜','⒝','⒞','⒟','⒠','⒡','⒢','⒣']
    }   #regular letters aren't wide enough

Default = {
    8:['♜','♞','♝','♛','♚','♝','♞','♜'],
    7:['♟','♟','♟','♟','♟','♟','♟','♟'],
    2:['♙','♙','♙','♙','♙','♙','♙','♙'],
    1:['♖','♘','♗','♕','♔','♗','♘','♖']
    }

Board = {}

def NewGame():
    Board.update(EmptyBoard)
    Board.update(Default)
    # some more code

NewGame()

this is fine until I have to edit a block in Board like so:

Board[3][2] = "X"
print(EmptyBoard[3][2]) # ==> Results in 'X', should stay '☐' or '☒'

this changes both Board[x][y] and whichever one of EmptyBoard and Default that [x][y] happens to be in.

This clones the pieces for every move after their first.

How do I make it so that only Board is edited?

Body:
Both Default and EmptyBoard are dictionaries from something to list. When you call update in NewGame, you set Board[3] (for example) to refer to the exact same list as EmptyBoard[3]. Then, if you write something like:

Board[3][4] = X

you change that list - which is shared between Board and EmptyBord (or Board and Default).

To fix it, use deepcopy:

import copy

def NewGame():
    Board.update(copy.deepcopy(EmptyBoard))
    Board.update(copy.deepcopy(Default))
    ...

One more thing - the convention is to start variables in python with a small letter.


问:
Laravel 7: Why when I'm logged I can access route for reset password?
I realized can access to reset password route even when I'm logged. I want to can access only if user is logout.

How can I change this?

答:
add the following in Reset Controller</p>

```<code>public function __construct()
    {
        $this->middleware('guest');
    }
</code>```

Body:
add the following in Reset Controller

public function __construct()
    {
        $this->middleware('guest');
    }


问:
Mapply error after updating R and tidyverse
I have been working on a rejection sampling code using several loops.
After updating R and tidyverse I found that the code no longer works, displaying the following error:

```<code>Error: Assigned data `mapply(...)` must be compatible with existing data.
i Error occurred for column `sampled`.
x Can't convert from <integer> to <logical> due to loss of precision.
* Locations: 1.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
In seq.default(x, y, na.rm = TRUE) :
 extra argument ‘na.rm’ will be disregarded
</code>```

The code worked previously, and is related to a previous question, linked [here][1].
I have tried to work through (avoid) the issue by using older versions of R (3.6) and tidyverse (1.3.0), but now I have some additional packages that I need to use which are incompatible with older versions of R. I'm not looking to rework the entire code, and I hoping that it will only take a few tweaks to get it working with the newer versions of R and tidyverse.

Edit I made a mistake regarding the initial df I provided for this question. Columns ID, After_1, and After_2 should have contained a combination of letters and numbers instead of only numbers. The example df has been updated.

Here is a modified code example that is displaying the same errors as my actual code:

```<code>df <- dfsource
temp_df<-df #temp_pithouse_join used for dynamically created samples
temp_df$sampled <- NA #blanking out the sample column so I can check against NA for the dynamic detereminatination.
temp_df %>% mutate_if(is.factor, as.character) -> temp_df #change factors to characters

for (i in 1:100){ #determines how many iterations to run

  row_list<-as.list(1:nrow(temp_df))
  q<-0

  while(length(row_list)!=0 & q<10){
    q<-q+1 #to make sure that we don't spinning off in an infinite loop
    for(j in row_list){ #this loop replaces the check values
      skip_flag<-FALSE #initialize skip flag used to check the replacement sampling
      for(k in 4:5){ #checking the topoafter columns
        if(is.na(temp_df[j,k])){
          # print("NA break")
          # print(i)
          break
        } else if(is.na(as.integer(temp_df[j,k]))==FALSE) { #if it's already an integer, well, a character vector containing an integer, we already did this, next
          # print("integer next")
          next
          # print("integer next")
        } else if(temp_df[j,k]==""){ #check for blank values
          # print("empty string next")
          temp_df[j,k]<-NA #if blank value found, replace with NA
          # print("fixed blank to NA")
          next
        }
        else if(is.na(filter(temp_df,ID==as.character(temp_df[j,k]))["sampled"])) { #if the replacement has not yet been generated, move on, but set flag to jump this to the end
          skip_flag<-TRUE
          # print("skip flag set")
        } else {
          temp_df[j,k]<-as.integer(filter(temp_df,ID==temp_df[j,k])[6]) #replacing IDs with the sampled dates of those IDs
          # print("successful check value grab")
        } #if-else
      } #k for loop
      if(skip_flag==FALSE){
        row_list<-row_list[row_list!=j]
      } else {
        next
      }

      #sampling section
      if(skip_flag==FALSE){
        temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
          sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
        temp_df[j,7]<-i #identifying the run number

        if(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
          # print(j)
          while(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
            temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
              sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
          } #while
          temp_df[j,7]=i
        }#if
      }
    } #j for loop
  } #while loop wrapper around j loop
  if(i==1){
    df2<-temp_df
  }else{
    df2<-rbind(df2,temp_df)
  }#else

  #blank out temp_df to prepare for another run
  temp_df<-df
  temp_df$sampled <- NA
  temp_df %>% mutate_if(is.factor, as.character) -> temp_df

}#i for loop
</code>```

And here is the sample data to use which I would read in as dfsource:

```<code>structure(list(ID = c("A1", "A2", "A3", "A4", "A5", "A6", "A7",
"A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15", "A16",
"A17", "A18", "A19", "A20", "A21", "A22", "A23", "A24", "A25",
"A26", "A27", "A28", "A29", "A30"), Start = c(1, 1, 1, 1, 1,
50, 50, 50, 50, 50, 100, 100, 100, 100, 100, 200, 200, 300, 250,
350, 300, 300, 400, 500, 400, 400, 450, 500, 550, 500), End = c(1000,
1000, 1000, 1000, 1000, 950, 950, 950, 950, 950, 1000, 1000,
1000, 1000, 900, 800, 900, 750, 650, 650, 600, 850, 700, 600,
600, 700, 550, 550, 600, 550), After_1 = c("A3", "", "", "",
"A3", "", "", "", "", "", "", "A11", "", "A11", "", "", "", "",
"", "", "", "A21", "", "", "", "", "", "", "", "A28"), After_2 = c("",
"", "", "", "A2", "", "", "", "", "", "", "", "", "A12", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", ""),
    sampled = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -30L), spec = structure(list(cols = list(
    ID = structure(list(), class = c("collector_character", "collector"
    )), Start = structure(list(), class = c("collector_double",
    "collector")), End = structure(list(), class = c("collector_double",
    "collector")), After_1 = structure(list(), class = c("collector_character",
    "collector")), After_2 = structure(list(), class = c("collector_character",
    "collector")), sampled = structure(list(), class = c("collector_logical",
    "collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))```

  [1]: https://stackoverflow.com/questions/58653809/sample-using-start-and-end-values-within-a-loop-in-r
```

答: I want to thank those of you that offered alternate methods to try to deal with this problem. The issue seems to have been caused by an older version of dplyr. I was using dplyr 0.8.3 when I was getting the error, but the code is now working with dplyr 1.0.0.</p>

Body:
I have been working on a rejection sampling code using several loops.
After updating R and tidyverse I found that the code no longer works, displaying the following error:

Error: Assigned data `mapply(...)` must be compatible with existing data.
i Error occurred for column `sampled`.
x Can't convert from <integer> to <logical> due to loss of precision.
* Locations: 1.
Run `rlang::last_error()` to see where the error occurred.
In addition: Warning message:
In seq.default(x, y, na.rm = TRUE) :
 extra argument ‘na.rm’ will be disregarded

The code worked previously, and is related to a previous question, linked [here][1].
I have tried to work through (avoid) the issue by using older versions of R (3.6) and tidyverse (1.3.0), but now I have some additional packages that I need to use which are incompatible with older versions of R. I'm not looking to rework the entire code, and I hoping that it will only take a few tweaks to get it working with the newer versions of R and tidyverse.

Edit I made a mistake regarding the initial df I provided for this question. Columns ID, After_1, and After_2 should have contained a combination of letters and numbers instead of only numbers. The example df has been updated.

Here is a modified code example that is displaying the same errors as my actual code:

df <- dfsource
temp_df<-df #temp_pithouse_join used for dynamically created samples
temp_df$sampled <- NA #blanking out the sample column so I can check against NA for the dynamic detereminatination.
temp_df %>% mutate_if(is.factor, as.character) -> temp_df #change factors to characters

for (i in 1:100){ #determines how many iterations to run

  row_list<-as.list(1:nrow(temp_df))
  q<-0

  while(length(row_list)!=0 & q<10){
    q<-q+1 #to make sure that we don't spinning off in an infinite loop
    for(j in row_list){ #this loop replaces the check values
      skip_flag<-FALSE #initialize skip flag used to check the replacement sampling
      for(k in 4:5){ #checking the topoafter columns
        if(is.na(temp_df[j,k])){
          # print("NA break")
          # print(i)
          break
        } else if(is.na(as.integer(temp_df[j,k]))==FALSE) { #if it's already an integer, well, a character vector containing an integer, we already did this, next
          # print("integer next")
          next
          # print("integer next")
        } else if(temp_df[j,k]==""){ #check for blank values
          # print("empty string next")
          temp_df[j,k]<-NA #if blank value found, replace with NA
          # print("fixed blank to NA")
          next
        }
        else if(is.na(filter(temp_df,ID==as.character(temp_df[j,k]))["sampled"])) { #if the replacement has not yet been generated, move on, but set flag to jump this to the end
          skip_flag<-TRUE
          # print("skip flag set")
        } else {
          temp_df[j,k]<-as.integer(filter(temp_df,ID==temp_df[j,k])[6]) #replacing IDs with the sampled dates of those IDs
          # print("successful check value grab")
        } #if-else
      } #k for loop
      if(skip_flag==FALSE){
        row_list<-row_list[row_list!=j]
      } else {
        next
      }

      #sampling section
      if(skip_flag==FALSE){
        temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
          sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
        temp_df[j,7]<-i #identifying the run number

        if(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
          # print(j)
          while(any(as.numeric(temp_df[j,4:5])>as.numeric(temp_df[j,6]),na.rm=TRUE)){
            temp_df[j,6]<-mapply(function(x, y) if(any(is.na(x) || is.na(y))) NA else
              sample(seq(x, y, na.rm = TRUE), 1), temp_df[j,"Start"], temp_df[j,"End"])
          } #while
          temp_df[j,7]=i
        }#if
      }
    } #j for loop
  } #while loop wrapper around j loop
  if(i==1){
    df2<-temp_df
  }else{
    df2<-rbind(df2,temp_df)
  }#else

  #blank out temp_df to prepare for another run
  temp_df<-df
  temp_df$sampled <- NA
  temp_df %>% mutate_if(is.factor, as.character) -> temp_df

}#i for loop

And here is the sample data to use which I would read in as dfsource:

structure(list(ID = c("A1", "A2", "A3", "A4", "A5", "A6", "A7",
"A8", "A9", "A10", "A11", "A12", "A13", "A14", "A15", "A16",
"A17", "A18", "A19", "A20", "A21", "A22", "A23", "A24", "A25",
"A26", "A27", "A28", "A29", "A30"), Start = c(1, 1, 1, 1, 1,
50, 50, 50, 50, 50, 100, 100, 100, 100, 100, 200, 200, 300, 250,
350, 300, 300, 400, 500, 400, 400, 450, 500, 550, 500), End = c(1000,
1000, 1000, 1000, 1000, 950, 950, 950, 950, 950, 1000, 1000,
1000, 1000, 900, 800, 900, 750, 650, 650, 600, 850, 700, 600,
600, 700, 550, 550, 600, 550), After_1 = c("A3", "", "", "",
"A3", "", "", "", "", "", "", "A11", "", "A11", "", "", "", "",
"", "", "", "A21", "", "", "", "", "", "", "", "A28"), After_2 = c("",
"", "", "", "A2", "", "", "", "", "", "", "", "", "A12", "",
"", "", "", "", "", "", "", "", "", "", "", "", "", "", ""),
    sampled = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA)), class = c("spec_tbl_df", "tbl_df", "tbl", "data.frame"
), row.names = c(NA, -30L), spec = structure(list(cols = list(
    ID = structure(list(), class = c("collector_character", "collector"
    )), Start = structure(list(), class = c("collector_double",
    "collector")), End = structure(list(), class = c("collector_double",
    "collector")), After_1 = structure(list(), class = c("collector_character",
    "collector")), After_2 = structure(list(), class = c("collector_character",
    "collector")), sampled = structure(list(), class = c("collector_logical",
    "collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))```

  [1]: https://stackoverflow.com/questions/58653809/sample-using-start-and-end-values-within-a-loop-in-r


问:
Windows 10 Visual Studio 2019 IIS Express won't start with error 500
We have an API project in .Net Core 3.1.
It is working in all the computers in the team but when tried to debug it on a new member computer it failed.
It states there is a server error (500) and won't start the program.
It works as a local service, without IIS.

We have tried to format the computer and start fresh, with no use.
I saw posts relating to the project configurations and launch settings, but since it is working on other machines I don't think this is the issue.
We also tried to add the required lines for the aspnetcore modules in iis template files and the dlls as seen in other places where it was recommended, getting the same issue.

Any suggestion will be appreciated!

Error text from your HttpFailure_08-24-17.tml file

NOTE: you really should have copied/pasted as text, instead of a attaching a screen shot:

```<code>The description for Event ID 1034 from source IIS Express AspNetCore Module V2 cannot found.
Either the component that raises this event is not installed on your local computer or the installation is corrupted.
You can install or repair the component on the local computer.
...
The following information was included with the event:

Could not load configuration. Exception message: Unable to get required configuration section 'system.webServer/aspNetCore'.  Possible reason is web.config authoring error.

The request is not supported.
</code>```

EDIT:
Program.cs:

```<code> public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            Console.Error.WriteLine("Starting application (from error log without errors)");

            var config = new ConfigurationBuilder().AddEnvironmentVariables("ASPNETCORE_").Build();

            Console.WriteLine("Config set");

            var hostBuilder = new WebHostBuilder()
                .UseKestrel(opt => opt.AddServerHeader = false)
                .UseConfiguration(config)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>();

            Console.WriteLine("hostBuilder set");

            // ConfigureServices is only used to delay execution until UseIISIntegration()
            // has actually set the "urls" setting.

            Console.WriteLine("urls for hostBuilder " + hostBuilder.GetSetting("urls"));

            hostBuilder.ConfigureServices(services =>
            {
                var urls = hostBuilder.GetSetting("urls");
                urls = string.IsNullOrWhiteSpace(urls) ? "127.0.0.1" : urls.Replace("localhost", "127.0.0.1");
                hostBuilder.UseSetting("urls", urls);
            });

            Console.WriteLine("hostBuilder.ConfigureServices set");

            var host = hostBuilder.Build();

            Console.WriteLine("host set");

            host.Run();

        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.Message);
        }
    }
}
</code>```

答:
The error is warning you about AspNetCore Module V2 being corrupt or missing.

There is a module required to be installed in IIS to be compatible with AspNetCore projects (in particular, working with the default Kestrel server).

You need to follow these instructions and install this module. As far as I can recall, it does not require any additional configuration.

EDIT:

I stumbled upon this article, which refers that they also had issues with IIS Express. Maybe it can be of help to you, and follow their guide to find what is wrong in your configuration?

https://blog.maartenballiauw.be/post/2019/02/26/asp-net-core-iis-express-empty-error-starting-application.html

Body:
We have an API project in .Net Core 3.1.
It is working in all the computers in the team but when tried to debug it on a new member computer it failed.
It states there is a server error (500) and won't start the program.
It works as a local service, without IIS.

We have tried to format the computer and start fresh, with no use.
I saw posts relating to the project configurations and launch settings, but since it is working on other machines I don't think this is the issue.
We also tried to add the required lines for the aspnetcore modules in iis template files and the dlls as seen in other places where it was recommended, getting the same issue.

Any suggestion will be appreciated!

Error text from your HttpFailure_08-24-17.tml file

NOTE: you really should have copied/pasted as text, instead of a attaching a screen shot:

The description for Event ID 1034 from source IIS Express AspNetCore Module V2 cannot found.
Either the component that raises this event is not installed on your local computer or the installation is corrupted.
You can install or repair the component on the local computer.
...
The following information was included with the event:

Could not load configuration. Exception message: Unable to get required configuration section 'system.webServer/aspNetCore'.  Possible reason is web.config authoring error.

The request is not supported.

EDIT:
Program.cs:

 public class Program
{
    public static void Main(string[] args)
    {
        try
        {
            Console.Error.WriteLine("Starting application (from error log without errors)");

            var config = new ConfigurationBuilder().AddEnvironmentVariables("ASPNETCORE_").Build();

            Console.WriteLine("Config set");

            var hostBuilder = new WebHostBuilder()
                .UseKestrel(opt => opt.AddServerHeader = false)
                .UseConfiguration(config)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>();

            Console.WriteLine("hostBuilder set");

            // ConfigureServices is only used to delay execution until UseIISIntegration()
            // has actually set the "urls" setting.

            Console.WriteLine("urls for hostBuilder " + hostBuilder.GetSetting("urls"));

            hostBuilder.ConfigureServices(services =>
            {
                var urls = hostBuilder.GetSetting("urls");
                urls = string.IsNullOrWhiteSpace(urls) ? "127.0.0.1" : urls.Replace("localhost", "127.0.0.1");
                hostBuilder.UseSetting("urls", urls);
            });

            Console.WriteLine("hostBuilder.ConfigureServices set");

            var host = hostBuilder.Build();

            Console.WriteLine("host set");

            host.Run();

        }
        catch (Exception ex)
        {
            Console.Error.WriteLine(ex.Message);
        }
    }
}


问:
ajax POST int parameter in asp.net core
I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.

I can pass a model and string parameters into the controller, however, ints are not working for me.

I can wrap them into a JSON object as a string parameter such as [FromBody]string objId in the controller, but then I have to parse the int val from the Json {'objId' : 1}.

Is there a way I can avoid this and just pass an int?

below is the code I am trying.

```<code>[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
    //DO stuff with int here
}
</code>```

here is the js.

```<code>var data = { "objId": 1};
    $.ajax({
        url: '@Url.Action("PassIntFromView", "ControllerName")',
        data: JSON.stringify(data),
        type: "POST",
        dataType: 'JSON',
        contentType: "application/json",
        success: function(data) {
            //do stuff with json result
        },
        error: function(passParams) {
            console.log("Error is " + passParams);
        }
    });
</code>```

The objId is always 0 in the controller.

I have tried this without doing JSON.stringify(data) as well with no result.

I have also tried all the different form attribute variations.

答:
I got it working like this</p>

```<code>let numberFour = JSON.stringify(4);

$.ajax({
    .......
    .......
    data: numberFour,
    type: "POST",
    dataType: 'JSON',
    contentType: "application/json",
    ......
    ........
});

</code>```

Title: ajax POST int parameter in asp.net core

Body:
I am migrating my MVC project to Core and I have been having a hard time fixing all the old ajax calls.

I can pass a model and string parameters into the controller, however, ints are not working for me.

I can wrap them into a JSON object as a string parameter such as [FromBody]string objId in the controller, but then I have to parse the int val from the Json {'objId' : 1}.

Is there a way I can avoid this and just pass an int?

below is the code I am trying.

[HttpPost]
public JsonResult PassIntFromView([FromBody]int objId)
{
    //DO stuff with int here
}

here is the js.

var data = { "objId": 1};
    $.ajax({
        url: '@Url.Action("PassIntFromView", "ControllerName")',
        data: JSON.stringify(data),
        type: "POST",
        dataType: 'JSON',
        contentType: "application/json",
        success: function(data) {
            //do stuff with json result
        },
        error: function(passParams) {
            console.log("Error is " + passParams);
        }
    });

The objId is always 0 in the controller.

I have tried this without doing JSON.stringify(data) as well with no result.

I have also tried all the different form attribute variations.

Body:
I got it working like this

let numberFour = JSON.stringify(4);

$.ajax({
    .......
    .......
    data: numberFour,
    type: "POST",
    dataType: 'JSON',
    contentType: "application/json",
    ......
    ........
});


问:
Android sharedpreferences
I've been following this tutorial and i am stuck.

```<code>public class Main extends Activity {

    SharedPreferences mPrefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        firstRunPreferences();

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();
        }
        else
        {
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
     }

}`
</code>```

Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".

Thanks

答: I'm not sure but I think SharedPreferences are removed when uninstalling, but not when updating an app.</p>

Title: Android sharedpreferences

Body:
I've been following this tutorial and i am stuck.

public class Main extends Activity {

    SharedPreferences mPrefs;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        firstRunPreferences();

        if(getFirstRun())
        {
            Toast.makeText(Main.this, "firstrun", Toast.LENGTH_SHORT).show();
            setRunned();
        }
        else
        {
            Toast.makeText(Main.this, "not firstrun", Toast.LENGTH_SHORT).show();
        }

    }

    public boolean getFirstRun() {
        return mPrefs.getBoolean("firstRun", true);
     }
    public void setRunned() {
        SharedPreferences.Editor edit = mPrefs.edit();
        edit.putBoolean("firstRun", false);
        edit.commit();
     }
    public void firstRunPreferences() {
        Context mContext = Main.this.getApplicationContext();
        mPrefs = mContext.getSharedPreferences("myAppPrefs", 0);
     }

}`

Everytime i run it in Eclipse it says "not firstrun". I guess the preferences reset every time the app is reinstalled, so what is wrong with the code? As far as i remember, i saw once "firstrun".

Thanks


问:
JS: detect a dom mutation of a watched div (or change-event-listener to innerHTML)
:)

I'm using the NicEdit WYSIWYG editor. The DIV is patched with a hidden textarea field.

The problem is that all changes are just synced onSubmit().

Now I need a way to listen for changes. For example to change backgound color of the field on changing content (inputs) (flagged as unsaved). But there is no addEventListener for changed InnerHTML, as far as I know.
So maybe it's possible to use a callback function like a domMutationObserver. But I have no ideas how to deal with that.

js code:

```<code>let domField = document.querySelector('.contents .subpage[data-pagename="Index"][data-culture="en-US"] .nicEdit-main');
</code>```

I can detect the selector of the editor div. So how to detect changes inside this element/node?

I read something about an "observer" to detect dom mutations. Maybe somebody can give me a simple and easy example.

Thx for everything. ;)

EDIT: And I hope we all agree that I won't set an interval (just to save browser performance). But yeah that could be a way. So watching for mutations or changing innerHTML of my DIV element.

pseudo code:

```<code>domElement.innerHTML.watch('change', elem => {
    elem.classList.add('changed'); //or unsaved
});
</code>```

答:
After doing some research, I managed to create an Observer.

Unfortunately, this fires with every single DOM change during runtime.

js code:

```<code>let domElement = document.querySelector('.contents .subpage[data-pagename="Index"] .culture[data-culture="de-DE"] .nicEdit-main');

let observer = new window.MutationObserver((e) => {
    console.log(domElement.innerHTML);
});

observer.observe(domElement, {
    characterData: true,
    subtree: true
});
</code>```

In the meantime, I think that watching the blur event would be enough. Then it just should be checked whether the "new" innerHTML differs from the "old" (or initially loaded) innerHTML.

js code:

```<code>let domElement = document.querySelector('.contents .subpage[data-pagename="Index"] .culture[data-culture="de-DE"] .nicEdit-main');

domElement.addEventListener('blur', (e) => {
    //check .innerHTML changed (compared to init value)
    alert('onblur');
});
</code>```

Of course, this isn't a DOM observer / watching, but it costs the browser significantly less performance, if not each separate change fires, but only leave-focus interaction of the user and a manually check for .innerHTML changes.

Body:
:)

I'm using the NicEdit WYSIWYG editor. The DIV is patched with a hidden textarea field.

The problem is that all changes are just synced onSubmit().

Now I need a way to listen for changes. For example to change backgound color of the field on changing content (inputs) (flagged as unsaved). But there is no addEventListener for changed InnerHTML, as far as I know.
So maybe it's possible to use a callback function like a domMutationObserver. But I have no ideas how to deal with that.

js code:

let domField = document.querySelector('.contents .subpage[data-pagename="Index"][data-culture="en-US"] .nicEdit-main');

I can detect the selector of the editor div. So how to detect changes inside this element/node?

I read something about an "observer" to detect dom mutations. Maybe somebody can give me a simple and easy example.

Thx for everything. ;)

EDIT: And I hope we all agree that I won't set an interval (just to save browser performance). But yeah that could be a way. So watching for mutations or changing innerHTML of my DIV element.

pseudo code:

domElement.innerHTML.watch('change', elem => {
    elem.classList.add('changed'); //or unsaved
});

Body:
After doing some research, I managed to create an Observer.

Unfortunately, this fires with every single DOM change during runtime.

js code:

let domElement = document.querySelector('.contents .subpage[data-pagename="Index"] .culture[data-culture="de-DE"] .nicEdit-main');

let observer = new window.MutationObserver((e) => {
    console.log(domElement.innerHTML);
});

observer.observe(domElement, {
    characterData: true,
    subtree: true
});

In the meantime, I think that watching the blur event would be enough. Then it just should be checked whether the "new" innerHTML differs from the "old" (or initially loaded) innerHTML.

js code:

let domElement = document.querySelector('.contents .subpage[data-pagename="Index"] .culture[data-culture="de-DE"] .nicEdit-main');

domElement.addEventListener('blur', (e) => {
    //check .innerHTML changed (compared to init value)
    alert('onblur');
});

Of course, this isn't a DOM observer / watching, but it costs the browser significantly less performance, if not each separate change fires, but only leave-focus interaction of the user and a manually check for .innerHTML changes.


问:
Show message half way through processing method in C#
I am creating a number program. Part of it looping through numbers and half way through I want it to stop and ask the user if they want to continue.

```<code>public bool NumberLoop()
{
    int max = 100;
    int counter = 0;
    while (counter < max)
    {
        counter++;

        if (counter == 50)
        {
             bool userWantsToContinue = // Show the user a message box asking if they want to continue

             if (!userWantsToContinue)
                 break;
        }
    }
}
</code>```

This is a sample snippet of what I have so far. To note the method above is in a C# class library and this is called from an aspx page in a web application project. Preferably I was looking at having the message box appear in a new browser window with 2 buttons yes and no.

答:
The simplest wat to show this alert would be through the JavaScript function Window.confirm().

Here are the docs on how this method is used: https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm

It'll return the boolean true if the user hits "ok" and false otherwise.

Here's a similar StackOverflow question if you want the entire logic to live in the code behind: JavaScript: Alert.Show(message) From ASP.NET Code-behind

Body:
I am creating a number program. Part of it looping through numbers and half way through I want it to stop and ask the user if they want to continue.

public bool NumberLoop()
{
    int max = 100;
    int counter = 0;
    while (counter < max)
    {
        counter++;

        if (counter == 50)
        {
             bool userWantsToContinue = // Show the user a message box asking if they want to continue

             if (!userWantsToContinue)
                 break;
        }
    }
}

This is a sample snippet of what I have so far. To note the method above is in a C# class library and this is called from an aspx page in a web application project. Preferably I was looking at having the message box appear in a new browser window with 2 buttons yes and no.


问:
function for the sum of all even numbers
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

```<code>function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")
</code>```

答:
A one line solution to get the result. Hope this helps

let text = "2543sadadfh7896";
let evenNums = text.match(/\d+/g);
let result = evenNums!== null ? evenNums.join().split('').filter(i => i%2 ===0).reduce((a, b) => Number(a) + Number(b)) : 0;

console.log(result)```

Body:
I wanted to create a function which take a string of any numbers and characters as a one parameter. the task is  to find all the even numbers(digits) and sum them up then display the total value in console.
for example, if the following string  is passed to this function as a one parameter ("112,sf34,4)-k)") the result should be :    The sum of  all even  numbers: 10

So far I have come with solution and solve after this. Help me. Thanks in advance.

function functionFive(str) {
    const string = [...str].map(char => {
        const numberString = char.match(/^\d+$/)
        if (numberString !== null){
            const number = parseInt(numberString)
            return number
        }

    const num = string.map(number=>{
        if (number !== undefined && number%2 === 0){
             console.log(number)
        }
    })
}
functionFive("sau213e89q8e7ey1")


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答: My understanding is that a WORD is the amount of bits that can be shoved into the CPU with one action (on a particular machine), so in a 8bit-architecture it is 8 bits and on a modern 64-bit architecture it is 64 bits.</p>

OwnerDisplayName: mixedpickles

OwnerDisplayName: Peter Miehle

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: moocha


问:
How can I populate a drop down list control Collection?
How can I populate a drop down list control (ASP.NET) from a SPListTemplateCollection (SharePoint 2007) ?

```<code>SPWeb web = SPContext.Current.Web;

ddlTemplateList = new DropDownList();
ddlTemplateList.DataSource = web.ListTemplates;
ddlTemplateList.DataBind();
</code>```

This code doesn't work in a right way... The name of the list template is not showed.

答:
use DisplayMember and ValueMember property!

update

DisplayMember and ValueMember are property for WinForm controls.

For asp.net correct solution, as metioned by Muhammad, is to use DataTextField and DataValueField.

Body:
How can I populate a drop down list control (ASP.NET) from a SPListTemplateCollection (SharePoint 2007) ?

SPWeb web = SPContext.Current.Web;

ddlTemplateList = new DropDownList();
ddlTemplateList.DataSource = web.ListTemplates;
ddlTemplateList.DataBind();

This code doesn't work in a right way... The name of the list template is not showed.