问:
Checkmark on TableView is repeating when scrolling
Edit:
Added an else statement to remove the checkmark. However, now, it doesn't repeat the checkmarks anymore, but if two or more cells are marked and I scroll down and back up, it removes all of them except one. Any ideas why? I am having a hard time understanding cell recycling, when this happens.

I've been pulling my hair out at this problem, as I am just not able to figure it out. Any pointers or help would be greatly appreciated.

Everytime I choose a cell and scroll, it repeats the checkmark randomly. I am deciding if a cell needs a checkmark, by checking the indexPath.row with an array that contains the indexPath.row + 1.

Updating the titles and descriptions when scrolling works just fine, it's just the checkmarks that are acting up.

This is my current code for cellForRowAtIndexPath:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"KnuterItem";
    if([s.taskArray valueForKey:@"TaskData"] != [NSNull null])
    {
        KJBasicCell *cell = (KJBasicCell*)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

        // Add utility buttons
        NSMutableArray *rightUtilityButtons = [NSMutableArray new];

        [rightUtilityButtons sw_addUtilityButtonWithColor:
         [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                    title:@"Les mer"];

        cell.rightUtilityButtons = rightUtilityButtons;
        cell.delegate = self;

        if (cell == nil) {

            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"KnuterItem" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }

        NSDictionary    *item = [s.taskArray objectAtIndex:indexPath.row];

        if([item objectForKey:@"Title"] != [NSNull null])
            cell.titleLabel.text = [item objectForKey:@"Title"];
                if(s.textColor)
                    cell.titleLabel.textColor = s.textColor;

        if([item objectForKey:@"Description"] != [NSNull null]){
            if (s.isNotAutoRowHeight == 0) {
                cell.descLabel.numberOfLines = 0;
            } else {
                cell.descLabel.numberOfLines = 1;
            }
            cell.descLabel.text = [item objectForKey:@"Description"];
                if(s.textColor)
                    cell.descLabel.textColor = s.textColor;
            cell.descriptionText = [item objectForKey:@"Description"];
        }

        if([[s.selfArray valueForKey:@"CheckStat"] isEqualToString:@"(null)"])
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else if([[s.selfArray valueForKey:@"CheckStat"] length] == 0)
        {
            if ([[item objectForKey:@"CheckStat"] containsString:@"1"])
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            else
                cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else
        {
            NSLog(@"array: %@", [s.selfArray valueForKey:@"CheckStat"]);
            for(int i = 0; i < [[[s.selfArray valueForKey:@"CheckStat"] componentsSeparatedByString:@","] count]; i++)
            {
                NSString    *checkedNumStr = [[[s.selfArray valueForKey:@"CheckStat"] componentsSeparatedByString:@","] objectAtIndex:i];
                if ([checkedNumStr intValue] == indexPath.row + 1)
                        cell.accessoryType = UITableViewCellAccessoryCheckmark;
                else
                    cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }

        return cell;
    }
    else
        return  nil;
}
</code>```

didSelectRowAtIndex:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(cell.accessoryType == UITableViewCellAccessoryCheckmark)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CheckStatStr = nil;
    for(int i = 0; i < [s.taskArray count]; i++)
    {
        NSIndexPath *eachPath = [NSIndexPath indexPathForRow:i inSection:0] ;
        UITableViewCell *eachCell = [tableView cellForRowAtIndexPath:eachPath];
        if(eachCell.accessoryType == UITableViewCellAccessoryCheckmark)
        {
            if([CheckStatStr length] == 0 || !CheckStatStr)
            {
                CheckStatStr = [[NSMutableString alloc] init];
                [CheckStatStr setString:(NSString*)[NSString stringWithFormat:@"%d",i+1]];
            }
            else
                [CheckStatStr appendString:[NSString stringWithFormat:@",%d",i+1]];
        }
    }
    if(CheckStatStr){
        s.OldCheckStatStr = [s.selfArray valueForKey:@"CheckStat"];
        [s.selfArray setValue:CheckStatStr forKey:@"CheckStat"];
    }else{
        [s.selfArray setValue:@"0" forKey:@"CheckStat"];
    }
}
</code>```

答:
How I solve This Issue in Swift 5

Main Reason of repeating checkmark is cell reusable . then displaying cell resuse and checkmark Still Apear . How I resolve this issue :

```<code>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.schedulTable.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        as! scheduleCell

    cell.timeLable.text = self.timeArray[indexPath.row]
    // here is the code which clear checkmark on reuse
    if item.num >= 0 && item.isSelected == true{
        if item.num == indexPath.row{
            cell.accessoryType = .checkmark
        }else{
             cell.accessoryType = .none
        }
    }

       return cell
   }

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 selected_Time = self.timeArray[indexPath.row]
    item.isSelected = true
   item.num = indexPath.row
    schedulTable.cellForRow(at: indexPath)?.accessoryType = .checkmark
  //schedulTable.reloadData()

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    schedulTable.cellForRow(at: indexPath)?.accessoryType = .none
}

struct Item {
 var num : Int
 var isSelected : Bool
init() {
    num = -1
    isSelected = false
}}
</code>```

Body:
Edit:
Added an else statement to remove the checkmark. However, now, it doesn't repeat the checkmarks anymore, but if two or more cells are marked and I scroll down and back up, it removes all of them except one. Any ideas why? I am having a hard time understanding cell recycling, when this happens.

I've been pulling my hair out at this problem, as I am just not able to figure it out. Any pointers or help would be greatly appreciated.

Everytime I choose a cell and scroll, it repeats the checkmark randomly. I am deciding if a cell needs a checkmark, by checking the indexPath.row with an array that contains the indexPath.row + 1.

Updating the titles and descriptions when scrolling works just fine, it's just the checkmarks that are acting up.

This is my current code for cellForRowAtIndexPath:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"KnuterItem";
    if([s.taskArray valueForKey:@"TaskData"] != [NSNull null])
    {
        KJBasicCell *cell = (KJBasicCell*)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];

        // Add utility buttons
        NSMutableArray *rightUtilityButtons = [NSMutableArray new];

        [rightUtilityButtons sw_addUtilityButtonWithColor:
         [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                    title:@"Les mer"];

        cell.rightUtilityButtons = rightUtilityButtons;
        cell.delegate = self;

        if (cell == nil) {

            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"KnuterItem" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }

        NSDictionary    *item = [s.taskArray objectAtIndex:indexPath.row];

        if([item objectForKey:@"Title"] != [NSNull null])
            cell.titleLabel.text = [item objectForKey:@"Title"];
                if(s.textColor)
                    cell.titleLabel.textColor = s.textColor;

        if([item objectForKey:@"Description"] != [NSNull null]){
            if (s.isNotAutoRowHeight == 0) {
                cell.descLabel.numberOfLines = 0;
            } else {
                cell.descLabel.numberOfLines = 1;
            }
            cell.descLabel.text = [item objectForKey:@"Description"];
                if(s.textColor)
                    cell.descLabel.textColor = s.textColor;
            cell.descriptionText = [item objectForKey:@"Description"];
        }

        if([[s.selfArray valueForKey:@"CheckStat"] isEqualToString:@"(null)"])
        {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else if([[s.selfArray valueForKey:@"CheckStat"] length] == 0)
        {
            if ([[item objectForKey:@"CheckStat"] containsString:@"1"])
                cell.accessoryType = UITableViewCellAccessoryCheckmark;
            else
                cell.accessoryType = UITableViewCellAccessoryNone;
        }
        else
        {
            NSLog(@"array: %@", [s.selfArray valueForKey:@"CheckStat"]);
            for(int i = 0; i < [[[s.selfArray valueForKey:@"CheckStat"] componentsSeparatedByString:@","] count]; i++)
            {
                NSString    *checkedNumStr = [[[s.selfArray valueForKey:@"CheckStat"] componentsSeparatedByString:@","] objectAtIndex:i];
                if ([checkedNumStr intValue] == indexPath.row + 1)
                        cell.accessoryType = UITableViewCellAccessoryCheckmark;
                else
                    cell.accessoryType = UITableViewCellAccessoryNone;
            }
        }

        return cell;
    }
    else
        return  nil;
}

didSelectRowAtIndex:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if(cell.accessoryType == UITableViewCellAccessoryCheckmark)
    {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    else
    {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CheckStatStr = nil;
    for(int i = 0; i < [s.taskArray count]; i++)
    {
        NSIndexPath *eachPath = [NSIndexPath indexPathForRow:i inSection:0] ;
        UITableViewCell *eachCell = [tableView cellForRowAtIndexPath:eachPath];
        if(eachCell.accessoryType == UITableViewCellAccessoryCheckmark)
        {
            if([CheckStatStr length] == 0 || !CheckStatStr)
            {
                CheckStatStr = [[NSMutableString alloc] init];
                [CheckStatStr setString:(NSString*)[NSString stringWithFormat:@"%d",i+1]];
            }
            else
                [CheckStatStr appendString:[NSString stringWithFormat:@",%d",i+1]];
        }
    }
    if(CheckStatStr){
        s.OldCheckStatStr = [s.selfArray valueForKey:@"CheckStat"];
        [s.selfArray setValue:CheckStatStr forKey:@"CheckStat"];
    }else{
        [s.selfArray setValue:@"0" forKey:@"CheckStat"];
    }
}

Body:
How I solve This Issue in Swift 5

Main Reason of repeating checkmark is cell reusable . then displaying cell resuse and checkmark Still Apear . How I resolve this issue :

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = self.schedulTable.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        as! scheduleCell

    cell.timeLable.text = self.timeArray[indexPath.row]
    // here is the code which clear checkmark on reuse
    if item.num >= 0 && item.isSelected == true{
        if item.num == indexPath.row{
            cell.accessoryType = .checkmark
        }else{
             cell.accessoryType = .none
        }
    }

       return cell
   }

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
 selected_Time = self.timeArray[indexPath.row]
    item.isSelected = true
   item.num = indexPath.row
    schedulTable.cellForRow(at: indexPath)?.accessoryType = .checkmark
  //schedulTable.reloadData()

}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    schedulTable.cellForRow(at: indexPath)?.accessoryType = .none
}

struct Item {
 var num : Int
 var isSelected : Bool
init() {
    num = -1
    isSelected = false
}}


来源: stackexchange

问:
How to make Navigation bottom bar transparent
I am trying to create a transparent bottom navigation bar and here's my bottom bar part:

```<code>Align(
                      alignment: Alignment.bottomCenter,
                      child: Theme(
                          data: Theme.of(context)
                              .copyWith(canvasColor: Colors.transparent),
                          child: BottomNavigationBar(
                            currentIndex: 0,
                            items: [
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.location_on),
                                  title: Text('Map')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.line_style),
                                  title: Text('List')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.add), title: Text('Add Property'))
                            ],
                          ))),
</code>```

and this is my full Scafold Widget:

```<code>return Scaffold(
      backgroundColor: AppTheme.white,
      body: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  appBar(),
                  // tabBar(),
                  Expanded(
                    child: FutureBuilder<bool>(
                      future: getData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<bool> snapshot) {
                        if (!snapshot.hasData) {
                          return const SizedBox();
                        } else {
                          return ChangeNotifierProvider(
                            create: (context) => Properties(),
                            child: PropertiesGrid(_showOnlyFavorites),
                          );
                        }
                      },
                    ),
                  ),
                  Align(
                      alignment: Alignment.bottomCenter,
                      child: Theme(
                          data: Theme.of(context)
                              .copyWith(canvasColor: Colors.transparent),
                          child: BottomNavigationBar(
                            currentIndex: 0,
                            items: [
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.location_on),
                                  title: Text('Map')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.line_style),
                                  title: Text('List')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.add), title: Text('Add Property'))
                            ],
                          ))),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    Icons.location_on,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget tabBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
    );
  }
}

</code>```

But I see that it doesn't show the page background as in the transparent bar to shown as the below image

I hope some one could help me to figure out where's the problem exactly..

答:
you should use the futurebuilder outside the scaffold, not inside the body, because you really want to change the whole page

```<code>return FutureBuilder<bool>(
      future: getData(),
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        if (!snapshot.hasData) {
          return const SizedBox();
        } else
          return Scaffold(
            backgroundColor: AppTheme.white,
            extendBody: true, //the body of the scaffold is shown behind the bottomNavigationBar
            appBar: AppBar( //use an AppBar widget instead of the one you created
              centerTitle: true, //this centers the title, in this case the image
              leading: IconButton(
                icon: const Icon(Icons.menu),
                onPressed: null,
              ), //the button of the left
              title: Padding( //your image
                padding: const EdgeInsets.only(top: 4),
                child: Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
              actionsIconTheme: IconThemeData(color: AppTheme.dark_grey), //this change the theme of the action buttons, the one at the right
              actions: [
                IconButton(
                   icon: const Icon(Icons.location_on),
                   onPressed: () {
                     setState(() {
                       multiple = !multiple;
                     });
                  },
               )
             ],
            ),
            body: ChangeNotifierProvider(
              create: (context) => Properties(),
              child: PropertiesGrid(_showOnlyFavorites),
            ),
           bottomNavigationBar: BottomNavigationBar(
             backgroundColor: Colors.transparent, //no color
             elevation: 0.0, // no shadow
             currentIndex: 0,
             items: [
               BottomNavigationBarItem(
                 icon: Icon(Icons.location_on),
                 title: Text('Map')),
               BottomNavigationBarItem(
                 icon: Icon(Icons.line_style),
                 title: Text('List')),
               BottomNavigationBarItem(
                 icon: Icon(Icons.add), title: Text('Add Property'))
             ],
           ),
          )
        }
    );
</code>```

you had a second future builder inside with the same future, which is irrelevant because you already had the value in the first one so I deleted it. when the future is waiting and there is no data, it will show a sizedBox() like you wanted, when the future is complete it will build the scaffold and you can use its parameters to build your page with tha appbar and BottomNavigationBarItem where it should be

UPDATE

I changed the appbar with the widget AppBar() that the scaffold expects (it expects one that implements a PreferredSizeWidget Class)

```<code>Widget appBar() {
    return SizedBox(....);
  }
</code>```

This widget you created uses a SizedBox as the first widget in the treee, which doesn't implement that class, so it gives you the error, It's preferred to use the one that flutter gives you out of the box at first, and later you can create your own extending PreferredSizeWidget (if you need to implement something different) when you understood how it works

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a transparent bottom navigation bar and here's my bottom bar part:

Align(
                      alignment: Alignment.bottomCenter,
                      child: Theme(
                          data: Theme.of(context)
                              .copyWith(canvasColor: Colors.transparent),
                          child: BottomNavigationBar(
                            currentIndex: 0,
                            items: [
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.location_on),
                                  title: Text('Map')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.line_style),
                                  title: Text('List')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.add), title: Text('Add Property'))
                            ],
                          ))),

and this is my full Scafold Widget:

return Scaffold(
      backgroundColor: AppTheme.white,
      body: FutureBuilder<bool>(
        future: getData(),
        builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
          if (!snapshot.hasData) {
            return const SizedBox();
          } else {
            return Padding(
              padding: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  appBar(),
                  // tabBar(),
                  Expanded(
                    child: FutureBuilder<bool>(
                      future: getData(),
                      builder:
                          (BuildContext context, AsyncSnapshot<bool> snapshot) {
                        if (!snapshot.hasData) {
                          return const SizedBox();
                        } else {
                          return ChangeNotifierProvider(
                            create: (context) => Properties(),
                            child: PropertiesGrid(_showOnlyFavorites),
                          );
                        }
                      },
                    ),
                  ),
                  Align(
                      alignment: Alignment.bottomCenter,
                      child: Theme(
                          data: Theme.of(context)
                              .copyWith(canvasColor: Colors.transparent),
                          child: BottomNavigationBar(
                            currentIndex: 0,
                            items: [
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.location_on),
                                  title: Text('Map')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.line_style),
                                  title: Text('List')),
                              BottomNavigationBarItem(
                                  icon: Icon(Icons.add), title: Text('Add Property'))
                            ],
                          ))),
                ],
              ),
            );
          }
        },
      ),
    );
  }

  Widget appBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 8, left: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
            ),
          ),
          Expanded(
            child: Center(
              child: Padding(
                padding: const EdgeInsets.only(top: 4),
                child:
                    Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.only(top: 8, right: 8),
            child: Container(
              width: AppBar().preferredSize.height - 8,
              height: AppBar().preferredSize.height - 8,
              color: Colors.white,
              child: Material(
                color: Colors.transparent,
                child: InkWell(
                  borderRadius:
                      BorderRadius.circular(AppBar().preferredSize.height),
                  child: Icon(
                    Icons.location_on,
                    color: AppTheme.dark_grey,
                  ),
                  onTap: () {
                    setState(() {
                      multiple = !multiple;
                    });
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget tabBar() {
    return SizedBox(
      height: AppBar().preferredSize.height,
    );
  }
}

But I see that it doesn't show the page background as in the transparent bar to shown as the below image

I hope some one could help me to figure out where's the problem exactly..

Body:
you should use the futurebuilder outside the scaffold, not inside the body, because you really want to change the whole page

return FutureBuilder<bool>(
      future: getData(),
      builder: (BuildContext context, AsyncSnapshot<bool> snapshot) {
        if (!snapshot.hasData) {
          return const SizedBox();
        } else
          return Scaffold(
            backgroundColor: AppTheme.white,
            extendBody: true, //the body of the scaffold is shown behind the bottomNavigationBar
            appBar: AppBar( //use an AppBar widget instead of the one you created
              centerTitle: true, //this centers the title, in this case the image
              leading: IconButton(
                icon: const Icon(Icons.menu),
                onPressed: null,
              ), //the button of the left
              title: Padding( //your image
                padding: const EdgeInsets.only(top: 4),
                child: Image.asset('assets/images/logo.png', fit: BoxFit.contain),
              ),
              actionsIconTheme: IconThemeData(color: AppTheme.dark_grey), //this change the theme of the action buttons, the one at the right
              actions: [
                IconButton(
                   icon: const Icon(Icons.location_on),
                   onPressed: () {
                     setState(() {
                       multiple = !multiple;
                     });
                  },
               )
             ],
            ),
            body: ChangeNotifierProvider(
              create: (context) => Properties(),
              child: PropertiesGrid(_showOnlyFavorites),
            ),
           bottomNavigationBar: BottomNavigationBar(
             backgroundColor: Colors.transparent, //no color
             elevation: 0.0, // no shadow
             currentIndex: 0,
             items: [
               BottomNavigationBarItem(
                 icon: Icon(Icons.location_on),
                 title: Text('Map')),
               BottomNavigationBarItem(
                 icon: Icon(Icons.line_style),
                 title: Text('List')),
               BottomNavigationBarItem(
                 icon: Icon(Icons.add), title: Text('Add Property'))
             ],
           ),
          )
        }
    );

you had a second future builder inside with the same future, which is irrelevant because you already had the value in the first one so I deleted it. when the future is waiting and there is no data, it will show a sizedBox() like you wanted, when the future is complete it will build the scaffold and you can use its parameters to build your page with tha appbar and BottomNavigationBarItem where it should be

UPDATE

I changed the appbar with the widget AppBar() that the scaffold expects (it expects one that implements a PreferredSizeWidget Class)

Widget appBar() {
    return SizedBox(....);
  }

This widget you created uses a SizedBox as the first widget in the treee, which doesn't implement that class, so it gives you the error, It's preferred to use the one that flutter gives you out of the box at first, and later you can create your own extending PreferredSizeWidget (if you need to implement something different) when you understood how it works


问:
GlobalKTable Refresh Logic
When there are updates done to an underlying topic of a GlobalKTable, what is the logic for all instances of KStream apps to get the latest data? Below are my follow up questions:

Would the GlobalKTable be locked at record level or table level when the updates are happening?

According to this blog: Kafka GlobalKTable Latency Issue, can the latency go upto 0.5s?! If so, is there any alternative to reduce the latency?

Since GlobalKTable uses RocksDB by default as the state store, are all features of RocksDB available to use?

I understand the GlobalKTable should not be used for use-cases that require frequent updates to the lookup data. Is there any other key-value store that we can use for use-cases that might require updates on table data - Redis for example?

I could not find much documentation about GlobalKTable and its internals. Is there any available documentations available?

答:
GlobalKTables are updated async. Hence, there is no guarantee whatsoever when the different instances are updated.

Also, the "global thread" uses a dedicated "global consumer" that you can fine tune individually to reduce latency: https://docs.confluent.io/current/streams/developer-guide/config-streams.html#naming

RocksDB is integrated via JNI and the JNI interface does not expose all features of RocksDB. Furthermore, the "table" abstraction "hides" RocksDB to some extent. However, you can tune RocksDB via rocksdb.config.setter (https://docs.confluent.io/current/streams/developer-guide/config-streams.html#rocksdb-config-setter).

Title: GlobalKTable Refresh Logic


问:
How to filter elements in vanilla Javascript like in jQuery?
For example, in jQuery, if i want all
 and
 elements, I do this:

```<code>var $x = $("p, div");
</code>```

And then if i want all the
 elements in x, then I do this:

```<code>var $divs = $x.filter("div");
</code>```

So how do i do this simple filter thing in vanilla JavaScript?

For example, to select all
 and
, then I can do this:

```<code>var x = document.querySelectorAll("div, p");
</code>```

But vanilla JavaScript doesn't have the filter function like in jQuery, so I can't do this:

```<code>var divs = x.filter("div"); // ERROR
</code>```

Hope someone can help me with this :-)

Thanks in advance.

UPDATE

Some comments/answers have suggested to do something like .tagName == "DIV" to find the divs, however, i want a solution with a string selector like in jQuery.

The reason is because i also want to filter with attributes, classes and even multiple selectors where you put in comma. And the string selector must be dynamic.

That means, i dont know whats in the selector. It could be "div[foo='asd'], .bar" or "#hello, [xx='yy'], p"

So  i cant just hardcode the .tagName == "DIV", beacuse i dont know whats in the selector string.

答:
You can use the matches function to check if a CSS selector matches a given element.

```<code>var x = document.querySelectorAll("div, p");
var divs = [];

// Iterate through the elements that the first query selector matched
//  (is a paragraph or a div tag)
for (var elem of x) {
    // Check if the given element matches the second query selector
    //  (is a div tag)
    if (elem.matches('div')) {
        divs.push(elem);
    }
}
</code>```

This code can be written more succinctly (and with more modern code) using:

```<code>let x = document.querySelectorAll("div, p");
let divs = Array.from(x).filter(elem => elem.matches("div"));
</code>```

Body:
For example, in jQuery, if i want all
 and
 elements, I do this:

var $x = $("p, div");

And then if i want all the
 elements in x, then I do this:

var $divs = $x.filter("div");

So how do i do this simple filter thing in vanilla JavaScript?

For example, to select all
 and
, then I can do this:

var x = document.querySelectorAll("div, p");

But vanilla JavaScript doesn't have the filter function like in jQuery, so I can't do this:

var divs = x.filter("div"); // ERROR

Hope someone can help me with this :-)

Thanks in advance.

UPDATE

Some comments/answers have suggested to do something like .tagName == "DIV" to find the divs, however, i want a solution with a string selector like in jQuery.

The reason is because i also want to filter with attributes, classes and even multiple selectors where you put in comma. And the string selector must be dynamic.

That means, i dont know whats in the selector. It could be "div[foo='asd'], .bar" or "#hello, [xx='yy'], p"

So  i cant just hardcode the .tagName == "DIV", beacuse i dont know whats in the selector string.

Body:
You can use the matches function to check if a CSS selector matches a given element.

var x = document.querySelectorAll("div, p");
var divs = [];

// Iterate through the elements that the first query selector matched
//  (is a paragraph or a div tag)
for (var elem of x) {
    // Check if the given element matches the second query selector
    //  (is a div tag)
    if (elem.matches('div')) {
        divs.push(elem);
    }
}

This code can be written more succinctly (and with more modern code) using:

let x = document.querySelectorAll("div, p");
let divs = Array.from(x).filter(elem => elem.matches("div"));


问:
ImagePicker set data to state
I'm trying to create an imagePicker in ReactNative, but when I select the image, I get the error:

TypeError: this.setState is not a function. (In 'this.setState ({
avatar: data}) ',' this.setState 'is undefined)

I don't understand why my state is undefined at the moment.

```<code>export default class ProfileEdit extends Component {
    constructor(props) {
        super(props);

        async function getRoutedUser() {
            const route = useRoute();

            return route.params.user;
        }

        this.state = {
            user: this.props.navigation.state.params.user,
            avatar: ""
        };

 imagePickerCallback(data) {

        this.setState({avatar: data})

    }

...
<Button style={styleProperties.buttonEditProfImage} type="outline"
       onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
    <Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...
</code>```

Thanks!!

答:
You should declare imagePickerCallback as an arrow function or you should bind this for your function in constructor. You can read more about Handling events in React here.
Try this:

export default class ProfileEdit extends Component {
    constructor(props) {
      super(props);

      async function getRoutedUser() {
          const route = useRoute();

          return route.params.user;
      }

      this.state = {
          user: this.props.navigation.state.params.user,
          avatar: ""
      };

  imagePickerCallback = (data) => {
      this.setState({avatar: data})
  }

...
<Button style={styleProperties.buttonEditProfImage} type="outline"
       onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
    <Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...```
</div>
</div>
</p>

<p>Or try this: </p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>export default class ProfileEdit extends Component {
    constructor(props) {
      super(props);

      async function getRoutedUser() {
          const route = useRoute();

          return route.params.user;
      }

      this.state = {
          user: this.props.navigation.state.params.user,
          avatar: ""
      }
      this.imagePickerCallback = this.imagePickerCallback.bind(this)
   }

  imagePickerCallback(data) {
      this.setState({avatar: data})
  }

...
<Button style={styleProperties.buttonEditProfImage} type="outline"
       onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
    <Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...</code>```

Title: ImagePicker set data to state

Body:
I'm trying to create an imagePicker in ReactNative, but when I select the image, I get the error:

TypeError: this.setState is not a function. (In 'this.setState ({
avatar: data}) ',' this.setState 'is undefined)

I don't understand why my state is undefined at the moment.

export default class ProfileEdit extends Component {
    constructor(props) {
        super(props);

        async function getRoutedUser() {
            const route = useRoute();

            return route.params.user;
        }

        this.state = {
            user: this.props.navigation.state.params.user,
            avatar: ""
        };

 imagePickerCallback(data) {

        this.setState({avatar: data})

    }

...
<Button style={styleProperties.buttonEditProfImage} type="outline"
       onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
    <Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...

Thanks!!

Body:
You should declare imagePickerCallback as an arrow function or you should bind this for your function in constructor. You can read more about Handling events in React here.
Try this:

export default class ProfileEdit extends Component {
    constructor(props) {
      super(props);

      async function getRoutedUser() {
          const route = useRoute();

          return route.params.user;
      }

      this.state = {
          user: this.props.navigation.state.params.user,
          avatar: ""
      };

  imagePickerCallback = (data) => {
      this.setState({avatar: data})
  }

...
<Button style={styleProperties.buttonEditProfImage} type="outline"
       onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
    <Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...

Or try this:

export default class ProfileEdit extends Component {
    constructor(props) {
      super(props);

      async function getRoutedUser() {
          const route = useRoute();

          return route.params.user;
      }

      this.state = {
          user: this.props.navigation.state.params.user,
          avatar: ""
      }
      this.imagePickerCallback = this.imagePickerCallback.bind(this)
   }

  imagePickerCallback(data) {
      this.setState({avatar: data})
  }

...
<Button style={styleProperties.buttonEditProfImage} type="outline"
       onPress={() => ImagePicker.showImagePicker({}, this.imagePickerCallback)}>
    <Text style={styleProperties.buttonEditProfText}>Escolha uma imagem</Text>
</Button>
...


问:
Make copy of an array
I have an array a which is constantly being updated. Let's say a = [1,2,3,4,5]. I need to make an exact duplicate copy of a and call it b. If a were to change to [6,7,8,9,10], b should still be [1,2,3,4,5]. What is the best way to do this? I tried a for loop like:

```<code>for(int i=0; i<5; i++) {
    b[i]=a[i];
}
</code>```

but that doesn't seem to work correctly. Please don't use advanced terms like deep copy, etc., because I do not know what that means.

答:
I had a similar problem with 2D arrays and ended here.
I was copying the main array and changing the inner arrays' values and was surprised when the values changed in both copies. Basically both copies were independent but contained references to the same inner arrays and I had to make an array of copies of the inner arrays to get what I wanted.

This is sometimes called a deep copy. The same term "deep copy" can also have a completely different and arguably more complex meaning, which can be confusing, especially to someone not figuring out why their copied arrays don't behave as they should. It probably isn't the OP's problem, but I hope it can still be helpful.

Title: Make copy of an array

Body:
I have an array a which is constantly being updated. Let's say a = [1,2,3,4,5]. I need to make an exact duplicate copy of a and call it b. If a were to change to [6,7,8,9,10], b should still be [1,2,3,4,5]. What is the best way to do this? I tried a for loop like:

for(int i=0; i<5; i++) {
    b[i]=a[i];
}

but that doesn't seem to work correctly. Please don't use advanced terms like deep copy, etc., because I do not know what that means.


问:
OpenCV C++ 3 Dimensional Mat Data Access Wrong Values
I am using C++ OpenCV DNN to get results into a Mat. Here, dnnResult is the output Mat. The output values are float. I want extract 66 values into 3 separate arrays or a 3 x 66 matrix.

```<code>dnnResult.size[0] = 3
dnnResult.size[1] = 1
dnnResult.size[2] = 66
dnnResult.dims = 3
</code>```

I tried looping like this to get value, but the results are wrong. There is no error for accessing out of bound data from 3d Mat.

```<code>for(int m = 0; m < 3; m++){
    for(int n = 0; n < 66; n++){
        myNetOutput2d[m][n] = dnnResult.at<double>(m, 0, n);
    }
}
</code>```

I also tried following How to access a 3 dimensional Matrix elements?,

```<code>typedef Vec<double, 66> Vec66d;
for(int m = 0; m < 3; m++){
    for(int n = 0; n < 66; n++){
        Vec66d tmp_vec66d = dnnResult.at<double>(0, m);
        myNetOutput2d[m][n] = tmp_vec66d.val[n];

    }
}
</code>```

I am trying to get python equivalent of assigning values of size 66 into 3 separate arrays,

```<code>arr1, arr2, arr3 = dnnResult
</code>```

答:
change
dnnResult.at<double>(..) to dnnResult.at<float>(..)

+ more information about cv::Mat::at

```<code>template<typename _Tp> inline
_Tp& Mat::at(int i0, int i1, int i2)
{
    CV_DbgAssert( elemSize() == sizeof(_Tp) );
    return *(_Tp*)ptr(i0, i1, i2);
}

inline
const uchar* Mat::ptr(int i0, int i1, int i2) const
{
    CV_DbgAssert(dims >= 3);
    CV_DbgAssert(data);
    CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]);
    CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]);
    CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]);
    return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2];
}
</code>```

cv::Mat holds data with a raw pointer, and cv::Mat::at<_Tp> access its data with casting a pointer to _Tp*. The index is not out of bound, but the actual data is got from out bounds because double is 64 bit, while the float is 32 bit in OpenCV.

So, you have to know you're cv::Mat's correct type when accessing to it.

If you want to cast the data do double, you have to cast after getting the correct data.

```<code>myNetOutput2d[m][n] = (double)dnnResult.at<float>(m, 0, n);
</code>```

or, convert the dnnResult's type to double before accessing to it.

```<code>dnnResult.convertTo(dnnResult, CV_64F);
...
myNetOutput2d[m][n] = dnnResult.at<double>(m, 0, n);
</code>```

Body:
I am using C++ OpenCV DNN to get results into a Mat. Here, dnnResult is the output Mat. The output values are float. I want extract 66 values into 3 separate arrays or a 3 x 66 matrix.

dnnResult.size[0] = 3
dnnResult.size[1] = 1
dnnResult.size[2] = 66
dnnResult.dims = 3

I tried looping like this to get value, but the results are wrong. There is no error for accessing out of bound data from 3d Mat.

for(int m = 0; m < 3; m++){
    for(int n = 0; n < 66; n++){
        myNetOutput2d[m][n] = dnnResult.at<double>(m, 0, n);
    }
}

I also tried following How to access a 3 dimensional Matrix elements?,

typedef Vec<double, 66> Vec66d;
for(int m = 0; m < 3; m++){
    for(int n = 0; n < 66; n++){
        Vec66d tmp_vec66d = dnnResult.at<double>(0, m);
        myNetOutput2d[m][n] = tmp_vec66d.val[n];

    }
}

I am trying to get python equivalent of assigning values of size 66 into 3 separate arrays,

arr1, arr2, arr3 = dnnResult

Body:
change
dnnResult.at<double>(..) to dnnResult.at<float>(..)

+ more information about cv::Mat::at

template<typename _Tp> inline
_Tp& Mat::at(int i0, int i1, int i2)
{
    CV_DbgAssert( elemSize() == sizeof(_Tp) );
    return *(_Tp*)ptr(i0, i1, i2);
}

inline
const uchar* Mat::ptr(int i0, int i1, int i2) const
{
    CV_DbgAssert(dims >= 3);
    CV_DbgAssert(data);
    CV_DbgAssert((unsigned)i0 < (unsigned)size.p[0]);
    CV_DbgAssert((unsigned)i1 < (unsigned)size.p[1]);
    CV_DbgAssert((unsigned)i2 < (unsigned)size.p[2]);
    return data + i0 * step.p[0] + i1 * step.p[1] + i2 * step.p[2];
}

cv::Mat holds data with a raw pointer, and cv::Mat::at<_Tp> access its data with casting a pointer to _Tp*. The index is not out of bound, but the actual data is got from out bounds because double is 64 bit, while the float is 32 bit in OpenCV.

So, you have to know you're cv::Mat's correct type when accessing to it.

If you want to cast the data do double, you have to cast after getting the correct data.

myNetOutput2d[m][n] = (double)dnnResult.at<float>(m, 0, n);

or, convert the dnnResult's type to double before accessing to it.

dnnResult.convertTo(dnnResult, CV_64F);
...
myNetOutput2d[m][n] = dnnResult.at<double>(m, 0, n);


问:
Python3 and Tkinter - How can I check which Notebook Tab is open?
my window contains three main widgets, two buttons ("Cancel" and "Export") and a Notebook. The latter has two tabs with others widgets, and both of them must use the same buttons placed in the window. now, keeping in mind what I just wrote, how can I track in which Notebook tab the user are working in order to adapt the button's behaviour to the active tab? in other words, I want to change the "Export" button's behaviour depending on which Notebook tab is used. how can I reach my goal?

```<code>from tkinter import *
from tkinter import ttk, scrolledtext, filedialog

class MainWindow:

def __init__(self, window):

    ### MAIN WINDOW

    self.window = window
    self.window.title("My Software")
    self.window.configure(background="#f0f0f0")
    self.window.geometry("530x438+360+200")
    self.window.resizable (width=False, height=False)

    style = ttk.Style()
    style.configure("InWhiteFrame.TButton", background="#ffffff", padding = 0)
    style.configure("TButton", padding = 0)
    style.configure("BluText.TLabel", foreground="#99c1e8")
    style.configure("GreyBackground.TLabel", foreground="adadad", background="#e1e1e1", insertbackground="red", fieldbackground= 'blue')

    self.MyNotebook = ttk.Notebook(self.window)
    self.MyNotebook.place(x = 12, y = 12)

    Frame_1 = Frame(self.MyNotebook, background = "#ffffff", width = 506, height = 354, highlightbackground = "#d3d5d9", highlightthickness = 0)
    Frame_1.place(x = 12, y = 12)

    Frame_2 = Frame(self.MyNotebook, background = "#ffffff", width = 506, height = 354, highlightbackground = "#d3d5d9", highlightthickness = 0)
    Frame_2.place(x = 12, y = 12)

    self.MyNotebook.add(Frame_1, text = "Tab 1")
    self.MyNotebook.add(Frame_2, text = "Tab 2")

    self.ExportButton = ttk.Button(self.window, text = "Export", width = 16, command = self.__Save)
    self.ExportButton.place(x = 336, y = 403)
    self.ExportButton.config(state='disable')

    ttk.Button(self.window, text = "Cancel", width = 11, command = self.__Close).place(x = 445, y = 403)

    ### TAB 1

    self.SV1 = StringVar()
    ttk.Label(Frame_1, text = "File 1:", background = "#ffffff").place(x = 16, y = 80)
    self.Entry1 = ttk.Entry(Frame_1, text="", width = 52, textvariable=self.SV1)
    self.Entry1.place(x = 116, y = 80)
    ttk.Button(Frame_1, text="...", width = 4, style = "InWhiteFrame.TButton", command = self.__GetEntry1).place(x = 440, y = 79)

    self.SV2 = StringVar()
    ttk.Label(Frame_1, text = "File 2:", background = "#ffffff").place(x = 16, y = 111)
    self.Entry2 = ttk.Entry(Frame_1, text = "", width = 52, textvariable=self.SV2)
    self.Entry2.place(x = 116, y = 111)
    self.Entry2.config(state='disable')
    self.Entry2Button = ttk.Button(Frame_1, text="...", width = 4, style = "InWhiteFrame.TButton", command = self.__GetEntry2)
    self.Entry2Button.place(x = 440, y = 109)
    self.Entry2Button.config(state='disable')

    self.SV3 = StringVar()
    ttk.Label(Frame_1, text = "File 3:", background = "#ffffff").place(x = 16, y = 218)
    self.Entry3 = ttk.Entry(Frame_1, text = "", width = 52, textvariable=self.SV3)
    self.Entry3.place(x = 116, y = 218)
    self.Entry3.config(state='disable')
    self.Entry3Button = ttk.Button(Frame_1, text="...", width = 4, style = "InWhiteFrame.TButton", command = self.__GetEntry3)
    self.Entry3Button.place(x = 440, y = 217)
    self.Entry3Button.config(state='disable')

    self.window.protocol("WM_DELETE_WINDOW", self.__Close)

    self.SV1.trace("w", self.__Trace)
    self.SV2.trace("w", self.__Trace)
    self.SV3.trace("w", self.__Trace)
    self.window.bind("<<NotebookTabChanged>>", self.__GetActiveTab)

    ### TAB 2

    self.LeftSide = scrolledtext.ScrolledText(Frame_2, wrap = WORD, width = 34, height = 11, font = ("Segoe UI", 9))
    self.LeftSide.place(x = 18, y = 42)
    Canvas(Frame_2, width = 207, height = 1, background = "#a0a0a0", highlightthickness = 0).place(x = 18, y = 210)

    RightSide = scrolledtext.ScrolledText(Frame_2, wrap = WORD, width = 34, height = 11, font = ("Segoe UI", 9), state="disable")
    RightSide.place(x = 262, y = 42)
    Canvas(Frame_2, width = 207, height = 1, background = "#a0a0a0", highlightthickness = 0).place(x = 262, y = 210)

    self.SV4 = StringVar()
    self.SV4.set("Option 1")
    ExportOptions = ttk.Combobox(Frame_2, values = ("Option 1", "Option 2", "Option 3"), state="readonly", textvariable = self.SV4, width = 14)
    ExportOptions.place(x = 93, y = 292)

    self.SV5 = StringVar()
    self.SV5.set("1")
    SaveOptions = ttk.Combobox(Frame_2, values = ("1", "2"), state="readonly", textvariable = self.SV5, width = 8)
    SaveOptions.place(x = 299, y = 292)

def __Trace(self, *args):
    if self.SV1.get() != "":
        self.ExportButton.config(state = "normal")
        self.Entry2.config(state = "normal")
        self.Entry2Button.config(state = "normal")
        self.Entry3.config(state = "normal")
        self.Entry3Button.config(state = "normal")
        if self.SV2.get() != "":
            self.Entry3.config(state = "disable")
            self.Entry3Button.config(state = "disable")
        elif self.SV3.get() != "":
            self.Entry2.config(state = "disable")
            self.Entry2Button.config(state = "disable")
    else:
        self.ExportButton.config(state = "disable")
        self.Entry2.delete(-1, END)
        self.Entry2.config(state = "disable")
        self.Entry2Button.config(state = "disable")
        self.Entry3.delete(-1, END)
        self.Entry3.config(state = "disable")
        self.Entry3Button.config(state = "disable")

def __GetEntry1(self):
    path = filedialog.askopenfilename(parent = self.window)
    if path != "":
        self.Entry1.delete(-1, END)
        self.Entry1.insert(0, path)

def __GetEntry2(self):
    path = filedialog.askopenfilename(parent = self.window)
    if path != "":
        self.Entry2.delete(-1, END)
        self.Entry2.insert(0, path)

def __GetEntry3(self):
    path = filedialog.askopenfilename(parent = self.window)
    if path != "":
        self.Entry3.delete(-1, END)
        self.Entry3.insert(0, path)

def __GetActiveTab(self, event):
    self.tab = self.MyNotebook.index(self.MyNotebook.select())

def __Save(self):
    print("The user clicked the \"Export\" button in the tab :", self.tab)
    print("It means that I will export the information specified in the tab ", self.tab)

def __Close(self):
    self.window.destroy()

def main():
root = Tk()
app = MainWindow(root)
root.mainloop()

if __name__ == "__main__":
main()
</code>```

答:
ttk.Notebook has an event called <<NotebookTabChanged>>.

Here is an minimal example:

```<code>import tkinter as tk
from tkinter import ttk

def tab_changed(event):
    print(notebook.select())  # get the instance of tab
    print(notebook.index(notebook.select()))  # get the index of the tab.

root = tk.Tk()

notebook = ttk.Notebook(root)
notebook.pack()

tab1 = tk.Frame()
notebook.add(tab1, text="tab1")

tab2 = tk.Frame()
notebook.add(tab2, text="tab2")

root.bind("<<NotebookTabChanged>>", tab_changed)

root.mainloop()
</code>```

Reference:ttk document

Body:
my window contains three main widgets, two buttons ("Cancel" and "Export") and a Notebook. The latter has two tabs with others widgets, and both of them must use the same buttons placed in the window. now, keeping in mind what I just wrote, how can I track in which Notebook tab the user are working in order to adapt the button's behaviour to the active tab? in other words, I want to change the "Export" button's behaviour depending on which Notebook tab is used. how can I reach my goal?

from tkinter import *
from tkinter import ttk, scrolledtext, filedialog

class MainWindow:

def __init__(self, window):

    ### MAIN WINDOW

    self.window = window
    self.window.title("My Software")
    self.window.configure(background="#f0f0f0")
    self.window.geometry("530x438+360+200")
    self.window.resizable (width=False, height=False)

    style = ttk.Style()
    style.configure("InWhiteFrame.TButton", background="#ffffff", padding = 0)
    style.configure("TButton", padding = 0)
    style.configure("BluText.TLabel", foreground="#99c1e8")
    style.configure("GreyBackground.TLabel", foreground="adadad", background="#e1e1e1", insertbackground="red", fieldbackground= 'blue')

    self.MyNotebook = ttk.Notebook(self.window)
    self.MyNotebook.place(x = 12, y = 12)

    Frame_1 = Frame(self.MyNotebook, background = "#ffffff", width = 506, height = 354, highlightbackground = "#d3d5d9", highlightthickness = 0)
    Frame_1.place(x = 12, y = 12)

    Frame_2 = Frame(self.MyNotebook, background = "#ffffff", width = 506, height = 354, highlightbackground = "#d3d5d9", highlightthickness = 0)
    Frame_2.place(x = 12, y = 12)

    self.MyNotebook.add(Frame_1, text = "Tab 1")
    self.MyNotebook.add(Frame_2, text = "Tab 2")

    self.ExportButton = ttk.Button(self.window, text = "Export", width = 16, command = self.__Save)
    self.ExportButton.place(x = 336, y = 403)
    self.ExportButton.config(state='disable')

    ttk.Button(self.window, text = "Cancel", width = 11, command = self.__Close).place(x = 445, y = 403)

    ### TAB 1

    self.SV1 = StringVar()
    ttk.Label(Frame_1, text = "File 1:", background = "#ffffff").place(x = 16, y = 80)
    self.Entry1 = ttk.Entry(Frame_1, text="", width = 52, textvariable=self.SV1)
    self.Entry1.place(x = 116, y = 80)
    ttk.Button(Frame_1, text="...", width = 4, style = "InWhiteFrame.TButton", command = self.__GetEntry1).place(x = 440, y = 79)

    self.SV2 = StringVar()
    ttk.Label(Frame_1, text = "File 2:", background = "#ffffff").place(x = 16, y = 111)
    self.Entry2 = ttk.Entry(Frame_1, text = "", width = 52, textvariable=self.SV2)
    self.Entry2.place(x = 116, y = 111)
    self.Entry2.config(state='disable')
    self.Entry2Button = ttk.Button(Frame_1, text="...", width = 4, style = "InWhiteFrame.TButton", command = self.__GetEntry2)
    self.Entry2Button.place(x = 440, y = 109)
    self.Entry2Button.config(state='disable')

    self.SV3 = StringVar()
    ttk.Label(Frame_1, text = "File 3:", background = "#ffffff").place(x = 16, y = 218)
    self.Entry3 = ttk.Entry(Frame_1, text = "", width = 52, textvariable=self.SV3)
    self.Entry3.place(x = 116, y = 218)
    self.Entry3.config(state='disable')
    self.Entry3Button = ttk.Button(Frame_1, text="...", width = 4, style = "InWhiteFrame.TButton", command = self.__GetEntry3)
    self.Entry3Button.place(x = 440, y = 217)
    self.Entry3Button.config(state='disable')

    self.window.protocol("WM_DELETE_WINDOW", self.__Close)

    self.SV1.trace("w", self.__Trace)
    self.SV2.trace("w", self.__Trace)
    self.SV3.trace("w", self.__Trace)
    self.window.bind("<<NotebookTabChanged>>", self.__GetActiveTab)

    ### TAB 2

    self.LeftSide = scrolledtext.ScrolledText(Frame_2, wrap = WORD, width = 34, height = 11, font = ("Segoe UI", 9))
    self.LeftSide.place(x = 18, y = 42)
    Canvas(Frame_2, width = 207, height = 1, background = "#a0a0a0", highlightthickness = 0).place(x = 18, y = 210)

    RightSide = scrolledtext.ScrolledText(Frame_2, wrap = WORD, width = 34, height = 11, font = ("Segoe UI", 9), state="disable")
    RightSide.place(x = 262, y = 42)
    Canvas(Frame_2, width = 207, height = 1, background = "#a0a0a0", highlightthickness = 0).place(x = 262, y = 210)

    self.SV4 = StringVar()
    self.SV4.set("Option 1")
    ExportOptions = ttk.Combobox(Frame_2, values = ("Option 1", "Option 2", "Option 3"), state="readonly", textvariable = self.SV4, width = 14)
    ExportOptions.place(x = 93, y = 292)

    self.SV5 = StringVar()
    self.SV5.set("1")
    SaveOptions = ttk.Combobox(Frame_2, values = ("1", "2"), state="readonly", textvariable = self.SV5, width = 8)
    SaveOptions.place(x = 299, y = 292)

def __Trace(self, *args):
    if self.SV1.get() != "":
        self.ExportButton.config(state = "normal")
        self.Entry2.config(state = "normal")
        self.Entry2Button.config(state = "normal")
        self.Entry3.config(state = "normal")
        self.Entry3Button.config(state = "normal")
        if self.SV2.get() != "":
            self.Entry3.config(state = "disable")
            self.Entry3Button.config(state = "disable")
        elif self.SV3.get() != "":
            self.Entry2.config(state = "disable")
            self.Entry2Button.config(state = "disable")
    else:
        self.ExportButton.config(state = "disable")
        self.Entry2.delete(-1, END)
        self.Entry2.config(state = "disable")
        self.Entry2Button.config(state = "disable")
        self.Entry3.delete(-1, END)
        self.Entry3.config(state = "disable")
        self.Entry3Button.config(state = "disable")

def __GetEntry1(self):
    path = filedialog.askopenfilename(parent = self.window)
    if path != "":
        self.Entry1.delete(-1, END)
        self.Entry1.insert(0, path)

def __GetEntry2(self):
    path = filedialog.askopenfilename(parent = self.window)
    if path != "":
        self.Entry2.delete(-1, END)
        self.Entry2.insert(0, path)

def __GetEntry3(self):
    path = filedialog.askopenfilename(parent = self.window)
    if path != "":
        self.Entry3.delete(-1, END)
        self.Entry3.insert(0, path)

def __GetActiveTab(self, event):
    self.tab = self.MyNotebook.index(self.MyNotebook.select())

def __Save(self):
    print("The user clicked the \"Export\" button in the tab :", self.tab)
    print("It means that I will export the information specified in the tab ", self.tab)

def __Close(self):
    self.window.destroy()

def main():
root = Tk()
app = MainWindow(root)
root.mainloop()

if __name__ == "__main__":
main()

Body:
ttk.Notebook has an event called <<NotebookTabChanged>>.

Here is an minimal example:

import tkinter as tk
from tkinter import ttk

def tab_changed(event):
    print(notebook.select())  # get the instance of tab
    print(notebook.index(notebook.select()))  # get the index of the tab.

root = tk.Tk()

notebook = ttk.Notebook(root)
notebook.pack()

tab1 = tk.Frame()
notebook.add(tab1, text="tab1")

tab2 = tk.Frame()
notebook.add(tab2, text="tab2")

root.bind("<<NotebookTabChanged>>", tab_changed)

root.mainloop()

Reference:ttk document


Title: I want to apply a formula in R, multiply a value in one vector by that in another vector and so on

Body:
I have a complexity vector with ratings from 1-9, and time durations for each complexity rating, I want to multiple the durations by the corresponding complexity score for that period and weight by the time duration, for example:

subject S001, replicate 1, stimulus S1, "soft" attribute: 2*(0.99 - 0.77) / 0.99-0.77 = 2

then in an example where there is more than 1 complexity rating for,

subject S001, replicate 2, stimulus S1, "soft" attribute: 2*(0.32-0.14)+1*(0.99-0.32)/(0.32-0.14)+(0.99-0.32) = 1.21

structure(list(Replicate = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L,
2L, 2L, 2L, 2L, 2L, 2L), Stimulus = c(1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Subject = c("S001", "S001",
"S001", "S001", "S001", "S001", "S001", "S001", "S001", "S001",
"S001", "S001", "S001", "S001", "S001", "S001", "S001", "S001",
"S001", "S001", "S001", "S001", "S001", "S001", "S001", "S001",
"S001", "S001", "S001", "S001"), Attribute = c("Soft", "Soft",
"Soft", "Soft", "Soft", "Soft", "Soft", "Soft", "Soft", "Soft",
"Soft", "Soft", "Soft", "Soft", "Soft", "Soft", "Soft", "Soft",
"Soft", "Soft", "Soft", "Soft", "Soft", "Soft", "Soft", "Soft",
"Soft", "Soft", "Soft", "Soft"), Timepoint = c(0.77, 0.78, 0.79,
0.8, 0.81, 0.82, 0.83, 0.84, 0.85, 0.86, 0.87, 0.88, 0.89, 0.9,
0.91, 0.92, 0.93, 0.94, 0.95, 0.96, 0.97, 0.98, 0.99, 0.19, 0.2,
0.21, 0.22, 0.23, 0.24, 0.25), Dominant = c(1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Complexity = c(2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L), start_time = c(0.77,
0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77,
0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77, 0.77,
0.19, 0.19, 0.19, 0.19, 0.19, 0.24, 0.24), end_time = c(0.99,
0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99,
0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99, 0.99,
0.23, 0.23, 0.23, 0.23, 0.23, 0.99, 0.99), duration = c(0.22,
0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22,
0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22, 0.22,
0.04, 0.04, 0.04, 0.04, 0.04, 0.75, 0.75), complexity_x_duration = c(NA,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, NA, 0, 0, 0, 0, 0.75, 0)), row.names = c(NA, -30L), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), groups = structure(list(Replicate = 1:2,
    Stimulus = c(1L, 1L), Subject = c("S001", "S001"), Attribute = c("Soft",
    "Soft"), .rows = list(1:23, 24:30)), row.names = c(NA, -2L
), class = c("tbl_df", "tbl", "data.frame"), .drop = TRUE))

My best attempt so far is below, but it returns only zeros. I feel I am going about this in a roundabout way and could maybe use a forloop to make it easier.

tds_merged_duration4<-modified_tds_merged %>%
  group_by(Replicate, Stimulus, Subject, Attribute) %>%
  mutate(duration = end_time - start_time) %>%
  mutate(complexity_x_duration = ifelse(Complexity!=lag(Complexity, 1), duration*Complexity,0))

This is another attempt:

 for (i in 1:20614) {
    if (tds_merged_duration3$Complexity==lag(tds_merged_duration3$Complexity,1)){
      NA
    }else{
      (tds_merged_duration3$Complexity*tds_merged_duration3$duration)/tds_merged_duration3$duration
    }
}

Body:
Here is the result of your code running on my PC with what appears to be a correctly calculated column complexity_x_duration:

> tail(tds_merged_duration4,20)
# A tibble: 20 x 11
# Groups:   Replicate, Stimulus, Subject, Attribute [2]
   Replicate Stimulus Subject Attribute Timepoint Dominant Complexity start_time end_time duration complexity_x_duration
       <int>    <int> <chr>   <chr>         <dbl>    <int>      <int>      <dbl>    <dbl>    <dbl>                 <dbl>
 1         1        1 S001    Soft           0.87        1          2       0.77     0.99    0.220                 0.440
 2         1        1 S001    Soft           0.88        1          2       0.77     0.99    0.220                 0.440
 3         1        1 S001    Soft           0.89        1          2       0.77     0.99    0.220                 0.440
 4         1        1 S001    Soft           0.9         1          2       0.77     0.99    0.220                 0.440
 5         1        1 S001    Soft           0.91        1          2       0.77     0.99    0.220                 0.440
 6         1        1 S001    Soft           0.92        1          2       0.77     0.99    0.220                 0.440
 7         1        1 S001    Soft           0.93        1          2       0.77     0.99    0.220                 0.440
 8         1        1 S001    Soft           0.94        1          2       0.77     0.99    0.220                 0.440
 9         1        1 S001    Soft           0.95        1          2       0.77     0.99    0.220                 0.440
10         1        1 S001    Soft           0.96        1          2       0.77     0.99    0.220                 0.440
11         1        1 S001    Soft           0.97        1          2       0.77     0.99    0.220                 0.440
12         1        1 S001    Soft           0.98        1          2       0.77     0.99    0.220                 0.440
13         1        1 S001    Soft           0.99        1          2       0.77     0.99    0.220                 0.440
14         2        1 S001    Soft           0.19        1          2       0.19     0.23    0.04                 NA
15         2        1 S001    Soft           0.2         1          2       0.19     0.23    0.04                  0.08
16         2        1 S001    Soft           0.21        1          2       0.19     0.23    0.04                  0.08
17         2        1 S001    Soft           0.22        1          2       0.19     0.23    0.04                  0.08
18         2        1 S001    Soft           0.23        1          2       0.19     0.23    0.04                  0.08
19         2        1 S001    Soft           0.24        1          1       0.24     0.99    0.75                  0
20         2        1 S001    Soft           0.25        1          1       0.24     0.99    0.75                  0.75


问:
Get domain the server was reached over?
In general on any non-HTTP server. Would there be a way to detect what domain was used to reach the IP?

I know HTTP servers get the domain passed within the request header, but would this be possible with any other server that does not require this information to be received from the client?

I'm especially looking for a way to do this with the minecraft server (Bukkit) so my preferred language (if needed for you to answer) would be Java. But I'd like to not have the theories about this language specific.

答: No, if there are no means for this in the protocol itself like the Host header in HTTP you cannot find out which hostname was used on the client to resolve your IP address.</p>

ContentLicense: CC BY-SA 3.0

Title: Get domain the server was reached over?


问:
Subsetting, Matrices
I am super new to R and currently playing with the "diamond" dataset.

I am trying to return the row corresponding to the lowest, mean and largest prices and put everything in a 10 by 4 matrix. Please explain an easier way of doing this if possible.

```<code>library(ggplot2)
data(diamonds)

min(diamonds$price)
mean(diamonds$price)
max(diamonds$price) # this one gives me the wrong val!

M<-matrix(1:cols, nrow = 1, ncol = cols)
colnames(M)<-c("carat","cut" , "color" , "clarity", "depth" , "table" , "price" ,  "x" , "y" ,"z")

# Here I need to add the rows corresponding to the min,mean,max to this matrix.
</code>```

Thanks

答:
If all you want to do is to select the rows in the diamonds data frame corresponding to the mean, minimum, and maximum of price, this is easily accomplished with a combination of the $ and [ forms of the extract operator in Base R.

Note that this will return a data frame with 3 rows, not 4, because there are two rows at the minimum price, no rows at the mean price, and one row at the maximum price.

```<code>library(ggplot2)
data(diamonds)

diamonds[diamonds$price %in% c(min(diamonds$price),mean(diamonds$price),max(diamonds$price)),]
</code>```

...and the output:

```<code>  carat cut     color clarity depth table price     x     y     z
  <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
3  2.29 Premium I     VS2      60.8    60 18823  8.5   8.47  5.16
</code>```

A solution with dplyr uses filter() as follows.

```<code># dplyr solution
library(dplyr)
diamonds %>% filter(price %in% c(min(price),mean(price),max(price)))
</code>```

...and the output:

```<code># A tibble: 3 x 10
  carat cut     color clarity depth table price     x     y     z
  <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
3  2.29 Premium I     VS2      60.8    60 18823  8.5   8.47  5.16
>
</code>```

Title: Subsetting, Matrices

Body:
I am super new to R and currently playing with the "diamond" dataset.

I am trying to return the row corresponding to the lowest, mean and largest prices and put everything in a 10 by 4 matrix. Please explain an easier way of doing this if possible.

library(ggplot2)
data(diamonds)

min(diamonds$price)
mean(diamonds$price)
max(diamonds$price) # this one gives me the wrong val!

M<-matrix(1:cols, nrow = 1, ncol = cols)
colnames(M)<-c("carat","cut" , "color" , "clarity", "depth" , "table" , "price" ,  "x" , "y" ,"z")

# Here I need to add the rows corresponding to the min,mean,max to this matrix.

Thanks

Body:
If all you want to do is to select the rows in the diamonds data frame corresponding to the mean, minimum, and maximum of price, this is easily accomplished with a combination of the $ and [ forms of the extract operator in Base R.

Note that this will return a data frame with 3 rows, not 4, because there are two rows at the minimum price, no rows at the mean price, and one row at the maximum price.

library(ggplot2)
data(diamonds)

diamonds[diamonds$price %in% c(min(diamonds$price),mean(diamonds$price),max(diamonds$price)),]

...and the output:

  carat cut     color clarity depth table price     x     y     z
  <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
3  2.29 Premium I     VS2      60.8    60 18823  8.5   8.47  5.16

A solution with dplyr uses filter() as follows.

# dplyr solution
library(dplyr)
diamonds %>% filter(price %in% c(min(price),mean(price),max(price)))

...and the output:

# A tibble: 3 x 10
  carat cut     color clarity depth table price     x     y     z
  <dbl> <ord>   <ord> <ord>   <dbl> <dbl> <int> <dbl> <dbl> <dbl>
1  0.23 Ideal   E     SI2      61.5    55   326  3.95  3.98  2.43
2  0.21 Premium E     SI1      59.8    61   326  3.89  3.84  2.31
3  2.29 Premium I     VS2      60.8    60 18823  8.5   8.47  5.16
>


问:
Spring RestTemplate timeout
I would like to set the connection timeouts for a rest service used by my web application.  I'm using Spring's RestTemplate to talk to my service.  I've done some research and I've found and used the xml below (in my application xml) which I believe is meant to set the timeout.  I'm using Spring 3.0.

I've also seen the same problem here Timeout configuration for spring webservices with RestTemplate but the solutions don't seem that clean, I'd prefer to set the timeout values via Spring config

```<code><bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
    <constructor-arg>

      <bean class="org.springframework.http.client.CommonsClientHttpRequestFactory">
        <property name="readTimeout" value="${restURL.connectionTimeout}" />
      </bean>
    </constructor-arg>
</bean>
</code>```

It seems whatever I set the readTimeout to be I get the following:

Network cable disconnected:
Waits about 20 seconds and reports following exception:

org.springframework.web.client.ResourceAccessException: I/O error: No route to host: connect; nested exception is java.net.NoRouteToHostException: No route to host: connect

Url incorrect so 404 returned by rest service:
Waits about 10 seconds and reports following exception:

org.springframework.web.client.HttpClientErrorException: 404 Not Found

My requirements require shorter timeouts so I need to be able to change these.  Any ideas as to what I'm doing wrong?

Many thanks.

答:
RestTemplate timeout with SimpleClientHttpRequestFactory
To programmatically override the timeout properties, we can customize the SimpleClientHttpRequestFactory class as below.

Override timeout with SimpleClientHttpRequestFactory

```<code>//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
    SimpleClientHttpRequestFactory clientHttpRequestFactory
                      = new SimpleClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}
</code>```

RestTemplate timeout with HttpComponentsClientHttpRequestFactory
SimpleClientHttpRequestFactory helps in setting timeout but it is very limited in functionality and may not prove sufficient in realtime applications. In production code, we may want to use HttpComponentsClientHttpRequestFactory which support HTTP Client library along with resttemplate.

HTTPClient provides other useful features such as connection pool, idle connection management etc.

Read More : Spring RestTemplate + HttpClient configuration example

Override timeout with HttpComponentsClientHttpRequestFactory

```<code>//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
                      = new HttpComponentsClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}
</code>```

reference: Spring RestTemplate timeout configuration example

Title: Spring RestTemplate timeout

Body:
I would like to set the connection timeouts for a rest service used by my web application.  I'm using Spring's RestTemplate to talk to my service.  I've done some research and I've found and used the xml below (in my application xml) which I believe is meant to set the timeout.  I'm using Spring 3.0.

I've also seen the same problem here Timeout configuration for spring webservices with RestTemplate but the solutions don't seem that clean, I'd prefer to set the timeout values via Spring config

<bean id="RestOperations" class="org.springframework.web.client.RestTemplate">
    <constructor-arg>

      <bean class="org.springframework.http.client.CommonsClientHttpRequestFactory">
        <property name="readTimeout" value="${restURL.connectionTimeout}" />
      </bean>
    </constructor-arg>
</bean>

It seems whatever I set the readTimeout to be I get the following:

Network cable disconnected:
Waits about 20 seconds and reports following exception:

org.springframework.web.client.ResourceAccessException: I/O error: No route to host: connect; nested exception is java.net.NoRouteToHostException: No route to host: connect

Url incorrect so 404 returned by rest service:
Waits about 10 seconds and reports following exception:

org.springframework.web.client.HttpClientErrorException: 404 Not Found

My requirements require shorter timeouts so I need to be able to change these.  Any ideas as to what I'm doing wrong?

Many thanks.

Body:
RestTemplate timeout with SimpleClientHttpRequestFactory
To programmatically override the timeout properties, we can customize the SimpleClientHttpRequestFactory class as below.

Override timeout with SimpleClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
    SimpleClientHttpRequestFactory clientHttpRequestFactory
                      = new SimpleClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}

RestTemplate timeout with HttpComponentsClientHttpRequestFactory
SimpleClientHttpRequestFactory helps in setting timeout but it is very limited in functionality and may not prove sufficient in realtime applications. In production code, we may want to use HttpComponentsClientHttpRequestFactory which support HTTP Client library along with resttemplate.

HTTPClient provides other useful features such as connection pool, idle connection management etc.

Read More : Spring RestTemplate + HttpClient configuration example

Override timeout with HttpComponentsClientHttpRequestFactory

//Create resttemplate
RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());

//Override timeouts in request factory
private SimpleClientHttpRequestFactory getClientHttpRequestFactory()
{
    HttpComponentsClientHttpRequestFactory clientHttpRequestFactory
                      = new HttpComponentsClientHttpRequestFactory();
    //Connect timeout
    clientHttpRequestFactory.setConnectTimeout(10_000);

    //Read timeout
    clientHttpRequestFactory.setReadTimeout(10_000);
    return clientHttpRequestFactory;
}

reference: Spring RestTemplate timeout configuration example


问:
Chrome custom tabs - setCloseButtonIcon() not changing icon
I'm trying to change icon for close button in Chrome custom tabs. But it is not changing.

Here's my code:

```<code>CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setCloseButtonIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back));
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));
</code>```

答:
According to this documentation, the close icon needs to be 24dp x 24dp. Something like this works:</p>

```<code><vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M7.2,14.4m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M14.8,18m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M15.2,8.8m-4.8,0a4.8,4.8 0,1 1,9.6 0a4.8,4.8 0,1 1,-9.6 0"/>
</vector>
</code>```

Body:
I'm trying to change icon for close button in Chrome custom tabs. But it is not changing.

Here's my code:

CustomTabsIntent.Builder builder = new CustomTabsIntent.Builder();
builder.setCloseButtonIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_arrow_back));
CustomTabsIntent customTabsIntent = builder.build();
customTabsIntent.launchUrl(this, Uri.parse(url));

Body:
According to this documentation, the close icon needs to be 24dp x 24dp. Something like this works:

<vector xmlns:android="http://schemas.android.com/apk/res/android"
    android:width="24dp"
    android:height="24dp"
    android:viewportWidth="24"
    android:viewportHeight="24"
    android:tint="?attr/colorControlNormal">
  <path
      android:fillColor="@android:color/white"
      android:pathData="M7.2,14.4m-3.2,0a3.2,3.2 0,1 1,6.4 0a3.2,3.2 0,1 1,-6.4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M14.8,18m-2,0a2,2 0,1 1,4 0a2,2 0,1 1,-4 0"/>
  <path
      android:fillColor="@android:color/white"
      android:pathData="M15.2,8.8m-4.8,0a4.8,4.8 0,1 1,9.6 0a4.8,4.8 0,1 1,-9.6 0"/>
</vector>


问:
How do you create a file in assembly with a dynamically specified file path?
This question is mainly how to handle the pathname which is an arbitrarily long string, in assembly, without db or any helpers like that. I have seen several examples such as this which shows:

```<code>section .text
   global _start         ;must be declared for using gcc

_start:                  ;tell linker entry point
   ;create the file
   mov  eax, 8
   mov  ebx, file_name
   mov  ecx, 0777        ;read, write and execute by all
   int  0x80             ;call kernel

   section  .data
file_name db 'myfile.txt'
</code>```

However, I would specifically like to understand how to do this dynamically. I would like to (1) better understand the requirements of the filename in terms of assembly (does it need a null terminator, etc.), and more importantly (2) specify the file name without the use of db or any assembler helpers. For example, you could specify the file name through the command line, and its structure would be unknown to the object file.

How do you do this?

答: Just build the string in memory somehow (with a null terminator, as was pointed out in the comments), and then pass the pointer to it in place of file_name. To use a command-line argument, it's already built for you, so just point to it, like this: mov  ebx, [esp + 8] (for reference, that's equivalent to argv[1]). By the way, in a real program, you should check argc (which lives at [esp]) before you do that to make sure it's at least 2.

Body:
This question is mainly how to handle the pathname which is an arbitrarily long string, in assembly, without db or any helpers like that. I have seen several examples such as this which shows:

section .text
   global _start         ;must be declared for using gcc

_start:                  ;tell linker entry point
   ;create the file
   mov  eax, 8
   mov  ebx, file_name
   mov  ecx, 0777        ;read, write and execute by all
   int  0x80             ;call kernel

   section  .data
file_name db 'myfile.txt'

However, I would specifically like to understand how to do this dynamically. I would like to (1) better understand the requirements of the filename in terms of assembly (does it need a null terminator, etc.), and more importantly (2) specify the file name without the use of db or any assembler helpers. For example, you could specify the file name through the command line, and its structure would be unknown to the object file.

How do you do this?


问:
Conditional Validation with Multiple Conditions
I am familiar with simple conditional validation in FluentValidation using When, Unless, and Otherwise. This works well for validating on a single condition.

I would like to validate based off of an if-elseif-else statement, but I cannot determine how to do so.

I want to achieve

```<code>if (product == Product.A)
{
    // Validation for Product A
}
else if (product == Product.B)
{
    // Validation for Product B
}
else
{
    // Fail validation for other products
}
</code>```

What I currently have works if I only want to check for a single product, e.g. Product A

```<code>When(
    order => order.Product == Product.A,
    () =>
    {
    RuleFor(order => order.State)
        .Must(
            state => state == State.HI
            || state == State.AK)
        .WithMessage("Product A only valid in Hawaii and Alaska.");
    }).Otherwise(
    () =>
    {
        RuleFor(order => order.Product)
            .Equal(Product.A)
            .WithMessage("Order only available with Product A.");
    });
</code>```

What I'd like is to combine multiple When methods for Products A and B and have an otherwise that fails with the message "Order is only available with Products A or B".

答:
I've tackled similar problems by splitting up the rules, and putting guards on them.

Following your if-else psuedo code:

```<code>RuleFor(order => order.State)
    .Must(state => state == State.HI || state == State.AK)
    .WithMessage("Product A only valid in Hawaii and Alaska."))
    .When(order => order.Product == Product.A);

RuleFor(order => order.State)
    .Must(state => state == State.DC || state == State.CA)
    .WithMessage("Product B only valid in Washington and California."))
    .When(order => order.Product == Product.B);

// the not Product.A or Product.B case (I'm not sure what you want here) - but this
// demonstrates a kind of "meta" rule to be applied to the whole order
RuleFor(order => order)
    .Must(order => order.Product == Product.A || order.Product == Product.B)
    .WithName("Order")
    .WithMessage(order => $"Order must be either {Product.A} or {Product.B}");
</code>```

Body:
I am familiar with simple conditional validation in FluentValidation using When, Unless, and Otherwise. This works well for validating on a single condition.

I would like to validate based off of an if-elseif-else statement, but I cannot determine how to do so.

I want to achieve

if (product == Product.A)
{
    // Validation for Product A
}
else if (product == Product.B)
{
    // Validation for Product B
}
else
{
    // Fail validation for other products
}

What I currently have works if I only want to check for a single product, e.g. Product A

When(
    order => order.Product == Product.A,
    () =>
    {
    RuleFor(order => order.State)
        .Must(
            state => state == State.HI
            || state == State.AK)
        .WithMessage("Product A only valid in Hawaii and Alaska.");
    }).Otherwise(
    () =>
    {
        RuleFor(order => order.Product)
            .Equal(Product.A)
            .WithMessage("Order only available with Product A.");
    });

What I'd like is to combine multiple When methods for Products A and B and have an otherwise that fails with the message "Order is only available with Products A or B".

Body:
I've tackled similar problems by splitting up the rules, and putting guards on them.

Following your if-else psuedo code:

RuleFor(order => order.State)
    .Must(state => state == State.HI || state == State.AK)
    .WithMessage("Product A only valid in Hawaii and Alaska."))
    .When(order => order.Product == Product.A);

RuleFor(order => order.State)
    .Must(state => state == State.DC || state == State.CA)
    .WithMessage("Product B only valid in Washington and California."))
    .When(order => order.Product == Product.B);

// the not Product.A or Product.B case (I'm not sure what you want here) - but this
// demonstrates a kind of "meta" rule to be applied to the whole order
RuleFor(order => order)
    .Must(order => order.Product == Product.A || order.Product == Product.B)
    .WithName("Order")
    .WithMessage(order => $"Order must be either {Product.A} or {Product.B}");


问:
Is there a built in function to get the back half of a strsep()?
In short, currently the code below outputs: The substring is AES. Unfortunately, I'm looking to get the result The substring is 100. This is due to the fact that strsep() keeps only the first portion of the split, and not the second. Is there a way to make the 2nd portion the one that's kept instead?

```<code>#include <stdio.h>
#include <string.h>

int main () {
   const char haystack[50] = "SHA1 = 99\nAES = 100";
   const char needle[10] = "Point";
   char *ret;
   char *bonus;
   ret = strstr(haystack, "AES");

   bonus = strsep(&ret, "=");

   printf("The substring is: %s\n", bonus);

   return(0);
}
</code>```

答:
From strsep function's documentation :

  ```<code>char *strsep(char **stringp, const char *delim);
</code>```

If *stringp is NULL, the strsep() function returns NULL and does
  nothing else.  Otherwise, this function finds the first token in the
  string *stringp, that is delimited by one of the bytes in the string
  delim.  This token is terminated by overwriting the delimiter with a
  null byte ('\0'), and *stringp is updated to point past the token.
  In case no delimiter was found, the token is taken to be the entire
  string *stringp, and *stringp is made NULL.

So in your program's case you should print ret instead of bonus:

```<code>bonus = strsep(&ret, "=");

printf("The substring is: %s\n", ret);
</code>```

Since ret will point past the token "=".

Body:
In short, currently the code below outputs: The substring is AES. Unfortunately, I'm looking to get the result The substring is 100. This is due to the fact that strsep() keeps only the first portion of the split, and not the second. Is there a way to make the 2nd portion the one that's kept instead?

#include <stdio.h>
#include <string.h>

int main () {
   const char haystack[50] = "SHA1 = 99\nAES = 100";
   const char needle[10] = "Point";
   char *ret;
   char *bonus;
   ret = strstr(haystack, "AES");

   bonus = strsep(&ret, "=");

   printf("The substring is: %s\n", bonus);

   return(0);
}

Body:
From strsep function's documentation :

char *strsep(char **stringp, const char *delim);

If *stringp is NULL, the strsep() function returns NULL and does
  nothing else.  Otherwise, this function finds the first token in the
  string *stringp, that is delimited by one of the bytes in the string
  delim.  This token is terminated by overwriting the delimiter with a
  null byte ('\0'), and *stringp is updated to point past the token.
  In case no delimiter was found, the token is taken to be the entire
  string *stringp, and *stringp is made NULL.

So in your program's case you should print ret instead of bonus:

bonus = strsep(&ret, "=");

printf("The substring is: %s\n", ret);

Since ret will point past the token "=".


问:
PHP strip unknown file extension
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

```<code>basename('path/to/file.php','.php')
</code>```

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

答:
You can try with this:</p>

```<code>$filepath = 'path/to/file.extension';
$extension = strtolower(substr(strrchr($filepath, '.'), 1));
</code>```

Title: PHP strip unknown file extension

Body:
I understand that using PHP's basename() function you can strip a known file extension from a path like so,

basename('path/to/file.php','.php')

but what if you didn't know what extension the file had or the length of that extension? How would I accomplish this?

Thanks in advance!

Body:
You can try with this:

$filepath = 'path/to/file.extension';
$extension = strtolower(substr(strrchr($filepath, '.'), 1));