问:
How to Sort a List<T> by a property in the object
I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:

    List<Order> objListOrder = new List<Order>();
    GetOrderList(objListOrder); // fill list of orders
```

I want to sort the list based on one property of the Order object; for example, either by the order date or the order id.

How can I do this in C#?

答:
Suppose you have the following code, in this code, we have a Passenger class with a couple of properties that we want to sort based on.

```<code>public class Passenger
{
    public string Name { get; }
    public string LastName { get; }
    public string PassportNo { get; }
    public string Nationality { get; }

    public Passenger(string name, string lastName, string passportNo, string nationality)
    {
        this.Name = name;
        this.LastName = lastName;
        this.PassportNo = passportNo;
        this.Nationality = nationality;
    }

    public static int CompareByName(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.Name, passenger2.Name);
    }

    public static int CompareByLastName(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.LastName, passenger2.LastName);
    }

    public static int CompareNationality(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.Nationality, passenger2.Nationality);
    }
}

public class TestPassengerSort
{
    Passenger p1 = new Passenger("Johon", "Floid", "A123456789", "USA");
    Passenger p2 = new Passenger("Jo", "Sina", "A987463215", "UAE");
    Passenger p3 = new Passenger("Ped", "Zoola", "A987855215", "Italy");

    public void SortThem()
    {
        Passenger[] passengers = new Passenger[] { p1, p2, p3 };
        List<Passenger> passengerList = new List<Passenger> { p1, p2, p3 };

        Array.Sort(passengers, Passenger.CompareByName);
        Array.Sort(passengers, Passenger.CompareByLastName);
        Array.Sort(passengers, Passenger.CompareNationality);

        passengerList.Sort(Passenger.CompareByName);
        passengerList.Sort(Passenger.CompareByLastName);
        passengerList.Sort(Passenger.CompareNationality);

    }
}
</code>```

So you can implement your sort structure by using Composition delegate.

Body:
I have a class called Order which has properties such as OrderId, OrderDate, Quantity, and Total. I have a list of this Order class:

    List<Order> objListOrder = new List<Order>();
    GetOrderList(objListOrder); // fill list of orders

I want to sort the list based on one property of the Order object; for example, either by the order date or the order id.

How can I do this in C#?

Body:
Suppose you have the following code, in this code, we have a Passenger class with a couple of properties that we want to sort based on.

public class Passenger
{
    public string Name { get; }
    public string LastName { get; }
    public string PassportNo { get; }
    public string Nationality { get; }

    public Passenger(string name, string lastName, string passportNo, string nationality)
    {
        this.Name = name;
        this.LastName = lastName;
        this.PassportNo = passportNo;
        this.Nationality = nationality;
    }

    public static int CompareByName(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.Name, passenger2.Name);
    }

    public static int CompareByLastName(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.LastName, passenger2.LastName);
    }

    public static int CompareNationality(Passenger passenger1, Passenger passenger2)
    {
        return String.Compare(passenger1.Nationality, passenger2.Nationality);
    }
}

public class TestPassengerSort
{
    Passenger p1 = new Passenger("Johon", "Floid", "A123456789", "USA");
    Passenger p2 = new Passenger("Jo", "Sina", "A987463215", "UAE");
    Passenger p3 = new Passenger("Ped", "Zoola", "A987855215", "Italy");

    public void SortThem()
    {
        Passenger[] passengers = new Passenger[] { p1, p2, p3 };
        List<Passenger> passengerList = new List<Passenger> { p1, p2, p3 };

        Array.Sort(passengers, Passenger.CompareByName);
        Array.Sort(passengers, Passenger.CompareByLastName);
        Array.Sort(passengers, Passenger.CompareNationality);

        passengerList.Sort(Passenger.CompareByName);
        passengerList.Sort(Passenger.CompareByLastName);
        passengerList.Sort(Passenger.CompareNationality);

    }
}

So you can implement your sort structure by using Composition delegate.


来源: stackexchange

问:
Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory
I have a project on Laravel 5 and I work with it at the office and at home too. It works fine, but recently at home it stopped working. Laravel show me two ErrorException

```<code>file_put_contents(G:\project\storage\framework\views/751d8a0fd8a7d4138c09ceb6a34bb377aa2d6265.php):
failed to open stream: No such file or directory
</code>```

and

```<code>file_put_contents(G:\project\storage\framework/sessions/aIXycR4LIAUBVIqZu0T590paOMIpV8vfZGIroEp0):
failed to open stream: No such file or directory
</code>```

I'm searching problem decision with Google and find information about correct rights. All advice is about Linux, but I'am work in Windows at the office and at home too.

When I try to clear application cache and view cache, artisan talk to me - ...cleared. But cache data and views are present in storage.

How can I fix this problem?

答:
The solution that worked for me is to just serve the app as admin
if you are

On mac or linux use sudo php artisan serve

On Windows try to open CMD as an adminstrator and then go to project directory and run php artisan serve

ContentLicense: CC BY-SA 4.0

Body:
I have a project on Laravel 5 and I work with it at the office and at home too. It works fine, but recently at home it stopped working. Laravel show me two ErrorException

file_put_contents(G:\project\storage\framework\views/751d8a0fd8a7d4138c09ceb6a34bb377aa2d6265.php):
failed to open stream: No such file or directory

and

file_put_contents(G:\project\storage\framework/sessions/aIXycR4LIAUBVIqZu0T590paOMIpV8vfZGIroEp0):
failed to open stream: No such file or directory

I'm searching problem decision with Google and find information about correct rights. All advice is about Linux, but I'am work in Windows at the office and at home too.

When I try to clear application cache and view cache, artisan talk to me - ...cleared. But cache data and views are present in storage.

How can I fix this problem?


问:
How to open a link in new tab (chrome) using Selenium WebDriver?
```<code>System.setProperty("webdriver.chrome.driver", "D:\\softwares\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://mail.google.com/");
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);
</code>```

New tab is opening but URL link is not opening.

答:
for clicking on the link which expected to be opened from the new tab use this</p>
```<code>WebDriver driver = new ChromeDriver();
driver.get("https://www.yourSite.com");
WebElement link = driver.findElement(By.xpath("path_to_link"));

Actions actions = new Actions(driver);
actions.keyDown(Keys.LEFT_CONTROL)
       .click(link)
       .keyUp(Keys.LEFT_CONTROL)
       .build()
       .perform();

ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));
</code>```

Body:
System.setProperty("webdriver.chrome.driver", "D:\\softwares\\chromedriver_win32\\chromedriver.exe");

WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://mail.google.com/");
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText("www.facebook.com")).sendKeys(selectLinkOpeninNewTab);

New tab is opening but URL link is not opening.

Body:
for clicking on the link which expected to be opened from the new tab use this

WebDriver driver = new ChromeDriver();
driver.get("https://www.yourSite.com");
WebElement link = driver.findElement(By.xpath("path_to_link"));

Actions actions = new Actions(driver);
actions.keyDown(Keys.LEFT_CONTROL)
       .click(link)
       .keyUp(Keys.LEFT_CONTROL)
       .build()
       .perform();

ArrayList<String> tab = new ArrayList<>(driver.getWindowHandles());
driver.switchTo().window(tab.get(1));


问:
Error occured while reading WSGI handler. ModuleNotFoundError' while hosting DJango on IIS. Can't find settings
I am doing this for the first time. I am trying to host my Django rest app on Windows IIS server. I have followed this tutorial https://medium.com/@Jonny_Waffles/deploy-django-on-iis-def658beae92 but I am getting the following error. Does it have to do something with my conda environment? I haven't used any config file. I've set the environment variables in the system variables instead.

In my settings.py

WSGI_APPLICATION = 'webapi.wsgi.application'
```

<p>IN wsgi.py</p>

<pre class="lang-py prettyprint-override"><code>import os

from django.core.wsgi import get_wsgi_application
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webapi.settings')

    application = get_wsgi_application()
</code>```

Error occurred while reading WSGI handler:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 791, in main
    env, handler = read_wsgi_handler(response.physical_path)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler
    handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler
    raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb))
ValueError: "webapi.wsgi.application" could not be imported: Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler
    handler = __import__(module_name, fromlist=[name_list[0][0]])
  File "C:\inetpub\wwwroot\webapi\webapi\wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application
    django.setup(set_prefix=False)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
    self._setup(name)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 66, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 157, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named 'C:\\inetpub\\wwwroot\\webapi\\webapi\\settings'

StdOut:

StdErr:
```

答:
For me the problem that lead to this same error message was that in the settings of my FastCGI handler the environment variable DJANGO_SETTINGS_MODULE was wrong.

it has to be a module path, i.e. MyProject.settings instead of C:\inetpub\wwwroot\MyProject\MyProject\settings.py as I assume was in your case.

so for you: DJANGO_SETTINGS_MODULE  = webapi.settings

Body:
I am doing this for the first time. I am trying to host my Django rest app on Windows IIS server. I have followed this tutorial https://medium.com/@Jonny_Waffles/deploy-django-on-iis-def658beae92 but I am getting the following error. Does it have to do something with my conda environment? I haven't used any config file. I've set the environment variables in the system variables instead.

In my settings.py

WSGI_APPLICATION = 'webapi.wsgi.application'

IN wsgi.py

import os

from django.core.wsgi import get_wsgi_application
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webapi.settings')

    application = get_wsgi_application()

Error occurred while reading WSGI handler:

Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 791, in main
    env, handler = read_wsgi_handler(response.physical_path)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 633, in read_wsgi_handler
    handler = get_wsgi_handler(os.getenv("WSGI_HANDLER"))
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 616, in get_wsgi_handler
    raise ValueError('"%s" could not be imported%s' % (handler_name, last_tb))
ValueError: "webapi.wsgi.application" could not be imported: Traceback (most recent call last):
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\wfastcgi.py", line 600, in get_wsgi_handler
    handler = __import__(module_name, fromlist=[name_list[0][0]])
  File "C:\inetpub\wwwroot\webapi\webapi\wsgi.py", line 16, in <module>
    application = get_wsgi_application()
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application
    django.setup(set_prefix=False)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\__init__.py", line 19, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__
    self._setup(name)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 66, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\site-packages\django\conf\__init__.py", line 157, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\ProgramData\Anaconda3\envs\api_env\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
ModuleNotFoundError: No module named 'C:\\inetpub\\wwwroot\\webapi\\webapi\\settings'

StdOut:

StdErr:


问:
How do I create objects based on a query in EF Core (keyless entities)?
I am trying to map the results of a complex SQL query to a keyless entity in EF Core. (I basically need to create a view client-side due to having to deal with a preexisting database.)

However, when trying to retrieve my data, I get an InvalidOperationException "Sequence contains no elements".  I can map base tables in the DB to normal entities, so I know the connection string is correct.  A simplified, but complete example:

using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        using (var db = new QueryDbContext())
        {
            List<Model> result = db.Orders.ToList();  // <-- exception occurs here.
            Console.WriteLine($"Found: {result.Count}");
        }
    }
}

public class Model
{
    public string OrderId { get; }
}

public class QueryDbContext : DbContext
{
    public QueryDbContext()
        : base()
    {}

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            _ = optionsBuilder
                .UseSqlServer("myconnectionstring");
        }
    }

    public DbSet<Model> Orders { get; set; }
    private const string _OrdersSql =
        "select top 5 orderid from tbl_orders order by transacttime desc";

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Model>(m =>
            {
                m.HasNoKey();
                m.ToQuery(() => Set<Model>().FromSqlRaw(_OrdersSql));
            });
    }
}

```

Set<>() is the current version (since EFCore 3.0) of Query<>() as described in the answer to FromSql with Non-Existing Entity.

答:
The problem was that the model properties need both setters and getters, even though the model is read-only.  So the model should be

public class Model
{
    public string OrderId { get; set; }
}
```

Body:
I am trying to map the results of a complex SQL query to a keyless entity in EF Core. (I basically need to create a view client-side due to having to deal with a preexisting database.)

However, when trying to retrieve my data, I get an InvalidOperationException "Sequence contains no elements".  I can map base tables in the DB to normal entities, so I know the connection string is correct.  A simplified, but complete example:

using System;
using System.Linq;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;

class Program
{
    static void Main(string[] args)
    {
        using (var db = new QueryDbContext())
        {
            List<Model> result = db.Orders.ToList();  // <-- exception occurs here.
            Console.WriteLine($"Found: {result.Count}");
        }
    }
}

public class Model
{
    public string OrderId { get; }
}

public class QueryDbContext : DbContext
{
    public QueryDbContext()
        : base()
    {}

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            _ = optionsBuilder
                .UseSqlServer("myconnectionstring");
        }
    }

    public DbSet<Model> Orders { get; set; }
    private const string _OrdersSql =
        "select top 5 orderid from tbl_orders order by transacttime desc";

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder
            .Entity<Model>(m =>
            {
                m.HasNoKey();
                m.ToQuery(() => Set<Model>().FromSqlRaw(_OrdersSql));
            });
    }
}

Set<>() is the current version (since EFCore 3.0) of Query<>() as described in the answer to FromSql with Non-Existing Entity.


问:
update data frame based on data from another data frame using pandas python
I have two data frames df1 and df2. Both have first column common SKUCode=SKU

df1:

df2:

I want to update df1 and set SKUStatus=0 if SKUCode matches SKU in df2.

I want to add new row to df1 if SKU from df2 has no match to SKUCode.

So after the operation df1 looks like following:

One way I could get this done is via df2.iterrows() and looping through values however I think there must be another neat way of doing this?
Thank you

```<code>import pandas as pdx

df1=pdx.DataFrame({'SKUCode':['A','B','C','D'],'ListPrice':[1798,2997,1798,999],'SalePrice':[1798,2997,1798,999],'SKUStatus':[1,1,1,0],'CostPrice':[500,773,525,300]})

df2=pdx.DataFrame({'SKUCode':['X','Y','B'],'Status':[0,0,0],'e_date':['31-05-2020','01-06-2020','01-06-2020']})

df1.merge(df2,left_on='SKUCode')
</code>```

答:
try this, using outer merge which gives both matching and non-matching records.

```<code>In [75]: df_m = df1.merge(df2, on="SKUCode", how='outer')

In [76]: mask = df_m['Status'].isnull()

In [77]: df_m.loc[~mask, 'SKUStatus'] = df_m.loc[~mask, 'Status']

In [78]: df_m[['SKUCode', "ListPrice", "SalePrice", "SKUStatus", "CostPrice"]].fillna(0.0)
</code>```

output

```<code>  SKUCode  ListPrice  SalePrice  SKUStatus  CostPrice
0       A     1798.0     1798.0        1.0      500.0
1       B     2997.0     2997.0        0.0      773.0
2       C     1798.0     1798.0        1.0      525.0
3       D      999.0      999.0        0.0      300.0
4       X        0.0        0.0        0.0        0.0
5       Y        0.0        0.0        0.0        0.0
</code>```

Body:
I have two data frames df1 and df2. Both have first column common SKUCode=SKU

df1:

df2:

I want to update df1 and set SKUStatus=0 if SKUCode matches SKU in df2.

I want to add new row to df1 if SKU from df2 has no match to SKUCode.

So after the operation df1 looks like following:

One way I could get this done is via df2.iterrows() and looping through values however I think there must be another neat way of doing this?
Thank you

import pandas as pdx

df1=pdx.DataFrame({'SKUCode':['A','B','C','D'],'ListPrice':[1798,2997,1798,999],'SalePrice':[1798,2997,1798,999],'SKUStatus':[1,1,1,0],'CostPrice':[500,773,525,300]})

df2=pdx.DataFrame({'SKUCode':['X','Y','B'],'Status':[0,0,0],'e_date':['31-05-2020','01-06-2020','01-06-2020']})

df1.merge(df2,left_on='SKUCode')

Body:
try this, using outer merge which gives both matching and non-matching records.

In [75]: df_m = df1.merge(df2, on="SKUCode", how='outer')

In [76]: mask = df_m['Status'].isnull()

In [77]: df_m.loc[~mask, 'SKUStatus'] = df_m.loc[~mask, 'Status']

In [78]: df_m[['SKUCode', "ListPrice", "SalePrice", "SKUStatus", "CostPrice"]].fillna(0.0)

output

  SKUCode  ListPrice  SalePrice  SKUStatus  CostPrice
0       A     1798.0     1798.0        1.0      500.0
1       B     2997.0     2997.0        0.0      773.0
2       C     1798.0     1798.0        1.0      525.0
3       D      999.0      999.0        0.0      300.0
4       X        0.0        0.0        0.0        0.0
5       Y        0.0        0.0        0.0        0.0


问:
Inside of MatterialApp. MediaQuery.of() called with a context that does not contain a MediaQuery
I'm trying to set a drawer size dynamically.

```<code>import 'package:flutter/material.dart';
import './screens/tab_screen.dart';

//widgets
import './widgets/main_drawer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: TabWidget(),
        endDrawer: Container(
          width: MediaQuery.of(context).size.width * 0.65,
          child: MainDrawer(),
        ),
      ),
      title: "Ali Azad",
      // routes: {
      //   '/': (_) => TabWidget(),
      // },
    );
  }
}
</code>```

but I have got this error = MediaQuery.of() called with a context that does not contain a MediaQuery.;

答:
If you take a look better in your code, you will see that your build method is called with a context and by the time of that call, there isn't any previous Widget, which mean that your MaterialApp doesn't exist yet when your build is called, so that BuildContext doesn't have any previous MaterialApp, you can solve this just by splitting your code like this:

```<code>class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
      title: "Ali Azad",
    );
  }
}

// This Home Widget will be a child of MaterialApp, and the BuildContext has access to this Material widget.
class Home extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return Scaffold(
      body: TabWidget(),
      endDrawer: Container(
         width: MediaQuery.of(context).size.width * 0.65,
         child: MainDrawer(),
      )
    );
  }
}
</code>```

Or if you don't want to create another Widget, then you should use a Builder widget that will generate a new BuildContext for you. Your Widget would look like this:

```<code>MaterialApp(
  home: Builder(
    build: (BuildContext context) {
      return Scaffold(
        body: TabWidget(),
        endDrawer: Container(
           width: MediaQuery.of(context).size.width * 0.65,
           child: MainDrawer(),
        )
      );
    }
  ),
  title: "Ali Azad",
);
</code>```

Body:
I'm trying to set a drawer size dynamically.

import 'package:flutter/material.dart';
import './screens/tab_screen.dart';

//widgets
import './widgets/main_drawer.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: TabWidget(),
        endDrawer: Container(
          width: MediaQuery.of(context).size.width * 0.65,
          child: MainDrawer(),
        ),
      ),
      title: "Ali Azad",
      // routes: {
      //   '/': (_) => TabWidget(),
      // },
    );
  }
}

but I have got this error = MediaQuery.of() called with a context that does not contain a MediaQuery.;

Body:
If you take a look better in your code, you will see that your build method is called with a context and by the time of that call, there isn't any previous Widget, which mean that your MaterialApp doesn't exist yet when your build is called, so that BuildContext doesn't have any previous MaterialApp, you can solve this just by splitting your code like this:

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
      title: "Ali Azad",
    );
  }
}

// This Home Widget will be a child of MaterialApp, and the BuildContext has access to this Material widget.
class Home extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return Scaffold(
      body: TabWidget(),
      endDrawer: Container(
         width: MediaQuery.of(context).size.width * 0.65,
         child: MainDrawer(),
      )
    );
  }
}

Or if you don't want to create another Widget, then you should use a Builder widget that will generate a new BuildContext for you. Your Widget would look like this:

MaterialApp(
  home: Builder(
    build: (BuildContext context) {
      return Scaffold(
        body: TabWidget(),
        endDrawer: Container(
           width: MediaQuery.of(context).size.width * 0.65,
           child: MainDrawer(),
        )
      );
    }
  ),
  title: "Ali Azad",
);


问:
Multiply dataframe rows based on a datetime condition
I have the following example dataframe:

```<code>df = pd.DataFrame(columns=['Total_concentration'], index=pd.to_datetime([]))
df.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3], ['Total_concentration'])
</code>```

I would like to add a column "Total_flux" which is the "Total_concentration" column multiplied by 2 between the dates 2017-01-02 and 2017-01-03 and the "Total_concentration" column multiplied by 3 between the dates 2017-01-04 and 2017-01-05. I.e. the resulting dataframe would look like the following:

```<code>df2 = pd.DataFrame(columns=['Total_concentration','Total_flux'], index=pd.to_datetime([]))
df2.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1,1], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2,4], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1,3], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3,3], ['Total_concentration','Total_flux'])
</code>```

What is the most effective way to do this?

答:
Use the following code:

```<code>df['Total_flux'] = df.Total_concentration.multiply(pd.cut(df.index.to_series(),
    [pd.Timestamp('2017-01-02'), pd.Timestamp('2017-01-04'), pd.Timestamp('2017-01-06')],
    right=False, labels=[2, 3]).dropna().astype(int), fill_value=1)
</code>```

The idea to compute the new column is to:

cut the index of df into bins:

between 2017-01-02 and 2017-01-04, with label 2,

between 2017-01-04 and 2017-01-06, with label 3
(both ranges open at the right edge),

convert the (Categorical) result to int,

multiply Total_concentration by the above result with
fill_value of 1.

Body:
I have the following example dataframe:

df = pd.DataFrame(columns=['Total_concentration'], index=pd.to_datetime([]))
df.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2], ['Total_concentration'])
df.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3], ['Total_concentration'])

I would like to add a column "Total_flux" which is the "Total_concentration" column multiplied by 2 between the dates 2017-01-02 and 2017-01-03 and the "Total_concentration" column multiplied by 3 between the dates 2017-01-04 and 2017-01-05. I.e. the resulting dataframe would look like the following:

df2 = pd.DataFrame(columns=['Total_concentration','Total_flux'], index=pd.to_datetime([]))
df2.loc[pd.Timestamp(year=2017, month=1, day=1, hour=12)] = pd.Series([1,1], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=2, hour=12)] = pd.Series([2,4], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=3, hour=12)] = pd.Series([3,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=4, hour=12)] = pd.Series([1,3], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=5, hour=12)] = pd.Series([2,6], ['Total_concentration','Total_flux'])
df2.loc[pd.Timestamp(year=2017, month=1, day=6, hour=12)] = pd.Series([3,3], ['Total_concentration','Total_flux'])

What is the most effective way to do this?

Body:
Use the following code:

df['Total_flux'] = df.Total_concentration.multiply(pd.cut(df.index.to_series(),
    [pd.Timestamp('2017-01-02'), pd.Timestamp('2017-01-04'), pd.Timestamp('2017-01-06')],
    right=False, labels=[2, 3]).dropna().astype(int), fill_value=1)

The idea to compute the new column is to:

cut the index of df into bins:

between 2017-01-02 and 2017-01-04, with label 2,

between 2017-01-04 and 2017-01-06, with label 3
(both ranges open at the right edge),

convert the (Categorical) result to int,

multiply Total_concentration by the above result with
fill_value of 1.


问:
jQuery code - IE8 problem
I have this code that changes input fields name attribute value, works great in all major browsers except IE8, IE7 and IE6. For IE the name just stay name="participant_name[{i}]", should be name="participant_name[1]".

```<code>var i = 1;
var input_name = null;
$('.dubl input').each(function () {
   var new_input_name = $(this).attr('name').substring(0, $(this).attr('name').indexOf('['));
   if (input_name !== new_input_name) {
       input_name = new_input_name;
       i = 1;
   }
   $(this).attr('name', input_name + '[' + i + ']');
   i++;
});
</code>```

HTML

```<code><input type="text" name="participant_name[{i}]">
</code>```

答:
use .replace!

here's a quick fiddle example:
http://jsfiddle.net/H5fkq/

ContentLicense: CC BY-SA 3.0

Title: jQuery code - IE8 problem

Body:
I have this code that changes input fields name attribute value, works great in all major browsers except IE8, IE7 and IE6. For IE the name just stay name="participant_name[{i}]", should be name="participant_name[1]".

var i = 1;
var input_name = null;
$('.dubl input').each(function () {
   var new_input_name = $(this).attr('name').substring(0, $(this).attr('name').indexOf('['));
   if (input_name !== new_input_name) {
       input_name = new_input_name;
       i = 1;
   }
   $(this).attr('name', input_name + '[' + i + ']');
   i++;
});

HTML

<input type="text" name="participant_name[{i}]">


问:
Where to access persistance in DDD
I am looking into Domain Driven Design (yes, I am quite late for that party) and so far I have come to the realization that the Domain Model should be the center of the universe. The data persistance is merely a practical detail.

However, if this is true, then I have a hard time figuring out where the communication with the persititance part (e.g. a repository) should be.

For instance, if I want to be able to add a new grade to a student, should I call the repository from inside the student domain model, like this?

```<code>interface IGradeRepository
{
    void SaveGrade(int courseId, string grade);
    // ...other methods
}

class Student
{
    IGradeRepository _gradeRepository;
    List<Grade> _grades = new List<Grade>();

    public Student(IGradeRepository gradeRepository)
    {
        _gradeRepository = gradeRepository;
    }

    int StudentId { get; set; }

    void AddGrade(int courseId, string grade)
    {
        var grade = new Grade(this.StudentId, courseId, grade);
        _grades.Add(grade);

        // Do I put the call to the data persistance here?
        _gradeRepository.SaveGrade(grade);
    }
}
</code>```

As you can see, my best bet is to access the repository from inside the domain model. However, I am not sure if this is the way to go about it. It seems to be one of the things that is left out in many tutorials.

So to summarize: From where do I access the data layer, when doing Domain Driven Design?

Update

As some have commented, it is not clear from my example, how I would access the student class. I would probably do that from a view model or through some sort of use case service.

Example with view model:

```<code>class StudentGradesViewModel
{
    // (...) all sort of VM-stuff

    private Student _student;
    private Course _selectedCourse;

    public void AddGrade(string grade)
    {
        _student.AddGrade(_course.CourseId, grade);
    }
}
</code>```

答:
First of all: The repository should only refer to aggregate. In your case, you have student which can have multiple grades.
So, you repository should always be the persistance for the aggregate, not an entity inside an aggregate.

Here is the solution with the way I would choose:

Aggregate in Domain Layer:

```<code>class Student
{
    List<Grade> _grades = new List<Grade>();
    int StudentId { get; set; }

    public Student()
    {
    }

    void AddGrade(int courseId, string grade)
    {
        var grade = new Grade(this.StudentId, courseId, grade);
        _grades.Add(grade);
    }
}
</code>```

Repository Interface in Domain Layer:

```<code>interface IStudentRepository
{
    void SaveStudent(int studentId);
    // ...other methods
}
</code>```

Of course, as it was mentioned in posts above, the implementation of Repository should take place infrastructure layer.

You should create Application Service or CommandHandler (if you're using CQRS) in order to integrate domain logic and infrstructure:

```<code>class AddGradeService
{
    private readonly IStudentRepository _studentRepository;

    public AddGradeService(IStudentRepository studentRepository)
    {
        _studentRepository = studentRepository;
    }

    void Handle(int studentId, int courseId, string grade)
    {
        Student student = _studentRepository.Get(studentId);
        student.AddGrade(courseId, grade);
        _studentRepository.Save(student);
    }
}
</code>```

This is how it should be done :)
You can also refer to my example od DDD if you want: https://github.com/czarek-szok/DDD.Ecommerce/

Title: Where to access persistance in DDD

Body:
I am looking into Domain Driven Design (yes, I am quite late for that party) and so far I have come to the realization that the Domain Model should be the center of the universe. The data persistance is merely a practical detail.

However, if this is true, then I have a hard time figuring out where the communication with the persititance part (e.g. a repository) should be.

For instance, if I want to be able to add a new grade to a student, should I call the repository from inside the student domain model, like this?

interface IGradeRepository
{
    void SaveGrade(int courseId, string grade);
    // ...other methods
}

class Student
{
    IGradeRepository _gradeRepository;
    List<Grade> _grades = new List<Grade>();

    public Student(IGradeRepository gradeRepository)
    {
        _gradeRepository = gradeRepository;
    }

    int StudentId { get; set; }

    void AddGrade(int courseId, string grade)
    {
        var grade = new Grade(this.StudentId, courseId, grade);
        _grades.Add(grade);

        // Do I put the call to the data persistance here?
        _gradeRepository.SaveGrade(grade);
    }
}

As you can see, my best bet is to access the repository from inside the domain model. However, I am not sure if this is the way to go about it. It seems to be one of the things that is left out in many tutorials.

So to summarize: From where do I access the data layer, when doing Domain Driven Design?

Update

As some have commented, it is not clear from my example, how I would access the student class. I would probably do that from a view model or through some sort of use case service.

Example with view model:

class StudentGradesViewModel
{
    // (...) all sort of VM-stuff

    private Student _student;
    private Course _selectedCourse;

    public void AddGrade(string grade)
    {
        _student.AddGrade(_course.CourseId, grade);
    }
}

Body:
First of all: The repository should only refer to aggregate. In your case, you have student which can have multiple grades.
So, you repository should always be the persistance for the aggregate, not an entity inside an aggregate.

Here is the solution with the way I would choose:

Aggregate in Domain Layer:

class Student
{
    List<Grade> _grades = new List<Grade>();
    int StudentId { get; set; }

    public Student()
    {
    }

    void AddGrade(int courseId, string grade)
    {
        var grade = new Grade(this.StudentId, courseId, grade);
        _grades.Add(grade);
    }
}

Repository Interface in Domain Layer:

interface IStudentRepository
{
    void SaveStudent(int studentId);
    // ...other methods
}

Of course, as it was mentioned in posts above, the implementation of Repository should take place infrastructure layer.

You should create Application Service or CommandHandler (if you're using CQRS) in order to integrate domain logic and infrstructure:

class AddGradeService
{
    private readonly IStudentRepository _studentRepository;

    public AddGradeService(IStudentRepository studentRepository)
    {
        _studentRepository = studentRepository;
    }

    void Handle(int studentId, int courseId, string grade)
    {
        Student student = _studentRepository.Get(studentId);
        student.AddGrade(courseId, grade);
        _studentRepository.Save(student);
    }
}

This is how it should be done :)
You can also refer to my example od DDD if you want: https://github.com/czarek-szok/DDD.Ecommerce/


问:
Error calculating time difference in Python
Quick question. Does someone know why I'am getting an 'Invalid Syntax' error usign this code? Thank you all.</p>

```<code>def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
    return f"{time_difference.hour}:{time_difference.minute}"

get_time_difference(1-1-2020 1:50)
</code>```

答:
```<code>from datetime import datetime

def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
    return f"{time_difference.seconds // 3600}:{time_difference.seconds // 60 % 60}"

print(get_time_difference('1-1-2020', '1:50'))
</code>```

Output

15:50

Body:
Quick question. Does someone know why I'am getting an 'Invalid Syntax' error usign this code? Thank you all.

def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
    return f"{time_difference.hour}:{time_difference.minute}"

get_time_difference(1-1-2020 1:50)

Body:
from datetime import datetime

def get_time_difference(date, time_string):
    time_difference = datetime.now() - datetime.strptime(f"{date} {time_string}", "%d-%m-%Y %H:%M")
    return f"{time_difference.seconds // 3600}:{time_difference.seconds // 60 % 60}"

print(get_time_difference('1-1-2020', '1:50'))

Output

15:50


问:
Error 3358 : The InitiatedType field is missing
Have been using SagePay integration v4 for some months now and since midnight tonight suddenly receiving lots of:

"Error 3358 : The InitiatedType field is missing".

What have SagePay changed?  The Direct Integration document I've got is dated 24/05/19, so over a year old so it's possible that this has been updated but not communicated out

答:
I've heard back from SagePay and this is related to changes that were made this morning relating specifically to using stored credit cards due to changes being implemented by the banks.  This has resulted in additional fields being added.

One point that was made is that Version 4 is considered not suitable for use in production as it is susceptible to having changes implemented without any notice.  This is counter to what I was told last year (the gent I spoke to apologised for this).


问:
Will the JVM ever inline an object's instance variables and methods?
Suppose I have a very tight inner loop, each iteration of which accesses and mutates a single bookkeeping object that stores some simple data about the algorithm and has simple logic for manipulating it

The bookkeeping object is private and final and all of its methods are private, final and @inline. Here's an example (in Scala syntax):

```<code>object Frobnicate {
  private class DataRemaining(val start: Int, val end: Int) {
    @inline private def nextChunk = ....
  }

  def frobnicate {
    // ...
    val bookkeeper = new DataRemaining(0, 1000)
    while( bookeeper.hasData ) {
      val data = bookkeeper.nextChunk
      // ......
    }
  }
 }
</code>```

Will the JVM ever inline the whole DataRemaining object into Frobnicate.frobnicate? That is, will it treat start and end as local variables and inline the nextChunk code directly into frobnicate?

答: In Java it can inline fields and methods in a situation as you have.  It does not eliminate the Object completely, but gets close.  I assume Scala would work similarly.</p>

Body:
Suppose I have a very tight inner loop, each iteration of which accesses and mutates a single bookkeeping object that stores some simple data about the algorithm and has simple logic for manipulating it

The bookkeeping object is private and final and all of its methods are private, final and @inline. Here's an example (in Scala syntax):

object Frobnicate {
  private class DataRemaining(val start: Int, val end: Int) {
    @inline private def nextChunk = ....
  }

  def frobnicate {
    // ...
    val bookkeeper = new DataRemaining(0, 1000)
    while( bookeeper.hasData ) {
      val data = bookkeeper.nextChunk
      // ......
    }
  }
 }

Will the JVM ever inline the whole DataRemaining object into Frobnicate.frobnicate? That is, will it treat start and end as local variables and inline the nextChunk code directly into frobnicate?


问:
How to set a child item of a QTreeWidget tobe auto selected and highlighted when click on its parent
Here is my code ,it will work for sometime but most times don't. I have searched for this but the solutions just don't work.

(I am using pyside2, not pyqt5)

Click parent

AutoSelect child

```<code>import sys
import time

from PySide2.QtWidgets import QWidget,QPushButton,QApplication,QListWidget,QGridLayout,\
QLabel,QMainWindow,QLineEdit,QScrollArea,QVBoxLayout,QMessageBox,QComboBox,QMenu,QAction,\
QDialog,QTreeWidget,QTreeWidgetItem,QSlider,QAbstractItemView,QHBoxLayout
from PySide2.QtCore import QTimer,QDateTime,QSize,Qt,Signal,Slot,QThread,QMutex,QMutexLocker,QItemSelectionModel
from PySide2.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.resize(320, 300)
        self.setWindowTitle("--")
        self.setStyleSheet(
            """
            QMainWindow
            {
                background-color:white;
                color:white;
                margin:0px
            }
            """
        )
        self.InitializeWindow()

    def InitializeWindow(self):
        self.center = QWidget(self)
        self.center.setGeometry(0, 0, 320, 300);
        layout=QHBoxLayout()

        self.tree=QTreeWidget()
        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels(['func'])

        root1=QTreeWidgetItem(self.tree)
        root1.setText(0,'-A')

        self.tree.setColumnWidth(0,100)
        self.child1_1=QTreeWidgetItem(root1)
        self.child1_1.setText(0,'--aa')

        self.child1_2=QTreeWidgetItem(root1)
        self.child1_2.setText(0,'--bb')

        root2=QTreeWidgetItem(self.tree)
        root2.setText(0,'-B')

        self.child2_1=QTreeWidgetItem(root2)
        self.child2_1.setText(0,'--cc')

        self.child2_2=QTreeWidgetItem(root2)
        self.child2_2.setText(0,'--dd')

        self.child2_3=QTreeWidgetItem(root2)
        self.child2_3.setText(0,'--ee')

        self.tree.addTopLevelItem(root1)
        self.tree.addTopLevelItem(root2)

        self.area_op=QWidget()
        self.area_op.setMinimumWidth(100)
        self.area_op.setStyleSheet(
            '''QWidget
            {
                background-color:white;
                color:white;
                font-size:15px;
                border:0px solid #708090;
                margin:0px
            }'''
            )

        self.tree.currentItemChanged.connect(self.tree_onClick)

        layout.addWidget(self.tree)
        layout.addWidget(self.area_op)
        self.center.setLayout(layout)
        self.show()

    def tree_onClick(self):
        getSelected = self.tree.currentItem()
        #print(str(sys._getframe().f_lineno),getSelected)
        if getSelected:
            if(getSelected.text(0)=='--cc'):
                pass
            elif(getSelected.text(0)=="-A"):
                getSelected.setExpanded(True)
                self.tree.setCurrentItem(self.child1_1)
            elif(getSelected.text(0)=="-B"):
                getSelected.setExpanded(True)
                self.tree.setCurrentItem(self.child2_1,0,QItemSelectionModel.Select)
                if self.child2_1.isSelected()==False:
                    self.child2_1.setSelected(True)
            else:
                pass
        else:
            print(str(sys._getframe().f_lineno),"tree error ",getSelected)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())
</code>```

答:
If you want to automatically select the first child, you shouldn't check for the item text, but if it actually has child items.

Also, using currentItemChanged might not be a good idea, as that signal might create some inconstinstency if you're trying to change the current item as its result (which might be the source of your problem, even if I wasn't able to reproduce it).

The solution is to use the itemClicked() signal instead, and also take advantage of its first argument (the clicked item).

```<code>        # ...
        self.tree.itemClicked.connect(self.tree_onClick)
        # ...

    def tree_onClick(self, item, column):
        if item.childCount():
            self.tree.setCurrentItem(item.child(0))
</code>```

Body:
Here is my code ,it will work for sometime but most times don't. I have searched for this but the solutions just don't work.

(I am using pyside2, not pyqt5)

Click parent

AutoSelect child

import sys
import time

from PySide2.QtWidgets import QWidget,QPushButton,QApplication,QListWidget,QGridLayout,\
QLabel,QMainWindow,QLineEdit,QScrollArea,QVBoxLayout,QMessageBox,QComboBox,QMenu,QAction,\
QDialog,QTreeWidget,QTreeWidgetItem,QSlider,QAbstractItemView,QHBoxLayout
from PySide2.QtCore import QTimer,QDateTime,QSize,Qt,Signal,Slot,QThread,QMutex,QMutexLocker,QItemSelectionModel
from PySide2.QtGui import *

class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.resize(320, 300)
        self.setWindowTitle("--")
        self.setStyleSheet(
            """
            QMainWindow
            {
                background-color:white;
                color:white;
                margin:0px
            }
            """
        )
        self.InitializeWindow()

    def InitializeWindow(self):
        self.center = QWidget(self)
        self.center.setGeometry(0, 0, 320, 300);
        layout=QHBoxLayout()

        self.tree=QTreeWidget()
        self.tree.setColumnCount(1)
        self.tree.setHeaderLabels(['func'])

        root1=QTreeWidgetItem(self.tree)
        root1.setText(0,'-A')

        self.tree.setColumnWidth(0,100)
        self.child1_1=QTreeWidgetItem(root1)
        self.child1_1.setText(0,'--aa')

        self.child1_2=QTreeWidgetItem(root1)
        self.child1_2.setText(0,'--bb')

        root2=QTreeWidgetItem(self.tree)
        root2.setText(0,'-B')

        self.child2_1=QTreeWidgetItem(root2)
        self.child2_1.setText(0,'--cc')

        self.child2_2=QTreeWidgetItem(root2)
        self.child2_2.setText(0,'--dd')

        self.child2_3=QTreeWidgetItem(root2)
        self.child2_3.setText(0,'--ee')

        self.tree.addTopLevelItem(root1)
        self.tree.addTopLevelItem(root2)

        self.area_op=QWidget()
        self.area_op.setMinimumWidth(100)
        self.area_op.setStyleSheet(
            '''QWidget
            {
                background-color:white;
                color:white;
                font-size:15px;
                border:0px solid #708090;
                margin:0px
            }'''
            )

        self.tree.currentItemChanged.connect(self.tree_onClick)

        layout.addWidget(self.tree)
        layout.addWidget(self.area_op)
        self.center.setLayout(layout)
        self.show()

    def tree_onClick(self):
        getSelected = self.tree.currentItem()
        #print(str(sys._getframe().f_lineno),getSelected)
        if getSelected:
            if(getSelected.text(0)=='--cc'):
                pass
            elif(getSelected.text(0)=="-A"):
                getSelected.setExpanded(True)
                self.tree.setCurrentItem(self.child1_1)
            elif(getSelected.text(0)=="-B"):
                getSelected.setExpanded(True)
                self.tree.setCurrentItem(self.child2_1,0,QItemSelectionModel.Select)
                if self.child2_1.isSelected()==False:
                    self.child2_1.setSelected(True)
            else:
                pass
        else:
            print(str(sys._getframe().f_lineno),"tree error ",getSelected)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())

Body:
If you want to automatically select the first child, you shouldn't check for the item text, but if it actually has child items.

Also, using currentItemChanged might not be a good idea, as that signal might create some inconstinstency if you're trying to change the current item as its result (which might be the source of your problem, even if I wasn't able to reproduce it).

The solution is to use the itemClicked() signal instead, and also take advantage of its first argument (the clicked item).

        # ...
        self.tree.itemClicked.connect(self.tree_onClick)
        # ...

    def tree_onClick(self, item, column):
        if item.childCount():
            self.tree.setCurrentItem(item.child(0))


问:
How to create an alert in a Excel cell based on a condition
I have an account with a brokerage company. When am attempting to sell a limit stock, I get the following error. "The limit price you have entered is too far away from the Bid Price for this security. Please use the following guidelines when entering your limit price: For sell limit orders in which your limit price is above the current Bid Price, Your limit price can be no more than 50% away from the Bid Price. I have a Google sheet with columns with stocks prices etc. Would you have any ideas how to create an alert text as below?

STOCK Symbol: TEST

My Limit Price: $40 (Cell: A1)

Current bid price: $21 (Cell : B1)

In Cell C1: How can I create an alert to appear "fill-limit-order-transaction-now" once the condition to add the limit sell transaction "limit price can be no more than 50% away from the Bid Price" is met.

What I am struggling with is how to come up with a relationship between the target price and the condition..

no more than 50% ....> $21 + 50% of $21...> $31.50... so how can I link this number to my target $40? to come up with an alert condition so I can create a future sell transaction? Thanks!

答:
To summarize what I have understood from your question:

1. You have a product/stock which has a maximum selling price of $40.

2. You want to be alerted to a potential sale when you receive a bid higher than $26.66.

If my understanding is correct, please check if this formula works for you:

My Limit Price: $40 (Cell: A1)

Current bid price: $21 (Cell : B1)

Formula in cell C1:

```<code>=IF((B1+(B1*50%))>A1,"fill-limit-order-transaction-now","Threshold not reached")
</code>```

Body:
To summarize what I have understood from your question:

1. You have a product/stock which has a maximum selling price of $40.

2. You want to be alerted to a potential sale when you receive a bid higher than $26.66.

If my understanding is correct, please check if this formula works for you:

My Limit Price: $40 (Cell: A1)

Current bid price: $21 (Cell : B1)

Formula in cell C1:

=IF((B1+(B1*50%))>A1,"fill-limit-order-transaction-now","Threshold not reached")


问:
Select statement with columns that are select statement but not subqueries
SQL Masters,

I don't understand part of this query. In the select statement there are what look like independent 'select statements'almost like a function. This code is vendor written Blackbaud CRM. As independent code there is no join in the code for the info they bring into the data set as you can see in the from clause. One last odd item is that in the column aliased Spouse_id the column SPOUSE.RECIPROCALCONSTITUENTID dose not even exist in the table referred to. Any BBCRM people out there that can explain this?

Thanks

    select
        CONSTITUENT.ID,
        CONSTITUENT.ISORGANIZATION,
        CONSTITUENT.KEYNAME,
        CONSTITUENT.FIRSTNAME,
        CONSTITUENT.MIDDLENAME,
        CONSTITUENT.MAIDENNAME,
        CONSTITUENT.NICKNAME,
        (select SPOUSE.RECIPROCALCONSTITUENTID
         from dbo.RELATIONSHIP as SPOUSE
         where SPOUSE.RELATIONSHIPCONSTITUENTID = CONSTITUENT.ID
           and SPOUSE.ISSPOUSE = 1) as [SPOUSE_ID],
        (select MARITALSTATUSCODE.DESCRIPTION
         from dbo.MARITALSTATUSCODE
         where MARITALSTATUSCODE.ID = CONSTITUENT.MARITALSTATUSCODEID) as [MARITALSTATUSCODEID_TRANSLATION]
    From
        dbo.constituent
    left join
        dbo.ORGANIZATIONDATA on ORGANIZATIONDATA.ID = CONSTITUENT.ID
    where
       (CONSTITUENT.ISCONSTITUENT = 1)
```

答:
These are correlated subqueries.  Although there is no explicit JOIN, there is a link to the outer table which behaves like a join (although more constrained than explicit JOINs):

```<code>(select SPOUSE.RECIPROCALCONSTITUENTID
 from dbo.RELATIONSHIP as SPOUSE
 where SPOUSE.RELATIONSHIPCONSTITUENTID = CONSTITUENT.ID AND
-------^ correlation clause connecting to outer table
       SPOUSE.ISSPOUSE = 1
) as [SPOUSE_ID],
</code>```

This behaves like a LEFT JOIN.  If no rows match, then the result is NULL.

Note that in this context, the correlated subquery is also a scalar subquery.  That means that it returns exactly one column and at most one row.

If the query returned more than one column, you would get a compile-time error on the query.  If the query returns more than one row, you will get a run-time error on the query.

Body:
These are correlated subqueries.  Although there is no explicit JOIN, there is a link to the outer table which behaves like a join (although more constrained than explicit JOINs):

(select SPOUSE.RECIPROCALCONSTITUENTID
 from dbo.RELATIONSHIP as SPOUSE
 where SPOUSE.RELATIONSHIPCONSTITUENTID = CONSTITUENT.ID AND
-------^ correlation clause connecting to outer table
       SPOUSE.ISSPOUSE = 1
) as [SPOUSE_ID],

This behaves like a LEFT JOIN.  If no rows match, then the result is NULL.

Note that in this context, the correlated subquery is also a scalar subquery.  That means that it returns exactly one column and at most one row.

If the query returned more than one column, you would get a compile-time error on the query.  If the query returns more than one row, you will get a run-time error on the query.


问:
Read and write complex numbers from a file in C++ (translation from C)?
I have a big problem. I get a task in which I should write a program in C++, which I previously write in C. This program in C++ must read complex numbers from a file and write them. I must create a class and real and imaginary parts must be private. I also must create operators << and >>. I don't know what I should do. This is my input file
data.txt

```<code>(2.3,5) (7.12,-2.91) (7.99,8)
(5,3.25)
</code>```

My output file should be
result.txt

```<code>2.3, 5
7.12 -2.91
</code>```

In C I use these functions

```<code>void readZ(FILE *wp, double *a, double *b)
{
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,a,&c,b,&c,&c));

}
int writeZ(FILE *wp, double complex z)
{
    fprintf(wp, "%.2f, %.2f\n", creal(z), cimag(z));

    return 1;
}
</code>```

Now I must do this in C++
This is my code
main.cpp

```<code>#include <iostream>
#include <fstream>
#include <cstdlib>
#include "read.h"

using namespace std;

int main(int argc, char* argv[])
{
    ifstream inFile;
    ostream  outFile;

    char c;
    ifstream read(argv[1]);
    if (!read)
        { cerr << "Open error: " << argv[1] << endl; exit(1);}
    ofstream write(argv[2]);
    if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
    while(read.get(c))
        write.put(c);

    Complex_num x1;
    read >> x1;
    write << x1;

    inFile.close();
    outFile.close();

    return 0;
}
</code>```

read.h

```<code>#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }

    friend std::ostream& operator<<(std::ostream&, const Complex_num&)
    {
        cout << real << '.' << imag << ',' << ' ';
    }
    friend std::istream& operator>>(std::istream&, Complex_num&){
        char c;
        cin>>c>>&real>>c>>&imag>>c>>c;
    }
};
</code>```

read.cpp

```<code>#include <iostream>
#include <fstream>
#include <cstdlib>
#include "read.h"

using namespace std;

Complex_num::Complex_num(double r, double i)
{
    real=r;
    imag=i;
}
</code>```

I have so many errors I dont even know what I should do

```<code>g++ -c read.cpp -Wall
In file included from read.cpp:4:0:
read.h: In function ‘std::ostream& operator<<(std::ostream&, const Complex_num&)’:
read.h:18:17: error: invalid use of non-static data member ‘Complex_num::real’
         cout << real << '.' << imag << ',' << ' ';
                 ^~~~
read.h:8:12: note: declared here
     double real, imag;
            ^~~~
read.h:18:32: error: invalid use of non-static data member ‘Complex_num::imag’
         cout << real << '.' << imag << ',' << ' ';
                                ^~~~
read.h:8:18: note: declared here
     double real, imag;
                  ^~~~
read.h:19:5: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
read.h: In function ‘std::istream& operator>>(std::istream&, Complex_num&)’:
read.h:22:18: error: invalid use of non-static data member ‘Complex_num::real’
         cin>>c>>&real>>c>>&imag>>c>>c;
                  ^~~~
read.h:8:12: note: declared here
     double real, imag;
            ^~~~
read.h:22:28: error: invalid use of non-static data member ‘Complex_num::imag’
         cin>>c>>&real>>c>>&imag>>c>>c;
                            ^~~~
read.h:8:18: note: declared here
     double real, imag;
                  ^~~~
read.h:23:5: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
read.cpp: At global scope:
read.cpp:8:1: error: prototype for ‘Complex_num::Complex_num(double, double)’ does not match any in class ‘Complex_num’
 Complex_num::Complex_num(double r, double i)
 ^~~~~~~~~~~
In file included from read.cpp:4:0:
read.h:7:7: error: candidates are: constexpr Complex_num::Complex_num(Complex_num&&)
 class Complex_num {
       ^~~~~~~~~~~
read.h:7:7: error:                 constexpr Complex_num::Complex_num(const Complex_num&)
read.h:10:5: error:                 Complex_num::Complex_num()
     Complex_num(){
     ^~~~~~~~~~~
</code>```

答:
```<code>read.h:18:17: error: invalid use of non-static data member ‘Complex_num::real’
         cout << real << '.' << imag << ',' << ' ';
</code>```

Your friend operator functions are not member functions, so they dont have access to member variables. You should make use of their parameters:

```<code>friend std::ostream& operator<<(std::ostream& os,  const Complex_num& c)
{
    os << c.real << '.' << c.imag << ',' << ' ';
    return os;
}
friend std::istream& operator>>(std::istream& is, Complex_num& cn){
    char c;
    is>>c>>cn.real>>c>>cn.imag>>c>>c;
    return is;
}
</code>```

Body:
I have a big problem. I get a task in which I should write a program in C++, which I previously write in C. This program in C++ must read complex numbers from a file and write them. I must create a class and real and imaginary parts must be private. I also must create operators << and >>. I don't know what I should do. This is my input file
data.txt

(2.3,5) (7.12,-2.91) (7.99,8)
(5,3.25)

My output file should be
result.txt

2.3, 5
7.12 -2.91

In C I use these functions

void readZ(FILE *wp, double *a, double *b)
{
    char c;
    assert(fscanf(wp,"%c%lg%c%lg%c%c",&c,a,&c,b,&c,&c));

}
int writeZ(FILE *wp, double complex z)
{
    fprintf(wp, "%.2f, %.2f\n", creal(z), cimag(z));

    return 1;
}

Now I must do this in C++
This is my code
main.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
#include "read.h"

using namespace std;

int main(int argc, char* argv[])
{
    ifstream inFile;
    ostream  outFile;

    char c;
    ifstream read(argv[1]);
    if (!read)
        { cerr << "Open error: " << argv[1] << endl; exit(1);}
    ofstream write(argv[2]);
    if(!write) { cerr << "Open error: " << argv[2] << endl; exit(2);}
    while(read.get(c))
        write.put(c);

    Complex_num x1;
    read >> x1;
    write << x1;

    inFile.close();
    outFile.close();

    return 0;
}

read.h

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;

class Complex_num {
    double real, imag;
public:
    Complex_num(){
    real=0;
    imag=0;
    }

    friend std::ostream& operator<<(std::ostream&, const Complex_num&)
    {
        cout << real << '.' << imag << ',' << ' ';
    }
    friend std::istream& operator>>(std::istream&, Complex_num&){
        char c;
        cin>>c>>&real>>c>>&imag>>c>>c;
    }
};

read.cpp

#include <iostream>
#include <fstream>
#include <cstdlib>
#include "read.h"

using namespace std;

Complex_num::Complex_num(double r, double i)
{
    real=r;
    imag=i;
}

I have so many errors I dont even know what I should do

g++ -c read.cpp -Wall
In file included from read.cpp:4:0:
read.h: In function ‘std::ostream& operator<<(std::ostream&, const Complex_num&)’:
read.h:18:17: error: invalid use of non-static data member ‘Complex_num::real’
         cout << real << '.' << imag << ',' << ' ';
                 ^~~~
read.h:8:12: note: declared here
     double real, imag;
            ^~~~
read.h:18:32: error: invalid use of non-static data member ‘Complex_num::imag’
         cout << real << '.' << imag << ',' << ' ';
                                ^~~~
read.h:8:18: note: declared here
     double real, imag;
                  ^~~~
read.h:19:5: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
read.h: In function ‘std::istream& operator>>(std::istream&, Complex_num&)’:
read.h:22:18: error: invalid use of non-static data member ‘Complex_num::real’
         cin>>c>>&real>>c>>&imag>>c>>c;
                  ^~~~
read.h:8:12: note: declared here
     double real, imag;
            ^~~~
read.h:22:28: error: invalid use of non-static data member ‘Complex_num::imag’
         cin>>c>>&real>>c>>&imag>>c>>c;
                            ^~~~
read.h:8:18: note: declared here
     double real, imag;
                  ^~~~
read.h:23:5: warning: no return statement in function returning non-void [-Wreturn-type]
     }
     ^
read.cpp: At global scope:
read.cpp:8:1: error: prototype for ‘Complex_num::Complex_num(double, double)’ does not match any in class ‘Complex_num’
 Complex_num::Complex_num(double r, double i)
 ^~~~~~~~~~~
In file included from read.cpp:4:0:
read.h:7:7: error: candidates are: constexpr Complex_num::Complex_num(Complex_num&&)
 class Complex_num {
       ^~~~~~~~~~~
read.h:7:7: error:                 constexpr Complex_num::Complex_num(const Complex_num&)
read.h:10:5: error:                 Complex_num::Complex_num()
     Complex_num(){
     ^~~~~~~~~~~

Body:
read.h:18:17: error: invalid use of non-static data member ‘Complex_num::real’
         cout << real << '.' << imag << ',' << ' ';

Your friend operator functions are not member functions, so they dont have access to member variables. You should make use of their parameters:

friend std::ostream& operator<<(std::ostream& os,  const Complex_num& c)
{
    os << c.real << '.' << c.imag << ',' << ' ';
    return os;
}
friend std::istream& operator>>(std::istream& is, Complex_num& cn){
    char c;
    is>>c>>cn.real>>c>>cn.imag>>c>>c;
    return is;
}


问:
EMF: External Interface as Supertype in Model
Is it possible to use a manually created Interface from another plug-in as a supertype in an emf-model?

I tried adding the Interface as an EData Type and using the instance type name to point to the externeal interface, which worked fine.
But I cannot select it as a supertype in the Model.

The methods which the interface wants are already satisfied in the model entity.

答: Create a new EClass with "Instance Type Name" set to "my.qualified.name.to.interface" and "interface" set to "true"; and then your second EClass can set this first EClass as its supertype, and the generated EClass will extend your Java interface.</p>


问:
Error running android: Gradle project sync failed. Please fix your project and try again
Android Studio (1.2 RC0) keeps telling me
Error running android: Gradle project sync failed. Please fix your project and try again.
How can I find out what the problem is? Unfortunately the solutions from this SO thread did not help.

答: Delete .gradle folder(root directory) and build folder(project directory) and then invalidate caches/restart android studio, run your project again hopefully it will work. It might take some time for the background tasks. In some countries, you may need to turn on the VPN to download.</p>


问:
Select a Column in SQL not in Group By
I have been trying to find some info on how to select a non-aggregate column that is not contained in the Group By statement in SQL, but nothing I've found so far seems to answer my question. I have a table with three columns that I want from it. One is a create date, one is a ID that groups the records by a particular Claim ID, and the final is the PK. I want to find the record that has the max creation date in each group of claim IDs. I am selecting the MAX(creation date), and Claim ID (cpe.fmgcms_cpeclaimid), and grouping by the Claim ID. But I need the PK from these records (cpe.fmgcms_claimid), and if I try to add it to my select clause, I get an error. And I can't add it to my group by clause because then it will throw off my intended grouping. Does anyone know any workarounds for this? Here is a sample of my code:

```<code>Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid
</code>```

This is the result I'd like to get:

```<code>Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, cpe.fmgcms_claimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid
</code>```

答:
Thing I like to do is to wrap addition columns in aggregate function, like max().
It works very good when you don't expect duplicate values.

```<code>Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, MAX(cpe.fmgcms_claimid) As fmgcms_claimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid
</code>```

Title: Select a Column in SQL not in Group By

Body:
I have been trying to find some info on how to select a non-aggregate column that is not contained in the Group By statement in SQL, but nothing I've found so far seems to answer my question. I have a table with three columns that I want from it. One is a create date, one is a ID that groups the records by a particular Claim ID, and the final is the PK. I want to find the record that has the max creation date in each group of claim IDs. I am selecting the MAX(creation date), and Claim ID (cpe.fmgcms_cpeclaimid), and grouping by the Claim ID. But I need the PK from these records (cpe.fmgcms_claimid), and if I try to add it to my select clause, I get an error. And I can't add it to my group by clause because then it will throw off my intended grouping. Does anyone know any workarounds for this? Here is a sample of my code:

Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid

This is the result I'd like to get:

Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, cpe.fmgcms_claimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid

Body:
Thing I like to do is to wrap addition columns in aggregate function, like max().
It works very good when you don't expect duplicate values.

Select MAX(cpe.createdon) As MaxDate, cpe.fmgcms_cpeclaimid, MAX(cpe.fmgcms_claimid) As fmgcms_claimid
from Filteredfmgcms_claimpaymentestimate cpe
where cpe.createdon < 'reportstartdate'
group by cpe.fmgcms_cpeclaimid


问:
Securely serving up data via API to app and the residing site
I'm not quite sure if an API is the way to go with this, so a little background.

I have been building up a back end which has a very useful set of data and tools for someone to run a site. The front end also uses the same data to show to customers, as one would expect. A mobile app could probably be added in the near future to enable changes to be made to the site, via the app. But the back end can potentially go onto any website like a standard script (ie. it is not centrally stored nor does any data go back and forth between the client and us).

So I thought that the best way around this would be to make an API for the site. Naturally for an app to access the API, it would need a key to authenticate with the API (which the end user can set via their back end). However, I would like the back and front ends to use the API to access the same data so nothing needs to be written twice.

I'm sure it is clear that APIs are a new thing to me, which they are. But, I am trying to improve and adapt my coding to be more efficient.

I thought perhaps that the API could perhaps do some checks from the location of the query to see if it were local request (back/front end) or via an app (which uses a key + user authentication). So how would one go about ensuring that the back and front end could securely access the API, while no one can access it via spoofing. I imagine the checks could be on the lines of the requesting URL, but I am worried that this could be spoofed or other things (that could be checked) could be spoofed. What is the best way to allow local access? Is there anything that can't be spoofed?

I know I could write in a key into the code, but since the code is distributed, I don't want this access key to be public - nor do I want to manually change the key for each site - and nor do I really want the end user to enter some random letters and numbers during setup.

答: You should use a public/private key. Your front/back end's, mobile versions, or even 3rd party developers will then use the their keys to authenticate each other.</p>


问:
how to change NextJS root path page
I am using next js for my toy project.

if nextjs is requested url that is root path, It find page named index.js in the pages folder.

However, I want to show user the page named home.js, not index.js when they request root url.

How can I change it? I guess It can be resolve if I custom next js server. But I want to more simple way. Is it possible?

答:
This is possible without using a custom server, but the caveat is you have to use experimental features redirects or rewrites depending on how you want to build your home.js page.

For example if you want to just redirect the user to /home when they visit the root / path, you can define a redirect rule in next.config.js in the root dir of your project.

// in next.config.js (should be located in the root of your project if not create one)
module.exports = {
  experimental: {
    async redirects() {
      return [
        { source: '/', destination: '/home', permanent: true }, // a permanent redirect
      ];
    },
  },
};
```

However, if you plan to take your project to production I suggest using a custom server for now, make use of the redirects and rewrites features when they become available in stable branch.

Title: how to change NextJS root path page

Body:
This is possible without using a custom server, but the caveat is you have to use experimental features redirects or rewrites depending on how you want to build your home.js page.

For example if you want to just redirect the user to /home when they visit the root / path, you can define a redirect rule in next.config.js in the root dir of your project.

// in next.config.js (should be located in the root of your project if not create one)
module.exports = {
  experimental: {
    async redirects() {
      return [
        { source: '/', destination: '/home', permanent: true }, // a permanent redirect
      ];
    },
  },
};

However, if you plan to take your project to production I suggest using a custom server for now, make use of the redirects and rewrites features when they become available in stable branch.


问:
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>```

答:
Instead of storing true or false inside the checked variable, you should store the value inside of checked. Like this:

```<code>const onChangeAttribute = (value) => {
  console.log(value);
  setCheckBoxChecked(value);
};
</code>```

And now while rendering the checkbox you should check if checked is equal to the name of that checkbox like this:

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

This should resolve your issue.

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:
Instead of storing true or false inside the checked variable, you should store the value inside of checked. Like this:

const onChangeAttribute = (value) => {
  console.log(value);
  setCheckBoxChecked(value);
};

And now while rendering the checkbox you should check if checked is equal to the name of that checkbox like this:

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

This should resolve your issue.


问:
selenium isn't loading the page
```<code>from selenium import webdriver
driver= webdriver.Chrome()
driver.get('https://www.realestate.com.au/sold/') #opens normally but anything I search for doesn't load
driver.get('https://www.realestate.com.au/sold/in-alice+springs+-+greater+region%2c+nt%3b/list-1')
</code>```

The website opens and I don't get any captcha or block but the page doesn't load

答: I guess they are blocking the use of selenium, see the related request is returning 429. Maybe you can a way to escape from this.

Title: selenium isn't loading the page

Body:
from selenium import webdriver
driver= webdriver.Chrome()
driver.get('https://www.realestate.com.au/sold/') #opens normally but anything I search for doesn't load
driver.get('https://www.realestate.com.au/sold/in-alice+springs+-+greater+region%2c+nt%3b/list-1')

The website opens and I don't get any captcha or block but the page doesn't load