问:
passing CoreData from UITableViewCell to viewcontroller
I'm trying to create the feature where when a user clicks on a specific cell in my UITableView, the Project will segue to a new ViewController and show all the information that has been saved in the CoreData. The Problem is that when I touch on a cell I get an error of

```<code>Unexpected nil while unwrapping optional value
</code>```

Here is my code as it is right now within the ViewController that has the TableView

```<code>class ContactViewController: UIViewController, UITableViewDataSource, NSFetchedResultsControllerDelegate, UITableViewDelegate {
        var selectName:String?
    var selectPhone:String?
var selectComment:String?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectName = contact[indexPath.row].name
        selectPhone = contact[indexPath.row].phone
        selectComment = contact[indexPath.row].comments
        performSegue(withIdentifier: "MySegue", sender: self)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MySegue"{
            if let destVC = segue.destination as? IndiViewController {
                destVC.NameLabel = selectName
                destVC.PhoneLabel = selectPhone
                destVC.CommentLabel = selectComment
            }
        }
    }
</code>```

This is my code in IndiViewController (the VC in which I want the user to view the contact)

```<code>class IndiViewController: UIViewController {

    @IBOutlet var NameLabel: UILabel!
    @IBOutlet var PhoneLabel: UILabel!
    @IBOutlet var CommentsLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}
</code>```

I've tried a few other methods but all still delivered the same error

I troubleshooted a bit to see which variable truly was causing the nil by doing this:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MySegue"{
            if let destVC = segue.destination as? IndiViewController {
                destVC.NameLabel = "selectName" //I thought if perhaps the nil was the var selectName this would at least let me know

            }
        }
</code>```

However even through this, the app crashes and gives the same error. So I think the issue is with the Labels in the IndiViewController.

So I tried creating an empty String and assigning it to NameLabel like this:

```<code>class IndiViewController: UIViewController {

    @IBOutlet var NameLabel: UILabel!

var name = ""

override func viewDidLoad() {
        super.viewDidLoad()
NameLabel.text = name
    }
}
</code>```

but still no luck.

What am I doing wrong?

答:
Yet it can be an IBOutlet error, even for typo.

delete @IBOutlet var NameLabel: UILabel!

remove the link in the StoryBoard "referencing outlets" tab

click-drag a new outlet for the UILabel and do not name it with a capital letter

// @IBOutlet var NameLabel: UILabel!

@IBOutlet var nameLabel: UILabel!

Edit

Also try to pass your informations in two times :

create a new var in your destinationViewController like :

```<code>class IndiViewController: UIViewController {

    @IBOutlet var nameLabel: UILabel!

    var myText: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        nameLabel.text = myText // assign the var to the labels text
    }
</code>```

}

In your prepareForSegue method assign myText and not the nameLabel.text

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "MySegue"{
        if let destVC = segue.destination as? IndiViewController {
            destVC.myText = "selectName"
        }
    }
}
</code>```

my guess is that you cant acces IBOutlets in prepare(for segue:) method. The destination ViewController is not built yet

Body:
I'm trying to create the feature where when a user clicks on a specific cell in my UITableView, the Project will segue to a new ViewController and show all the information that has been saved in the CoreData. The Problem is that when I touch on a cell I get an error of

Unexpected nil while unwrapping optional value

Here is my code as it is right now within the ViewController that has the TableView

class ContactViewController: UIViewController, UITableViewDataSource, NSFetchedResultsControllerDelegate, UITableViewDelegate {
        var selectName:String?
    var selectPhone:String?
var selectComment:String?

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectName = contact[indexPath.row].name
        selectPhone = contact[indexPath.row].phone
        selectComment = contact[indexPath.row].comments
        performSegue(withIdentifier: "MySegue", sender: self)
    }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MySegue"{
            if let destVC = segue.destination as? IndiViewController {
                destVC.NameLabel = selectName
                destVC.PhoneLabel = selectPhone
                destVC.CommentLabel = selectComment
            }
        }
    }

This is my code in IndiViewController (the VC in which I want the user to view the contact)

class IndiViewController: UIViewController {

    @IBOutlet var NameLabel: UILabel!
    @IBOutlet var PhoneLabel: UILabel!
    @IBOutlet var CommentsLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()

    }
}

I've tried a few other methods but all still delivered the same error

I troubleshooted a bit to see which variable truly was causing the nil by doing this:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "MySegue"{
            if let destVC = segue.destination as? IndiViewController {
                destVC.NameLabel = "selectName" //I thought if perhaps the nil was the var selectName this would at least let me know

            }
        }

However even through this, the app crashes and gives the same error. So I think the issue is with the Labels in the IndiViewController.

So I tried creating an empty String and assigning it to NameLabel like this:

class IndiViewController: UIViewController {

    @IBOutlet var NameLabel: UILabel!

var name = ""

override func viewDidLoad() {
        super.viewDidLoad()
NameLabel.text = name
    }
}

but still no luck.

What am I doing wrong?

Body:
Yet it can be an IBOutlet error, even for typo.

delete @IBOutlet var NameLabel: UILabel!

remove the link in the StoryBoard "referencing outlets" tab

click-drag a new outlet for the UILabel and do not name it with a capital letter

// @IBOutlet var NameLabel: UILabel!

@IBOutlet var nameLabel: UILabel!

Edit

Also try to pass your informations in two times :

create a new var in your destinationViewController like :

class IndiViewController: UIViewController {

    @IBOutlet var nameLabel: UILabel!

    var myText: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        nameLabel.text = myText // assign the var to the labels text
    }

}

In your prepareForSegue method assign myText and not the nameLabel.text

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "MySegue"{
        if let destVC = segue.destination as? IndiViewController {
            destVC.myText = "selectName"
        }
    }
}

my guess is that you cant acces IBOutlets in prepare(for segue:) method. The destination ViewController is not built yet


来源: stackexchange

问:
Validation with Compare fails in Blazor
I am trying Blazor client side Form validation. Apparently the Compare validation doesn't work correctly, or I am doing something wrong.

<EditForm Model="@user" OnValidSubmit="@OnValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

        Email
        <InputText Class="form-control col-sm-10" id="email" bind-value="@user.Email" />

        Password
        <InputText Class="form-control col-10" id="password" bind-value="@user.Password" />

        Confirm Password
        <InputText Class="form-control col-10" id="confirmPassword" bind-value="@user.PasswordConfirm" />

            <button type="submit" class="btn btn-primary form-control">Register</button>

</EditForm>

@functions {
    class RegisterModel
    {
        [Required, EmailAddress]
        public string Email { get; set; }
        [Required, MinLength(6)]
        public string Password { get; set; }
        [Compare(nameof(Password))]
        public string PasswordConfirm { get; set; }
    }
    private RegisterModel user = new RegisterModel();

    private void OnValidSubmit()
    {
        Console.WriteLine("Valid");
    }
}
```

This is what happens:

1) Write a valid email

2) Write a valid password

3) Click the Register Button

Expected -> Validation Error (password fields different) and no call to OnValidSubmit

Effective -> No validation error, OnValidSubmit called.

If I write something in ConfirmPassword (different from Password), the first click detects the validation error, but the second clears the error and calls OnValidSubmit.

答:
This is probably a bug related to...

Quote:

I found a bug the way it handles the CompareAttribute, I will try to
  fix this and send a PR.

Source: https://remibou.github.io/Using-the-Blazor-form-validation/

See also this: https://github.com/aspnet/AspNetCore/issues/10643

Hope this helps...

ContentLicense: CC BY-SA 4.0

Title: Validation with Compare fails in Blazor

Body:
I am trying Blazor client side Form validation. Apparently the Compare validation doesn't work correctly, or I am doing something wrong.

<EditForm Model="@user" OnValidSubmit="@OnValidSubmit">
    <DataAnnotationsValidator />
    <ValidationSummary />

        Email
        <InputText Class="form-control col-sm-10" id="email" bind-value="@user.Email" />

        Password
        <InputText Class="form-control col-10" id="password" bind-value="@user.Password" />

        Confirm Password
        <InputText Class="form-control col-10" id="confirmPassword" bind-value="@user.PasswordConfirm" />

            <button type="submit" class="btn btn-primary form-control">Register</button>

</EditForm>

@functions {
    class RegisterModel
    {
        [Required, EmailAddress]
        public string Email { get; set; }
        [Required, MinLength(6)]
        public string Password { get; set; }
        [Compare(nameof(Password))]
        public string PasswordConfirm { get; set; }
    }
    private RegisterModel user = new RegisterModel();

    private void OnValidSubmit()
    {
        Console.WriteLine("Valid");
    }
}

This is what happens:

1) Write a valid email

2) Write a valid password

3) Click the Register Button

Expected -> Validation Error (password fields different) and no call to OnValidSubmit

Effective -> No validation error, OnValidSubmit called.

If I write something in ConfirmPassword (different from Password), the first click detects the validation error, but the second clears the error and calls OnValidSubmit.


问:
React: Unable to send file to the backend
I am trying to send an image to the backend but I am getting an error.

I am trying to do it like this:

```<code>SignupPublicProfileAPICall({
   headerimage: startupFourthStepForm.headerimage
})
...

          <FormFieldFile
            type="file"
            onChange={e => {
              startupFourthStepFormActionHandler({
                headerimage: e.target.files[0],
              });
            }}
          />
</code>```

What I send is this:

```<code>lastModified: 1559082933991
lastModifiedDate: Tue May 28 2019 16:35:33 GMT-0600 (Central Standard Time) {}
name: "010919_North-Park_Guava-Queen_Front-View_a072fdd7-f1e9-4ee9-aae6-97b7bb5c2b54_800x454.png"
size: 127234
type: "image/png"
webkitRelativePath: ""
</code>```

But the weird thing I see is if I do something like this:

setState({ headerimage: startupFourthStepForm.headerimage });

And then I log console.log(state.headerimage) I get an empty object {}.

This is the body of the fetch call:

```<code>      body: JSON.stringify({
        headerimage,
      }),
</code>```

Why?

答:
You should create FormData object instead of stringifing headerImage.

```<code><FormFieldFile
            type="file"
            onChange={e => {
              let formData = new FormData();
              formData.append('file', e.target.files[0]); // set the proper name of property

              startupFourthStepFormActionHandler({
                headerimage: formData
              });
            }}
          />
</code>```

and then in your  fetch call just replace body with this:

```<code>body: headerimage,
</code>```

Body:
I am trying to send an image to the backend but I am getting an error.

I am trying to do it like this:

SignupPublicProfileAPICall({
   headerimage: startupFourthStepForm.headerimage
})
...

          <FormFieldFile
            type="file"
            onChange={e => {
              startupFourthStepFormActionHandler({
                headerimage: e.target.files[0],
              });
            }}
          />

What I send is this:

lastModified: 1559082933991
lastModifiedDate: Tue May 28 2019 16:35:33 GMT-0600 (Central Standard Time) {}
name: "010919_North-Park_Guava-Queen_Front-View_a072fdd7-f1e9-4ee9-aae6-97b7bb5c2b54_800x454.png"
size: 127234
type: "image/png"
webkitRelativePath: ""

But the weird thing I see is if I do something like this:

setState({ headerimage: startupFourthStepForm.headerimage });

And then I log console.log(state.headerimage) I get an empty object {}.

This is the body of the fetch call:

      body: JSON.stringify({
        headerimage,
      }),

Why?

Body:
You should create FormData object instead of stringifing headerImage.

<FormFieldFile
            type="file"
            onChange={e => {
              let formData = new FormData();
              formData.append('file', e.target.files[0]); // set the proper name of property

              startupFourthStepFormActionHandler({
                headerimage: formData
              });
            }}
          />

and then in your  fetch call just replace body with this:

body: headerimage,


问:
how to fix runtime error in C++ bad alloc
I have written a code using classes and it complies and runs however the full main is not executed as I obtain this message:

```<code>libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
Abort trap: 6
</code>```

The code is executed up to the very end the part of 'dealing out remaining cards:', then I get the error message.
I'm not sure why this is happening, this is my code:

```<code>class CardSet
{
    public:
        CardSet();
        CardSet(int);
        ~CardSet();
        int Size() const;
        bool IsEmpty() const;
        void Shuffle();
        int Deal();
        void Deal(int,CardSet&,CardSet&);
        void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
        void AddCard(int);
        void MergeShuffle(CardSet&);
        void Print() const;
    private:
        int* Card;
        int nCards;
};

void PrintCard(int);

void PrintCard(int c)
{
    int Rank = c%13;
    int Suit = c/13;
    const char NameSuit[5] = "SCDH";
    const char NameRank[14] = "23456789XJQKA";
    cout << NameRank[Rank] << NameSuit[Suit];
}

/*Default constructor that sets up a set of 0 cards*/
CardSet::CardSet()
{
    Card = NULL;
    nCards = 0;
}

/*Initialising constructor where the number of cards is the argument passed*/
CardSet::CardSet(int c)
{
    nCards=c;
    Card = new int[c]; /*Create memory in the array using the new operator*/
        for(int i = 0; i < c; i++) /*for loop to set each value*/
    {
    Card[i] = (i % 52); /*Uses mod operator to ensure number of cards never exceeds 51*/
    }
}

/*Destructor that deletes/cleans up the memory previously set in the array*/
CardSet::~CardSet()
{

    if (Card!=NULL)

        delete [] Card;

    Card = NULL;
}

/*If cardset is empty bool returns true*/
bool CardSet::IsEmpty() const
{
     if (Size() == 0) /*If the set of cards is empty*/

        return true;

    else

        return false;
}

/*Print function passes cards to PrintCard function to print out the contents of the set, 24 cards to a line*/
void CardSet::Print() const
{
    for (int i = 0; i < nCards; i++) /*Prints out the cards from i = 0 to i = ncards*/

    {
        if (i%24 == 0 && i != 0) /*when it hits the 24th card, start a new line*/
            cout << endl;

        else
            cout << " "; /*else enters space between cards*/

        PrintCard(Card[i]);
    }
    cout << endl; /*New line*/

}

/*Returns the number of cards in the set*/
int CardSet::Size() const
{

    return nCards;

}

/*rearranges the cards in the set in a random manner*/
void CardSet::Shuffle()
{

    int temp;

    for (int i = 0; i < nCards; i++){

        int j = rand() % (nCards - 1);

        if (i != j){

            temp = Card[i];

            Card[i] = Card[j];

            Card[j] = temp;

        }

    }

}

/*takes current set and set provided as an argument and makes current set contain contain all the cards from the two sets*/
void CardSet::MergeShuffle(CardSet& set)
{
    while(set.IsEmpty()==false){

        int dealCard = set.Deal();

        AddCard(dealCard);
    }

    Shuffle(); /*call to shuffle function*/

}

/*add a card to the current hand*/
void CardSet::AddCard(int c)
{
int *hand;

    hand = new int[nCards+1]; /*memory allocation to hand*/

    for(int i = 0; i<nCards; i++){ /*for each card i in the set nCards*/

        hand[i] = Card[i];

    }

    hand[nCards] = c;

    delete [] Card; /*delete memory in the array*/

    Card = hand;

    nCards++;
}

/*return the value of the first card in the set which is located in the 0th element of the array*/
int CardSet::Deal()
{
 int *nDeck;

    int temp = 0;

    nDeck = new int[nCards-1]; /*Make fresh memory*/

    temp = Card[0]; /*temp is the first card which we are returning*/

    if (IsEmpty()){ /*If the set is empty*/

        cout << "This set is empty." << endl;

        return -1;

    }

    int j = 0;

    for (int i = 1; i < nCards; i++){

        nDeck[j] = Card[i]; /*Move the old memory to new memory*/

        j++;

    }

    delete []Card; /*Delete the old memory*/

    Card=nDeck;

    nCards--;

    return temp; /*return the value of the first card*/
}

/*deals two hands in the two CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2)
{
    for (int i = 0; i < c; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument passed*/

    }
}

/*deals four hands in the four CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2,CardSet& set3,CardSet& set4)
{
    for (int i = 0; i < c && IsEmpty()==false; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument and so on for 3rd and 4th set*/

        dealCard = Deal();

        set3.AddCard(dealCard);

        dealCard = Deal();

        set4.AddCard(dealCard);

    }
}

</code>```

and this is my main:

```<code>int main()
{
    cout << "BEGINNING OF CARDSET TESTS . . .  "<< endl << endl;

    //--------- STEP 1 TESTS ---------------------------------------------------

    cout << "Testing constructors, Print(), Size() & IsEmpty():" << endl;
    CardSet CardSet1; // empty cCardSet
    CardSet CardSet2(12); // CardSet with 12 cards
    if(CardSet1.IsEmpty()) cout<<"CardSet1 is empty"<<endl;
    else cout<<"CardSet1 has "<< CardSet1.Size() <<" cards" << endl;
    if(CardSet2.IsEmpty()) cout<<"CardSet2 is empty"<<endl;
    else cout<<"CardSet2 has "<< CardSet2.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet1.Print();
    cout << "Printout of CardSet2: ";
    CardSet2.Print();
    cout << endl;

    /*--------- STEP 2 TESTS ---------------------------------------------*/

    cout << "Testing Normal Shuffle: "<< endl;
    CardSet CardSet3(24); // CardSet with 24 cards
    cout << "Unshuffled CardSet: ";
    CardSet3.Print();
    CardSet3.Shuffle();
    cout << "Shuffled CardSet:   ";
    CardSet3.Print();
    cout << endl;

    cout << "Testing Merge Shuffle: "<< endl;
    CardSet CardSet4(12); // CardSet with 12 cards
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << "Merge shuffling both CardSets into CardSet1:\n";
    CardSet2.MergeShuffle(CardSet4);
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: " ;
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << endl;

    cout << "Testing Adding and removing cards to a CardSet:"<< endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    int Card = CardSet2.Deal();
    cout << "Dealing 1 card: ";
    PrintCard(Card);
    cout << endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Adding card: ";
    PrintCard(Card);
    cout << endl;
    CardSet2.AddCard(Card);
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into two other CardSets:" << endl;
    CardSet CardSet5,CardSet6(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Dealing 3 Cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into four other CardSets:" << endl;
    CardSet CardSet7,CardSet8(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing 3 cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing out remaining cards: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << endl;

    cout << ". . . END OF TESTS"<< endl;

    return 0;
}

</code>```

Any help would be greatly appreciated.

答:
you are allocating memory in int CardSet::Deal() function:

nDeck = new int[nCards - 1]; /*Make fresh memory*/

while nCards became zero. you have to terminate your program when the nCards is zero I suppose.

Body:
I have written a code using classes and it complies and runs however the full main is not executed as I obtain this message:

libc++abi.dylib: terminating with uncaught exception of type std::bad_alloc: std::bad_alloc
Abort trap: 6

The code is executed up to the very end the part of 'dealing out remaining cards:', then I get the error message.
I'm not sure why this is happening, this is my code:

class CardSet
{
    public:
        CardSet();
        CardSet(int);
        ~CardSet();
        int Size() const;
        bool IsEmpty() const;
        void Shuffle();
        int Deal();
        void Deal(int,CardSet&,CardSet&);
        void Deal(int,CardSet&,CardSet&,CardSet&,CardSet&);
        void AddCard(int);
        void MergeShuffle(CardSet&);
        void Print() const;
    private:
        int* Card;
        int nCards;
};

void PrintCard(int);

void PrintCard(int c)
{
    int Rank = c%13;
    int Suit = c/13;
    const char NameSuit[5] = "SCDH";
    const char NameRank[14] = "23456789XJQKA";
    cout << NameRank[Rank] << NameSuit[Suit];
}

/*Default constructor that sets up a set of 0 cards*/
CardSet::CardSet()
{
    Card = NULL;
    nCards = 0;
}

/*Initialising constructor where the number of cards is the argument passed*/
CardSet::CardSet(int c)
{
    nCards=c;
    Card = new int[c]; /*Create memory in the array using the new operator*/
        for(int i = 0; i < c; i++) /*for loop to set each value*/
    {
    Card[i] = (i % 52); /*Uses mod operator to ensure number of cards never exceeds 51*/
    }
}

/*Destructor that deletes/cleans up the memory previously set in the array*/
CardSet::~CardSet()
{

    if (Card!=NULL)

        delete [] Card;

    Card = NULL;
}

/*If cardset is empty bool returns true*/
bool CardSet::IsEmpty() const
{
     if (Size() == 0) /*If the set of cards is empty*/

        return true;

    else

        return false;
}

/*Print function passes cards to PrintCard function to print out the contents of the set, 24 cards to a line*/
void CardSet::Print() const
{
    for (int i = 0; i < nCards; i++) /*Prints out the cards from i = 0 to i = ncards*/

    {
        if (i%24 == 0 && i != 0) /*when it hits the 24th card, start a new line*/
            cout << endl;

        else
            cout << " "; /*else enters space between cards*/

        PrintCard(Card[i]);
    }
    cout << endl; /*New line*/

}

/*Returns the number of cards in the set*/
int CardSet::Size() const
{

    return nCards;

}

/*rearranges the cards in the set in a random manner*/
void CardSet::Shuffle()
{

    int temp;

    for (int i = 0; i < nCards; i++){

        int j = rand() % (nCards - 1);

        if (i != j){

            temp = Card[i];

            Card[i] = Card[j];

            Card[j] = temp;

        }

    }

}

/*takes current set and set provided as an argument and makes current set contain contain all the cards from the two sets*/
void CardSet::MergeShuffle(CardSet& set)
{
    while(set.IsEmpty()==false){

        int dealCard = set.Deal();

        AddCard(dealCard);
    }

    Shuffle(); /*call to shuffle function*/

}

/*add a card to the current hand*/
void CardSet::AddCard(int c)
{
int *hand;

    hand = new int[nCards+1]; /*memory allocation to hand*/

    for(int i = 0; i<nCards; i++){ /*for each card i in the set nCards*/

        hand[i] = Card[i];

    }

    hand[nCards] = c;

    delete [] Card; /*delete memory in the array*/

    Card = hand;

    nCards++;
}

/*return the value of the first card in the set which is located in the 0th element of the array*/
int CardSet::Deal()
{
 int *nDeck;

    int temp = 0;

    nDeck = new int[nCards-1]; /*Make fresh memory*/

    temp = Card[0]; /*temp is the first card which we are returning*/

    if (IsEmpty()){ /*If the set is empty*/

        cout << "This set is empty." << endl;

        return -1;

    }

    int j = 0;

    for (int i = 1; i < nCards; i++){

        nDeck[j] = Card[i]; /*Move the old memory to new memory*/

        j++;

    }

    delete []Card; /*Delete the old memory*/

    Card=nDeck;

    nCards--;

    return temp; /*return the value of the first card*/
}

/*deals two hands in the two CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2)
{
    for (int i = 0; i < c; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument passed*/

    }
}

/*deals four hands in the four CardSet arguments passed*/
void CardSet::Deal(int c,CardSet& set1,CardSet& set2,CardSet& set3,CardSet& set4)
{
    for (int i = 0; i < c && IsEmpty()==false; i++){

        int dealCard = Deal(); /*Deal a card from the original deck*/

        set1.AddCard(dealCard); /*Add it to the 1st set argument passed*/

        dealCard = Deal(); /*Deal another card*/

        set2.AddCard(dealCard); /*Add it to the 2nd set argument and so on for 3rd and 4th set*/

        dealCard = Deal();

        set3.AddCard(dealCard);

        dealCard = Deal();

        set4.AddCard(dealCard);

    }
}

and this is my main:

int main()
{
    cout << "BEGINNING OF CARDSET TESTS . . .  "<< endl << endl;

    //--------- STEP 1 TESTS ---------------------------------------------------

    cout << "Testing constructors, Print(), Size() & IsEmpty():" << endl;
    CardSet CardSet1; // empty cCardSet
    CardSet CardSet2(12); // CardSet with 12 cards
    if(CardSet1.IsEmpty()) cout<<"CardSet1 is empty"<<endl;
    else cout<<"CardSet1 has "<< CardSet1.Size() <<" cards" << endl;
    if(CardSet2.IsEmpty()) cout<<"CardSet2 is empty"<<endl;
    else cout<<"CardSet2 has "<< CardSet2.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet1.Print();
    cout << "Printout of CardSet2: ";
    CardSet2.Print();
    cout << endl;

    /*--------- STEP 2 TESTS ---------------------------------------------*/

    cout << "Testing Normal Shuffle: "<< endl;
    CardSet CardSet3(24); // CardSet with 24 cards
    cout << "Unshuffled CardSet: ";
    CardSet3.Print();
    CardSet3.Shuffle();
    cout << "Shuffled CardSet:   ";
    CardSet3.Print();
    cout << endl;

    cout << "Testing Merge Shuffle: "<< endl;
    CardSet CardSet4(12); // CardSet with 12 cards
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << "Merge shuffling both CardSets into CardSet1:\n";
    CardSet2.MergeShuffle(CardSet4);
    cout<<"CardSet1 has "<< CardSet2.Size() <<" cards and cardSet2 has "<< CardSet4.Size() <<" cards" << endl;
    cout << "Printout of CardSet1: " ;
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet4.Print();
    cout << endl;

    cout << "Testing Adding and removing cards to a CardSet:"<< endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    int Card = CardSet2.Deal();
    cout << "Dealing 1 card: ";
    PrintCard(Card);
    cout << endl;
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Adding card: ";
    PrintCard(Card);
    cout << endl;
    CardSet2.AddCard(Card);
    cout << "CardSet Size: " << CardSet2.Size() << endl;
    cout << "Printout of CardSet: ";
    CardSet2.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into two other CardSets:" << endl;
    CardSet CardSet5,CardSet6(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Dealing 3 Cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << endl;

    cout << "Testing Dealing out cards from one CardSet into four other CardSets:" << endl;
    CardSet CardSet7,CardSet8(6); // CardSets with 0 & 6 cards
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing 3 cards from CardSet1 into CardSet2 and CardSet3: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << "Printout of CardSet2: ";
    CardSet5.Print();
    cout << "Printout of CardSet3: ";
    CardSet6.Print();
    cout << "Printout of CardSet4: ";
    CardSet7.Print();
    cout << "Printout of CardSet5: ";
    CardSet8.Print();
    cout << "Dealing out remaining cards: " << endl;
    CardSet2.Deal(3,CardSet5,CardSet6,CardSet7,CardSet8);
    cout << "Printout of CardSet1: ";
    CardSet2.Print();
    cout << endl;

    cout << ". . . END OF TESTS"<< endl;

    return 0;
}

Any help would be greatly appreciated.


问:
How to convert sourceSets from a project to kotlin kts
I have a multi module gradle project. I'm converting all build.gradle configuration files to Kotlin kts.

But I can't find how to convert this code below to kotlin kts.

I tried to place groovy code inside kts and checked the documentation, but I could't find anything.

```<code>    testCompile project(":entities").sourceSets.test.output
</code>```

答:
After some investigation, I found that the syntax in this area has changed recently.

This gives some history:

https://github.com/gradle/kotlin-dsl/issues/577

The Kotlin DSL 1.0-RC3 introduced some breaking changes:

https://github.com/gradle/kotlin-dsl/releases/tag/v1.0-RC3

the sourceSets collection does still exist on the project:   https://docs.gradle.org/5.0/dsl/org.gradle.api.Project.html#org.gradle.api.Project:sourceSets)

this collection can be cross-referenced via a peer project

I tried a few variants, and discovered that:

```<code>dependencies {
  testImplementation(project(":entities").sourceSets["test"].output)
}
</code>```

results in

```<code>testImplementation(project(":entities").sourceSets["test"].output)
                                     ^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
                                                        public val Project.sourceSets: SourceSetContainer defined in org.gradle.kotlin.dsl
</code>```

But the following works just fine, as long as the Java plugin is enabled:

```<code>val entityTests: SourceSetOutput = project(":entities").sourceSets["test"].output

dependencies {
  testImplementation(entityTests)
}
</code>```

Body:
I have a multi module gradle project. I'm converting all build.gradle configuration files to Kotlin kts.

But I can't find how to convert this code below to kotlin kts.

I tried to place groovy code inside kts and checked the documentation, but I could't find anything.

    testCompile project(":entities").sourceSets.test.output

Body:
After some investigation, I found that the syntax in this area has changed recently.

This gives some history:

https://github.com/gradle/kotlin-dsl/issues/577

The Kotlin DSL 1.0-RC3 introduced some breaking changes:

https://github.com/gradle/kotlin-dsl/releases/tag/v1.0-RC3

the sourceSets collection does still exist on the project:   https://docs.gradle.org/5.0/dsl/org.gradle.api.Project.html#org.gradle.api.Project:sourceSets)

this collection can be cross-referenced via a peer project

I tried a few variants, and discovered that:

dependencies {
  testImplementation(project(":entities").sourceSets["test"].output)
}

results in

testImplementation(project(":entities").sourceSets["test"].output)
                                     ^ Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
                                                        public val Project.sourceSets: SourceSetContainer defined in org.gradle.kotlin.dsl

But the following works just fine, as long as the Java plugin is enabled:

val entityTests: SourceSetOutput = project(":entities").sourceSets["test"].output

dependencies {
  testImplementation(entityTests)
}


问:
Button click event on a user control dynamically created to a WPF form
I am adding the user controls during runtime based on a query of a database of XML data. So, the number of user controls is different.

Also, given the type of XML received, I cannot bind the user control to the list created from the XML data because there will instances where I will pull different fields based on whether this is a new client versus an existing client. For an existing client, there are only 8 fields. A new client needs 40 or 50 fields.

I am creating one of two user control based on new client versus the existing client.

I believe this is what is needed on the user control.

Here is the code snippet.

```<code>public event RoutedEventHandler btnAddClient_Click;

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    if(btnAddClient_Click !=null)
        {
            btnAddClient_Click(this, new RoutedEventArgs());
        }
}
public ucNewClient()
{
    InitializeComponent();
}
</code>```

I need to know how to set the click event on the dynamically created user control and also the main form.

Any help would be greatly appreciated.

I have done multiple research and did not find help. What I found were user controls with a click event. However, the user control was not dynamically/during runtime.

I expect to perform an action of adding or updating a client to a list to perform tasks later in the project.

答:
Welcome to SO.

Any time you need to render a list of items in WPF you should use ItemsControl or one of it's derived classes. Start with a list of the data elements you want to display in your view model (or whatever your DataContext is set to):

```<code>    private ObservableCollection<SomeBaseClass> _MyItems;
    public ObservableCollection<SomeBaseClass> MyItems
    {
        get { return this._MyItems; }
        set
        {
            if (this._MyItems != value)
            {
                this._MyItems = value;
                RaisePropertyChanged(() => this.MyItems);
            }
        }
    }
</code>```

You then declare an ItemsControl that binds to this list:

```<code> <ItemsControl ItemsSource="{Binding MyItems}" />
</code>```

A vertical stackpanel is the default layout panel, but you can change that to something else if you need. Either way you then create a data template for each type of data you want to display:

```<code><Window.Resources>

    <DataTemplate DataType="{x:Type local:DataTypeA">
        <TextBlock Text="This is data type A" />
    </DataTemplate>

    <DataTemplate DataType="{x:Type local:DataTypeB">
        <TextBlock Text="This is data type B" />
    </DataTemplate>

   ... etc ...

</Window.Resources>
</code>```

And that's it!

Sometimes you'll want to display things differently depending on actual data itself, and in that case you can use a single data template with data triggers instead:

```<code><ControlTemplate x:Key="TemplateA">
    <TextBlock Text="This is template A" />
</ControlTemplate>

<ControlTemplate x:Key="TemplateB">
    <TextBlock Text="This is template B" />
</ControlTemplate>

<DataTemplate DataType="{x:Type local:SomeBaseClass}">
    <ContentControl Content="{Binding}">
        <ContentControl.Style>
            <Style TargetType="{x:Type ContentControl}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SomeProperty}" Value="ValueA">
                        <Setter Property="Template" Value="{StaticResource TemplateA}" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding SomeProperty}" Value="ValueB">
                        <Setter Property="Template" Value="{StaticResource TemplateB}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>
</code>```

Body:
I am adding the user controls during runtime based on a query of a database of XML data. So, the number of user controls is different.

Also, given the type of XML received, I cannot bind the user control to the list created from the XML data because there will instances where I will pull different fields based on whether this is a new client versus an existing client. For an existing client, there are only 8 fields. A new client needs 40 or 50 fields.

I am creating one of two user control based on new client versus the existing client.

I believe this is what is needed on the user control.

Here is the code snippet.

public event RoutedEventHandler btnAddClient_Click;

private void OnButtonClick(object sender, RoutedEventArgs e)
{
    if(btnAddClient_Click !=null)
        {
            btnAddClient_Click(this, new RoutedEventArgs());
        }
}
public ucNewClient()
{
    InitializeComponent();
}

I need to know how to set the click event on the dynamically created user control and also the main form.

Any help would be greatly appreciated.

I have done multiple research and did not find help. What I found were user controls with a click event. However, the user control was not dynamically/during runtime.

I expect to perform an action of adding or updating a client to a list to perform tasks later in the project.

Body:
Welcome to SO.

Any time you need to render a list of items in WPF you should use ItemsControl or one of it's derived classes. Start with a list of the data elements you want to display in your view model (or whatever your DataContext is set to):

    private ObservableCollection<SomeBaseClass> _MyItems;
    public ObservableCollection<SomeBaseClass> MyItems
    {
        get { return this._MyItems; }
        set
        {
            if (this._MyItems != value)
            {
                this._MyItems = value;
                RaisePropertyChanged(() => this.MyItems);
            }
        }
    }

You then declare an ItemsControl that binds to this list:

 <ItemsControl ItemsSource="{Binding MyItems}" />

A vertical stackpanel is the default layout panel, but you can change that to something else if you need. Either way you then create a data template for each type of data you want to display:

<Window.Resources>

    <DataTemplate DataType="{x:Type local:DataTypeA">
        <TextBlock Text="This is data type A" />
    </DataTemplate>

    <DataTemplate DataType="{x:Type local:DataTypeB">
        <TextBlock Text="This is data type B" />
    </DataTemplate>

   ... etc ...

</Window.Resources>

And that's it!

Sometimes you'll want to display things differently depending on actual data itself, and in that case you can use a single data template with data triggers instead:

<ControlTemplate x:Key="TemplateA">
    <TextBlock Text="This is template A" />
</ControlTemplate>

<ControlTemplate x:Key="TemplateB">
    <TextBlock Text="This is template B" />
</ControlTemplate>

<DataTemplate DataType="{x:Type local:SomeBaseClass}">
    <ContentControl Content="{Binding}">
        <ContentControl.Style>
            <Style TargetType="{x:Type ContentControl}">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding SomeProperty}" Value="ValueA">
                        <Setter Property="Template" Value="{StaticResource TemplateA}" />
                    </DataTrigger>
                    <DataTrigger Binding="{Binding SomeProperty}" Value="ValueB">
                        <Setter Property="Template" Value="{StaticResource TemplateB}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>


问:
Show Results of Each Table as Row
I am currently building a prototype website that shows data. The data is being entered into 1 database using a cronjob. The cronjob submits random data to 3 tables in the 1 database. For the most part, I have figured out the majority of the queries I would like to use (see website). There is one more query that I just cant seem to wrap my head around. So each table is its own location and so far I am able to create totals for hourly, weekly, monthly, etc...

My issue is, I want to generate a comparison page to compare the resource usage between locations. So instead of the resources being the columns in the table from the query, I want the location name in the columns with a total from that location.

Currently

```<code>May 29, 2019 6:00pm | Water Total | Electric Total | N. Gas Total | Solar Total
</code>```

What I Want

```<code>May 29, 2019 6:00pm | Location 1 | Location 2 | Location 3
</code>```

The above example (What I Want) would only show one resource, like WATER TOTAL.

Here is a screenshot of my db structure.

Any help would be greatly appreciated as I am not a DB administrator or expert by any means. Once I see it done I can surely manipulate it and make it do exactly what I need for different time frames.

答:
Join the 3 tables:

```<code>SELECT t1.timestamp, t1.water as location1, t2.water as location2, t3.water AS location3
FROM wpdatable_23_1 AS t1
JOIN wpdatable_23_1_1 AS t2 ON t1.timestamp = t2.timestamp
JOIN wpdatable_23_1_2 AS t3 ON t1.timestamp = t3.timestamp
</code>```

Make sure you have an index on this column:

```<code>ALTER TABLE wpdatable_23_1 ADD UNIQUE INDEX (timestamp);
ALTER TABLE wpdatable_23_1_1 ADD UNIQUE INDEX (timestamp);
ALTER TABLE wpdatable_23_1_2 ADD UNIQUE INDEX (timestamp);
</code>```

Title: Show Results of Each Table as Row

Body:
I am currently building a prototype website that shows data. The data is being entered into 1 database using a cronjob. The cronjob submits random data to 3 tables in the 1 database. For the most part, I have figured out the majority of the queries I would like to use (see website). There is one more query that I just cant seem to wrap my head around. So each table is its own location and so far I am able to create totals for hourly, weekly, monthly, etc...

My issue is, I want to generate a comparison page to compare the resource usage between locations. So instead of the resources being the columns in the table from the query, I want the location name in the columns with a total from that location.

Currently

May 29, 2019 6:00pm | Water Total | Electric Total | N. Gas Total | Solar Total

What I Want

May 29, 2019 6:00pm | Location 1 | Location 2 | Location 3

The above example (What I Want) would only show one resource, like WATER TOTAL.

Here is a screenshot of my db structure.

Any help would be greatly appreciated as I am not a DB administrator or expert by any means. Once I see it done I can surely manipulate it and make it do exactly what I need for different time frames.

Body:
Join the 3 tables:

SELECT t1.timestamp, t1.water as location1, t2.water as location2, t3.water AS location3
FROM wpdatable_23_1 AS t1
JOIN wpdatable_23_1_1 AS t2 ON t1.timestamp = t2.timestamp
JOIN wpdatable_23_1_2 AS t3 ON t1.timestamp = t3.timestamp

Make sure you have an index on this column:

ALTER TABLE wpdatable_23_1 ADD UNIQUE INDEX (timestamp);
ALTER TABLE wpdatable_23_1_1 ADD UNIQUE INDEX (timestamp);
ALTER TABLE wpdatable_23_1_2 ADD UNIQUE INDEX (timestamp);


问:
How to efficiently find a specific substring in PHP?
OK, I know how to do this but I'm interested in better/more elegant solutions (if any) for this problem.

Imagine I have the following string :

Mozilla/4.0 (compatible; MSIE 7.0;
  Windows NT 5.1; Trident/4.0; GTB6.6;
  Mozilla/4.0 (compatible; MSIE 6.0;
  Windows NT 5.1; SV1) ; .NET CLR
  1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)

I'm interested to find the highest MSIE version in that string (in that case 7.0).

Currently I use explode and preg_match a couple of times in combination with str_replace then I loop between matches and then compare the version string. It works but it's far from elegant. Any ideas on how to improve this?

Keep in mind that:

The string can have any number of MSIE occurrences (or even none)

MSIE is case insensitive

MSIE is followed by a white space (space, tab...) then by the version. The version can contain number letters and dots. The version string is ended by either a white space, a ; or the end of the line.

Thanks!

答:
This work may have already been done for you.

You may want to look up PHP's get_browser() function, along with the related browsecap.ini file.

However, I would generally advise that doing browser detection is generally a bad idea. It is fundamentally unreliable because the browser can fake its user agent string. And even if the browser doesn't do it, it can still be changed or blanked out by proxies and security software.

ContentLicense: CC BY-SA 3.0


问:
Getting Value from a ComboBox?
I have had a look at numerous other threads on here that have a similar problem but have been unable to resolve my issue. I'm using the following code for my combobox:

```<code><sq8:ComboBox runat="server" ID="cboAgree"><Items>
<sq8:ComboBoxItem runat="server" Text="Agree"></sq8:ComboBoxItem>
<sq8:ComboBoxItem runat="server" Text="Disagree"></sq8:ComboBoxItem>
</Items>
</sq8:ComboBox>
<sq:BindableControl runat="server" TargetControlID="cboAgree" DataField="Agreement"></sq:BindableControl>
</code>```

I want to get the value selected (either "Agree" or "Disagree") and use that as a condition to hide/unhide a grid on my form:

```<code>   if (value == "Disagree") {
  commentsGrid.style.visibility = "visible";
  }else{
  commentsGrid.style.visibility = "hidden";
  }
</code>```

I've tried a number of things but it seems like the problem is to do with the way the form loads and the combobox doesn't have a value at that point. I always get an error that my comboBox "cboAgree" is null.

Could anyone advise?

答:
I believe what you want - based on how you have the code structured in your other post, is to add an event handler to your combo box so that when the selected index is changed, you check the selection.

This scenario is covered in the documentation here but basically what you want to do is:

Add the following block inside your existing javascript:

```<code>function onSelectedIndexChanged(sender, eventArgs)
{
    var item = eventArgs.get_item();

    if (value == "Disagree") {
        commentsGrid.style.display = "block";
    } else {
        commentsGrid.style.display = "none";
    }
}
</code>```

I would suggest setting the display property to none and block instead of using visibility with hidden and visible. This answer covers the differences and why you should prefer using the display property in this instance.

Update your ComboBox to call the new Javascript method:

```<code><sq8:ComboBox runat="server" ID="cboAgree"
onclientselectedindexchanged="onSelectedIndexChanged">
</code>```

Title: Getting Value from a ComboBox?

Body:
I have had a look at numerous other threads on here that have a similar problem but have been unable to resolve my issue. I'm using the following code for my combobox:

<sq8:ComboBox runat="server" ID="cboAgree"><Items>
<sq8:ComboBoxItem runat="server" Text="Agree"></sq8:ComboBoxItem>
<sq8:ComboBoxItem runat="server" Text="Disagree"></sq8:ComboBoxItem>
</Items>
</sq8:ComboBox>
<sq:BindableControl runat="server" TargetControlID="cboAgree" DataField="Agreement"></sq:BindableControl>

I want to get the value selected (either "Agree" or "Disagree") and use that as a condition to hide/unhide a grid on my form:

   if (value == "Disagree") {
  commentsGrid.style.visibility = "visible";
  }else{
  commentsGrid.style.visibility = "hidden";
  }

I've tried a number of things but it seems like the problem is to do with the way the form loads and the combobox doesn't have a value at that point. I always get an error that my comboBox "cboAgree" is null.

Could anyone advise?

Body:
I believe what you want - based on how you have the code structured in your other post, is to add an event handler to your combo box so that when the selected index is changed, you check the selection.

This scenario is covered in the documentation here but basically what you want to do is:

Add the following block inside your existing javascript:

function onSelectedIndexChanged(sender, eventArgs)
{
    var item = eventArgs.get_item();

    if (value == "Disagree") {
        commentsGrid.style.display = "block";
    } else {
        commentsGrid.style.display = "none";
    }
}

I would suggest setting the display property to none and block instead of using visibility with hidden and visible. This answer covers the differences and why you should prefer using the display property in this instance.

Update your ComboBox to call the new Javascript method:

<sq8:ComboBox runat="server" ID="cboAgree"
onclientselectedindexchanged="onSelectedIndexChanged">


问:
na not picking missing values?
Have a DF med562. A categorical variable has distribution below

```<code>I    6119923

O     764905

      166666

Name: IND, dtype: int64
</code>```

Want to just impute the 166666 missing values using value of I, the one with 6119923 rows. Wrote this

```<code>med562['IND']=med562['IND'].fillna(value='I')

Catcounts=med562.IND.value_counts(dropna=False)

Catcounts
</code>```

It did not change, still the same distribution. This is running on Python 3.7.3. Should not be software issue. Any thought? Thanks.

答:
That is not NaN, it is whitespace , if that is NaN when you do value_counts it will not show in the result , since dropna=True in value_counts defaulted as True

```<code>med562['IND']=med562['IND'].replace({'':'I'})

Catcounts=med562.IND.value_counts(dropna=False)
</code>```

Title: na not picking missing values?

Body:
Have a DF med562. A categorical variable has distribution below

I    6119923

O     764905

      166666

Name: IND, dtype: int64

Want to just impute the 166666 missing values using value of I, the one with 6119923 rows. Wrote this

med562['IND']=med562['IND'].fillna(value='I')

Catcounts=med562.IND.value_counts(dropna=False)

Catcounts

It did not change, still the same distribution. This is running on Python 3.7.3. Should not be software issue. Any thought? Thanks.

Body:
That is not NaN, it is whitespace , if that is NaN when you do value_counts it will not show in the result , since dropna=True in value_counts defaulted as True

med562['IND']=med562['IND'].replace({'':'I'})

Catcounts=med562.IND.value_counts(dropna=False)


问:
Replace if last value of group is missing with a POSIXct variable
I would like to replace the last value of the enddt variable to the value "2019-03-31 23:59:59" if it is missing.

```<code>ID  stdt                enddt               goal
1   11/21/2018 7:11     12/31/2018 23:59    12/31/2018 23:59
1   1/21/2019 0:00      1/22/2019 5:19      1/22/2019 5:19
1   1/22/2018 5:19                          3/31/2019 23:59
2   12/17/2018 16:49    3/31/2018 21:59     3/31/2018 21:59
2   3/31/2018 22:00     12/21/2018 23:05    12/21/2018 23:05
2   12/21/2018 23:05    1/16/2019 8:32      1/16/2019 8:32
</code>```

My attempt didn't work. It generates a single value for each id (first enddt value).

```<code>df <- df %>%
  group_by(ID) %>%
  mutate(goal= ifelse(is.null(last(enddt)), "2019-03-31 23:59:59", enddt)) %>%
  ungroup()

hh3$goal<- as.POSIXct(hh3$goal, origin = "1960-01-01")
</code>```

My date/time variable are a "POSIXct" "POSIXt" class. Perhaps I need to change the class of this variable using chron??

Thank you in advance.
Marvin

答:
There are two funky things you are running up against.

ifelse() on a date often has unexpected outputs. Because enddt has a POSIXct class, the new result of goal should have it as well.

in the ifelse() statement, you are asking if 1 thing is TRUE and then to go row-by-row and generate an output. This too can create unexpected warnings and outputs. A way around this is to create a helper column as I did below (missing_date). The other way to fix this is something like this ifelse(rep(is.na(last(enddt)), n()), as.POSIXct("2019-03-31 23:59:59"), enddt) but I think the helper column is easier to follow.

See if this helps you along

library(tidyverse)
library(lubridate) #mdy_hm function

df <- data.table::fread(
  "ID   stdt    enddt   goal
  1 11/21/2018 7:11 3/31/2019 23:59 3/31/2019 23:59
  1 11/21/2018 7:11 11/22/2018 5:19 11/22/2018 5:19
  1 11/22/2018 5:19     3/31/2018 23:59
  2 12/17/2018 16:49    3/31/2019 23:59 3/31/2019 23:59
  2 12/17/2018 16:49    12/21/2018 23:05    12/21/2018 23:05
  2 12/21/2018 23:05    1/16/2019 8:32  1/16/2019 8:32"
  ) %>%
  mutate_at(vars(c(ends_with("dt"), "goal")), mdy_hm)

df %>%
  group_by(ID) %>%
  mutate(
    # this puts a T/F in every column, note, is.na vs is.null
    missing_date = is.na(last(enddt)),
    goal = ifelse(missing_date, as.POSIXct("2019-03-31 23:59:59"), enddt)
  ) %>%
  ungroup() %>%
  # 1970 instead of 1960
  mutate(goal = as.POSIXct(goal, origin = "1970-01-01")) %>%
  # remove this column
  select(-missing_date)
```

Body:
I would like to replace the last value of the enddt variable to the value "2019-03-31 23:59:59" if it is missing.

ID  stdt                enddt               goal
1   11/21/2018 7:11     12/31/2018 23:59    12/31/2018 23:59
1   1/21/2019 0:00      1/22/2019 5:19      1/22/2019 5:19
1   1/22/2018 5:19                          3/31/2019 23:59
2   12/17/2018 16:49    3/31/2018 21:59     3/31/2018 21:59
2   3/31/2018 22:00     12/21/2018 23:05    12/21/2018 23:05
2   12/21/2018 23:05    1/16/2019 8:32      1/16/2019 8:32

My attempt didn't work. It generates a single value for each id (first enddt value).

df <- df %>%
  group_by(ID) %>%
  mutate(goal= ifelse(is.null(last(enddt)), "2019-03-31 23:59:59", enddt)) %>%
  ungroup()

hh3$goal<- as.POSIXct(hh3$goal, origin = "1960-01-01")

My date/time variable are a "POSIXct" "POSIXt" class. Perhaps I need to change the class of this variable using chron??

Thank you in advance.
Marvin


问:
In-component data fetching depending on cookie
I have a component like this:

```<code>class MyComponent extends React.PureComponent {
  componentDidMount() {
    const { params } = this.props.match
    fetch(`/o/${params.id}`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(r => r.json())
    .then(json => {
      this.props.setData(json)
    })
  }
  render() {
    const { t, payload, cookies } = this.props;
    return <div>
      {cookies.cookies.language}
      {payload.myData}
    </div>
  }
}
</code>```

So, I fetch my data in the component. But what's important, the resultant data differ depending on one of my cookies. So after changing my cookie I'd like also re-fetch my data, but I don't know what is the most elegant way to do this. I use react-cookie library, so now every cookie change is updated in my view. But of course re-fetching my data in the render method is not a good idea, and I think componentDidUpdate is also a bad place for it. So, how should I solve this problem?

PS. I use Redux too.

答:
You need to have a componentDidUpdate() and inside that you can check if the cookies have changed and then make your fetch call.

It would be something like this:

```<code>componentDidUpdate(prevProps) {
  if (this.props.cookies !== prevProps.cookies) {
    this.fetchData(this.props.cookies).then(...)
  }
}
</code>```

But it looks like this logic along with componentDidMount() should be moved one component up where the component is not pure.

Body:
I have a component like this:

class MyComponent extends React.PureComponent {
  componentDidMount() {
    const { params } = this.props.match
    fetch(`/o/${params.id}`, {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      }
    })
    .then(r => r.json())
    .then(json => {
      this.props.setData(json)
    })
  }
  render() {
    const { t, payload, cookies } = this.props;
    return

      {cookies.cookies.language}
      {payload.myData}

  }
}

So, I fetch my data in the component. But what's important, the resultant data differ depending on one of my cookies. So after changing my cookie I'd like also re-fetch my data, but I don't know what is the most elegant way to do this. I use react-cookie library, so now every cookie change is updated in my view. But of course re-fetching my data in the render method is not a good idea, and I think componentDidUpdate is also a bad place for it. So, how should I solve this problem?

PS. I use Redux too.

Body:
You need to have a componentDidUpdate() and inside that you can check if the cookies have changed and then make your fetch call.

It would be something like this:

componentDidUpdate(prevProps) {
  if (this.props.cookies !== prevProps.cookies) {
    this.fetchData(this.props.cookies).then(...)
  }
}

But it looks like this logic along with componentDidMount() should be moved one component up where the component is not pure.


问:
ASP.NET MVC Controller with multiple repositories?
I have a View where I am searching my db for an object(i.e. Books)..

My controller for this view depends on a BooksRepository that implements a search method.

Everything works fine. I also have the option to do an advanced search which presents a larger form in a Modal popup. This form has many fields including a Dropdown box to select an 'Author' to search by.

I would like to pass a list of authors in my viewmodel so in my conroller I instantiate an instance of my view model, I need to call a repository method to bring back the list of authors's...

My thinking is that this GetAuthors() method should be in an AuthorRepository...

Is it bad practice to inject multiple repo's into a controller?  or should I have an Author controller that gets injected with the author repo...and call a method in the Author controller from my BookSearch controller?

答: I think it's perfectly fine to refer to multiple repositories in a controller. A controller's job is to wrap data in a model and pass it to a view, regardless of how it gets to the data. Doing cross-controller calls can get messy. </p>


问:
Why am I seeing this weird lag when going between pages?
When clicking on an icon in the AppBar that's supposed to take me to my Profile page there is some weirdness.  The contents of the Profile page immediately show up on top of the previous page and then a second later the Profile page loads and everything is fine.  Same thing happens when going back from Profile page to the previous page.

Here is a link to the screen recording https://vimeo.com/user99110764/review/339241883/a39312e6d8

Below is the code for the Profile button that is in the AppBar

class ProfileButton extends StatelessWidget {

  final store = AppStore.store;

  @override
  Widget build(BuildContext context) {

    return IconButton(
      onPressed: () async {
        if (store.state.userState.user == null) {
          AppNavigator.signInPage();
        } else {
          AppNavigator.profilePage();
        }
      },
      tooltip: 'Profile',
      icon: Icon(Icons.person),
    );
  }
}

EDIT:

static profilePage() {
  navigator.currentState.pushNamed('/profile');
}

static signInPage() {
  navigator.currentState.pushNamed('/sign_in');
}
```

Since the video is not working I'll try to explain what's happening.  I'm on the main page of the app that has a list view.  I click on the profile button in the AppBar after I've already signed in so it navigates to the Profile page, but what happens is that the contents of the Profile page (image + logout button) get immediately rendered on top of the main page and after about a second, the background of the Profile page loads and everything looks how it's supposed to.

答: An async function uses the await expression. Hopefully, this could help...Dart asynchronous programming

Body:
When clicking on an icon in the AppBar that's supposed to take me to my Profile page there is some weirdness.  The contents of the Profile page immediately show up on top of the previous page and then a second later the Profile page loads and everything is fine.  Same thing happens when going back from Profile page to the previous page.

Here is a link to the screen recording https://vimeo.com/user99110764/review/339241883/a39312e6d8

Below is the code for the Profile button that is in the AppBar

class ProfileButton extends StatelessWidget {

  final store = AppStore.store;

  @override
  Widget build(BuildContext context) {

    return IconButton(
      onPressed: () async {
        if (store.state.userState.user == null) {
          AppNavigator.signInPage();
        } else {
          AppNavigator.profilePage();
        }
      },
      tooltip: 'Profile',
      icon: Icon(Icons.person),
    );
  }
}

EDIT:

static profilePage() {
  navigator.currentState.pushNamed('/profile');
}

static signInPage() {
  navigator.currentState.pushNamed('/sign_in');
}

Since the video is not working I'll try to explain what's happening.  I'm on the main page of the app that has a list view.  I click on the profile button in the AppBar after I've already signed in so it navigates to the Profile page, but what happens is that the contents of the Profile page (image + logout button) get immediately rendered on top of the main page and after about a second, the background of the Profile page loads and everything looks how it's supposed to.


问:
Exactly how is fixed point more accurate than floating point
I (think) I understand the both fixed and floating point representations of fractional numbers in binary. However, I often see fixed point described as more accurate with less range, and floating point described as less accurate with more range. Now, if I understand correctly, floating points inaccuracies stem from the fact it cannot represent 0.1 and thus many other real numbers = I thought that fixed point had the same issue, so how is it described as more "accurate". If I'm not mistaken Von Neumann also seemed to champion this idea, and said we should not use floating point and instead fixed, but WHY?</p>

答:
When using 32 bits for a floating-point representation, they are commonly partitioned into 1 bit to encode the sign, 8 bits to encode the exponent, and 23 bits for the primary encoding of the significand. Due to some special treatment with the exponent, the full significand has 24 bits. In this format, the resolution of floating-point numbers is 1 part in 223, in the sense that changing the low bit changes the represented value by 2−23 times the value of the high bit.

When using 32 bits for a fixed-point representation, the high bit is typically used to indicate sign, so the highest value bit is the next highest, and it represents 230 times the value of the low bit. So, with this format, the resolution of fixed-point numbers is 1 part in 230.

Therefore, using the same number of bits, fixed-point has more resolution than floating-point. Even with other choices of how many bits to use for which parts, floating-point needs to use some bits for the exponent, and fixed-point uses zero, so fixed-point always has finer resolution than floating-point.

Floating-point offers dynamic range, meaning it can handle large or small numbers by varying the exponent as part of calculations. Fixed-point has only static range—it can represent large numbers or small numbers, but you have to choose the range when designing the code. (To some extent, this can be finessed, such as by choosing a small range for the input values but then increasing the range as values are added together to form greater and greater sums or other results. However, the scale for each particular calculation must be chosen at design time.) If you need higher resolution and do not need dynamic range, then use fixed-point. If you need dynamic range and do not need higher resolution, then used floating-point. If you need both, use more bits.

Note that the fixed scale means fixed-point will sometimes be less accurate than floating-point. Floating-point adjusts its scale to move the leading digit to the high position, up to the limits of its exponent range. So it keeps the resolution ratio around 1 in 223 in the format described above. But fixed point is stuck with the scale chosen at design time. If it needs to represent a number whose magnitude falls at, say, bit 2 of the fixed-point format, then its resolution for that number is only around 1 in 22.


问:
combining resolvers for interface and concrete types
For some reason I'm having a hard time figuring out how to combine resolvers for a GraphQL interface and a type that implements said interface.

Say I have the following schema:

```<code>interface IPerson {
  id: ID!
  firstName: String!
  lastName: String!
}

type ClubMember implements IPerson {
  ...IPerson fields
  memberType: String!
  memberSince: DateTime!
}

type StaffMember implements IPerson {
  ...IPerson fields
  hireDate: DateTime!
  reportsTo: StaffMember
}

extend type Query {
  people(ids: [Int!]): [IPerson]
}
</code>```

A full ClubMember query with all fields, such as:

```<code>query {
  people(ids: [123456,234567,345678]) {
    id
    firstName
    lastName
    ... on ClubMember {
      memberType
      memberSince
    }
  }
}
</code>```

would produce a response like the following:

```<code>[
  {
    "id": 123456,
    "firstName": "Member",
    "lastName": "McMemberface",
    "memberType": "VIP",
    "memberSince": "2019-05-28T16:05:55+00:00"
  },
  ...etc.
]
</code>```

I've used makeExecutableSchema() from apollo-server with inheritResolversFromInterfaces: true, and I want to be able to make use of default resolvers for each interface/type by having the model classes backing IPerson, ClubMember, etc. return objects with only the fields relevant to each type, i.e., the model class for IPerson fetches only the fields required by IPerson, etc. That is, the response above would execute 2 SQL statements:

```<code>SELECT id, firstName, lastName FROM Contacts WHERE id IN(?);
</code>```

and

```<code>SELECT contactId, memberType, memberSince FROM Members WHERE contactId IN(?);
</code>```

Of course, I could get all the data in one SQL statement by doing a JOIN at the database level, but I really want to have one (and only one) way of resolving the fields required by IPerson, and let the other types augment that data with their own resolvers.

My question is, do I need to "join" the resulting objects together myself in the resolver for the people query type? E.g.

```<code>const resolvers = {
  Query: {
    people: function( parent, args, context, info ) {
      let persons = context.models.Person.getByIds( args.ids );
      let members = context.models.Member.getByIds( args.ids );
      /*
      return an array of {...person, ...member} where person.id === member.id
      */
    }
  }
}
</code>```

Or is there some way that Apollo handles this for us? Do I want something like apollo-resolvers? The docs on unions and interfaces isn't super helpful; I have __resolveType on IPerson, but the docs don't specify how the fields for each concrete type are resolved. Is there a better way to achieve this with Dataloader, or a different approach?

I think this question is related to my issue, in that I don't want to fetch data for a concrete type if the query doesn't request any of that type's fields via a fragment. There's also this issue on Github.

Many thanks!

Edit:
__resolveType looks as follows:

```<code>{
  IPerson: {
    __resolveType: function ( parent, context, info ) {
      if ( parent.memberType ) {
        return 'ClubMember';
      }
      ...etc.
    }
  }
}
</code>```

答:
This problem really isn't specific to Apollo Server or even GraphQL -- querying multiple tables and getting a single set of results, especially when you're dealing with multiple data models, is going to get tricky.

You can, of course, query each table separately and combine the results, but it's not particularly efficient. I think by far the easiest way to handle this kind of scenario is to create a view in your database, something like:

```<code>CREATE VIEW people AS
    SELECT club_members.id           AS id,
           club_members.first_name   AS first_name,
           club_members.last_name    AS last_name,
           club_members.member_type  AS member_type,
           club_members.member_since AS member_since,
           null                      AS hire_date,
           null                      AS reports_to,
           'ClubMember'              AS __typename
    FROM club_members
    UNION
    SELECT staff_members.id         AS id,
           staff_members.first_name AS first_name,
           staff_members.last_name  AS last_name,
           null                     AS member_type,
           null                     AS member_since,
           staff_members.hire_date  AS hire_date,
           staff_members.reports_to AS reports_to
           'StaffMember'            AS __typename
    FROM staff_members;
</code>```

You can also just use a single table instead, but a view allows you to keep your data in separate tables and query them together. Now you can add a data model for your view and use that to query all "people".

Note: I've added a __typename column here for convenience -- by returning a __typename, you can omit specifying your own __resolveType function -- GraphQL will assign the appropriate type at runtime for you.

Body:
For some reason I'm having a hard time figuring out how to combine resolvers for a GraphQL interface and a type that implements said interface.

Say I have the following schema:

interface IPerson {
  id: ID!
  firstName: String!
  lastName: String!
}

type ClubMember implements IPerson {
  ...IPerson fields
  memberType: String!
  memberSince: DateTime!
}

type StaffMember implements IPerson {
  ...IPerson fields
  hireDate: DateTime!
  reportsTo: StaffMember
}

extend type Query {
  people(ids: [Int!]): [IPerson]
}

A full ClubMember query with all fields, such as:

query {
  people(ids: [123456,234567,345678]) {
    id
    firstName
    lastName
    ... on ClubMember {
      memberType
      memberSince
    }
  }
}

would produce a response like the following:

[
  {
    "id": 123456,
    "firstName": "Member",
    "lastName": "McMemberface",
    "memberType": "VIP",
    "memberSince": "2019-05-28T16:05:55+00:00"
  },
  ...etc.
]

I've used makeExecutableSchema() from apollo-server with inheritResolversFromInterfaces: true, and I want to be able to make use of default resolvers for each interface/type by having the model classes backing IPerson, ClubMember, etc. return objects with only the fields relevant to each type, i.e., the model class for IPerson fetches only the fields required by IPerson, etc. That is, the response above would execute 2 SQL statements:

SELECT id, firstName, lastName FROM Contacts WHERE id IN(?);

and

SELECT contactId, memberType, memberSince FROM Members WHERE contactId IN(?);

Of course, I could get all the data in one SQL statement by doing a JOIN at the database level, but I really want to have one (and only one) way of resolving the fields required by IPerson, and let the other types augment that data with their own resolvers.

My question is, do I need to "join" the resulting objects together myself in the resolver for the people query type? E.g.

const resolvers = {
  Query: {
    people: function( parent, args, context, info ) {
      let persons = context.models.Person.getByIds( args.ids );
      let members = context.models.Member.getByIds( args.ids );
      /*
      return an array of {...person, ...member} where person.id === member.id
      */
    }
  }
}

Or is there some way that Apollo handles this for us? Do I want something like apollo-resolvers? The docs on unions and interfaces isn't super helpful; I have __resolveType on IPerson, but the docs don't specify how the fields for each concrete type are resolved. Is there a better way to achieve this with Dataloader, or a different approach?

I think this question is related to my issue, in that I don't want to fetch data for a concrete type if the query doesn't request any of that type's fields via a fragment. There's also this issue on Github.

Many thanks!

Edit:
__resolveType looks as follows:

{
  IPerson: {
    __resolveType: function ( parent, context, info ) {
      if ( parent.memberType ) {
        return 'ClubMember';
      }
      ...etc.
    }
  }
}

Body:
This problem really isn't specific to Apollo Server or even GraphQL -- querying multiple tables and getting a single set of results, especially when you're dealing with multiple data models, is going to get tricky.

You can, of course, query each table separately and combine the results, but it's not particularly efficient. I think by far the easiest way to handle this kind of scenario is to create a view in your database, something like:

CREATE VIEW people AS
    SELECT club_members.id           AS id,
           club_members.first_name   AS first_name,
           club_members.last_name    AS last_name,
           club_members.member_type  AS member_type,
           club_members.member_since AS member_since,
           null                      AS hire_date,
           null                      AS reports_to,
           'ClubMember'              AS __typename
    FROM club_members
    UNION
    SELECT staff_members.id         AS id,
           staff_members.first_name AS first_name,
           staff_members.last_name  AS last_name,
           null                     AS member_type,
           null                     AS member_since,
           staff_members.hire_date  AS hire_date,
           staff_members.reports_to AS reports_to
           'StaffMember'            AS __typename
    FROM staff_members;

You can also just use a single table instead, but a view allows you to keep your data in separate tables and query them together. Now you can add a data model for your view and use that to query all "people".

Note: I've added a __typename column here for convenience -- by returning a __typename, you can omit specifying your own __resolveType function -- GraphQL will assign the appropriate type at runtime for you.


问:
React Dropzone cancel file upload on a button click
I'm using react-dropzone to upload files to my server in my react app. Everything is working great but I want to add a feature where if a file is taking too long to upload due to its size, the user can cancel the process with the click of a button. </p>

```<code><Dropzone
  multiple={ false }
  accept={ allowedMimeTypes }
  onDrop={ this.onDrop }
  onDragEnter={ this.onDragEnter }
  onDragLeave={ this.onDragLeave }
  className={ classes.dropzone }
  maxSize={ MAX_UPLOAD_BYTES }
  >
</Dropzone>
<button onClick={ this.onCancelUpload }>Cancel</button>
</code>```

<p>Please advise, if It is possible using react-dropzone. I can't think of a way to stop the event that is already triggered and is uploading the file. </p>

答:
I was able to solve the above problem using the Axios Cancel Token.

Use Axios to handle the upload as a promise.

Create a source at the start of your code.

const CancelToken = axios.CancelToken;
let source = CancelToken.source();
```

<ol start="3">
<li>Pass on the source to the request in config.</li>
</ol>

<pre class="lang-js prettyprint-override"><code>const {
  acceptedFiles
} = this.state;

const uploaders = acceptedFiles.map((file) => {
  const formData = new FormData();
  // data must be set BEFORE sending file
  formData.append('document', file);

  const uploadConfig = {
    onUploadProgress: (progressEvent) => {
      const progressUpload = (progressEvent.loaded * 100) / progressEvent.total;
      this.setState({
        progressUpload
      });
    },
    cancelToken: source.token,
  };

  return inkerzApi.post('/uploads/file', formData, uploadConfig)
    .then(response => response.data)
    .catch(() => console.log('Upload canceled'));
});

Promise.all(uploaders).then((filesMetadata) => {
  filesMetadata.forEach((metadata) => {
    if (metadata && metadata.mediaLink && metadata.totalPages) {
      this.onNewFileUploaded(metadata);
      // show success message here
    } else if (this.state.uploadCanceled) {
      // show cancelation notification here
      this.setState({
        uploadCanceled: false
      });
    }
  });
  this.setState({
    acceptedFiles: [],
    progressUpload: 0,
  });
});
</code>```

On Cancel Button Click

onCancelUpload = () => {
        source.cancel('Operation canceled by the user.');
        source = CancelToken.source();
        this.setState({ uploadCanceled: true });
    }
```

This worked out for me. Hope this helps others as well.

Body:
I'm using react-dropzone to upload files to my server in my react app. Everything is working great but I want to add a feature where if a file is taking too long to upload due to its size, the user can cancel the process with the click of a button.

<Dropzone
  multiple={ false }
  accept={ allowedMimeTypes }
  onDrop={ this.onDrop }
  onDragEnter={ this.onDragEnter }
  onDragLeave={ this.onDragLeave }
  className={ classes.dropzone }
  maxSize={ MAX_UPLOAD_BYTES }
  >
</Dropzone>
<button onClick={ this.onCancelUpload }>Cancel</button>

Please advise, if It is possible using react-dropzone. I can't think of a way to stop the event that is already triggered and is uploading the file.

Body:
I was able to solve the above problem using the Axios Cancel Token.

Use Axios to handle the upload as a promise.

Create a source at the start of your code.

const CancelToken = axios.CancelToken;
let source = CancelToken.source();

Pass on the source to the request in config.

const {
  acceptedFiles
} = this.state;

const uploaders = acceptedFiles.map((file) => {
  const formData = new FormData();
  // data must be set BEFORE sending file
  formData.append('document', file);

  const uploadConfig = {
    onUploadProgress: (progressEvent) => {
      const progressUpload = (progressEvent.loaded * 100) / progressEvent.total;
      this.setState({
        progressUpload
      });
    },
    cancelToken: source.token,
  };

  return inkerzApi.post('/uploads/file', formData, uploadConfig)
    .then(response => response.data)
    .catch(() => console.log('Upload canceled'));
});

Promise.all(uploaders).then((filesMetadata) => {
  filesMetadata.forEach((metadata) => {
    if (metadata && metadata.mediaLink && metadata.totalPages) {
      this.onNewFileUploaded(metadata);
      // show success message here
    } else if (this.state.uploadCanceled) {
      // show cancelation notification here
      this.setState({
        uploadCanceled: false
      });
    }
  });
  this.setState({
    acceptedFiles: [],
    progressUpload: 0,
  });
});

On Cancel Button Click

onCancelUpload = () => {
        source.cancel('Operation canceled by the user.');
        source = CancelToken.source();
        this.setState({ uploadCanceled: true });
    }

This worked out for me. Hope this helps others as well.


问:
vs2010 freezes on validating web site forever
I converted from VS2008 to VS2010.
when I build the solution it gets frozen on validating web site, and it was frozen for a few minutes on a dll build.

it won't complete!

what can be the problem?

thanks

答:
The validating step does a number of things.  It checks your web.config file to make sure it is correct and then checks the .aspx files to make sure they are properly written.  I would check the web.config file since this is a likely choice for errors during the conversion.

Also you can get a dump of the debug info by following the directions here:

http://blogs.msdn.com/b/mikhailarkhipov/archive/2007/09/19/how-to-obtain-debug-information-from-a-hung-frozen-application.aspx

this could help you find out whats wrong


问:
Key Shortcut for Eclipse Imports
It's been a while since I last used Eclipse.  I used to love this handy key shortcut that added all the imports to the top of the source file, but I've forgotten it.  Does anyone know what this shortcut is?</p>

答: For static import select the field and press Ctrl+Shift+M</p>

Title: Key Shortcut for Eclipse Imports


问:
Python. How to call a function that expect ctypes array. Strand/Straus7
I'm using python scripting for Strand/Straus7 importing his DLL.

I'm trying to call a function for set the units, called St7SetUnits, following the manual (Img.1) and watching the .py scripting of the DLL that I imported (Img.2). The function expected a c_long and a ctypes.POINTER.(c_long), as specify in the script (Img.3)

Here the complete manual  strand7.com/downloads/Strand7%20R246%20API%20Manual%20TOC.pdf

and here the .py scripting https://www.dropbox.com/s/88plz2funjqy1vb/St7API.py?dl=0

As specify at the beginning of the manual I have to convert the list in ctypes array (Img.4).
The function I call is the same of the example, but I can't call it correctly.
I write

```<code>import St7API as SA
import ctypes

SA.St7Init()

unitsArray = ctypes.c_int * SA.kLastUnit
units = unitsArray()
units[0] = 0
units[1] = 1
units[2] = 3
units[3] = 1
units[4] = 1
units[5] = 2
SA.St7SetUnits(1, units)
</code>```

But returns error

```<code>expected c_long, got c_long_Array_6
</code>```

If I try something else, for example an int from the array

```<code>SA.St7SetUnits(1, units[0])
</code>```

the error change in

```<code> expected LP_c_long, got int
</code>```

I tried many solution, but no one works.

Can anyone help me?

Thanks a lot

答:
From your screenshots it looks like you might be using Grasshopper. If so, you might need to explicitly cast the units array to a pointer by adding this line to the top of your script:

```<code>PI = ctypes.POINTER(ctypes.c_long)
</code>```

And do this whenever you pass an array from IronPython to St7API:

```<code>SA.St7SetUnits(1, PI(units))
</code>```

This answer has slightly more.

Body:
I'm using python scripting for Strand/Straus7 importing his DLL.

I'm trying to call a function for set the units, called St7SetUnits, following the manual (Img.1) and watching the .py scripting of the DLL that I imported (Img.2). The function expected a c_long and a ctypes.POINTER.(c_long), as specify in the script (Img.3)

Here the complete manual  strand7.com/downloads/Strand7%20R246%20API%20Manual%20TOC.pdf

and here the .py scripting https://www.dropbox.com/s/88plz2funjqy1vb/St7API.py?dl=0

As specify at the beginning of the manual I have to convert the list in ctypes array (Img.4).
The function I call is the same of the example, but I can't call it correctly.
I write

import St7API as SA
import ctypes

SA.St7Init()

unitsArray = ctypes.c_int * SA.kLastUnit
units = unitsArray()
units[0] = 0
units[1] = 1
units[2] = 3
units[3] = 1
units[4] = 1
units[5] = 2
SA.St7SetUnits(1, units)

But returns error

expected c_long, got c_long_Array_6

If I try something else, for example an int from the array

SA.St7SetUnits(1, units[0])

the error change in

 expected LP_c_long, got int

I tried many solution, but no one works.

Can anyone help me?

Thanks a lot

Body:
From your screenshots it looks like you might be using Grasshopper. If so, you might need to explicitly cast the units array to a pointer by adding this line to the top of your script:

PI = ctypes.POINTER(ctypes.c_long)

And do this whenever you pass an array from IronPython to St7API:

SA.St7SetUnits(1, PI(units))

This answer has slightly more.


问:
Wordpress returning HTML symbol codes in GraphQL query in Gatsby website
First, I'm not sure if this is a Wordpress issue, a Gatsby issue, or a GraphQL issue (or something else).

I'm building a Gatsby site using gatsby-source-wordpress to pull content from a self-hosted wordpress site.

I'm building a homepage that queries for the most recent posts and displays the titles along with some other info. If the title has a special character(-, &, etc.) then it returns the HTML code for that character in the title ('&' instead of '&' for instance). Then it gets displayed as the code, which just looks bad. See below for some of my code.

What are my options in terms of getting it to return without the HTML codes or for converting them back to the symbols?

This is the relevant part of the query

```<code>export const homepageQuery = graphql`
query homepageQuery {
    mainSection: allWordpressPost(limit: 3) {
      edges {
        node {
          id
          title
          date (formatString: "MMM DD, YYYY")
          featured_media {
            source_url
            alt_text
          }
          slug
          categories {
            id
            name
            link
          }
        }
      }
    }
}
</code>```

This is and example of a single post returned

```<code>{
  "data": {
    "mainSection": {
      "edges": [
        {
      "node": {
        "id": "d1e9b5e0-bb8a-5e73-a89a-ba73aae92e0d",
        "title": "Stories from the Bus Station Bistro & Creamery",
        "date": "Jul 15, 2018",
        "featured_media": {
          "source_url": "https://www.storynosh.com/wp-content/uploads/2018/07/IMG_9962_3.jpg",
          "alt_text": ""
        },
        "slug": "stories-bus-station-bistro-creamery",
        "categories": [
          {
            "id": "3bceb083-de92-5eff-90f3-e2da524f3c2a",
            "name": "Stories",
            "link": "https://www.storynosh.com/category/stories/"
          }
        ]
      }
    }
</code>```

This is the component the data ultimately is passed to which renders the data.

```<code>class MostRecent extends Component {
    render(){
        const bgimage = `url(${this.props.data.featured_media.source_url})`;

        return (
            <div className={`${styles.featured} ${styles['most-recent']}`} style={{backgroundImage: bgimage}} >
                <div className={styles['article-info-container']} >
                    <h1 className={styles['featured-header']} >{this.props.data.title}</h1>
                    <div>
                        <Link to={this.props.data.categories[0].link} className={styles['category-box-link']}>
                            <span className={styles['category-box']}>{this.props.data.categories[0].name}</span>
                        </Link>
                        <span className={styles['featured-date']}>{this.props.data.date}</span>
                    </div>
                </div>
            </div>
        )
    }
}
</code>```

What the result looks like

答:
Using dangerouslySetInnerHTML solved this issue for me:

Replace:
{this.props.data.title}

With:

Body:
First, I'm not sure if this is a Wordpress issue, a Gatsby issue, or a GraphQL issue (or something else).

I'm building a Gatsby site using gatsby-source-wordpress to pull content from a self-hosted wordpress site.

I'm building a homepage that queries for the most recent posts and displays the titles along with some other info. If the title has a special character(-, &, etc.) then it returns the HTML code for that character in the title ('&' instead of '&' for instance). Then it gets displayed as the code, which just looks bad. See below for some of my code.

What are my options in terms of getting it to return without the HTML codes or for converting them back to the symbols?

This is the relevant part of the query

export const homepageQuery = graphql`
query homepageQuery {
    mainSection: allWordpressPost(limit: 3) {
      edges {
        node {
          id
          title
          date (formatString: "MMM DD, YYYY")
          featured_media {
            source_url
            alt_text
          }
          slug
          categories {
            id
            name
            link
          }
        }
      }
    }
}

This is and example of a single post returned

{
  "data": {
    "mainSection": {
      "edges": [
        {
      "node": {
        "id": "d1e9b5e0-bb8a-5e73-a89a-ba73aae92e0d",
        "title": "Stories from the Bus Station Bistro & Creamery",
        "date": "Jul 15, 2018",
        "featured_media": {
          "source_url": "https://www.storynosh.com/wp-content/uploads/2018/07/IMG_9962_3.jpg",
          "alt_text": ""
        },
        "slug": "stories-bus-station-bistro-creamery",
        "categories": [
          {
            "id": "3bceb083-de92-5eff-90f3-e2da524f3c2a",
            "name": "Stories",
            "link": "https://www.storynosh.com/category/stories/"
          }
        ]
      }
    }

This is the component the data ultimately is passed to which renders the data.

class MostRecent extends Component {
    render(){
        const bgimage = `url(${this.props.data.featured_media.source_url})`;

        return (
            <div className={`${styles.featured} ${styles['most-recent']}`} style={{backgroundImage: bgimage}} >

{this.props.data.title}

                        <Link to={this.props.data.categories[0].link} className={styles['category-box-link']}>
                            {this.props.data.categories[0].name}
                        </Link>
                        {this.props.data.date}

        )
    }
}

What the result looks like

Body:
Using dangerouslySetInnerHTML solved this issue for me:

Replace: <h1>{this.props.data.title}</h1>

With: <h1 dangerouslySetInnerHTML={{ __html: this.props.data.title }} />