问:
given a unit test that make sure that prevent wrong-assigned values in a class argument, how to write a method that takes that into account?
I'm introduced recently to Test Driven Development. However, I am having a hard time understanding it.  The following unit test is a given:

```<code>public void Setup()
{
    invoicePosition = new InvoicePosition{
        Customer = new Customer(),
        ItemIdentifier = 0,
        ItemName = "SpringRoll",
        Orders = 2,
        SingleUnitPrice = 3.50m
    };

    pairs = new KeywordPair[]{
        new KeywordPair(new Keyword("ItemNumber"),invoicePosition.ItemIdentifier.ToString()),
        new KeywordPair(new Keyword("ItemName"), invoicePosition.ItemName),
        new KeywordPair(new Keyword("CustomerName"), invoicePosition.Customer.Name),
        new KeywordPair(new Keyword("AmountOrdered"), invoicePosition.Orders.ToString()),
        new KeywordPair(new Keyword("NetPrice"), invoicePosition.SingleUnitPrice.ToString())
    };
}

[Test]
public void Invoice_CreateOrderOrderedInput_Valid(){
    var invoice = InvoicePosition.CreateFromPairs(pairs);
    Assert.AreEqual(invoicePosition.ItemIdentifier, invoice.ItemIdentifier);
    Assert.AreEqual(invoicePosition.ItemName.GetType(), invoice.ItemName.GetType());
    Assert.AreEqual(invoicePosition.Customer.Name, invoice.Customer.Name);
    Assert.AreEqual(invoicePosition.Orders, invoice.Orders);
    Assert.AreEqual(invoicePosition.SingleUnitPrice, invoice.SingleUnitPrice);
}
</code>```

Please note that Keyword and Keyword structs are as follows:

```<code>public struct Keyword
{
        private string keyword;
        private KeywordTypes type;

        public Keyword(string keyword, KeywordTypes Type = KeywordTypes.String){
            this.keyword = keyword;
            this.type = Type;
}

public struct KeywordPair
{
        public Keyword Key;
        public string Value;

        public KeywordPair(Keyword key, string value)
        {
            this.Key = key;
            this.Value = value;
        }
}
</code>```

now I have written the following project for the previous unit test:
namespace SimpleShop

```<code>    public class InvoicePosition
    {
        public uint ItemIdentifier = 0;
        public string ItemName = "";
        public uint Orders = 0;
        public decimal SingleUnitPrice = 0.0m;
        public Customer Customer;
        public KeywordPair[] Pairs = new KeywordPair[0];

        public static InvoicePosition CreateFromPairs(KeywordPair[] pairs)
        {
            var invoice = new InvoicePosition();
            invoice.Pairs = pairs;
            return invoice;
        }
    }
</code>```

I need to write code that accounts for wrong serializations. for example, what if pairs is introduced to the program as follows:

```<code>pairs[3] = new KeywordPair(new Keyword("AmountOrdered"), "+%&/" + invoicePosition.Orders.ToString());
pairs[4] = new KeywordPair(new Keyword("NetPrice"), invoicePosition.SingleUnitPrice.ToString() +
"%&öä/");
</code>```

thank you, any help would be great.

答:
Given the test Invoice_CreateOrderOrderedInput_Valid, the InvoicePosition suggested in the OP does not pass the test. By using Visual Studio's various refactoring tools, something like this is the simplest thing that could possibly work:

```<code>public class InvoicePosition
{
    public Customer Customer { get; set; }
    public int ItemIdentifier { get; set; }
    public string ItemName { get; set; }
    public int Orders { get; set; }
    public decimal SingleUnitPrice { get; set; }

    public static InvoicePosition CreateFromPairs(KeywordPair[] pairs)
    {
        return new InvoicePosition
        {
            ItemName = "",
            Customer = new Customer(),
            Orders = 2,
            SingleUnitPrice = 3.5m
        };
    }
}
</code>```

The CreateFromPairs implementation is clearly not the full or correct implementation, but it passes all tests. The challenge with TDD is to figure out which test to write next.

TDD works best if you can move forward in as small steps as possible. You might want to consider the Transformation Priority Premise. Which part of the incorrect implementation would you first like to address?

Perhaps you're unhappy that ItemName is hard-coded to the empty string. How can you write a new test that encourages you to make the implementation more general?

I'd write another test that keeps everything from the first test constant, except the ItemName value.

The way the test is currently structured, with its big Setup method, makes that inconvenient. I recommend that you look into writing parametrised tests instead.

Body:
I'm introduced recently to Test Driven Development. However, I am having a hard time understanding it.  The following unit test is a given:

public void Setup()
{
    invoicePosition = new InvoicePosition{
        Customer = new Customer(),
        ItemIdentifier = 0,
        ItemName = "SpringRoll",
        Orders = 2,
        SingleUnitPrice = 3.50m
    };

    pairs = new KeywordPair[]{
        new KeywordPair(new Keyword("ItemNumber"),invoicePosition.ItemIdentifier.ToString()),
        new KeywordPair(new Keyword("ItemName"), invoicePosition.ItemName),
        new KeywordPair(new Keyword("CustomerName"), invoicePosition.Customer.Name),
        new KeywordPair(new Keyword("AmountOrdered"), invoicePosition.Orders.ToString()),
        new KeywordPair(new Keyword("NetPrice"), invoicePosition.SingleUnitPrice.ToString())
    };
}

[Test]
public void Invoice_CreateOrderOrderedInput_Valid(){
    var invoice = InvoicePosition.CreateFromPairs(pairs);
    Assert.AreEqual(invoicePosition.ItemIdentifier, invoice.ItemIdentifier);
    Assert.AreEqual(invoicePosition.ItemName.GetType(), invoice.ItemName.GetType());
    Assert.AreEqual(invoicePosition.Customer.Name, invoice.Customer.Name);
    Assert.AreEqual(invoicePosition.Orders, invoice.Orders);
    Assert.AreEqual(invoicePosition.SingleUnitPrice, invoice.SingleUnitPrice);
}

Please note that Keyword and Keyword structs are as follows:

public struct Keyword
{
        private string keyword;
        private KeywordTypes type;

        public Keyword(string keyword, KeywordTypes Type = KeywordTypes.String){
            this.keyword = keyword;
            this.type = Type;
}

public struct KeywordPair
{
        public Keyword Key;
        public string Value;

        public KeywordPair(Keyword key, string value)
        {
            this.Key = key;
            this.Value = value;
        }
}

now I have written the following project for the previous unit test:
namespace SimpleShop

    public class InvoicePosition
    {
        public uint ItemIdentifier = 0;
        public string ItemName = "";
        public uint Orders = 0;
        public decimal SingleUnitPrice = 0.0m;
        public Customer Customer;
        public KeywordPair[] Pairs = new KeywordPair[0];

        public static InvoicePosition CreateFromPairs(KeywordPair[] pairs)
        {
            var invoice = new InvoicePosition();
            invoice.Pairs = pairs;
            return invoice;
        }
    }

I need to write code that accounts for wrong serializations. for example, what if pairs is introduced to the program as follows:

pairs[3] = new KeywordPair(new Keyword("AmountOrdered"), "+%&/" + invoicePosition.Orders.ToString());
pairs[4] = new KeywordPair(new Keyword("NetPrice"), invoicePosition.SingleUnitPrice.ToString() +
"%&öä/");

thank you, any help would be great.

Body:
Given the test Invoice_CreateOrderOrderedInput_Valid, the InvoicePosition suggested in the OP does not pass the test. By using Visual Studio's various refactoring tools, something like this is the simplest thing that could possibly work:

public class InvoicePosition
{
    public Customer Customer { get; set; }
    public int ItemIdentifier { get; set; }
    public string ItemName { get; set; }
    public int Orders { get; set; }
    public decimal SingleUnitPrice { get; set; }

    public static InvoicePosition CreateFromPairs(KeywordPair[] pairs)
    {
        return new InvoicePosition
        {
            ItemName = "",
            Customer = new Customer(),
            Orders = 2,
            SingleUnitPrice = 3.5m
        };
    }
}

The CreateFromPairs implementation is clearly not the full or correct implementation, but it passes all tests. The challenge with TDD is to figure out which test to write next.

TDD works best if you can move forward in as small steps as possible. You might want to consider the Transformation Priority Premise. Which part of the incorrect implementation would you first like to address?

Perhaps you're unhappy that ItemName is hard-coded to the empty string. How can you write a new test that encourages you to make the implementation more general?

I'd write another test that keeps everything from the first test constant, except the ItemName value.

The way the test is currently structured, with its big Setup method, makes that inconvenient. I recommend that you look into writing parametrised tests instead.


来源: stackexchange

问:
Getting "undefined method `model_name' for NilClass:Class" in Rails 3, jQuery, Ajax
When a radio button is checked, the whole form is submitted. The answers_controller (below) does update the result, so everything works, but i get the aforementioned error in the console. I realize that in my update_result.js.erb (below) nothing is assigned to the @answers variable but i have been unable to make adjustments to it for the way i am passing the values.

answers_controller:

```<code>  def update_result
    params[:answer].each_pair do |key,value|
      @ans = Answer.find(key.to_i)
      @ans.update_attributes(:score => value)
    end
  end
</code>```

update_result.js.erb:

```<code>$("#answers").html("<%=escape_javascript(render(@answers)) %>");
</code>```

Thanks!

答:
Change the action like this:

```<code>def update_result
  @answers = []

  params[:answer].each_pair do |key,value|
    ans = Answer.find(key.to_i)
    ans.update_attributes(:score => value)
    @answers << ans
  end
end
</code>```

Change the update_result.js.erb like this:

```<code>$("#answers").html("#{escape_javascript(render(@answers))}");
</code>```

ContentLicense: CC BY-SA 3.0

Body:
When a radio button is checked, the whole form is submitted. The answers_controller (below) does update the result, so everything works, but i get the aforementioned error in the console. I realize that in my update_result.js.erb (below) nothing is assigned to the @answers variable but i have been unable to make adjustments to it for the way i am passing the values.

answers_controller:

  def update_result
    params[:answer].each_pair do |key,value|
      @ans = Answer.find(key.to_i)
      @ans.update_attributes(:score => value)
    end
  end

update_result.js.erb:

$("#answers").html("<%=escape_javascript(render(@answers)) %>");

Thanks!

Body:
Change the action like this:

def update_result
  @answers = []

  params[:answer].each_pair do |key,value|
    ans = Answer.find(key.to_i)
    ans.update_attributes(:score => value)
    @answers << ans
  end
end

Change the update_result.js.erb like this:

$("#answers").html("#{escape_javascript(render(@answers))}");


问:
'System.__ComObject' does not contain a definition for .WithComCleanup()
Since upgrading a project from VS2010 to VS2012 I'm getting the error:

'System.__ComObject' does not contain a definition for
  .WithComCleanup())

When running this command line of code:

```<code>using (var cell = usedRange.Resource.Find(reservedWord, LookIn: XlFindLookIn.xlFormulas, After: usedRange.Resource.Cells[usedRange.Resource.Rows.Count, usedRange.Resource.Columns.Count]).WithComCleanup())
</code>```

答:
I solved the problem by turning Embed Interop Types to False for the reference DLL Microsoft.Office.Interop.Excel, but I get message:

```<code>System.IO.FileNotFoundException: "Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. Не удается найти указанный файл."
</code>```

Body:
Since upgrading a project from VS2010 to VS2012 I'm getting the error:

'System.__ComObject' does not contain a definition for
  .WithComCleanup())

When running this command line of code:

using (var cell = usedRange.Resource.Find(reservedWord, LookIn: XlFindLookIn.xlFormulas, After: usedRange.Resource.Cells[usedRange.Resource.Rows.Count, usedRange.Resource.Columns.Count]).WithComCleanup())

Body:
I solved the problem by turning Embed Interop Types to False for the reference DLL Microsoft.Office.Interop.Excel, but I get message:

System.IO.FileNotFoundException: "Could not load file or assembly 'office, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c'. Не удается найти указанный файл."

ContentLicense: CC BY-SA 4.0


问:
How to create custom shadow for view?
I wanna to create custom shadow for view which i customize as like as my plan.

Custom Shadow looks like Card View elevation.

I need this type of shadow

答:
Hm. This one is extremely simple and producing very similar (imo) result to what you requested. Obviously params like elevation, corner radius etc can/should be tweaked.

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <androidx.cardview.widget.CardView
        android:id="@+id/textview_first"
        android:layout_width="300dp"
        android:layout_height="100dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Title: How to create custom shadow for view?

Body:
Hm. This one is extremely simple and producing very similar (imo) result to what you requested. Obviously params like elevation, corner radius etc can/should be tweaked.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:padding="16dp"
    android:layout_height="match_parent"
    tools:context=".FirstFragment">

    <androidx.cardview.widget.CardView
        android:id="@+id/textview_first"
        android:layout_width="300dp"
        android:layout_height="100dp"
        app:cardCornerRadius="20dp"
        app:cardElevation="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>


问:
Mocha --watch fails on second run with "addEventListener is not a function"
I have a typescript project that I test with mocha. For convenience I use the --watch flag. When I start mocha, my tests succeed, but after touching a file and triggering mocha to re-run, I receive an exception:

```<code>TypeError: _a.addEventListener is not a function
</code>```

I created a small repository to reproduce the problem. Any ideas?

答: The solution was to use the sandbox for all stubs to have a clean state for every test.

Body:
I have a typescript project that I test with mocha. For convenience I use the --watch flag. When I start mocha, my tests succeed, but after touching a file and triggering mocha to re-run, I receive an exception:

TypeError: _a.addEventListener is not a function

I created a small repository to reproduce the problem. Any ideas?


问:
Localization in Standard Module
I'm coding a web application in Abp Framework in italian language.

Is it possible to override the localization string in the standard module of ABP Framework like Account and Identity?

Thanks.
Danilo

答:
You should extend existing resources. For example, if you want to extend TenantManagementResource, you can extend it like below in your module.cs file. And in your localization file you should redefine the same localization keys which you want to override.

```<code>ConfigureServices(ServiceConfigurationContext context)
    {
        ...
        ...
        Configure<AbpLocalizationOptions>(options =>
        {
            ...
            ...
            options.Resources
                .Get<AbpTenantManagementResource>()
                .AddVirtualJson("/Localization/YourTenantManagementResource");
        });
</code>```

Title: Localization in Standard Module

Body:
You should extend existing resources. For example, if you want to extend TenantManagementResource, you can extend it like below in your module.cs file. And in your localization file you should redefine the same localization keys which you want to override.

ConfigureServices(ServiceConfigurationContext context)
    {
        ...
        ...
        Configure<AbpLocalizationOptions>(options =>
        {
            ...
            ...
            options.Resources
                .Get<AbpTenantManagementResource>()
                .AddVirtualJson("/Localization/YourTenantManagementResource");
        });


问:
How to render with conditions in React
Having this classic render method:

```<code>render() {
  ...
  return (
    <div> ... </div>
  );
}
</code>```

my question is how can it be returned something different based on a condition?

For example, in my case it is a value on the state: this.state.value - if this value is true - return something, if it is false - return something else.

I've tried several ways but didn't find a working solution.

Ternary inside return:

```<code>render() {
  ...
  return (
    {this.state.value ?
       <div> something </div>
     : <div> something else </div>
    }
  );
}
</code>```

this one says: Parsing error: Unexpected keyword 'this'

if-else

```<code>render() {
  ...
  return (
    {
      if(this.state.value) {
       <div> something </div>
      } else {
        <div> something else </div>
      }
    }
  );
}
</code>```

it has the same error as above.

When I've tried to make an if-else statement with return ( ... ); for both if and else it says:  Unnecessary 'else' after 'return'  no-else-return

How can it return something different based on the value of this.state.value?

答:
You do not need to wrap ternary conditions within {} The following will work

```<code>render() {
  ...
  return this.state.value ?
       <div> something </div>
     : <div> something else </div>
  );
}
</code>```

Title: How to render with conditions in React

Body:
Having this classic render method:

render() {
  ...
  return (

 ...

  );
}

my question is how can it be returned something different based on a condition?

For example, in my case it is a value on the state: this.state.value - if this value is true - return something, if it is false - return something else.

I've tried several ways but didn't find a working solution.

Ternary inside return:

render() {
  ...
  return (
    {this.state.value ?

 something

     :
 something else

    }
  );
}

this one says: Parsing error: Unexpected keyword 'this'

if-else

render() {
  ...
  return (
    {
      if(this.state.value) {

 something

      } else {

 something else

      }
    }
  );
}

it has the same error as above.

When I've tried to make an if-else statement with return ( ... ); for both if and else it says:  Unnecessary 'else' after 'return'  no-else-return

How can it return something different based on the value of this.state.value?

Body:
You do not need to wrap ternary conditions within {} The following will work

render() {
  ...
  return this.state.value ?
       <div> something </div>
     : <div> something else </div>
  );
}


问:
Mockstrutstestcase testing Struts 1.2 App
I am using strutstestcase for testing my web application on struts 1.2.
When test runs and control goes to my action the request.getSession(false), i called in my action, returns null.

could Anyone one help me what i am missing ?

答: The problem was at my end. I am calling request.getSession(false) which returns null if session is not exist. request.getSession() gives me session and code works.


问:
How to determine probability of 0 to N events occurring given probability of each of those N events?
First time posting here, so if I make a mistake with something let me know and I'd be more than happy to fix it!

Given N events, each of which have an individual probability (from 0 to 100%) of occurring, I'd like to determine the probability of 0 to N of those events occurring together.

For example, if I have event 1, 2, 3,...,N and 5 (E1, E2, E3...,EN) where the individual probability of a specific event occurring is as follows:

E1 = 30% probability of occurring

E2 = 40% probability of occurring

E3 = 50% probability of occurring

...

EN = x% probability of occurring

I'd like to know the probability of having:

none of these events occurring

any 1 of these events occurring

any 2 of these events occurring

any 3 of these events occurring

...

all N of these events occurring

I understand that having 0 events occurring is (1-E1)(1-E2)...(1-EN) and that having all N events occurring is E1*E2*...*E3. However, I do not know how to calculate the other possibilities (1 to N-1 events occurring).

I have been looking for some recursive algorithm (binomial compound distribution) that could solve this but I have not found any explicit formula that does this. Wondering if any of you guys could help!

Thanks in advance!

EDIT: The events are indeed independent.

答:
None of these answers seemed to worked/was understandable for me so I computed it and made it myself in python:

def combin(n, k):
   if k > n//2:
       k = n-k
   x = 1
   y = 1
   i = n-k+1
   while i <= n:
       x = (x*i)//y
       y += 1
       i += 1
   return x

# proba being the probability of each of the N evenments, each being different from one another.

for i in range(N,0,-1):
    print(i)
    if sums[i]> 0:
        continue
    print(combin(N,i))
    for j in itertools.combinations(proba, i):
        sums[i]+=np.prod(j)
for i in range(N,0,-1):
    for j in range(i+1,N+1):
        icomb = combin(j,i)
        sums[str(i)] -= icomb*sums[str(j)]
```

the math is not super simple:

Let $C_{w_n}$ be the set of all unordered sets $(i,j,k...n)$

where $i,j,k...n\in w$

$Co(i,proba) = sum{C_{w_i}} - sum_{u from i+1..n}{(u \choose i) sum{C_{w_u}}}$*

$Co(i, P)$ being the probability of i events occuring given $P = {p_i...p_n}$, the bernouilli probability of each event.

Body:
None of these answers seemed to worked/was understandable for me so I computed it and made it myself in python:

def combin(n, k):
   if k > n//2:
       k = n-k
   x = 1
   y = 1
   i = n-k+1
   while i <= n:
       x = (x*i)//y
       y += 1
       i += 1
   return x

# proba being the probability of each of the N evenments, each being different from one another.

for i in range(N,0,-1):
    print(i)
    if sums[i]> 0:
        continue
    print(combin(N,i))
    for j in itertools.combinations(proba, i):
        sums[i]+=np.prod(j)
for i in range(N,0,-1):
    for j in range(i+1,N+1):
        icomb = combin(j,i)
        sums[str(i)] -= icomb*sums[str(j)]

the math is not super simple:

Let $C_{w_n}$ be the set of all unordered sets $(i,j,k...n)$

where $i,j,k...n\in w$

$Co(i,proba) = sum{C_{w_i}} - sum_{u from i+1..n}{(u \choose i) sum{C_{w_u}}}$*

$Co(i, P)$ being the probability of i events occuring given $P = {p_i...p_n}$, the bernouilli probability of each event.


问:
C++ random uniform_int_distribution return same values in all threads
I have the following code, I need to have a random number in given interval. Seems to work how I need.

```<code>   std::default_random_engine eng;
     std::uniform_int_distribution<int> dist(3, 7);
     int timeout = dist(eng);
</code>```

But then I run it in different threads and repeated in the loop.

```<code>    std::default_random_engine defRandEng(std::this_thread::get_id());
    std::uniform_int_distribution<int> dist(3, 7);
    int timeout; // if I put timeout = dist(defRandEng); here it's all the same

    while (true)
    {
        timeout = dist(defRandEng);
        std::cout<<"Thread "<<std::this_thread::get_id()<<" timeout = "<<timeout<<std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(timeout));
}
</code>```

But for every iteration in all threads the values are the same

```<code>Thread 139779167999744 timeout = 6
Thread 139779134428928 timeout = 6
Thread 139779067287296 timeout = 6
Thread 139779117643520 timeout = 6
Thread 139779100858112 timeout = 6
Thread 139779084072704 timeout = 6
Thread 139779151214336 timeout = 6
Thread 139779050501888 timeout = 6
Thread 139779033716480 timeout = 6
</code>```

next interation

```<code>Thread 139779167999744 timeout = 4
Thread 139779151214336 timeout = 4
Thread 139779134428928 timeout = 4
Thread 139779117643520 timeout = 4
Thread 139779100858112 timeout = 4
Thread 139779084072704 timeout = 4
Thread 139779067287296 timeout = 4
Thread 139779050501888 timeout = 4
Thread 139779033716480 timeout = 4
</code>```

答:
You need to provide a seed based on some naturally random value to your random engine. The below example, that was adopted from your code snippets, works fine with 3 threads:

```<code>std::mutex lock;

void sample_time_out()
{
   std::stringstream ss;
   ss << std::this_thread::get_id();
   uint64_t thread_id = std::stoull(ss.str());

   std::default_random_engine eng(thread_id);
   std::uniform_int_distribution<int> dis(3, 7);

   for (int i = 0; i < 3; i++)
   {
      auto timeout = dis(eng);

      std::this_thread::sleep_for(std::chrono::seconds(timeout));
      {
         std::unique_lock<std::mutex> lock1(lock);
         std::cout << "Thread " << std::this_thread::get_id() << " timeout = " << timeout << std::endl;
      }
   }
}

int main()
{
   std::thread t1(sample_time_out);
   std::thread t2(sample_time_out);
   std::thread t3(sample_time_out);

   t1.join();
   t2.join();
   t3.join();

   return 0;
}
</code>```

And the output of my first run is:

```<code>Thread 31420 timeout = 3
Thread 18616 timeout = 6
Thread 31556 timeout = 7
Thread 31420 timeout = 4
Thread 18616 timeout = 7
Thread 31420 timeout = 6
Thread 31556 timeout = 7
Thread 18616 timeout = 4
Thread 31556 timeout = 7
</code>```

Body:
I have the following code, I need to have a random number in given interval. Seems to work how I need.

   std::default_random_engine eng;
     std::uniform_int_distribution<int> dist(3, 7);
     int timeout = dist(eng);

But then I run it in different threads and repeated in the loop.

    std::default_random_engine defRandEng(std::this_thread::get_id());
    std::uniform_int_distribution<int> dist(3, 7);
    int timeout; // if I put timeout = dist(defRandEng); here it's all the same

    while (true)
    {
        timeout = dist(defRandEng);
        std::cout<<"Thread "<<std::this_thread::get_id()<<" timeout = "<<timeout<<std::endl;
        std::this_thread::sleep_for(std::chrono::seconds(timeout));
}

But for every iteration in all threads the values are the same

Thread 139779167999744 timeout = 6
Thread 139779134428928 timeout = 6
Thread 139779067287296 timeout = 6
Thread 139779117643520 timeout = 6
Thread 139779100858112 timeout = 6
Thread 139779084072704 timeout = 6
Thread 139779151214336 timeout = 6
Thread 139779050501888 timeout = 6
Thread 139779033716480 timeout = 6

next interation

Thread 139779167999744 timeout = 4
Thread 139779151214336 timeout = 4
Thread 139779134428928 timeout = 4
Thread 139779117643520 timeout = 4
Thread 139779100858112 timeout = 4
Thread 139779084072704 timeout = 4
Thread 139779067287296 timeout = 4
Thread 139779050501888 timeout = 4
Thread 139779033716480 timeout = 4

Body:
You need to provide a seed based on some naturally random value to your random engine. The below example, that was adopted from your code snippets, works fine with 3 threads:

std::mutex lock;

void sample_time_out()
{
   std::stringstream ss;
   ss << std::this_thread::get_id();
   uint64_t thread_id = std::stoull(ss.str());

   std::default_random_engine eng(thread_id);
   std::uniform_int_distribution<int> dis(3, 7);

   for (int i = 0; i < 3; i++)
   {
      auto timeout = dis(eng);

      std::this_thread::sleep_for(std::chrono::seconds(timeout));
      {
         std::unique_lock<std::mutex> lock1(lock);
         std::cout << "Thread " << std::this_thread::get_id() << " timeout = " << timeout << std::endl;
      }
   }
}

int main()
{
   std::thread t1(sample_time_out);
   std::thread t2(sample_time_out);
   std::thread t3(sample_time_out);

   t1.join();
   t2.join();
   t3.join();

   return 0;
}

And the output of my first run is:

Thread 31420 timeout = 3
Thread 18616 timeout = 6
Thread 31556 timeout = 7
Thread 31420 timeout = 4
Thread 18616 timeout = 7
Thread 31420 timeout = 6
Thread 31556 timeout = 7
Thread 18616 timeout = 4
Thread 31556 timeout = 7


问:
Storing $award_id in a cookie - PHP
I have created a MYBB forum wadakela.xyz. I have added newPoints Awards System in it. Which is integrated with CoinPayments for user to buy it.

img: https://i.imgur.com/sI7Edly.png

Now, for example I have 5 awards and user buys 3rd one. I have scripted files which send an email and PM to me notifying that "this" user has purchased an award with ''this award ID'' when the user gets on success (callback from coinpayment) page.

imgs: https://imgur.com/a/fzR1qQl

Initially, when it was not integrated with coinpayments, I used POST method to get the award ID from the form when someone clicks BUY button through awards page which actually was working fine. I could get the proper id using this code.

```<code>//awards page
<input type="hidden" name="award" value="{$award['aid']}">

//success page
$award_id = $_POST['award'];
</code>```

Now that it is integrated with CoinPayments, it's not going to the success.php directly so POST method isn't working. If I'm not wrong, I can get the award id in the success.php via cookies (or sessions maybe?). But, I'm failing to store award ID in a cookie.

As we know, it's now like this:

-awards page -> coinpayments site -> success page.

To get award ID from awards page to success page, I tried the following code to store award ID into the cookie:

```<code>//in awards page
setcookie("award",$award['aid'], time()+300);

//in the form
<input type="hidden" name="award" value="{$award['aid']}">

....processing with coinpayments....

//in success (callback) page
$award_id = $_COOKIE["award"];

echo $award_id;  //pm + email actually.

setcookie("award",$award_id, time()-60);
</code>```

in success page, $award_id Always returns "5". Maybe because there are 5 awards listed?

Other than this, the whole process is very smooth and working as intended. What I want to do is to store proper award ID in the cookie.

I'd appreciate if one could help me with this. And if there's any alternate to achieve this, I'd like to know about it as well.

And also, I really need to get it done by today..

If you need more information, please let me know.

Thank you. :)

答:
Success URL doesn't work as IPN. Instead, IPN is required to return POST data.

```<code><input type="hidden" name="ipn_url" value="https://wadakela.xyz/YOURIPNFILE.php">
<input type="hidden" name="ipn_type" value="simple">
</code>```

here YOURIPNFILE will return the POSTed data.

Title: Storing $award_id in a cookie - PHP

Body:
I have created a MYBB forum wadakela.xyz. I have added newPoints Awards System in it. Which is integrated with CoinPayments for user to buy it.

img: https://i.imgur.com/sI7Edly.png

Now, for example I have 5 awards and user buys 3rd one. I have scripted files which send an email and PM to me notifying that "this" user has purchased an award with ''this award ID'' when the user gets on success (callback from coinpayment) page.

imgs: https://imgur.com/a/fzR1qQl

Initially, when it was not integrated with coinpayments, I used POST method to get the award ID from the form when someone clicks BUY button through awards page which actually was working fine. I could get the proper id using this code.

//awards page
<input type="hidden" name="award" value="{$award['aid']}">

//success page
$award_id = $_POST['award'];

Now that it is integrated with CoinPayments, it's not going to the success.php directly so POST method isn't working. If I'm not wrong, I can get the award id in the success.php via cookies (or sessions maybe?). But, I'm failing to store award ID in a cookie.

As we know, it's now like this:

-awards page -> coinpayments site -> success page.

To get award ID from awards page to success page, I tried the following code to store award ID into the cookie:

//in awards page
setcookie("award",$award['aid'], time()+300);

//in the form
<input type="hidden" name="award" value="{$award['aid']}">

....processing with coinpayments....

//in success (callback) page
$award_id = $_COOKIE["award"];

echo $award_id;  //pm + email actually.

setcookie("award",$award_id, time()-60);

in success page, $award_id Always returns "5". Maybe because there are 5 awards listed?

Other than this, the whole process is very smooth and working as intended. What I want to do is to store proper award ID in the cookie.

I'd appreciate if one could help me with this. And if there's any alternate to achieve this, I'd like to know about it as well.

And also, I really need to get it done by today..

If you need more information, please let me know.

Thank you. :)

Body:
Success URL doesn't work as IPN. Instead, IPN is required to return POST data.

<input type="hidden" name="ipn_url" value="https://wadakela.xyz/YOURIPNFILE.php">
<input type="hidden" name="ipn_type" value="simple">

here YOURIPNFILE will return the POSTed data.


问:
how can I get some last objects from DB without reading all of the objects in Django?
There's some functions in Django to help you get first or last record, such as first(), earliest(), last() and latest(). What I'm looking for is a function to get some last objects without reading all of data. For example something like this to get last 3 object:

last_three_objects = my_model.objects.get_last(count=3)
```

<p>PS: I know that I can get it in this way:</p>

<pre class="lang-py prettyprint-override"><code>last_three_objects = my_model.objects.all()[:3]
</code>```

or:

last_three_objects = my_model.objects.all().order_by('-datetime')[:3]
```

But I think it will read all of my_model data from DB and it's not efficient! Any thoughts?

答:
create a datatime model

```<code>created = models.DateTimeField(auto_now_add=True, null=True)
</code>```

in view get the created field

```<code>course = Course.objects.all().order_by('-created')[:6]
</code>```

minus indicated the latest data in database and with the help of slicing we get the latest six item.

Body:
There's some functions in Django to help you get first or last record, such as first(), earliest(), last() and latest(). What I'm looking for is a function to get some last objects without reading all of data. For example something like this to get last 3 object:

last_three_objects = my_model.objects.get_last(count=3)

PS: I know that I can get it in this way:

last_three_objects = my_model.objects.all()[:3]

or:

last_three_objects = my_model.objects.all().order_by('-datetime')[:3]

But I think it will read all of my_model data from DB and it's not efficient! Any thoughts?

Body:
create a datatime model

created = models.DateTimeField(auto_now_add=True, null=True)

in view get the created field

course = Course.objects.all().order_by('-created')[:6]

minus indicated the latest data in database and with the help of slicing we get the latest six item.


答:
```<code>return this.state.value
 ? <div> something </div>
 : <div> something else </div>;
</code>```

or

```<code>if (this.state.value) {
  return <div> something </div>;
} else {
  return <div> something else </div>;
}
</code>```

In the first case you had extra {} around the return value, in the second case return if is not possible in JS since if does not return anything.

Consider JSX tags to be function calls (they're actually transpiled to calls to React.createElement).

Title: How to render with conditions in React

Body:
return this.state.value
 ? <div> something </div>
 : <div> something else </div>;

or

if (this.state.value) {
  return <div> something </div>;
} else {
  return <div> something else </div>;
}

In the first case you had extra {} around the return value, in the second case return if is not possible in JS since if does not return anything.

Consider JSX tags to be function calls (they're actually transpiled to calls to React.createElement).


问:
Combining csv with Python in new line
Iam trying to concatenate multiple csv but the output file has all the data in a single row. How to add a new line character while giving a output. Here is a sample code of mine

```<code>from os import chdir
from glob import glob
import pandas as pdlib

# Produce a single CSV after combining all files
def produceOneCSV(list_of_files, file_out):
   # Consolidate all CSV files into one object
   result_obj = pdlib.concat([pdlib.read_csv(file) for file in list_of_files], sort=False)
   # Convert the above object into a csv file and export

   result_obj.to_csv(file_out, index=False, encoding="utf-8")

# Move to the path that holds our CSV files
csv_file_path = 'Path_for_all_the_csv/'
chdir(csv_file_path)

# List all CSV files in the working dir
file_pattern = ".csv"
list_of_files = [file for file in glob('*.csv')]
print(list_of_files)

file_out = "ConsolidateOutput.csv"
produceOneCSV(list_of_files, file_out)
</code>```

I followed the document https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html. But didnt worked for me. Is there any change in document?

答:
Do you need pandas to concatenate a bunch of csvs?
If you're using linux, you can do it with one command.

$ cat *.csv > consolidated.csv
```

<p>And if you want to use python</p>

<pre class="lang-py prettyprint-override"><code>with open("consolidated.json", "w") as f:
    for ff in glob.glob("*.csv"):
        with open(ff) as fff:
            f.write(fff.read())
</code>```

Title: Combining csv with Python in new line

Body:
Iam trying to concatenate multiple csv but the output file has all the data in a single row. How to add a new line character while giving a output. Here is a sample code of mine

from os import chdir
from glob import glob
import pandas as pdlib

# Produce a single CSV after combining all files
def produceOneCSV(list_of_files, file_out):
   # Consolidate all CSV files into one object
   result_obj = pdlib.concat([pdlib.read_csv(file) for file in list_of_files], sort=False)
   # Convert the above object into a csv file and export

   result_obj.to_csv(file_out, index=False, encoding="utf-8")

# Move to the path that holds our CSV files
csv_file_path = 'Path_for_all_the_csv/'
chdir(csv_file_path)

# List all CSV files in the working dir
file_pattern = ".csv"
list_of_files = [file for file in glob('*.csv')]
print(list_of_files)

file_out = "ConsolidateOutput.csv"
produceOneCSV(list_of_files, file_out)

I followed the document https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html. But didnt worked for me. Is there any change in document?

Body:
Do you need pandas to concatenate a bunch of csvs?
If you're using linux, you can do it with one command.

$ cat *.csv > consolidated.csv

And if you want to use python

with open("consolidated.json", "w") as f:
    for ff in glob.glob("*.csv"):
        with open(ff) as fff:
            f.write(fff.read())


问:
Is there a way to add Share buttons to make plots shareable in Shiny
I have a Shiny Dashboard that outputs a couple of graphs. Is there a way to add "share social media" where a user would press to upload the graphs as a post to his facebook or twitter?

for example I want to have a button once clicked it will share phonePlot on twitter not the link...

```<code> # Rely on the 'WorldPhones' dataset in the datasets
 # package (which generally comes preloaded).
 library(datasets)

# Use a fluid Bootstrap layout
fluidPage(

  # Give the page a title
     titlePanel("Telephones by region"),

  # Generate a row with a sidebar
  sidebarLayout(

    # Define the sidebar with one input
    sidebarPanel(
      selectInput("region", "Region:",
                  choices=colnames(WorldPhones)),
      hr(),
      helpText("Data from AT&T (1961) The World's Telephones.")
    ),

    # Create a spot for the barplot
    mainPanel(
      plotOutput("phonePlot")
    )

  )
)
</code>```

Server

```<code># Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).
library(datasets)

# Use a fluid Bootstrap layout
fluidPage(

  # Give the page a title
  titlePanel("Telephones by region"),

  # Generate a row with a sidebar
  sidebarLayout(

    # Define the sidebar with one input
    sidebarPanel(
      selectInput("region", "Region:",
                  choices=colnames(WorldPhones)),
      hr(),
      helpText("Data from AT&T (1961) The World's Telephones.")
    ),

    # Create a spot for the barplot
    mainPanel(
      plotOutput("phonePlot")
    )

  )
)
</code>```

答:
In the following it is shown how a tweet including a picture can be posted.
For facebook i only found the following package:
https://cran.r-project.org/web/packages/Rfacebook/Rfacebook.pdf, which enables you to update your status, but does not seem to take media arguments. Therefore, sharing on facebook is not included in this answer.

In order to use the twitter api to programmatically post tweets you will need a developer account and (optimally) an R package that wraps the post request for you.

According to this page: https://rtweet.info/index.html you could use library(rtweet) (self-reference), or library(twitteR) for that. In the following library(rtweet) is used.

To be able to use your twitter developer account from within R, follow this detailed instruction: https://rtweet.info/articles/auth.html#rtweet. An initial setup is enough and can be confirmed by using rtweet::get_token(), see the code below.

Small walk through:

rtweet::post_tweet allows you to post tweets from within R. It takes pictures from disk in the media argument. If you generate a plot/picture in your shiny app, the data-URI scheme is used. Meaning, the plot is not (necessarily?) saved to disk, but embedded in the page. As rtweet::post_tweet takes File path to image or video media to be included in tweet. in the media argument, the plot has probably to be saved to disk first. One could also attempt to handover the "data-uri-path" (data:image/png;base64,i....) to rtweet::post_tweet but i would guess rtweet::post_tweet will not accept base64 encoded plot data (not tested).

A reproducible example (assuming you have fulfilled this steps: https://rtweet.info/articles/auth.html#rtweet):

```<code>library(shiny)
library(rtweet)
rtweet::get_token() # check if you have a correct app name and api_key

ui <- fluidPage(

  sidebarLayout(
    sidebarPanel(
      actionButton(
        inputId = "tweet",
        label = "Share",
        icon = icon("twitter")
      ),
      sliderInput(inputId = "nr", label = "nr", min = 1, max = 5, value = 2)
    ),

    mainPanel(
      plotOutput("twitter_plot")
    )

  )

)

plot_name <- "twitter_plot.png"
server <- function(input, output, session) {

  gen_plot <- reactive({
    plot(input$nr)
  })

  output$twitter_plot <- renderPlot({
    gen_plot()
  })

  observeEvent(input$tweet, {
    # post_tweet takes pictures from disk in the media argument. Therefore,
    # we can save the plot to disk and then hand it over to this function.
    png(filename = plot_name)
    gen_plot()
    dev.off()
    rtweet::post_tweet("Posted from R Shiny", media = plot_name)
  })

}

shinyApp(ui, server)
</code>```

Body:
I have a Shiny Dashboard that outputs a couple of graphs. Is there a way to add "share social media" where a user would press to upload the graphs as a post to his facebook or twitter?

for example I want to have a button once clicked it will share phonePlot on twitter not the link...

 # Rely on the 'WorldPhones' dataset in the datasets
 # package (which generally comes preloaded).
 library(datasets)

# Use a fluid Bootstrap layout
fluidPage(

  # Give the page a title
     titlePanel("Telephones by region"),

  # Generate a row with a sidebar
  sidebarLayout(

    # Define the sidebar with one input
    sidebarPanel(
      selectInput("region", "Region:",
                  choices=colnames(WorldPhones)),
      hr(),
      helpText("Data from AT&T (1961) The World's Telephones.")
    ),

    # Create a spot for the barplot
    mainPanel(
      plotOutput("phonePlot")
    )

  )
)

Server

# Rely on the 'WorldPhones' dataset in the datasets
# package (which generally comes preloaded).
library(datasets)

# Use a fluid Bootstrap layout
fluidPage(

  # Give the page a title
  titlePanel("Telephones by region"),

  # Generate a row with a sidebar
  sidebarLayout(

    # Define the sidebar with one input
    sidebarPanel(
      selectInput("region", "Region:",
                  choices=colnames(WorldPhones)),
      hr(),
      helpText("Data from AT&T (1961) The World's Telephones.")
    ),

    # Create a spot for the barplot
    mainPanel(
      plotOutput("phonePlot")
    )

  )
)

Body:
In the following it is shown how a tweet including a picture can be posted.
For facebook i only found the following package:
https://cran.r-project.org/web/packages/Rfacebook/Rfacebook.pdf, which enables you to update your status, but does not seem to take media arguments. Therefore, sharing on facebook is not included in this answer.

In order to use the twitter api to programmatically post tweets you will need a developer account and (optimally) an R package that wraps the post request for you.

According to this page: https://rtweet.info/index.html you could use library(rtweet) (self-reference), or library(twitteR) for that. In the following library(rtweet) is used.

To be able to use your twitter developer account from within R, follow this detailed instruction: https://rtweet.info/articles/auth.html#rtweet. An initial setup is enough and can be confirmed by using rtweet::get_token(), see the code below.

Small walk through:

rtweet::post_tweet allows you to post tweets from within R. It takes pictures from disk in the media argument. If you generate a plot/picture in your shiny app, the data-URI scheme is used. Meaning, the plot is not (necessarily?) saved to disk, but embedded in the page. As rtweet::post_tweet takes File path to image or video media to be included in tweet. in the media argument, the plot has probably to be saved to disk first. One could also attempt to handover the "data-uri-path" (data:image/png;base64,i....) to rtweet::post_tweet but i would guess rtweet::post_tweet will not accept base64 encoded plot data (not tested).

A reproducible example (assuming you have fulfilled this steps: https://rtweet.info/articles/auth.html#rtweet):

library(shiny)
library(rtweet)
rtweet::get_token() # check if you have a correct app name and api_key

ui <- fluidPage(

  sidebarLayout(
    sidebarPanel(
      actionButton(
        inputId = "tweet",
        label = "Share",
        icon = icon("twitter")
      ),
      sliderInput(inputId = "nr", label = "nr", min = 1, max = 5, value = 2)
    ),

    mainPanel(
      plotOutput("twitter_plot")
    )

  )

)

plot_name <- "twitter_plot.png"
server <- function(input, output, session) {

  gen_plot <- reactive({
    plot(input$nr)
  })

  output$twitter_plot <- renderPlot({
    gen_plot()
  })

  observeEvent(input$tweet, {
    # post_tweet takes pictures from disk in the media argument. Therefore,
    # we can save the plot to disk and then hand it over to this function.
    png(filename = plot_name)
    gen_plot()
    dev.off()
    rtweet::post_tweet("Posted from R Shiny", media = plot_name)
  })

}

shinyApp(ui, server)


问:
Can't get defaultRedirect to work
In my web.config, I have:

```<code><system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>
</code>```

In Views/Shared/Error.cshtml, I have:

```<code>@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}
<h2>
    Sorry, an error occurred while processing your request.
</h2>
</code>```

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.

答:
Edit you web.config as:

```<code><system.web>
    <customErrors mode="On" defaultRedirect="/Home/Error" />
</system.web>
</code>```

If you use asp.net mvc 1.0 or 2.0, you should add HandleError attribute for each controller:

```<code>[HandleError]
public class HomeController: Controller
{
    public ActionResult Error()
    {
        return View();
    }
}
</code>```

if you use asp.net mvc 3.0:

```<code>public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Start()
        {
            GlobalFilters.Filters.Add(new HandleErrorAttribute());
        }
}
</code>```

Title: Can't get defaultRedirect to work

Body:
In my web.config, I have:

<system.web>
    <customErrors mode="On" defaultRedirect="Error.cshtml" />
</system.web>

In Views/Shared/Error.cshtml, I have:

@model System.Web.Mvc.HandleErrorInfo
@{
    ViewBag.Title = "Error";
}

    Sorry, an error occurred while processing your request.

If I put an invalid URL/route into my browser, I get this:

Server Error in '/' Application.

The resource cannot be found.

Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.

Requested URL: /Error.cshtml

Why can't Error.cshtml be found? The file is definitely in Views/Shared.

Body:
Edit you web.config as:

<system.web>
    <customErrors mode="On" defaultRedirect="/Home/Error" />
</system.web>

If you use asp.net mvc 1.0 or 2.0, you should add HandleError attribute for each controller:

[HandleError]
public class HomeController: Controller
{
    public ActionResult Error()
    {
        return View();
    }
}

if you use asp.net mvc 3.0:

public class MvcApplication : System.Web.HttpApplication
{
        protected void Application_Start()
        {
            GlobalFilters.Filters.Add(new HandleErrorAttribute());
        }
}


问:
How to Call a Function with a Parameter in Blazor?
I am working with Blazor. I am learning this framework but I have got a problem. I can call a JavaScript function but when I call a C# function I get this error:

Severity Code Description Project File Line   Suppression State
  Error CS0411  The type arguments for method
  'RuntimeHelpers.CreateInferredEventCallback(object, Action, T)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.

I use Radzen and this my code block:

```<code><td>
<RadzenDropDown AllowClear="true" @bind-Value="(() => MultipleGetUser(item.UserID))" Multiple="true" Placeholder="Select..." Data="@UserList" TextProperty="UserName" ValueProperty="UserID" Change="@(args => ChangeUser(args, ""))" />
</td>
</code>```

This error in "@bind-Value". How call a function with a parameter?

答:
You cannot bind to function only field or property are allowed.

@bind- means it's bidirectional, so you need something you can set.

However you can create a computed property:

...

<RadzenDropDown AllowClear="true" @bind-Value="@this[item.UserID]" Multiple="true" Placeholder="Select..." Data="@UserList" TextProperty="UserName" ValueProperty="UserID" Change="@(args => ChangeUser(args, ""))" />

...
@code {
     User this[int id] // I assume you have a User class, replace by the one you use
     {
         get => MultipleGetUser(id);
         set => // as I don't how you can set your user by its Id I let you implement this code
     }

}
```

Body:
I am working with Blazor. I am learning this framework but I have got a problem. I can call a JavaScript function but when I call a C# function I get this error:

Severity Code Description Project File Line   Suppression State
  Error CS0411  The type arguments for method
  'RuntimeHelpers.CreateInferredEventCallback(object, Action, T)'
  cannot be inferred from the usage. Try specifying the type arguments
  explicitly.

I use Radzen and this my code block:

<RadzenDropDown AllowClear="true" @bind-Value="(() => MultipleGetUser(item.UserID))" Multiple="true" Placeholder="Select..." Data="@UserList" TextProperty="UserName" ValueProperty="UserID" Change="@(args => ChangeUser(args, ""))" />

This error in "@bind-Value". How call a function with a parameter?

Body:
You cannot bind to function only field or property are allowed.

@bind- means it's bidirectional, so you need something you can set.

However you can create a computed property:

...
<td>
<RadzenDropDown AllowClear="true" @bind-Value="@this[item.UserID]" Multiple="true" Placeholder="Select..." Data="@UserList" TextProperty="UserName" ValueProperty="UserID" Change="@(args => ChangeUser(args, ""))" />
</td>
...
@code {
     User this[int id] // I assume you have a User class, replace by the one you use
     {
         get => MultipleGetUser(id);
         set => // as I don't how you can set your user by its Id I let you implement this code
     }

}


问:
MongoError: can’t convert from BSON type string to Date in Meteor
In Meteor JS I want to find users whose birthday is today.I have this piece of code that runs fine on my computer (locally) but it fails in production :

```<code>let today = new Date()
let users = Meteor.users.find({
    "status.lastLogin": { $not: { $eq: null } },
    $expr: {
        $and: [
            {
                $eq: [
                    {
                        $dayOfMonth: {
                            date: "$profile.birthdate",
                            timezone: "Europe/Paris",
                        },
                    },
                    today.getDate(),
                ],
            },
            {
                $eq: [
                    {
                        $month: {
                            date: "$profile.birthdate",
                            timezone: "Europe/Paris",
                        },
                    },
                    today.getMonth() + 1,
                ],
            },
        ],
    },
})
</code>```

My server is hosted on Galaxy and the DB on mongodb.com
I checked the profile.birthdate type and it is Date on mongodb.com
The error is :

MongoError: can’t convert from BSON type string to Date\n at
Connection.
(/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/core/connection/pool.js:450:61)\n
at Connection.emit (events.js:311:20)\n at
Connection.EventEmitter.emit (domain.js:482:12)\n at processMessage
(/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/core/connection/connection.js:384:10)\n
at TLSSocket.

Does anyone know why this is happening and how can I fix it?

Edit: By following @Jankapunkt advice to use aggregate and by reading this post, I was able to write a better (I think...) query and now it is working.
This is the new code:

```<code>const today = new Date()
let users = Meteor.users.aggregate(
    {
        $project: {
            status: "$status",
            roles: "$roles",
            month: {
                $month: {
                    date: "$profile.birthdate",
                    timezone: "Europe/Paris",
                },
            },
            day: {
                $dayOfMonth: {
                    date: "$profile.birthdate",
                    timezone: "Europe/Paris",
                },
            },
        },
    },
    {
        $match: {
            "status.lastLogin": { $ne: null },
            roles: "candidate",
            month: today.getMonth() + 1,
            day: today.getDate(),
        },
    }
)
</code>```

答:
There are several issues here, I'd like to address:

$expr is usually only required in rare cases or when matching against a regular expression.

$dayOfMonth is an aggregate operator and not available in basic queries, but there are packages available

Meteor has builtin Date support through EJSON, which extends BSON by custom types (it abstracts the type conversion away for you):

Meteor.publish('allbirthdays', function () {
  const today = new Date()
  // correct timezone here
  return Meteor.users.find({ '$profile.birthdate': today })
}
```

<p>No need to convert Date to some mongo operators etc.</p>

<ul>
<li><p><code>$and</code> is a contradiction if differnt values are both required for the same field (<code>birthdate</code> can never be today and today in a month), did you intend to use <code>$or</code>?</p></li>
<li><p><code>{ $not: { $eq: null } }</code> can be written as <code>{ $ne: null }</code></p></li>
<li><p>Always disable the <code>services</code> field if you publish users! Services contains the (hashed) password and other oauth providers, including resume token, which could lead to serious security issues:</p></li>
</ul>

<h2>Saving / querying Dates without aggregate</h2>

<p>The above methods allow only an exact Date matches, because MongoDB provides Date-specific query only through <code>aggregate</code>.</p>

<p>Therefore, your options are:</p>

<ul>
<li><p>A) Use the aggregate package to build <code>$expr</code> for <code>$month</code> and <code>$dayOfMonth</code> as in your example code</p></li>
<li><p>B) Create the birthday only as locale field (which makes it a <code>String</code> type):</p></li>
</ul>

<pre class="lang-js prettyprint-override"><code>export const getDate = () => {
  // todo apply locale, timezone etc.
  return new Date().toLocaleString(undefined, {
    day: 'numeric', month: 'long'
  })
}
</code>```

and save it in the user's collection as a separate field (e.g. birthDay):

Meteor.users.update(userId, {
  $set: {
    '$profile.birthDay': getDate() // "June 3"
  }
})
```

<p>ans query only for this day:</p>

<pre class="lang-js prettyprint-override"><code>Meteor.publish('allbirthdays', function () {
  const today = getDate()
  return Meteor.users.find({ '$profile.birthDay': today })
}
</code>```

C) Save the month and day as Number types in separate fields:

const today = new Date()
Meteor.users.update(userId, {
  $set: {
    '$profile.birthDay': today.getDate()  // 3
    '$profile.birthMon': today.getMonth() // 6
  }
})
```

<p>ans query only for this day:</p>

<pre class="lang-js prettyprint-override"><code>Meteor.publish('allbirthdays', function () {
  const today = new Date()
  return Meteor.users.find({
    '$profile.birthDay': today.getDate()
    '$profile.birthMon': today.getMonth()
  })
})
</code>```

Body:
In Meteor JS I want to find users whose birthday is today.I have this piece of code that runs fine on my computer (locally) but it fails in production :

let today = new Date()
let users = Meteor.users.find({
    "status.lastLogin": { $not: { $eq: null } },
    $expr: {
        $and: [
            {
                $eq: [
                    {
                        $dayOfMonth: {
                            date: "$profile.birthdate",
                            timezone: "Europe/Paris",
                        },
                    },
                    today.getDate(),
                ],
            },
            {
                $eq: [
                    {
                        $month: {
                            date: "$profile.birthdate",
                            timezone: "Europe/Paris",
                        },
                    },
                    today.getMonth() + 1,
                ],
            },
        ],
    },
})

My server is hosted on Galaxy and the DB on mongodb.com
I checked the profile.birthdate type and it is Date on mongodb.com
The error is :

MongoError: can’t convert from BSON type string to Date\n at
Connection.
(/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/core/connection/pool.js:450:61)\n
at Connection.emit (events.js:311:20)\n at
Connection.EventEmitter.emit (domain.js:482:12)\n at processMessage
(/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb/lib/core/connection/connection.js:384:10)\n
at TLSSocket.

Does anyone know why this is happening and how can I fix it?

Edit: By following @Jankapunkt advice to use aggregate and by reading this post, I was able to write a better (I think...) query and now it is working.
This is the new code:

const today = new Date()
let users = Meteor.users.aggregate(
    {
        $project: {
            status: "$status",
            roles: "$roles",
            month: {
                $month: {
                    date: "$profile.birthdate",
                    timezone: "Europe/Paris",
                },
            },
            day: {
                $dayOfMonth: {
                    date: "$profile.birthdate",
                    timezone: "Europe/Paris",
                },
            },
        },
    },
    {
        $match: {
            "status.lastLogin": { $ne: null },
            roles: "candidate",
            month: today.getMonth() + 1,
            day: today.getDate(),
        },
    }
)

Body:
There are several issues here, I'd like to address:

$expr is usually only required in rare cases or when matching against a regular expression.

$dayOfMonth is an aggregate operator and not available in basic queries, but there are packages available

Meteor has builtin Date support through EJSON, which extends BSON by custom types (it abstracts the type conversion away for you):

Meteor.publish('allbirthdays', function () {
  const today = new Date()
  // correct timezone here
  return Meteor.users.find({ '$profile.birthdate': today })
}

No need to convert Date to some mongo operators etc.

$and is a contradiction if differnt values are both required for the same field (birthdate can never be today and today in a month), did you intend to use $or?

{ $not: { $eq: null } } can be written as { $ne: null }

Always disable the services field if you publish users! Services contains the (hashed) password and other oauth providers, including resume token, which could lead to serious security issues:

Saving / querying Dates without aggregate

The above methods allow only an exact Date matches, because MongoDB provides Date-specific query only through aggregate.

Therefore, your options are:

A) Use the aggregate package to build $expr for $month and $dayOfMonth as in your example code

B) Create the birthday only as locale field (which makes it a String type):

export const getDate = () => {
  // todo apply locale, timezone etc.
  return new Date().toLocaleString(undefined, {
    day: 'numeric', month: 'long'
  })
}

and save it in the user's collection as a separate field (e.g. birthDay):

Meteor.users.update(userId, {
  $set: {
    '$profile.birthDay': getDate() // "June 3"
  }
})

ans query only for this day:

Meteor.publish('allbirthdays', function () {
  const today = getDate()
  return Meteor.users.find({ '$profile.birthDay': today })
}

C) Save the month and day as Number types in separate fields:

const today = new Date()
Meteor.users.update(userId, {
  $set: {
    '$profile.birthDay': today.getDate()  // 3
    '$profile.birthMon': today.getMonth() // 6
  }
})

ans query only for this day:

Meteor.publish('allbirthdays', function () {
  const today = new Date()
  return Meteor.users.find({
    '$profile.birthDay': today.getDate()
    '$profile.birthMon': today.getMonth()
  })
})


问:
How to identify an element through classname even though there are multiple elements with the same classnames using Selenium and Python
```<code><div class="_2S1VP copyable-text selectable-text" data-tab="1" dir="ltr" spellcheck="true" contenteditable="true"></div>

<div class="_2S1VP copyable-text selectable-text" data-tab="3" dir="ltr" contenteditable="true"></div>
</code>```

I'm a beginner and I've had a hard time distinguishing / specifying the first class over the second one

```<code>typing = bot.find_element_by_xpath('//div[@class = "_1Plpp"]')
</code>```

this doesn't seem to work and just using the class name always brings up the unwanted second one with the same class name, I've noticed that it has data-tab="3" and the other one has data-tab="1"
how would i specify the one with data-tab="1" over the other one.

答:
As the class attribute of both the elements contains similar values, you won't be able to distinguish them only through class attribute and you may have to consider the some other attribute(s).

To identify the first element you can use either of the following Locator Strategies:

Using css_selector along with data-tab attribute:

```<code>typing = bot.find_element_by_css_selector("div.copyable-text.selectable-text[data-tab='1']")
</code>```

Using xpath along with data-tab attribute:

```<code>typing = bot.find_element_by_xpath("//div[contains(@class, 'copyable-text') and @data-tab='1']")
</code>```

Using xpath along with data-tab attribute:

```<code>typing = bot.find_element_by_xpath("//div[contains(@class, 'selectable-text') and @data-tab='1']")
</code>```

Body:
I'm a beginner and I've had a hard time distinguishing / specifying the first class over the second one

typing = bot.find_element_by_xpath('//div[@class = "_1Plpp"]')

this doesn't seem to work and just using the class name always brings up the unwanted second one with the same class name, I've noticed that it has data-tab="3" and the other one has data-tab="1"
how would i specify the one with data-tab="1" over the other one.

Body:
As the class attribute of both the elements contains similar values, you won't be able to distinguish them only through class attribute and you may have to consider the some other attribute(s).

To identify the first element you can use either of the following Locator Strategies:

Using css_selector along with data-tab attribute:

typing = bot.find_element_by_css_selector("div.copyable-text.selectable-text[data-tab='1']")

Using xpath along with data-tab attribute:

typing = bot.find_element_by_xpath("//div[contains(@class, 'copyable-text') and @data-tab='1']")

Using xpath along with data-tab attribute:

typing = bot.find_element_by_xpath("//div[contains(@class, 'selectable-text') and @data-tab='1']")


问:
How to get the foreign key in Entity Framework?
I am developing StudentApp in .NET 3.5 SP1 MVC Application.

I have two tables

Course

    CourseID, course_Name

Students

    studentID, student_Name, courseID(fk)

Now I made StudentApp.dbml which is having both table as entities.

As Foreign key will not be present in student entity,
I can not display courseID in student model, more over i can not generate add, edit, list views.

So tell me how to display courseID(fk) in student & i also want course name instead.

And also dropdownbox showing course name & storing courseID in edit view .

答:
If your using LINQ-to-SQL and created a DBML file in Visual Studio then the foreign keys can be listed through the Course property in the Student object (automatically generated so since it is a one-to-many relationship from Student). Sort of like this:

```<code>var studentCourseIds =
    from s in context.Students
    select s.Course.CourseID;
</code>```

Since your goal is to find the coursename then it is already accessible with Student.Course.course_Name.

OwnerDisplayName: Vikas

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Chad Moran

Body:
If your using LINQ-to-SQL and created a DBML file in Visual Studio then the foreign keys can be listed through the Course property in the Student object (automatically generated so since it is a one-to-many relationship from Student). Sort of like this:

var studentCourseIds =
    from s in context.Students
    select s.Course.CourseID;

Since your goal is to find the coursename then it is already accessible with Student.Course.course_Name.

OwnerDisplayName: Spoike


问:
php.ini wont work outside public_html directory
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

```<code><Files php.ini>
  Order allow,deny
  Deny from all
</Files>
</code>```

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions

答: It can't get cached by google if you block like that in .htaccess

Body:
Just very quick question about php.ini file. I created my own on my php.ini file and it works fine if I put it inside my 'public_html' directory. However the problem is it can obviously be viewed in browser through HTTP requests.

So, I am trying to move it outside my 'public_html' directory however it does not seem to work when outside my 'public_html'.

I know I could perhaps set in my .htaccess the following to avoid it being read:

<Files php.ini>
  Order allow,deny
  Deny from all
</Files>

However I do not want to do this as my php.ini can still get cached by Google if it's in the 'public_html' directory. Is there any suggestions to make it work outside my public_html?

I am running an Apache server. Thanks for any suggestions


问:
How to create custom shadow for view?
I wanna to create custom shadow for view which i customize as like as my plan.

Custom Shadow looks like Card View elevation.

I need this type of shadow

答:
Check this one. This works for me.

```<code><?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Bottom 2dp Shadow -->
<item>
    <shape  android:shape="rectangle">
        <solid android:color="#d8d8d8" />
        <corners android:radius="7dp" />
    </shape>
</item>

<!-- White Top color -->
<item android:bottom="3px">
    <shape  android:shape="rectangle">
        <solid android:color="#FFFFFF" />
        <corners android:radius="7dp" />
    </shape>
</item>
</code>```

Title: How to create custom shadow for view?

Body:
Check this one. This works for me.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Bottom 2dp Shadow -->
<item>
    <shape  android:shape="rectangle">
        <solid android:color="#d8d8d8" />
        <corners android:radius="7dp" />
    </shape>
</item>

<!-- White Top color -->
<item android:bottom="3px">
    <shape  android:shape="rectangle">
        <solid android:color="#FFFFFF" />
        <corners android:radius="7dp" />
    </shape>
</item>


问:
MinGW can't be installed on Windows 10
I am trying to install MinGW but it's always failing to install. See the picture for the error message.

Error

答: Since I cannot comment, I suppose there is no other way than write an answer. I am having the same issue and it seems to be related to the automated installer, it appears to be broken. Try installing manually (download the zip and manually place in correct directories and set system paths).</p>

Title: MinGW can't be installed on Windows 10


问:
How to use PendingIntent instead of an Intent with ConnectivityManager.ConnectivityAction with a callback in C# Xamarin API 28?
I need to make a simple callback in Xamarin, to check if the network status is connected or disconnected.

I have so far been doing it with this code:

```<code>class NetworkControl : INetworkControl
{
    private readonly INetworkControl.ICallback _callback;
    private readonly Context _context;
    private readonly NetworkBroadcastReceiver _receiver = new NetworkBroadcastReceiver();

    public NetworkControl(INetworkControl.ICallback callback, Context context)
    {
        _callback = callback;
        _context = context;
        IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
        context.RegisterReceiver(_receiver, filter);
    }

    public INetworkControl.ICallback Callback => _callback;

    public INetworkControl.NetworkStatus Status
    {
        get
        {
            var current = Connectivity.NetworkAccess;
            if (current == NetworkAccess.Internet)
            {
                return INetworkControl.NetworkStatus.Connected;
            }
            return INetworkControl.NetworkStatus.Disconnected;
        }
    }
}

class NetworkBroadcastReceiver : BroadcastReceiver
{

    private static String TAG = "NetworkBroadcastReceiver";

    public override void OnReceive(Context context, Intent intent)
    {

       if (ShellBridge.Instance != null)
       {
           if (intent.Action.Equals(ConnectivityManager.ConnectivityAction))
           {
               NetworkInfo ni = (NetworkInfo)intent.Extras.Get(ConnectivityManager.ExtraNetworkInfo);
               if (ni.isConnected)
               {
                   // do something if connected
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               } else
               {
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               }

           }

       }

    }
</code>```

The problem is, the function ConnectivityManager.ConnectivityAction in the Intent creating is depricated, and will soon be obsolete. After searching, I found that the pendingIntent should be used for that, but I could not find any valid example of how to use it.

The closest to what I need is this:

```<code>https://stackoverflow.com/questions/58588132/how-to-use-registernetworkcallback-with-pendingintent
</code>```

But, it has not all the information I need.
I need it to be all programmatically, without changing the manifest, for, my app should be a fore- and background app.

Please help, and thank you for your time.

答:
You can take a look at NetworkCallback .

```<code>public class ConnectionStateMonitor : NetworkCallback
    {
        NetworkRequest networkRequest;

        public ConnectionStateMonitor()
        {
            networkRequest = new NetworkRequest.Builder().
                AddTransportType(TransportType.Cellular).
                AddTransportType(TransportType.Wifi).Build();
        }

        public void enable(Context context) {
            ConnectivityManager connectivityManager = context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
            connectivityManager.RegisterNetworkCallback(networkRequest, this);
        }

        public override void OnAvailable(Network network)
        {
            //network available
        }

        public override void OnLost(Network network)
        {
            //network lost
        }
    }
</code>```

Usage

You just need to instantiate the class ConnectionStateMonitor  and enable it , you could detect the network status with the method OnAvailable and OnLost .

```<code>ConnectionStateMonitor m = new ConnectionStateMonitor ();
m.enable(context);
</code>```

Refer

https://github.com/xamarin/Essentials/issues/512

ConnectivityManager.CONNECTIVITY_ACTION deprecated

Body:
I need to make a simple callback in Xamarin, to check if the network status is connected or disconnected.

I have so far been doing it with this code:

class NetworkControl : INetworkControl
{
    private readonly INetworkControl.ICallback _callback;
    private readonly Context _context;
    private readonly NetworkBroadcastReceiver _receiver = new NetworkBroadcastReceiver();

    public NetworkControl(INetworkControl.ICallback callback, Context context)
    {
        _callback = callback;
        _context = context;
        IntentFilter filter = new IntentFilter(ConnectivityManager.ConnectivityAction);
        context.RegisterReceiver(_receiver, filter);
    }

    public INetworkControl.ICallback Callback => _callback;

    public INetworkControl.NetworkStatus Status
    {
        get
        {
            var current = Connectivity.NetworkAccess;
            if (current == NetworkAccess.Internet)
            {
                return INetworkControl.NetworkStatus.Connected;
            }
            return INetworkControl.NetworkStatus.Disconnected;
        }
    }
}

class NetworkBroadcastReceiver : BroadcastReceiver
{

    private static String TAG = "NetworkBroadcastReceiver";

    public override void OnReceive(Context context, Intent intent)
    {

       if (ShellBridge.Instance != null)
       {
           if (intent.Action.Equals(ConnectivityManager.ConnectivityAction))
           {
               NetworkInfo ni = (NetworkInfo)intent.Extras.Get(ConnectivityManager.ExtraNetworkInfo);
               if (ni.isConnected)
               {
                   // do something if connected
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               } else
               {
                   ShellBridge.Instance.NetworkBridge.Callback.NetworkStatusChanged(INetworkControl.NetworkStatus.Connected);
               }

           }

       }

    }

The problem is, the function ConnectivityManager.ConnectivityAction in the Intent creating is depricated, and will soon be obsolete. After searching, I found that the pendingIntent should be used for that, but I could not find any valid example of how to use it.

The closest to what I need is this:

https://stackoverflow.com/questions/58588132/how-to-use-registernetworkcallback-with-pendingintent

But, it has not all the information I need.
I need it to be all programmatically, without changing the manifest, for, my app should be a fore- and background app.

Please help, and thank you for your time.

Body:
You can take a look at NetworkCallback .

public class ConnectionStateMonitor : NetworkCallback
    {
        NetworkRequest networkRequest;

        public ConnectionStateMonitor()
        {
            networkRequest = new NetworkRequest.Builder().
                AddTransportType(TransportType.Cellular).
                AddTransportType(TransportType.Wifi).Build();
        }

        public void enable(Context context) {
            ConnectivityManager connectivityManager = context.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
            connectivityManager.RegisterNetworkCallback(networkRequest, this);
        }

        public override void OnAvailable(Network network)
        {
            //network available
        }

        public override void OnLost(Network network)
        {
            //network lost
        }
    }

Usage

You just need to instantiate the class ConnectionStateMonitor  and enable it , you could detect the network status with the method OnAvailable and OnLost .

ConnectionStateMonitor m = new ConnectionStateMonitor ();
m.enable(context);

Refer

https://github.com/xamarin/Essentials/issues/512

ConnectivityManager.CONNECTIVITY_ACTION deprecated


问:
How do I dynamically render new component after a change in previous component?
I want to create a CMS in React where a user can enter N amount of pictures.

To do this, i created a FileUploader component. I can track when the user interacts with the component and read the file from this component.

I want to make it so there are N+1 FileUploaders rendered for N images in this.state.images

So if I have 3 images in the array, I want to render 4 FileUploaders

How do I do this with React?

答:
Why not just create a loop that renders the FileUploaders? You already has the number of images. Therefore, it should be easy to just do
for (let i = 0; i < this.state.images.length + 1; i++)

Since you haven't presented some code to work with.. I just create some example code for you

const MyComponent = () => {
   const [images, setImages] = React.useState(["some stuff", "some stuff"]);

   return (
       <>
          {[...images, undefined].map(image => <FileUploaders />)}
       </>
   );
}

```

Notice that i add undefined at the end of the array, so we have one more entry to loop through. If you plan to use the image to something. You can just check if the image is undefined or not.

Body:
Why not just create a loop that renders the FileUploaders? You already has the number of images. Therefore, it should be easy to just do
for (let i = 0; i < this.state.images.length + 1; i++)

Since you haven't presented some code to work with.. I just create some example code for you

const MyComponent = () => {
   const [images, setImages] = React.useState(["some stuff", "some stuff"]);

   return (
       <>
          {[...images, undefined].map(image => <FileUploaders />)}
       </>
   );
}

Notice that i add undefined at the end of the array, so we have one more entry to loop through. If you plan to use the image to something. You can just check if the image is undefined or not.


问:
How can I check only one check box at a time instead of all in a list of checkboxes in React
I have a list of chat room channels for people to talk i.e there is a lifestyle channel, shopping channel, pets channel etc.

I am now trying to categorise each channel to make it easier for the user to find what they want. In order to do so, on creation of a chatroom channel I need the user to select which category the channel they are creating best fits into. A bit like YouTube does when you upload a video.

So far I have created a separate component which is a list of checkboxes with the different categories the user can put their channel into:

```<code>import React from 'react';

const options = [
  { label: "Lifestyle", value: "lifestyle"},
  { label: "Area", value: "area" },
  { label: "Random", value: "random" },
  { label: "Comedy", value: "comedy" },
  { label: "Entertainment", value: "entertainment" }
];
const ChannelCategory = (props) => {
return  (
  <div>
    {props.title}
    <ul>
    {options.map((option) => (
     <li key={props.key}>
       <label>
       {option.label}
       <input
         className={props.className}
         name="test"
         checked={props.checked}
         onChange={() => props.onChange(option.value)}
         type="checkbox"
       />
       </label>
     </li>
    ))}
  </ul>
  </div>
)
};
export default ChannelCategory;

</code>```

I am using the above component on the page below, I would like that when the user selects just ONE of the options only ONE input box is checked, however at the moment when I click ONE input box for instance lifestyle they ALLLL get checked and for every single channel too:( Any ideas why?

```<code>
 const [checked, setCheckBoxChecked] = useState(false);
[...]
  const onAddCategory = (value) => {
    console.log(value);
    if (value === "lifestyle") {
      setCheckBoxChecked(checked => !checked);
    }
    if (value === "area") {
      setCheckBoxChecked(checked => !checked);
    }
    if (value === "random") {
      setCheckBoxChecked(checked => !checked);
    }
    if (value === "comedy") {
      setCheckBoxChecked(checked => !checked);
    }
  };

[...]
  const options = [
    { label: "Lifestyle", value: "lifestyle"},
    { label: "Area", value: "area" },
    { label: "Random", value: "random" },
    { label: "Comedy", value: "comedy" },
    { label: "Entertainment", value: "entertainment" }
  ];

  return (
    <form noValidate autoComplete='off' onSubmit={onSubmit}>
      <Card style={styles.card}>
        <CardContent>
          <Box padding={3}>
            <FormLegend title={`${formTitle} (${channels.length})`} description={formDescription} />
            <Box marginTop={3} width='50%'>
              <Grid container direction='column' justify='flex-start' alignItems='stretch' spacing={1}>
                {channels.map(channel => {
                  return (
                  <Grid key={channel.key} item style={styles.gridItem} justify="space-between">
                    <ChannelListItem
                      channel={channel}
                      isSaving={isSaving}
                      onDeleteChannelClick={onDeleteChannelClick}
                      key={channel.Key}
                      onFormControlChange={onFormControlChange}
                      onUndoChannelClick={onUndoChannelClick}
                    />
                    <ChannelCategory
                      key={channel.key}
                      options={options}
                      onChange={value => onAddCategory(value)}
                      title="Add your chatroom to a category so that users can find it easily"
                      checked={checked}
                    />
                  </Grid>
                  )
                })}
          [...]
                </Grid>
              </Grid>
            </Box>
          </Box>
        </CardContent>
      </Card>

    </form>
  );
</code>```

答:
Use an array to store all checked boxes and in your ChannelCategory check if the current value exists in the checked array then set checked to true for that checkbox. If you want to select only one category use radio buttons

const {useState, useEffect} = React;

const options = [
  { label: "Lifestyle", value: "lifestyle" },
  { label: "Area", value: "area" },
  { label: "Random", value: "random" },
  { label: "Comedy", value: "comedy" },
  { label: "Entertainment", value: "entertainment" }
];

const ChannelCategory = props => {
  return (

      {props.title}

        {props.options.map(option => (

              {option.label}
              <input
                className={props.className}
                name={option.value}
                checked={props.checked.includes(option.value)}
                onChange={e => props.onChange(e.target.checked, option.value)}
                type="checkbox"
              />

        ))}

  );
};

function App() {
  const [checked, setCheckBoxChecked] = useState([]);

  const onAddCategory = (isChecked, value) => {
    const temp = [...checked];

    if (isChecked) {
      temp.push(value);
      setCheckBoxChecked(temp);

      return;
    }

    setCheckBoxChecked(temp.filter(item => item !== value));
  };

  return (

      <ChannelCategory
        key={"channel.key"}
        options={options}
        onChange={onAddCategory}
        title="Add your chatroom to a category so that users can find it easily"
        checked={checked}
      />

  );
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div></code>```

Radio buttons example

Body:
I have a list of chat room channels for people to talk i.e there is a lifestyle channel, shopping channel, pets channel etc.

I am now trying to categorise each channel to make it easier for the user to find what they want. In order to do so, on creation of a chatroom channel I need the user to select which category the channel they are creating best fits into. A bit like YouTube does when you upload a video.

So far I have created a separate component which is a list of checkboxes with the different categories the user can put their channel into:

import React from 'react';

const options = [
  { label: "Lifestyle", value: "lifestyle"},
  { label: "Area", value: "area" },
  { label: "Random", value: "random" },
  { label: "Comedy", value: "comedy" },
  { label: "Entertainment", value: "entertainment" }
];
const ChannelCategory = (props) => {
return  (

    {props.title}

    {options.map((option) => (

       {option.label}
       <input
         className={props.className}
         name="test"
         checked={props.checked}
         onChange={() => props.onChange(option.value)}
         type="checkbox"
       />

    ))}

)
};
export default ChannelCategory;

I am using the above component on the page below, I would like that when the user selects just ONE of the options only ONE input box is checked, however at the moment when I click ONE input box for instance lifestyle they ALLLL get checked and for every single channel too:( Any ideas why?

 const [checked, setCheckBoxChecked] = useState(false);
[...]
  const onAddCategory = (value) => {
    console.log(value);
    if (value === "lifestyle") {
      setCheckBoxChecked(checked => !checked);
    }
    if (value === "area") {
      setCheckBoxChecked(checked => !checked);
    }
    if (value === "random") {
      setCheckBoxChecked(checked => !checked);
    }
    if (value === "comedy") {
      setCheckBoxChecked(checked => !checked);
    }
  };

[...]
  const options = [
    { label: "Lifestyle", value: "lifestyle"},
    { label: "Area", value: "area" },
    { label: "Random", value: "random" },
    { label: "Comedy", value: "comedy" },
    { label: "Entertainment", value: "entertainment" }
  ];

  return (
    <form noValidate autoComplete='off' onSubmit={onSubmit}>
      <Card style={styles.card}>
        <CardContent>
          <Box padding={3}>
            <FormLegend title={`${formTitle} (${channels.length})`} description={formDescription} />
            <Box marginTop={3} width='50%'>
              <Grid container direction='column' justify='flex-start' alignItems='stretch' spacing={1}>
                {channels.map(channel => {
                  return (
                  <Grid key={channel.key} item style={styles.gridItem} justify="space-between">
                    <ChannelListItem
                      channel={channel}
                      isSaving={isSaving}
                      onDeleteChannelClick={onDeleteChannelClick}
                      key={channel.Key}
                      onFormControlChange={onFormControlChange}
                      onUndoChannelClick={onUndoChannelClick}
                    />
                    <ChannelCategory
                      key={channel.key}
                      options={options}
                      onChange={value => onAddCategory(value)}
                      title="Add your chatroom to a category so that users can find it easily"
                      checked={checked}
                    />
                  </Grid>
                  )
                })}
          [...]
                </Grid>
              </Grid>
            </Box>
          </Box>
        </CardContent>
      </Card>

    </form>
  );

Body:
Use an array to store all checked boxes and in your ChannelCategory check if the current value exists in the checked array then set checked to true for that checkbox. If you want to select only one category use radio buttons

const {useState, useEffect} = React;

const options = [
  { label: "Lifestyle", value: "lifestyle" },
  { label: "Area", value: "area" },
  { label: "Random", value: "random" },
  { label: "Comedy", value: "comedy" },
  { label: "Entertainment", value: "entertainment" }
];

const ChannelCategory = props => {
  return (
    <div>
      {props.title}
      <ul>
        {props.options.map(option => (
          <li key={props.key}>
            <label>
              {option.label}
              <input
                className={props.className}
                name={option.value}
                checked={props.checked.includes(option.value)}
                onChange={e => props.onChange(e.target.checked, option.value)}
                type="checkbox"
              />
            </label>
          </li>
        ))}
      </ul>
    </div>
  );
};

function App() {
  const [checked, setCheckBoxChecked] = useState([]);

  const onAddCategory = (isChecked, value) => {
    const temp = [...checked];

    if (isChecked) {
      temp.push(value);
      setCheckBoxChecked(temp);

      return;
    }

    setCheckBoxChecked(temp.filter(item => item !== value));
  };

  return (
    <div className="App">
      <ChannelCategory
        key={"channel.key"}
        options={options}
        onChange={onAddCategory}
        title="Add your chatroom to a category so that users can find it easily"
        checked={checked}
      />
    </div>
  );
}

ReactDOM.render(
  <App />,
  document.getElementById("react")
);

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

Radio buttons example