问:
how to use bottomNavigationBar while using ListView.builder
I want to use bottomNavigationBar with listview, I tried each one of them separately and they work fine, but when I use them together, the bottomNavigationBar doesn't work, you can press the icons but nothing happens.

note: I'm using an older version of dart to avoid null-safety which is dumb, but the reason is the book I read is from 2019 so I couldn't follow without using an older version.

note 2: I'm very new to programming.

main.dart

```<code>    //@dart=2.9
import 'package:flutter/material.dart';
import 'package:ch8_bottom_navigation/pages/home.dart';

void main() => runApp(Myapp());

class Myapp extends StatelessWidget {
  //this widget is the root of the app
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Starter Template',
      theme: ThemeData  (
        primarySwatch: Colors.blue,
        platform: TargetPlatform.iOS,

      ),
      home: Home(),
    );

  }

}
</code>```

home.dart

```<code>   //@dart=2.9
import 'package:flutter/material.dart';
import 'discover.dart';
import 'home2.dart';
import 'account.dart';

class Home extends StatefulWidget {
  const Home({Key key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;
  List _listPages = [];
  Widget _currentPage;
  @override
  void initState() {
    super.initState();

    _listPages
    ..add(Home2())
    ..add(Discover())
    ..add(Account());
    _currentPage = Discover();
  }
  void _changePage(int selectedIndex) {
    setState(() {
      _currentIndex = selectedIndex;
      _currentPage = _listPages[selectedIndex];
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView.builder(
          itemCount:20 ,
          itemBuilder: (BuildContext context , int index) {
            if (index >= 0 && index <= 0) {
              return Home2 (index:index);
            }
            else return null;
          },
        ),
      ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.live_tv),
                label: ('Home'),
            ),
            BottomNavigationBarItem(
                icon: Icon(Icons.explore_outlined),
              label: ('Discover'),
            ),
            BottomNavigationBarItem(
                icon: Icon(Icons.account_box_outlined),
              label: ('Account'),
            ),
          ],
          onTap: (selectedIndex) => _changePage(selectedIndex),
        ),

    );

  }
}
</code>```

home2.dart

```<code>//@dart=2.9
import 'package:flutter/material.dart';

class Home2 extends StatelessWidget {
  const Home2({Key key , @required this.index}) : super(key: key);
  final int index;
  @override
  Widget build(BuildContext context) {
    return Container(
        child:Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          color: Colors.white70,
          child: ListTile(
            leading: Image(
              image: AssetImage('assets/images/blackwidow.jpg'),
            ),
            title: Text('Black Widow'),
            subtitle: Text('By Disney'),
            trailing: Icon(Icons.movie),
            selected: true,
            onTap: () {
              print('Trapped on Row $index');
            },
          ),
        )
    );

  }
}
</code>```

答:
```<code>body: SafeArea(child: _currentPage),
</code>```

or

```<code>body: SafeArea(child: _listPages[selectedIndex]),
</code>```

Did you try this way?

Body:
I want to use bottomNavigationBar with listview, I tried each one of them separately and they work fine, but when I use them together, the bottomNavigationBar doesn't work, you can press the icons but nothing happens.

note: I'm using an older version of dart to avoid null-safety which is dumb, but the reason is the book I read is from 2019 so I couldn't follow without using an older version.

note 2: I'm very new to programming.

main.dart

    //@dart=2.9
import 'package:flutter/material.dart';
import 'package:ch8_bottom_navigation/pages/home.dart';

void main() => runApp(Myapp());

class Myapp extends StatelessWidget {
  //this widget is the root of the app
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Starter Template',
      theme: ThemeData  (
        primarySwatch: Colors.blue,
        platform: TargetPlatform.iOS,

      ),
      home: Home(),
    );

  }

}

home.dart

   //@dart=2.9
import 'package:flutter/material.dart';
import 'discover.dart';
import 'home2.dart';
import 'account.dart';

class Home extends StatefulWidget {
  const Home({Key key}) : super(key: key);

  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  int _currentIndex = 0;
  List _listPages = [];
  Widget _currentPage;
  @override
  void initState() {
    super.initState();

    _listPages
    ..add(Home2())
    ..add(Discover())
    ..add(Account());
    _currentPage = Discover();
  }
  void _changePage(int selectedIndex) {
    setState(() {
      _currentIndex = selectedIndex;
      _currentPage = _listPages[selectedIndex];
    });

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: ListView.builder(
          itemCount:20 ,
          itemBuilder: (BuildContext context , int index) {
            if (index >= 0 && index <= 0) {
              return Home2 (index:index);
            }
            else return null;
          },
        ),
      ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          items: [
            BottomNavigationBarItem(
                icon: Icon(Icons.live_tv),
                label: ('Home'),
            ),
            BottomNavigationBarItem(
                icon: Icon(Icons.explore_outlined),
              label: ('Discover'),
            ),
            BottomNavigationBarItem(
                icon: Icon(Icons.account_box_outlined),
              label: ('Account'),
            ),
          ],
          onTap: (selectedIndex) => _changePage(selectedIndex),
        ),

    );

  }
}

home2.dart

//@dart=2.9
import 'package:flutter/material.dart';

class Home2 extends StatelessWidget {
  const Home2({Key key , @required this.index}) : super(key: key);
  final int index;
  @override
  Widget build(BuildContext context) {
    return Container(
        child:Card(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          color: Colors.white70,
          child: ListTile(
            leading: Image(
              image: AssetImage('assets/images/blackwidow.jpg'),
            ),
            title: Text('Black Widow'),
            subtitle: Text('By Disney'),
            trailing: Icon(Icons.movie),
            selected: true,
            onTap: () {
              print('Trapped on Row $index');
            },
          ),
        )
    );

  }
}

Body:
body: SafeArea(child: _currentPage),

or

body: SafeArea(child: _listPages[selectedIndex]),

Did you try this way?


来源: stackexchange

问:
rails console cannot load such file but with one letter capitalized it works?
ruby version: 2.7.3

Hi! I am very puzzled...

I have a file path company/service/v1/my_proto_pb.rb. When I tried to require it in rails console it gives the cannot load such file error:

```<code>2.7.3 :005 > require "company/service/v1/my_proto_pb"
Traceback (most recent call last):
/usr/local/rvm/gems/ruby-2.7.3/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:34:in `require': cannot load such file -- company/service/v1/my_proto_pb (LoadError)

</code>```

HOWEVER when I capitalize the letter v to V it works:

```<code>2.7.3 :006 > require "company/service/V1/my_proto_pb"
 => true
</code>```

But the .rb and .rbi file both exist in the v1 folder. Why??? I cannot change the letter in code as it's auto-generated. Where exactly does the require look for and how can i check if what's being required exists or not?

Thank you!

答: Nevermind... The issue was that my local code was not synced to the remote rails server correctly. Locally the files are in the v1 folder but somehow remotely they are in the V1 folder, which caused the issue.

ContentLicense: CC BY-SA 4.0

Body:
ruby version: 2.7.3

Hi! I am very puzzled...

I have a file path company/service/v1/my_proto_pb.rb. When I tried to require it in rails console it gives the cannot load such file error:

2.7.3 :005 > require "company/service/v1/my_proto_pb"
Traceback (most recent call last):
/usr/local/rvm/gems/ruby-2.7.3/gems/bootsnap-1.9.3/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:34:in `require': cannot load such file -- company/service/v1/my_proto_pb (LoadError)

HOWEVER when I capitalize the letter v to V it works:

2.7.3 :006 > require "company/service/V1/my_proto_pb"
 => true

But the .rb and .rbi file both exist in the v1 folder. Why??? I cannot change the letter in code as it's auto-generated. Where exactly does the require look for and how can i check if what's being required exists or not?

Thank you!


问:
How to define imports, __init__.py files and structure of an importable Python module
I have written a Python module (AlloViz) consisting on multiple classes.

```<code>AlloViz
├── Classes
│   ├── Data.py
│   ├── Edges.py
│   ├── __init__.py
│   ├── Pair.py
│   ├── Pkgs
│   │   ├── Corrplus.py
│   │   ├── Dynetan.py
│   │   ├── Getcontacts.py
│   │   ├── __init__.py
│   │   ├── MDTASK.py
│   │   ├── Pkgs.py
│   │   └── Pytraj.py
│   └── State.py
├── __init__.py
└── utils.py
</code>```

When importing it, I would like to have available the classes from the Classes folder, and the classes defined in the Pkgs folder have to be used by State.py.

Either this way:

import AlloViz
# I want to access the classes this way:
AlloViz.Data
AlloViz.Edges
AlloViz.Pair
AlloViz.State
```
<p>or this way:</p>
<pre class="lang-py prettyprint-override"><code>from AlloViz import *
Data
Edges
Pair
State
</code>```

Moreover, in the top-folder __init__.py there are some imports of modules included with Python (e.g., os, sys, re...) and other modules (e.g. pandas, numpy...) that I want to be available for all the rest of the files (e.g., using re.search in the class defined in AlloViz/Classes/State.py). The functions defined in utils.py should also be available for all the rest of the files.

I have almost lost my whole mind trying to figure out what to put in each __init__.py so that the imports are successful, I would greatly appreciate some guidance. If it would simplify things, I could make a single Classes.py and Pkgs.py files within the AlloViz directory, although they would be very long then. If I could take a look at some existing module that has a similar structure to check how the files look like I think I could figure it out, but I have not found any.

答:
In general, you can use relative imports. These take the following form:

from .x import y which means: in the current level of the package hierarchy, look for a module x and import the name y from it.

from ..x import y which means: go one level up in the package hierarchy, then look for a module x and import the name y from it.

Case (2) can traverse arbitrary levels of the package hierarchy by just prefixing it with more dots (one dot per level). So for the example the following

from ...x.y import z
```
<p>means: go up 2 levels in the hierarchy, then find package <code>x</code>, then import module <code>y</code> from <code>x</code> and finally import <code>z</code> from <code>y</code>.</p>
<p>For controlling what gets imported when using <code>from x import *</code> you can use <code>__all__</code>.</p>
<p>So in your specific case this would be:</p>
<pre class="lang-py prettyprint-override"><code># AlloViz/__init__.py

from .Classes import Data, Edges, Pair, State

__all__ = ['Data', 'Edges', 'Pair', 'State']

# E.g. AlloViz/Classes/Pkgs/Corrplus.py

from ...utils import *
</code>```

If you want any (third party) modules to be available in your own modules, then you can just import them (it will not cause any overhead beyond the first import since the modules are cached in sys.modules). So just add import os or import numpy to all of the modules that need access to it.

Body:
I have written a Python module (AlloViz) consisting on multiple classes.

AlloViz
├── Classes
│   ├── Data.py
│   ├── Edges.py
│   ├── __init__.py
│   ├── Pair.py
│   ├── Pkgs
│   │   ├── Corrplus.py
│   │   ├── Dynetan.py
│   │   ├── Getcontacts.py
│   │   ├── __init__.py
│   │   ├── MDTASK.py
│   │   ├── Pkgs.py
│   │   └── Pytraj.py
│   └── State.py
├── __init__.py
└── utils.py

When importing it, I would like to have available the classes from the Classes folder, and the classes defined in the Pkgs folder have to be used by State.py.

Either this way:

import AlloViz
# I want to access the classes this way:
AlloViz.Data
AlloViz.Edges
AlloViz.Pair
AlloViz.State

or this way:

from AlloViz import *
Data
Edges
Pair
State

Moreover, in the top-folder __init__.py there are some imports of modules included with Python (e.g., os, sys, re...) and other modules (e.g. pandas, numpy...) that I want to be available for all the rest of the files (e.g., using re.search in the class defined in AlloViz/Classes/State.py). The functions defined in utils.py should also be available for all the rest of the files.

I have almost lost my whole mind trying to figure out what to put in each __init__.py so that the imports are successful, I would greatly appreciate some guidance. If it would simplify things, I could make a single Classes.py and Pkgs.py files within the AlloViz directory, although they would be very long then. If I could take a look at some existing module that has a similar structure to check how the files look like I think I could figure it out, but I have not found any.

Body:
In general, you can use relative imports. These take the following form:

from .x import y which means: in the current level of the package hierarchy, look for a module x and import the name y from it.

from ..x import y which means: go one level up in the package hierarchy, then look for a module x and import the name y from it.

Case (2) can traverse arbitrary levels of the package hierarchy by just prefixing it with more dots (one dot per level). So for the example the following

from ...x.y import z

means: go up 2 levels in the hierarchy, then find package x, then import module y from x and finally import z from y.

For controlling what gets imported when using from x import * you can use __all__.

So in your specific case this would be:

# AlloViz/__init__.py

from .Classes import Data, Edges, Pair, State

__all__ = ['Data', 'Edges', 'Pair', 'State']

# E.g. AlloViz/Classes/Pkgs/Corrplus.py

from ...utils import *

If you want any (third party) modules to be available in your own modules, then you can just import them (it will not cause any overhead beyond the first import since the modules are cached in sys.modules). So just add import os or import numpy to all of the modules that need access to it.


问:
Function pointers and functors
Are function pointers functors ? Is there a virtual functor in use that helps sibling functors compile silently ? </p>

答:
A function pointer is the address of a real function. A functor is a class for which the operator() has been overloaded; instances of these classes can be passed around and called with the same syntax as a function. So no, function pointers are not functors.

I don't know what "virtual functors" or "sibling functors" are, so I can't answer your second question.

ContentLicense: CC BY-SA 3.0

Title: Function pointers and functors


问:
powershell customize param prompt
The script starts off declaring a parameter:

```<code>param([Parameter(Position=0, Mandatory = $true)]$a)
</code>```

When i run the script without passing any arguments, I get:

```<code>Cmdlet test.ps1 at command pipeline position 2
Supply values for the following parameters:
a:
</code>```

I would like to suppress the first line "Cmdlet test.ps1..." that sounds quite awkward to the user. Then i would like to specify a textual request for the $a parameter instead of just showing its variable-name.

答:
Try it like that:

```<code>param (
    [Parameter(Mandatory)]
    [Alias("SourceKeyVault")]
    [string]${Source key vault},

    [Parameter(Mandatory)]
    [Alias("DestinationKeyVault")]
    [string]${Destination key vault}
)

$SourceKeyVault = ${Source key vault}
$DestinationKeyVault = ${Destination key vault}
</code>```

Mind that you cannot use special symbols in parameter descriptions in this way.
Afterwards, inside your script, just use the $SourceKeyVault etc (example) values.

Title: powershell customize param prompt

Body:
The script starts off declaring a parameter:

param([Parameter(Position=0, Mandatory = $true)]$a)

When i run the script without passing any arguments, I get:

Cmdlet test.ps1 at command pipeline position 2
Supply values for the following parameters:
a:

I would like to suppress the first line "Cmdlet test.ps1..." that sounds quite awkward to the user. Then i would like to specify a textual request for the $a parameter instead of just showing its variable-name.

Body:
Try it like that:

param (
    [Parameter(Mandatory)]
    [Alias("SourceKeyVault")]
    [string]${Source key vault},

    [Parameter(Mandatory)]
    [Alias("DestinationKeyVault")]
    [string]${Destination key vault}
)

$SourceKeyVault = ${Source key vault}
$DestinationKeyVault = ${Destination key vault}

Mind that you cannot use special symbols in parameter descriptions in this way.
Afterwards, inside your script, just use the $SourceKeyVault etc (example) values.


问:
Query where column match one or all, according to an argument
Sorry if this is basic. I have a function that get as an argument one of these 2 :

```<code>subjects ['ALL']. //search for any subject
subjects ['A','B','C'] //only one of these
</code>```

So in my function I need to query according to subjects argument

```<code>def function (subjects):

    query = ('''
                SELECT date_num, subject, in_col
                FROM base
                WHERE subject in {subjects} // = subject in ('A','B','C') works, but what about ALL ?

        ''').format(subjects=subjects)
</code>```

so when the subjects to be found are a,b,c there is no problem, but how can I tell it to search for ALL subjects in the case argument is ALL ?

Could I send * instead ? like subjects[*] ?

(I do turn the ['a','b'] into ('a','b') in my code )

答:
Create a generic query and add the where clause if needed</p>
```<code>query = "SELECT date_num, subject, in_col FROM base"
if subjects[0] != "ALL":
    query += f" WHERE subject in {subjects}"
</code>```

Body:
Sorry if this is basic. I have a function that get as an argument one of these 2 :

subjects ['ALL']. //search for any subject
subjects ['A','B','C'] //only one of these

So in my function I need to query according to subjects argument

def function (subjects):

    query = ('''
                SELECT date_num, subject, in_col
                FROM base
                WHERE subject in {subjects} // = subject in ('A','B','C') works, but what about ALL ?

        ''').format(subjects=subjects)

so when the subjects to be found are a,b,c there is no problem, but how can I tell it to search for ALL subjects in the case argument is ALL ?

Could I send * instead ? like subjects[*] ?

(I do turn the ['a','b'] into ('a','b') in my code )

Body:
Create a generic query and add the where clause if needed

query = "SELECT date_num, subject, in_col FROM base"
if subjects[0] != "ALL":
    query += f" WHERE subject in {subjects}"


问:
Split large csv file into multiple files based on column(s)
I would like to know of a fast/efficient way in any program (awk/perl/python) to split a csv file (say 10k columns) into multiple small files each containing 2 columns. I would be doing this on a unix machine.

```<code>#contents of large_file.csv
1,2,3,4,5,6,7,8
a,b,c,d,e,f,g,h
q,w,e,r,t,y,u,i
a,s,d,f,g,h,j,k
z,x,c,v,b,n,m,z
</code>```

I now want multiple files like this:

```<code># contents of 1.csv
1,2
a,b
q,w
a,s
z,x

# contents of 2.csv
1,3
a,c
q,e
a,d
z,c

# contents of 3.csv
1,4
a,d
q,r
a,f
z,v

and so on...
</code>```

I can do this currently with awk on small files (say 30 columns) like this:

```<code>awk -F, 'BEGIN{OFS=",";} {for (i=1; i < NF; i++) print $1, $(i+1) > i ".csv"}' large_file.csv
</code>```

The above takes a very long time with large files and I was wondering if there is a faster and more efficient way of doing the same.

Thanks in advance.

答:
I needed the same functionality and wrote it in bash.
Not sure if it will be faster than ravindersingh13's answer, but I hope it will help someone.

Actual version: https://github.com/pgrabarczyk/csv-file-splitter

```<code>#!/usr/bin/env bash
set -eu

SOURCE_CSV_PATH="${1}"
LINES_PER_FILE="${2}"
DEST_PREFIX_NAME="${3}"
DEBUG="${4:-0}"

split_files() {
  local source_csv_path="${1}"
  local lines_per_file="${2}"
  local dest_prefix_name="${3}"
  local debug="${4}"

  _print_log "source_csv_path: ${source_csv_path}"
  local dest_prefix_path="$(pwd)/output/${dest_prefix_name}"
  _print_log "dest_prefix_path: ${dest_prefix_path}"

  local headline=$(awk "NR==1" "${source_csv_path}")
  local file_no=0

  mkdir -p "$(dirname ${dest_prefix_path})"

  local lines_in_files=$(wc -l "${source_csv_path}" | awk '{print $1}')
  local files_to_create=$(((lines_in_files-1)/lines_per_file))
  _print_log "There is ${lines_in_files} lines in file. I will create ${files_to_create} files per ${lines_per_file} (Last file may have less)"

  _print_log "Start processing."

  for (( start_line=1; start_line<=lines_in_files; )); do
    last_line=$((start_line+lines_per_file))
    file_no=$((file_no+1))
    local file_path="${dest_prefix_path}$(printf "%06d" ${file_no}).csv"

    if [ $debug -eq 1 ]; then
      _print_log "Creating file ${file_path} with lines [${start_line};${last_line}]"
    fi

    echo "${headline}" > "${file_path}"
    awk "NR>${start_line} && NR<=${last_line}" "${source_csv_path}" >> "${file_path}"

    start_line=$last_line
  done

  _print_log "Done."
}

_print_log() {
  local log_message="${1}"
  local date_time=$(date "+%Y-%m-%d %H:%M:%S.%3N")
  printf "%s - %s\n" "${date_time}" "${log_message}" >&2
}

split_files "${SOURCE_CSV_PATH}" "${LINES_PER_FILE}" "${DEST_PREFIX_NAME}" "${DEBUG}"
</code>```

Execution:

```<code>bash csv-file-splitter.sh "sample.csv" 3 "result_" 1
</code>```

Body:
I would like to know of a fast/efficient way in any program (awk/perl/python) to split a csv file (say 10k columns) into multiple small files each containing 2 columns. I would be doing this on a unix machine.

#contents of large_file.csv
1,2,3,4,5,6,7,8
a,b,c,d,e,f,g,h
q,w,e,r,t,y,u,i
a,s,d,f,g,h,j,k
z,x,c,v,b,n,m,z

I now want multiple files like this:

# contents of 1.csv
1,2
a,b
q,w
a,s
z,x

# contents of 2.csv
1,3
a,c
q,e
a,d
z,c

# contents of 3.csv
1,4
a,d
q,r
a,f
z,v

and so on...

I can do this currently with awk on small files (say 30 columns) like this:

awk -F, 'BEGIN{OFS=",";} {for (i=1; i < NF; i++) print $1, $(i+1) > i ".csv"}' large_file.csv

The above takes a very long time with large files and I was wondering if there is a faster and more efficient way of doing the same.

Thanks in advance.

Body:
I needed the same functionality and wrote it in bash.
Not sure if it will be faster than ravindersingh13's answer, but I hope it will help someone.

Actual version: https://github.com/pgrabarczyk/csv-file-splitter

#!/usr/bin/env bash
set -eu

SOURCE_CSV_PATH="${1}"
LINES_PER_FILE="${2}"
DEST_PREFIX_NAME="${3}"
DEBUG="${4:-0}"

split_files() {
  local source_csv_path="${1}"
  local lines_per_file="${2}"
  local dest_prefix_name="${3}"
  local debug="${4}"

  _print_log "source_csv_path: ${source_csv_path}"
  local dest_prefix_path="$(pwd)/output/${dest_prefix_name}"
  _print_log "dest_prefix_path: ${dest_prefix_path}"

  local headline=$(awk "NR==1" "${source_csv_path}")
  local file_no=0

  mkdir -p "$(dirname ${dest_prefix_path})"

  local lines_in_files=$(wc -l "${source_csv_path}" | awk '{print $1}')
  local files_to_create=$(((lines_in_files-1)/lines_per_file))
  _print_log "There is ${lines_in_files} lines in file. I will create ${files_to_create} files per ${lines_per_file} (Last file may have less)"

  _print_log "Start processing."

  for (( start_line=1; start_line<=lines_in_files; )); do
    last_line=$((start_line+lines_per_file))
    file_no=$((file_no+1))
    local file_path="${dest_prefix_path}$(printf "%06d" ${file_no}).csv"

    if [ $debug -eq 1 ]; then
      _print_log "Creating file ${file_path} with lines [${start_line};${last_line}]"
    fi

    echo "${headline}" > "${file_path}"
    awk "NR>${start_line} && NR<=${last_line}" "${source_csv_path}" >> "${file_path}"

    start_line=$last_line
  done

  _print_log "Done."
}

_print_log() {
  local log_message="${1}"
  local date_time=$(date "+%Y-%m-%d %H:%M:%S.%3N")
  printf "%s - %s\n" "${date_time}" "${log_message}" >&2
}

split_files "${SOURCE_CSV_PATH}" "${LINES_PER_FILE}" "${DEST_PREFIX_NAME}" "${DEBUG}"

Execution:

bash csv-file-splitter.sh "sample.csv" 3 "result_" 1


问:
Is there R syntax to delete rows with specific, multiple NAs in columns?
Hello coding community,

If my data frame looks like:

```<code>ID     Col1 Col2 Col3 Col4
Per1   1    2    3    4
Per2   2    NA   NA   NA
Per3   NA   NA   5    NA
</code>```

Is there any syntax to delete the row associated with ID = Per2, on the basis that Col2, Col3, AND Col4 = NA? I am hoping for code that will allow me to delete a row on the basis that three specific columns (Col2, Col3, and Col4) ALL are NA. This code would NOT delete the row ID = Per3, even though there are three NAs.

Please note that I know how to delete a specific row, but my data frame is big so I do not want to manually sort through all rows/columns.

Big thanks!

答:
Test for NA and delete rows with a number of NA's equal to the number of columns tested using rowSums.

```<code>dat[!rowSums(is.na(dat[c('Col2', 'Col3', 'Col4')])) == 3, ]
#     ID Col1 Col2 Col3 Col4
# 1 Per1    1    2    3    4
# 3 Per3   NA   NA    5   NA
</code>```

Body:
Hello coding community,

If my data frame looks like:

ID     Col1 Col2 Col3 Col4
Per1   1    2    3    4
Per2   2    NA   NA   NA
Per3   NA   NA   5    NA

Is there any syntax to delete the row associated with ID = Per2, on the basis that Col2, Col3, AND Col4 = NA? I am hoping for code that will allow me to delete a row on the basis that three specific columns (Col2, Col3, and Col4) ALL are NA. This code would NOT delete the row ID = Per3, even though there are three NAs.

Please note that I know how to delete a specific row, but my data frame is big so I do not want to manually sort through all rows/columns.

Big thanks!

Body:
Test for NA and delete rows with a number of NA's equal to the number of columns tested using rowSums.

dat[!rowSums(is.na(dat[c('Col2', 'Col3', 'Col4')])) == 3, ]
#     ID Col1 Col2 Col3 Col4
# 1 Per1    1    2    3    4
# 3 Per3   NA   NA    5   NA


问:
catch forEach last iteration
```<code>arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});
</code>```

How to catch when the loop ending? I can do if(i == 3) but I might don't know what is the number of my array.

答:
I prefer this way:

```<code>arr.forEach(function(i, idx, array){
   if (idx + 1 === array.length){
       console.log("Last callback call at index " + idx + " with value " + i );
   }
});
</code>```

Seems Like more positive

Title: catch forEach last iteration

Body:
arr = [1,2,3];
arr.forEach(function(i){
// last iteration
});

How to catch when the loop ending? I can do if(i == 3) but I might don't know what is the number of my array.

Body:
I prefer this way:

arr.forEach(function(i, idx, array){
   if (idx + 1 === array.length){
       console.log("Last callback call at index " + idx + " with value " + i );
   }
});

Seems Like more positive


问:
More Float Right Questions
Here's the link: http://www.whiterootmedia.com/homepage_layout_test/

Here's the code:

```<code><div class="site" style="background:yellow;min-width: 577px; ">

<div class="banner" style="background:blue; height:100px; width:417px; float:left;">Banner   Banner   Banner   Banner   Banner   </div>
<div class="ads" style="background:green; height:800px; width:160px; float:right;">Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads  </div>
<div class="tree" style="background:orange; white-space:nowrap; height:400px; width:auto; min-width:417px; clear:left;">Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   </div>

</div>
</code>```

I would like the Orange div content not to go behind or on top of the green div when you shrink the window and  I would like the orange div text to push the green div off the screen.

Dusty

答:
You have a couple options:

Remove "white-space:nowrap;" (but I assume you have some reason for that)

Add an overflow:hidden to the orange div.  This will simply chop off the overflowing text -- it won't go either behind or on top of the green div.

But if you keep the "white-space:nowrap", and that line of "Tree" text doesn't fit, it has to go somewhere....  your options are behind, on top of, or getting chopped off with overflow:hidden.

Let me know if I'm missing what you are after.

Title: More Float Right Questions

Body:
Here's the link: http://www.whiterootmedia.com/homepage_layout_test/

Here's the code:

Banner   Banner   Banner   Banner   Banner

Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads  Ads

Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree   Tree

I would like the Orange div content not to go behind or on top of the green div when you shrink the window and  I would like the orange div text to push the green div off the screen.

Dusty


问:
Issue setting up Environment Variables with SAME NAME on PyCharm Configuration for Mujoco_py on Ubunutu
I am trying to get my OpenAI Gym w/ MuJoCo Python files running from a PyCharm configuration but I am getting "missing path to your environment variable" exception related to mujoco_py.

These are the Env Vars I can't seem to add to PyCharm because they have the same name and will 'replace' eachother.

```<code>LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/nvidia
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/<user>/.mujoco/mujoco210/bin
</code>```

I can run the Python scripts perfectly from the terminal, as all my env vars are in my .bashrc, but of course I want the console and such working in PyCharm.

So, the error I get when trying to run my script from PyCharm is:

```<code>raise Exception("\nMissing path to your environment variable. \n"
Exception:
Missing path to your environment variable.
Current values LD_LIBRARY_PATH=/home/<user>/anaconda3/envs/mujoco210_openai_gym/lib/python3.9/site-packages/cv2/../../lib64:
Please add following line to .bashrc:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/<user>/.mujoco/mujoco210/bin
</code>```

And when I add this Env Var in the "Edit Configuration", it moves onto the next Env Var I'm missing...

```<code>Please add following line to .bashrc:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/nvidia
</code>```

The problem that I run into is that they have the SAME NAME. If I put both of these Env Vars into my configuration, as separate Env Var fields, PyCharm will only read one and throw the same missing Env Var for the other.
If I combine them into the same Env Var field, with the same name, and separated by a semi-colon ; I still get the same issue.

How can I add both these Env Vars into PyCharm?

I am running Ubuntu 20.04, PyCharm 2021.2.3 Community Edition, MuJoCo 2.1.0, mujoco_py 1.50.1

Thank you greatly!

答:
When editing the configuration, it is necessary to separate multiple LD_LIBRARY_PATH environment variables with the same name with a colon. For example,</p>
```<code>LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/<user>/.mujoco/mujoco210/bin:$LD_LIBRARY_PATH:/usr/lib/nvidia.
</code>```

Body:
I am trying to get my OpenAI Gym w/ MuJoCo Python files running from a PyCharm configuration but I am getting "missing path to your environment variable" exception related to mujoco_py.

These are the Env Vars I can't seem to add to PyCharm because they have the same name and will 'replace' eachother.

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/nvidia
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/<user>/.mujoco/mujoco210/bin

I can run the Python scripts perfectly from the terminal, as all my env vars are in my .bashrc, but of course I want the console and such working in PyCharm.

So, the error I get when trying to run my script from PyCharm is:

raise Exception("\nMissing path to your environment variable. \n"
Exception:
Missing path to your environment variable.
Current values LD_LIBRARY_PATH=/home/<user>/anaconda3/envs/mujoco210_openai_gym/lib/python3.9/site-packages/cv2/../../lib64:
Please add following line to .bashrc:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/<user>/.mujoco/mujoco210/bin

And when I add this Env Var in the "Edit Configuration", it moves onto the next Env Var I'm missing...

Please add following line to .bashrc:
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/nvidia

The problem that I run into is that they have the SAME NAME. If I put both of these Env Vars into my configuration, as separate Env Var fields, PyCharm will only read one and throw the same missing Env Var for the other.
If I combine them into the same Env Var field, with the same name, and separated by a semi-colon ; I still get the same issue.

How can I add both these Env Vars into PyCharm?

I am running Ubuntu 20.04, PyCharm 2021.2.3 Community Edition, MuJoCo 2.1.0, mujoco_py 1.50.1

Thank you greatly!

Body:
When editing the configuration, it is necessary to separate multiple LD_LIBRARY_PATH environment variables with the same name with a colon. For example,

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/<user>/.mujoco/mujoco210/bin:$LD_LIBRARY_PATH:/usr/lib/nvidia.


问:
How to Insert records only where records do not exists in table to avoid duplicates Oracle
Hello please see script below i would love to edit the script so it inserts into the table "Book" certain records coming from table "Book2". In other to avoid duplicates , I want it to insert the records into Book only where the records do not exists in the table Book.
Database is Oracle</p>
```<code>insert into mol.bkp_Book
select * from mol.bkp_Book2
where session_id in ("3232323","23099999","567890111")
</code>```

答:
Use a MERGE statement:

MERGE INTO mol.bkp_Book dst
USING (
  select *
  from   mol.bkp_Book2
  where  session_id in ('3232323','23099999','567890111') -- Single quotes
) src
ON (
    dst.session_id = src.session_id
--AND dst.col1       = src.col1 -- Uncomment if you want to compare all columns
--AND dst.col2       = src.col2
--AND dst.col3       = src.col3
)
WHEN NOT MATCHED THEN
  INSERT (session_id, col1, col2, col3)
  VALUES (src.session_id, src.col1, src.col2, src.col3);
```

Body:
Hello please see script below i would love to edit the script so it inserts into the table "Book" certain records coming from table "Book2". In other to avoid duplicates , I want it to insert the records into Book only where the records do not exists in the table Book.
Database is Oracle

insert into mol.bkp_Book
select * from mol.bkp_Book2
where session_id in ("3232323","23099999","567890111")


问:
Jenkins and JFrog Artifactory - artifacts are not deleted after "maxBuilds"
I am successfully uploading my artifacts using the JFrong plugin.
I think I have set up everything for automatic deletion once the number of builds (artifacts) is more than 5. However my artifacts are not deleted (I have them more than maxBuilds property). In the target repo and folder I can see higher number of artifacts than the maxBuilds. My user does have permission to delete artifact (I have tried it manually).
Did I configure everything properly? Thanks

```<code>        stage ('Artifactory stage') {
            steps {
                rtServer (
                    id: 'Artifactory',
                    url: 'https://artifactory.domain/artifactory',
                    credentialsId: 'test',
                    timeout: 300
                )
            }
        }

        stage ('Build info stage ') {
            steps {
                rtBuildInfo (
                    maxBuilds: 5,
                    deleteBuildArtifacts: true
                )
            }
        }

        stage ('Upload stage') {
            steps {
                rtUpload (
                    serverId: 'Artifactory',
                    spec: '''{
                          "files": [
                            {
                              "pattern": "arena-*.zip",
                              "target": "project/packages/"
                            }
                         ]
                    }''',
                )
            }
        }

        stage ('Publish build info') {
            steps {
                rtPublishBuildInfo (
                    serverId: 'Artifactory'
                )
            }
        }
</code>```

Log information at the end of the build...

[Pipeline] stage [Pipeline] { (Build info stage ) [Pipeline] rtBuildInfo [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Upload stage) [Pipeline] rtUpload [consumer_0] Deploying artifact: https://artifactory.domain/artifactory/packages/arena-2022-02-07-11-31-58.zip } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Publish build info) [Pipeline] rtPublishBuildInfo Deploying build info to: https://artifactory.domain/artifactory/api/build Deploying build descriptor to: https://artifactory.domain/artifactory/api/build Build successfully deployed. Browse it in Artifactory under https://artifactory.domain/artifactory/webapp/builds/UUEAW%20::%20ArenaWebRuf%20::%20master/81 Sending request for build retention, deleting build artifacts, max number of builds to store: 5. [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Declarative: Post Actions)

答:
Add captureEnv: true to rtBuildInfo closure:

```<code>rtBuildInfo (
    captureEnv: true
    maxBuilds: 5,
    deleteBuildArtifacts: true
)
</code>```

Example here

Doc info here

Capturing Environment Variables

To set the Build-Info object to
automatically capture environment variables while downloading and
uploading files, add the following to your script.

By default, environment variables names which include "password",
"psw", "secret", "token", or "key" (case insensitive) are excluded and
will not be published to Artifactory.

Body:
I am successfully uploading my artifacts using the JFrong plugin.
I think I have set up everything for automatic deletion once the number of builds (artifacts) is more than 5. However my artifacts are not deleted (I have them more than maxBuilds property). In the target repo and folder I can see higher number of artifacts than the maxBuilds. My user does have permission to delete artifact (I have tried it manually).
Did I configure everything properly? Thanks

        stage ('Artifactory stage') {
            steps {
                rtServer (
                    id: 'Artifactory',
                    url: 'https://artifactory.domain/artifactory',
                    credentialsId: 'test',
                    timeout: 300
                )
            }
        }

        stage ('Build info stage ') {
            steps {
                rtBuildInfo (
                    maxBuilds: 5,
                    deleteBuildArtifacts: true
                )
            }
        }

        stage ('Upload stage') {
            steps {
                rtUpload (
                    serverId: 'Artifactory',
                    spec: '''{
                          "files": [
                            {
                              "pattern": "arena-*.zip",
                              "target": "project/packages/"
                            }
                         ]
                    }''',
                )
            }
        }

        stage ('Publish build info') {
            steps {
                rtPublishBuildInfo (
                    serverId: 'Artifactory'
                )
            }
        }

Log information at the end of the build...

[Pipeline] stage [Pipeline] { (Build info stage ) [Pipeline] rtBuildInfo [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Upload stage) [Pipeline] rtUpload [consumer_0] Deploying artifact: https://artifactory.domain/artifactory/packages/arena-2022-02-07-11-31-58.zip } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Publish build info) [Pipeline] rtPublishBuildInfo Deploying build info to: https://artifactory.domain/artifactory/api/build Deploying build descriptor to: https://artifactory.domain/artifactory/api/build Build successfully deployed. Browse it in Artifactory under https://artifactory.domain/artifactory/webapp/builds/UUEAW%20::%20ArenaWebRuf%20::%20master/81 Sending request for build retention, deleting build artifacts, max number of builds to store: 5. [Pipeline] } [Pipeline] // stage [Pipeline] stage [Pipeline] { (Declarative: Post Actions)

Body:
Add captureEnv: true to rtBuildInfo closure:

rtBuildInfo (
    captureEnv: true
    maxBuilds: 5,
    deleteBuildArtifacts: true
)

Example here

Doc info here

Capturing Environment Variables

To set the Build-Info object to
automatically capture environment variables while downloading and
uploading files, add the following to your script.

By default, environment variables names which include "password",
"psw", "secret", "token", or "key" (case insensitive) are excluded and
will not be published to Artifactory.


问:
Protractor - run test again if fails
I'm using shell script to run protractor tests.
I want to make sure that if the test fails (exit code != 0) then it will run again - three times most.
I'm already using Teamcity, but Teamcity sends the 'FAIL' email and only then tries again. I want the test will run three times before sending a message.
this is part of my script:

```<code>if [ "$#" -eq 0 ];
then
/usr/local/bin/protractor proactor-config.js --suite=sanity
</code>```

now I want to somehow check whether the Exit Code was 0  and of not - run again.
Thanks.

答:
If you use protractor with cucumber-js, you can choose to give each scenario (or all scenarios tagged as unstable) a number of retries:

```<code>./node_modules/cucumber/bin/cucumber-js --help
...
  --retry <NUMBER_OF_RETRIES>     specify the number of times to retry failing test cases (default: 0) (default: 0)
  --retryTagFilter <EXPRESSION>   only retries the features or scenarios with tags matching the expression (repeatable).
          This option requires '--retry' to be specified. (default: "")
</code>```

Unfortunately if every failed scenario has been successfully retried, Protractor will still return with exit code 1:
https://github.com/protractor-cucumber-framework/protractor-cucumber-framework/issues/176

As a workaround, when starting the protractor I append the following to its command line:

const directory = 'build';
ensureDirSync(directory);
const cucumberSummary = join(directory, 'cucumberSummary.log');

protractorCommandLine += ` --cucumberOpts.format=summary:${cucumberSummary} \
      || grep -P "^(\\d*) scenarios? \\(.*?\\1 passed" ${cucumberSummary} \
      && rm ${cucumberSummary}`;
```

Title: Protractor - run test again if fails

Body:
I'm using shell script to run protractor tests.
I want to make sure that if the test fails (exit code != 0) then it will run again - three times most.
I'm already using Teamcity, but Teamcity sends the 'FAIL' email and only then tries again. I want the test will run three times before sending a message.
this is part of my script:

if [ "$#" -eq 0 ];
then
/usr/local/bin/protractor proactor-config.js --suite=sanity

now I want to somehow check whether the Exit Code was 0  and of not - run again.
Thanks.

Body:
If you use protractor with cucumber-js, you can choose to give each scenario (or all scenarios tagged as unstable) a number of retries:

./node_modules/cucumber/bin/cucumber-js --help
...
  --retry <NUMBER_OF_RETRIES>     specify the number of times to retry failing test cases (default: 0) (default: 0)
  --retryTagFilter <EXPRESSION>   only retries the features or scenarios with tags matching the expression (repeatable).
          This option requires '--retry' to be specified. (default: "")

Unfortunately if every failed scenario has been successfully retried, Protractor will still return with exit code 1:
https://github.com/protractor-cucumber-framework/protractor-cucumber-framework/issues/176

As a workaround, when starting the protractor I append the following to its command line:

const directory = 'build';
ensureDirSync(directory);
const cucumberSummary = join(directory, 'cucumberSummary.log');

protractorCommandLine += ` --cucumberOpts.format=summary:${cucumberSummary} \
      || grep -P "^(\\d*) scenarios? \\(.*?\\1 passed" ${cucumberSummary} \
      && rm ${cucumberSummary}`;


问:
How do I run several codes at once?
I work with OLAP Cubes and have created code on several occasions for different purposes but now I would like to combine several functions, how do I succeed with that?

This is what I need help putting together. I am a real beginner and have solved most things through google before but now I cant find anything that I understand or that helps me.

1)

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$5" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Casino].[Casino].[Casino]").CurrentPageName = "[Casino].[Casino].&[" & Format(ActiveSheet.Cells(5, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub
</code>```

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$3" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Month Number].[Month Number]").CurrentPageName = "[Date].[Month Number].&[" & Format(ActiveSheet.Cells(3, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub
</code>```

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$2" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Year].[Year]").CurrentPageName = "[Date].[Year].&[" & Format(ActiveSheet.Cells(2, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub
</code>```

答:
Write everything in one procedure and do not repeat your code.

```<code>Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim PivFld As String
    Dim PageName As String

    On Error GoTo Fel
    Application.ScreenUpdating = False

    Select Case Target.Address
    Case "$A$5"
        PivFld = "[Casino].[Casino].[Casino]"
        PageName = "[Casino].[Casino].&[" & Format(ActiveSheet.Cells(5, 1).Value, "") & "]"
    Case "$A$3"
        PivFld = "[Date].[Month Number].[Month Number]"
        PageName = "[Date].[Month Number].&[" & Format(ActiveSheet.Cells(3, 1).Value, "") & "]"
    Case "$A$2"
        PivFld = "[Date].[Year].[Year]"
        PageName = "[Date].[Year].&[" & Format(ActiveSheet.Cells(2, 1).Value, "") & "]"
    Case Else
        Exit Sub
    End Select

    Dim ws As Worksheet
    For Each ws In Worksheets
        Dim pt As PivotTable
        For Each pt In ws.PivotTables
            pt.PivotFields(PivFld).CurrentPageName = PageName
            pt.PivotFields
        Next pt
    Next ws

    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True

End Sub
</code>```

Note that On Error Resume Next hides all error messages and you will never know if something goes wrong. Instead use On Error GoTo Fel and at least you get informed that something went wrong.

Title: How do I run several codes at once?

Body:
I work with OLAP Cubes and have created code on several occasions for different purposes but now I would like to combine several functions, how do I succeed with that?

This is what I need help putting together. I am a real beginner and have solved most things through google before but now I cant find anything that I understand or that helps me.

1)

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$5" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Casino].[Casino].[Casino]").CurrentPageName = "[Casino].[Casino].&[" & Format(ActiveSheet.Cells(5, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$3" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Month Number].[Month Number]").CurrentPageName = "[Date].[Month Number].&[" & Format(ActiveSheet.Cells(3, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address <> "$A$2" Then Exit Sub
    On Error Resume Next
    Application.ScreenUpdating = False
    Dim pt As PivotTable
    Dim ws As Worksheet
    For Each ws In Worksheets
        For Each pt In ws.PivotTables
            pt.PivotFields("[Date].[Year].[Year]").CurrentPageName = "[Date].[Year].&[" & Format(ActiveSheet.Cells(2, 1).Value, "") & "]"
            pt.PivotFields
        Next pt
    Next ws
    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True
End Sub

Body:
Write everything in one procedure and do not repeat your code.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim PivFld As String
    Dim PageName As String

    On Error GoTo Fel
    Application.ScreenUpdating = False

    Select Case Target.Address
    Case "$A$5"
        PivFld = "[Casino].[Casino].[Casino]"
        PageName = "[Casino].[Casino].&[" & Format(ActiveSheet.Cells(5, 1).Value, "") & "]"
    Case "$A$3"
        PivFld = "[Date].[Month Number].[Month Number]"
        PageName = "[Date].[Month Number].&[" & Format(ActiveSheet.Cells(3, 1).Value, "") & "]"
    Case "$A$2"
        PivFld = "[Date].[Year].[Year]"
        PageName = "[Date].[Year].&[" & Format(ActiveSheet.Cells(2, 1).Value, "") & "]"
    Case Else
        Exit Sub
    End Select

    Dim ws As Worksheet
    For Each ws In Worksheets
        Dim pt As PivotTable
        For Each pt In ws.PivotTables
            pt.PivotFields(PivFld).CurrentPageName = PageName
            pt.PivotFields
        Next pt
    Next ws

    GoTo Sluta
Fel:
    MsgBox "Något gick fel :("
Sluta:
    Application.ScreenUpdating = True

End Sub

Note that On Error Resume Next hides all error messages and you will never know if something goes wrong. Instead use On Error GoTo Fel and at least you get informed that something went wrong.


问:
Python PyQt5 QTableView Change selected row Backgroundcolor
I have a QTableView with QAbstractTableModel. I want to change row backgroundcolor when I click one cell. I know at least two methods that can change row backgroundcolor when clicking one cell. One is use delegate, and another is use setData method in QAbstractTable. But I have got none of them,,,oops. Here I tried using setData method in QAbstractTable to just change the selected cell backgroundcolor, but failed! Could you pls help me to correct my code in order to change a whole row color not just a cell. Anyway, changing cell color is not even ok! Much thanks! Code below</p>
```<code>import sys
import typing
import numpy as np
import pandas as pd
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, \
    QWidget, QTableView, QVBoxLayout
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex

class MyTableModel(QAbstractTableModel):
    def __init__(self, data:pd.DataFrame):
        super().__init__()
        self._data = data

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if role==Qt.DisplayRole:
            value = str(self._data.iloc[index.row()][index.column()])
            return value

    def setData(self, index: QModelIndex, value: typing.Any, role: int = ...) -> bool:
        if not index.isValid():
            return False
        else:
            if role==Qt.BackgroundColorRole:
                self.dataChanged.emit(index, index, [role])
                return True

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return self._data.shape[0]

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return self._data.shape[1]

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.myTable = QTableView()
        df = self.get_DataFrame_Data()
        self.model = MyTableModel(df)
        self.myTable.setModel(self.model)
        self.myTable.clicked.connect(self.change_row_bgcolor)
        hlayout = QVBoxLayout()
        hlayout.addWidget(self.myTable)
        dummy_widget = QWidget()
        dummy_widget.setLayout(hlayout)
        self.setCentralWidget(dummy_widget)
        self.setFixedSize(600, 600)

    def get_DataFrame_Data(self):
        ndarray = np.random.randint(10, 50, (7, 3))
        df = pd.DataFrame(data=ndarray, columns=['col1','col2','col3'])
        return df

    def change_row_bgcolor(self, index):
        self.model.setData(index,Qt.red,Qt.BackgroundColorRole)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
</code>```

答:
Solved! Two ways to changed QTableView Row background color when user mouse clicking.

Use QStyledItemDelegate.
Subclass QStyledItemDelegate. You should set a class property (etc tableview's currentindex) which can be reset value from outside the class, by this, the delegate's default loop will compare the tableview's currentindex.Code:

```<code>    class TableDelegate(QStyledItemDelegate):

        select_index = None

        def paint(self, painter: QtGui.QPainter, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> None:
            # option.state
            row = index.row()
            column = index.column()
            select_row = self.select_index.row()
            # self.initStyleOption(option,index)
            if row == select_row:
                # option.font.setItalic(True)
                option.font.setStyle(QFont.StyleOblique)
                bg = QColor(135, 206, 255)
                painter.fillRect(option.rect, bg)
                # painter.eraseRect(option.rect)
            QStyledItemDelegate.paint(self, painter, option, index)
</code>```

Use QAbstractTableModel.Also, you should set a class property, than the method data()'s default loop will compare with the class property(tableview's current index). and set backgroud color.Code:

```<code>    class MyTableModel(QAbstractTableModel):
        def __init__(self, data:pd.DataFrame):
            super().__init__()
            self._data = data
            self.color_enabled = False
            self.color_back = Qt.magenta
            self.target_row = -1

        def data(self, index: QModelIndex, role: int) -> typing.Any:
            if role==Qt.DisplayRole:
                # print(index.row())
                value = str(self._data.iloc[index.row()][index.column()])
                return value
            if role == Qt.BackgroundRole and index.row()==self.target_row \
                    and self.color_enabled==True:
                return QBrush(self.color_back)
</code>```

And,,! there is another special problem that should emphasized here. When user click one cell, there is a default backgroud which I see in my computer is blue.  If you want to whole row background color is same when clicking, you should do this after creating a QTableView:

```<code>self.myTable.setStyleSheet("QTableView::item:selected{"
                   "background:rgb(135, 206, 255)}")
</code>```

This means,you set the selected cell bgcolor by QSS, and then, either when you use QAbstractTableModel' data() method or pain() method in QStyledItemDelege, you should set the same color. Then everything is ok!

Body:
I have a QTableView with QAbstractTableModel. I want to change row backgroundcolor when I click one cell. I know at least two methods that can change row backgroundcolor when clicking one cell. One is use delegate, and another is use setData method in QAbstractTable. But I have got none of them,,,oops. Here I tried using setData method in QAbstractTable to just change the selected cell backgroundcolor, but failed! Could you pls help me to correct my code in order to change a whole row color not just a cell. Anyway, changing cell color is not even ok! Much thanks! Code below

import sys
import typing
import numpy as np
import pandas as pd
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, \
    QWidget, QTableView, QVBoxLayout
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex

class MyTableModel(QAbstractTableModel):
    def __init__(self, data:pd.DataFrame):
        super().__init__()
        self._data = data

    def data(self, index: QModelIndex, role: int = ...) -> typing.Any:
        if role==Qt.DisplayRole:
            value = str(self._data.iloc[index.row()][index.column()])
            return value

    def setData(self, index: QModelIndex, value: typing.Any, role: int = ...) -> bool:
        if not index.isValid():
            return False
        else:
            if role==Qt.BackgroundColorRole:
                self.dataChanged.emit(index, index, [role])
                return True

    def rowCount(self, parent: QModelIndex = ...) -> int:
        return self._data.shape[0]

    def columnCount(self, parent: QModelIndex = ...) -> int:
        return self._data.shape[1]

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.myTable = QTableView()
        df = self.get_DataFrame_Data()
        self.model = MyTableModel(df)
        self.myTable.setModel(self.model)
        self.myTable.clicked.connect(self.change_row_bgcolor)
        hlayout = QVBoxLayout()
        hlayout.addWidget(self.myTable)
        dummy_widget = QWidget()
        dummy_widget.setLayout(hlayout)
        self.setCentralWidget(dummy_widget)
        self.setFixedSize(600, 600)

    def get_DataFrame_Data(self):
        ndarray = np.random.randint(10, 50, (7, 3))
        df = pd.DataFrame(data=ndarray, columns=['col1','col2','col3'])
        return df

    def change_row_bgcolor(self, index):
        self.model.setData(index,Qt.red,Qt.BackgroundColorRole)

app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

Body:
Solved! Two ways to changed QTableView Row background color when user mouse clicking.

Use QStyledItemDelegate.
Subclass QStyledItemDelegate. You should set a class property (etc tableview's currentindex) which can be reset value from outside the class, by this, the delegate's default loop will compare the tableview's currentindex.Code:

    class TableDelegate(QStyledItemDelegate):

        select_index = None

        def paint(self, painter: QtGui.QPainter, option: 'QStyleOptionViewItem', index: QtCore.QModelIndex) -> None:
            # option.state
            row = index.row()
            column = index.column()
            select_row = self.select_index.row()
            # self.initStyleOption(option,index)
            if row == select_row:
                # option.font.setItalic(True)
                option.font.setStyle(QFont.StyleOblique)
                bg = QColor(135, 206, 255)
                painter.fillRect(option.rect, bg)
                # painter.eraseRect(option.rect)
            QStyledItemDelegate.paint(self, painter, option, index)

Use QAbstractTableModel.Also, you should set a class property, than the method data()'s default loop will compare with the class property(tableview's current index). and set backgroud color.Code:

    class MyTableModel(QAbstractTableModel):
        def __init__(self, data:pd.DataFrame):
            super().__init__()
            self._data = data
            self.color_enabled = False
            self.color_back = Qt.magenta
            self.target_row = -1

        def data(self, index: QModelIndex, role: int) -> typing.Any:
            if role==Qt.DisplayRole:
                # print(index.row())
                value = str(self._data.iloc[index.row()][index.column()])
                return value
            if role == Qt.BackgroundRole and index.row()==self.target_row \
                    and self.color_enabled==True:
                return QBrush(self.color_back)

And,,! there is another special problem that should emphasized here. When user click one cell, there is a default backgroud which I see in my computer is blue.  If you want to whole row background color is same when clicking, you should do this after creating a QTableView:

self.myTable.setStyleSheet("QTableView::item:selected{"
                   "background:rgb(135, 206, 255)}")

This means,you set the selected cell bgcolor by QSS, and then, either when you use QAbstractTableModel' data() method or pain() method in QStyledItemDelege, you should set the same color. Then everything is ok!


问:
Unable to download "prophet" in the Rstudio Instance in Jupyter notebook
Tried downloading the prophet but it says unavailable on the present R version 3.6.3. Updated it to 4.0.0 and still the same issue. Please suggest! Thanks!

答:
Try running this prior, this worked for me when installing prophet into Databricks:</p>
```<code>Sys.setenv(DOWNLOAD_STATIC_LIBV8 = 1)
remotes::install_github("jeroen/V8")
devtools::install_version("rstantools", version = "2.0.0")
install.packages('prophet')
</code>```

Body:
Try running this prior, this worked for me when installing prophet into Databricks:

Sys.setenv(DOWNLOAD_STATIC_LIBV8 = 1)
remotes::install_github("jeroen/V8")
devtools::install_version("rstantools", version = "2.0.0")
install.packages('prophet')


问:
heredoc for Windows batch?
Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:

```<code>cat <<EOF > out.txt
bla
bla
..
EOF
</code>```

The idea is to create a customized file from a template file..

答:
You can create a quoted block of text with a FOR /F loop, so you didn't need to escape special characters like <>|& only % have to be escaped.

This is sometimes usefull like creating a html output.

```<code>@echo off
setlocal EnableDelayedExpansion
set LF=^

REM Two empty lines are required
set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"

for /F "tokens=* delims=_" %%a in (^"%NL%
___"One<>&|"%NL%
___"two 100%%"%NL%
___%NL%
___"three "quoted" "%NL%
___"four"%NL%
") DO (
   @echo(%%~a
)
</code>```

Output

```<code>One<>&|
two 100%

three "quoted"
four
</code>```

I try to explain the code.
The LF variable contains one newline character, the NL variable contains ^<LF><LF>^.

This can be used with the percent expansion to place ONE newline character and one caret at the line end.

Normally a FOR /F split a quoted text into multiple tokens, but only once.

As I insert newline characters the FOR-loop also splits into multiple lines.

The quote at the first and at the last line are only to create the correct syntax for the FOR-loop.

At the front of any line are _ as the first character will be escaped from the multi line caret of the previous line, and if the quote is the first character it looses the escape capability.

The _ delims is used, as spaces or commas causes problems with XP (Else the XP-Bug spurious tries to access garbage filenames).

The caret at the line end is also only against the XP-Bug.

The XP-Bug comes in effect when a quoted text contains unquoted ,;=<space> characters

```<code>for /f "tokens=*" %%a in ("a","b","c") do echo %%a
</code>```

ContentLicense: CC BY-SA 2.5

Title: heredoc for Windows batch?

Body:
Is there a way of specifying multiline strings in batch in a way similar to heredoc in unix shells. Something similar to:

cat <<EOF > out.txt
bla
bla
..
EOF

The idea is to create a customized file from a template file..

Body:
You can create a quoted block of text with a FOR /F loop, so you didn't need to escape special characters like <>|& only % have to be escaped.

This is sometimes usefull like creating a html output.

@echo off
setlocal EnableDelayedExpansion
set LF=^

REM Two empty lines are required
set ^"NL=^^^%LF%%LF%^%LF%%LF%^^"

for /F "tokens=* delims=_" %%a in (^"%NL%
___"One<>&|"%NL%
___"two 100%%"%NL%
___%NL%
___"three "quoted" "%NL%
___"four"%NL%
") DO (
   @echo(%%~a
)

Output

One<>&|
two 100%

three "quoted"
four

I try to explain the code.
The LF variable contains one newline character, the NL variable contains ^<LF><LF>^.

This can be used with the percent expansion to place ONE newline character and one caret at the line end.

Normally a FOR /F split a quoted text into multiple tokens, but only once.

As I insert newline characters the FOR-loop also splits into multiple lines.

The quote at the first and at the last line are only to create the correct syntax for the FOR-loop.

At the front of any line are _ as the first character will be escaped from the multi line caret of the previous line, and if the quote is the first character it looses the escape capability.

The _ delims is used, as spaces or commas causes problems with XP (Else the XP-Bug spurious tries to access garbage filenames).

The caret at the line end is also only against the XP-Bug.

The XP-Bug comes in effect when a quoted text contains unquoted ,;=<space> characters

for /f "tokens=*" %%a in ("a","b","c") do echo %%a


问:
Replace na's in pandas dataframe with the mean value of two column if they don't contain na's
I have a dataset like this one

```<code>data = {'DATE': ['2012-01-01', '2013-05-16', '2013-05-28',
               '2013-06-05', '2013-06-07', '2014-02-02'],
               'Avarage_Temp': [21.8, 21.1, 22.8, 23.3, 14.4, np.nan],
               'Minimun_Temp': [14.4, np.nan, np.nan, np.nan, 15.6, 18.3],
               'Maximum_Temp': [6.7, 14.4, 11.7, 16.1, np.nan, 10.0]}
</code>```

When I execute the command

```<code>data['Avarage_Temp'] = data[['Minimun_Temp', 'Maximum_Temp']].mean(axis=1).round(1)
</code>```

I get this output:

```<code>data = {'DATE': ['2012-01-01', '2013-05-16', '2013-05-28',
               '2013-06-05', '2013-06-07', '2014-02-02'],
               'Avarage_Temp': [10.6, 14.4, 11.7, 16.1, 15.6, 14.1],
               'Minimun_Temp': [14.4, np.nan, np.nan, np.nan, 15.6, 18.3],
               'Maximum_Temp': [6.7, 14.4, 11.7, 16.1, np.nan, 10.0]}
</code>```

As you can see in rows 2-5 the result is wrong, because in these rows it return the value of the non missing value(if Minimun_Temp is na, gives the value of Maximum_Temp  in the Avarage_Temp).
So I want to have as output something like the 1st and 6th row.
I want to change the value of Avarage_Temp only if the column Maximum_Temp and Minimun_Temp in this row aren't na's.
If Maximum_Temp or Minimun_Temp is na, I want to keep the value of Avarage_Temp as it is.

答:
You can create NaNs if at least one value in Minimun_Temp, Maximum_Temp by parameter skipna=False in DataFrame.mean and then replace them by column Avarage_Temp:

```<code>df = pd.DataFrame(data)

df['Avarage_Temp'] = (df[['Minimun_Temp', 'Maximum_Temp']].mean(axis=1, skipna=False)
                                                          .round(1)
                                                          .fillna(df['Avarage_Temp']))
print (df)
         DATE  Avarage_Temp  Minimun_Temp  Maximum_Temp
0  2012-01-01          10.6          14.4           6.7
1  2013-05-16          21.1           NaN          14.4
2  2013-05-28          22.8           NaN          11.7
3  2013-06-05          23.3           NaN          16.1
4  2013-06-07          14.4          15.6           NaN
5  2014-02-02          14.2          18.3          10.0
</code>```

Another idea with Series.add for NaNs if at least one NaN per rows and for mean divide by 2:

```<code>df['Avarage_Temp'] = (df['Minimun_Temp'].add(df['Maximum_Temp'])
                                        .div(2)
                                        .round(1)
                                        .fillna(df['Avarage_Temp']))
print (df)
         DATE  Avarage_Temp  Minimun_Temp  Maximum_Temp
0  2012-01-01          10.6          14.4           6.7
1  2013-05-16          21.1           NaN          14.4
2  2013-05-28          22.8           NaN          11.7
3  2013-06-05          23.3           NaN          16.1
4  2013-06-07          14.4          15.6           NaN
5  2014-02-02          14.2          18.3          10.0
</code>```

Body:
I have a dataset like this one

data = {'DATE': ['2012-01-01', '2013-05-16', '2013-05-28',
               '2013-06-05', '2013-06-07', '2014-02-02'],
               'Avarage_Temp': [21.8, 21.1, 22.8, 23.3, 14.4, np.nan],
               'Minimun_Temp': [14.4, np.nan, np.nan, np.nan, 15.6, 18.3],
               'Maximum_Temp': [6.7, 14.4, 11.7, 16.1, np.nan, 10.0]}

When I execute the command

data['Avarage_Temp'] = data[['Minimun_Temp', 'Maximum_Temp']].mean(axis=1).round(1)

I get this output:

data = {'DATE': ['2012-01-01', '2013-05-16', '2013-05-28',
               '2013-06-05', '2013-06-07', '2014-02-02'],
               'Avarage_Temp': [10.6, 14.4, 11.7, 16.1, 15.6, 14.1],
               'Minimun_Temp': [14.4, np.nan, np.nan, np.nan, 15.6, 18.3],
               'Maximum_Temp': [6.7, 14.4, 11.7, 16.1, np.nan, 10.0]}

As you can see in rows 2-5 the result is wrong, because in these rows it return the value of the non missing value(if Minimun_Temp is na, gives the value of Maximum_Temp  in the Avarage_Temp).
So I want to have as output something like the 1st and 6th row.
I want to change the value of Avarage_Temp only if the column Maximum_Temp and Minimun_Temp in this row aren't na's.
If Maximum_Temp or Minimun_Temp is na, I want to keep the value of Avarage_Temp as it is.

Body:
You can create NaNs if at least one value in Minimun_Temp, Maximum_Temp by parameter skipna=False in DataFrame.mean and then replace them by column Avarage_Temp:

df = pd.DataFrame(data)

df['Avarage_Temp'] = (df[['Minimun_Temp', 'Maximum_Temp']].mean(axis=1, skipna=False)
                                                          .round(1)
                                                          .fillna(df['Avarage_Temp']))
print (df)
         DATE  Avarage_Temp  Minimun_Temp  Maximum_Temp
0  2012-01-01          10.6          14.4           6.7
1  2013-05-16          21.1           NaN          14.4
2  2013-05-28          22.8           NaN          11.7
3  2013-06-05          23.3           NaN          16.1
4  2013-06-07          14.4          15.6           NaN
5  2014-02-02          14.2          18.3          10.0

Another idea with Series.add for NaNs if at least one NaN per rows and for mean divide by 2:

df['Avarage_Temp'] = (df['Minimun_Temp'].add(df['Maximum_Temp'])
                                        .div(2)
                                        .round(1)
                                        .fillna(df['Avarage_Temp']))
print (df)
         DATE  Avarage_Temp  Minimun_Temp  Maximum_Temp
0  2012-01-01          10.6          14.4           6.7
1  2013-05-16          21.1           NaN          14.4
2  2013-05-28          22.8           NaN          11.7
3  2013-06-05          23.3           NaN          16.1
4  2013-06-07          14.4          15.6           NaN
5  2014-02-02          14.2          18.3          10.0


问:
RMagick complaining about libMagickCore.5.dylib not found in OSX
after running brew upgrade imagemagick, when I run rails s I'll get

```<code>/Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require': dlopen(/Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/rmagick-2.13.2/lib/RMagick2.bundle, 9): Library not loaded: /usr/local/lib/libMagickCore.5.dylib (LoadError)
  Referenced from: /Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/rmagick-2.13.2/lib/RMagick2.bundle
  Reason: image not found - /Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/rmagick-2.13.2/lib/RMagick2.bundle
</code>```

I'm using Carrierwave gem with RMagick,  OS is OSX Moutain Lion

答:
The issue was fixed for by running
gem uninstall rmagick
and
gem install rmagick

Body:
after running brew upgrade imagemagick, when I run rails s I'll get

/Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/activesupport-4.0.0/lib/active_support/dependencies.rb:228:in `require': dlopen(/Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/rmagick-2.13.2/lib/RMagick2.bundle, 9): Library not loaded: /usr/local/lib/libMagickCore.5.dylib (LoadError)
  Referenced from: /Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/rmagick-2.13.2/lib/RMagick2.bundle
  Reason: image not found - /Users/tomi/.rvm/gems/ruby-2.0.0-p247@ezaaa/gems/rmagick-2.13.2/lib/RMagick2.bundle

I'm using Carrierwave gem with RMagick,  OS is OSX Moutain Lion


问:
Is there a React Native InAppBrowser that works with expo?
I am trying to use a in app browser in react native using expo and came across the react-native-inappbrowser-reborn package and I tried to use the given code example but always get this error when I alert it:

My code:

```<code>async function handleLink(link) {
 try {
  const url = link;
  if (await InAppBrowser.isAvailable()) {

  } else Linking.openURL(url);
} catch (error) {
  alert(error.message)
}
</code>```

}

I was wondering if any of you know this error or if there is a working alternative?

答:
There is a solution which i found few weeks ago
here: How To Add A In-App Browser In React-Native</p>

Body:
I am trying to use a in app browser in react native using expo and came across the react-native-inappbrowser-reborn package and I tried to use the given code example but always get this error when I alert it:

My code:

async function handleLink(link) {
 try {
  const url = link;
  if (await InAppBrowser.isAvailable()) {

  } else Linking.openURL(url);
} catch (error) {
  alert(error.message)
}

}

I was wondering if any of you know this error or if there is a working alternative?


问:
Java Streams: Find first for multiple filter predicates
I have a Collection<Product> and a Collection<Predicate<Product>>. The Predicates are a simple combination of boolean flags. For example:

```<code>             | isNew | isSoldOut
--------------------------------
predicate 1: | false | false
predicate 2: | false | true
predicate 3: | true  | false
predicate 4: | true  | true
</code>```

I want to find "one of every kind", though I'd like to find the first match for every Predicate within the products Collection.

Currently my code looks like this:

List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();

List<Product> result = predicates.stream()
  .flatMap(predicate -> products.stream().filter(predicate).findFirst().stream())
  .collect(Collectors.toList());
```

But this of course will iterate of the products Collection multiple times, which is not desired, because in my case I have 100000 Products and 64 Predicates and it takes a long time.

In my special case the Predicates are mutually exclusive: If a Predicate returns true, then all other Predicates can be skipped for that particular Product. And because I use findFirst this Predicate then can be skipped for all other Products.

I was wondering if it is possible to iterate over the Product Collection instead, and check every Product only once against all the Predicates.

答:
How about doing it the other way around? Streaming the products, and applying predicates on them.

```<code>List<Predicate<Product>> predicates = getPredicates();
List<Product> products = getProducts();
List<Product> filtered = products.stream().filter(product -> {
    Iterator<Predicate<Product>> iterator = predicates.iterator();
    while (iterator.hasNext()) {
        Predicate<Product> currentPredicate = iterator.next();
        if (currentPredicate.test(product)) {
             iterator.remove();
             return true;
        }
    }
    return false;
}).collect(Collectors.toList());
</code>```

The downside is you have to be careful which collection you use for predicates, Iterator.remove is not always supported.

Edit: Looks like i wasn't reading carefully enough. I think getting one of each would be best with loop.

```<code>List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();
List<Product> matchingProducts = new ArrayList<>(predicates.size());
for (Product product : products) {
    if (predicates.isEmpty()) {
        break;
    }
    for (int predicateIndex = 0; predicateIndex < predicates.size(); predicateIndex++) {
        Predicate<Product> predicate = predicates.get(predicateIndex);
        if (predicate.test(product)) {
            matchingProducts.add(product);
            predicates.remove(predicateIndex);
            break;
        }
    }
}
</code>```

Actually managed to achieve it with a stream and takeWhile, you were correct, Benjamin.

```<code>List<Predicate<Product>> predicates = getPredicates();
List<Product> products = getProducts();
List<Product> matches = products.stream()
        .takeWhile(product -> !predicates.isEmpty())
        .filter(product -> {
            Iterator<Predicate<Product>> iterator = predicates.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().test(product)) {
                    iterator.remove();
                    return true;
                }
            }
            return false;
        })
        .collect(Collectors.toList());
</code>```

Just make sure takeWhile is before filter, otherwise last matching element gets skipped.

Body:
I have a Collection<Product> and a Collection<Predicate<Product>>. The Predicates are a simple combination of boolean flags. For example:

             | isNew | isSoldOut
--------------------------------
predicate 1: | false | false
predicate 2: | false | true
predicate 3: | true  | false
predicate 4: | true  | true

I want to find "one of every kind", though I'd like to find the first match for every Predicate within the products Collection.

Currently my code looks like this:

List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();

List<Product> result = predicates.stream()
  .flatMap(predicate -> products.stream().filter(predicate).findFirst().stream())
  .collect(Collectors.toList());

But this of course will iterate of the products Collection multiple times, which is not desired, because in my case I have 100000 Products and 64 Predicates and it takes a long time.

In my special case the Predicates are mutually exclusive: If a Predicate returns true, then all other Predicates can be skipped for that particular Product. And because I use findFirst this Predicate then can be skipped for all other Products.

I was wondering if it is possible to iterate over the Product Collection instead, and check every Product only once against all the Predicates.

Body:
How about doing it the other way around? Streaming the products, and applying predicates on them.

List<Predicate<Product>> predicates = getPredicates();
List<Product> products = getProducts();
List<Product> filtered = products.stream().filter(product -> {
    Iterator<Predicate<Product>> iterator = predicates.iterator();
    while (iterator.hasNext()) {
        Predicate<Product> currentPredicate = iterator.next();
        if (currentPredicate.test(product)) {
             iterator.remove();
             return true;
        }
    }
    return false;
}).collect(Collectors.toList());

The downside is you have to be careful which collection you use for predicates, Iterator.remove is not always supported.

Edit: Looks like i wasn't reading carefully enough. I think getting one of each would be best with loop.

List<Product> products = getProducts();
List<Predicate<Product>> predicates = getPredicates();
List<Product> matchingProducts = new ArrayList<>(predicates.size());
for (Product product : products) {
    if (predicates.isEmpty()) {
        break;
    }
    for (int predicateIndex = 0; predicateIndex < predicates.size(); predicateIndex++) {
        Predicate<Product> predicate = predicates.get(predicateIndex);
        if (predicate.test(product)) {
            matchingProducts.add(product);
            predicates.remove(predicateIndex);
            break;
        }
    }
}

Actually managed to achieve it with a stream and takeWhile, you were correct, Benjamin.

List<Predicate<Product>> predicates = getPredicates();
List<Product> products = getProducts();
List<Product> matches = products.stream()
        .takeWhile(product -> !predicates.isEmpty())
        .filter(product -> {
            Iterator<Predicate<Product>> iterator = predicates.iterator();
            while (iterator.hasNext()) {
                if (iterator.next().test(product)) {
                    iterator.remove();
                    return true;
                }
            }
            return false;
        })
        .collect(Collectors.toList());

Just make sure takeWhile is before filter, otherwise last matching element gets skipped.


问:
What is the difference between a decentralized system and a distributed system?

I am looking for an academic answer about the two terms "Decentralized" and "Distributed".
the idea I have now is that decentralized systems (like blockchain) don't have a single point of control when in the distributed system we can control the whole system from a single point of the network.

答:
Blockchain is a distributed ledger that can be centralized or decentralized.

Bitcoin is a decentralized distributed ledger, however, private blockchains are centralized distributed ledgers. Distributed system means 2 or more nodes work with each other in accordance to achieve the common goal. It does not tell you anything about central authority.

In private blockchains, the consensus is maintained internally by a consortium.


问:
Is it possible to make the navigation drawer always open in Flutter?
I want the drawer to always open in screen so the user do not have to slide the screen from left to right. I found many question regarding this issue but I could not find it in Dart/Flutter.

This is the solution from @aziza on how to change the content of the Scaffold. body content upon user click on the Drawer but I want it to always open.

Flutter Drawer Widget - change Scaffold.body content

Flutter Drawer Widget - change Scaffold.body content

答:
I have done this using scaffold drawer. Please see and try this</p>
```<code>class _Dashbord extends State<Dashbord> {
  Widget bodyWidget = DashboardInitialContent();

  @override
  Widget build(BuildContext context) {
    final bool displayMobileLayout = MediaQuery.of(context).size.width < 500;
    return Row(
      children: [
        if (!displayMobileLayout)
          Drawer(
            // Add a ListView to the drawer. This ensures the user can scroll
            // through the options in the drawer if there isn't enough vertical
            // space to fit everything.
            child: ListView(
              // Important: Remove any padding from the ListView.
              // padding: EdgeInsets.zero,
              children: [
                DrawerHeader(
                  // decoration: const BoxDecoration(
                  //   color: Colors.white,
                  // ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        child: Image.asset(
                            "assets/images/3c98d8a48cfed2f87f377ec2b30130b4b9195af4.png"),
                      ),
                    ],
                  ),
                ),
                ListTile(
                  hoverColor: Colors.grey,
                  leading: const Icon(
                    Icons.dashboard,
                    color: Colors.deepOrange,
                  ),
                  title: const Text(
                    'Dashboard',
                    style: TextStyle(
                      fontSize: 20.0,
                      fontWeight: FontWeight.w600,
                      color: Colors.deepOrange,
                    ),
                  ),
                  onTap: () {
                    // Update the state of the app
                    // ...
                    // Then close the drawer
                    setState(() {
                      bodyWidget = DashboardInitialContent();
                    });
                  },
                )
              ],
            ),
          ),
        Expanded(
          child: Scaffold(
            appBar: AppBar(
              automaticallyImplyLeading: displayMobileLayout ? true : false,
              backgroundColor: Colors.deepOrange,
              actions: [
                IconButton(
                  icon: const Icon(Icons.notification_important_rounded),
                  tooltip: 'Notification',
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('This is a snackbar')));
                  },
                ),
                PopupMenuButton(
                  icon: const Icon(Icons.person_rounded),
                  tooltip: 'Profile',
                  itemBuilder: (BuildContext context) => <PopupMenuEntry>[
                    PopupMenuItem(
                      child: ListTile(
                        leading: Icon(Icons.edit),
                        title: Text('Edit Profile'),
                        onTap: () {
                          setState(() {
                            bodyWidget = UserProfile();
                            Navigator.pop(context);
                          });
                        },
                      ),
                    ),
                    PopupMenuItem(
                      child: ListTile(
                        leading: Icon(Icons.lock),
                        title: Text('Change Password'),
                        onTap: () {
                          setState(() {
                            bodyWidget = ChangePassword();
                            Navigator.pop(context);
                          });
                        },
                      ),
                    ),
                    const PopupMenuItem(
                      child: ListTile(
                        leading: Icon(Icons.logout),
                        title: Text('Sign out'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            drawer: displayMobileLayout
                ? Drawer(
                    // Add a ListView to the drawer. This ensures the user can scroll
                    // through the options in the drawer if there isn't enough vertical
                    // space to fit everything.
                    child: ListView(
                      // Important: Remove any padding from the ListView.
                      // padding: EdgeInsets.zero,
                      children: [
                        DrawerHeader(
                          // decoration: const BoxDecoration(
                          //   color: Colors.white,
                          // ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                child: Image.asset(
                                    "assets/images/3c98d8a48cfed2f87f377ec2b30130b4b9195af4.png"),
                              ),
                            ],
                          ),
                        ),
                        ListTile(
                          hoverColor: Colors.grey,
                          leading: const Icon(
                            Icons.dashboard,
                            color: Colors.deepOrange,
                          ),
                          title: const Text(
                            'Dashboard',
                            style: TextStyle(
                              fontSize: 20.0,
                              fontWeight: FontWeight.w600,
                              color: Colors.deepOrange,
                            ),
                          ),
                          onTap: () {
                            // Update the state of the app
                            // ...
                            // Then close the drawer
                            setState(() {
                              bodyWidget = DashboardInitialContent();
                            });
                            Navigator.pop(context);
                          },
                        )
                      ],
                    ),
                  )
                : null,
            body: bodyWidget,
          ),
        )
      ],
    );
  }
}
</code>```

Body:
I have done this using scaffold drawer. Please see and try this

class _Dashbord extends State<Dashbord> {
  Widget bodyWidget = DashboardInitialContent();

  @override
  Widget build(BuildContext context) {
    final bool displayMobileLayout = MediaQuery.of(context).size.width < 500;
    return Row(
      children: [
        if (!displayMobileLayout)
          Drawer(
            // Add a ListView to the drawer. This ensures the user can scroll
            // through the options in the drawer if there isn't enough vertical
            // space to fit everything.
            child: ListView(
              // Important: Remove any padding from the ListView.
              // padding: EdgeInsets.zero,
              children: [
                DrawerHeader(
                  // decoration: const BoxDecoration(
                  //   color: Colors.white,
                  // ),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      SizedBox(
                        child: Image.asset(
                            "assets/images/3c98d8a48cfed2f87f377ec2b30130b4b9195af4.png"),
                      ),
                    ],
                  ),
                ),
                ListTile(
                  hoverColor: Colors.grey,
                  leading: const Icon(
                    Icons.dashboard,
                    color: Colors.deepOrange,
                  ),
                  title: const Text(
                    'Dashboard',
                    style: TextStyle(
                      fontSize: 20.0,
                      fontWeight: FontWeight.w600,
                      color: Colors.deepOrange,
                    ),
                  ),
                  onTap: () {
                    // Update the state of the app
                    // ...
                    // Then close the drawer
                    setState(() {
                      bodyWidget = DashboardInitialContent();
                    });
                  },
                )
              ],
            ),
          ),
        Expanded(
          child: Scaffold(
            appBar: AppBar(
              automaticallyImplyLeading: displayMobileLayout ? true : false,
              backgroundColor: Colors.deepOrange,
              actions: [
                IconButton(
                  icon: const Icon(Icons.notification_important_rounded),
                  tooltip: 'Notification',
                  onPressed: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(content: Text('This is a snackbar')));
                  },
                ),
                PopupMenuButton(
                  icon: const Icon(Icons.person_rounded),
                  tooltip: 'Profile',
                  itemBuilder: (BuildContext context) => <PopupMenuEntry>[
                    PopupMenuItem(
                      child: ListTile(
                        leading: Icon(Icons.edit),
                        title: Text('Edit Profile'),
                        onTap: () {
                          setState(() {
                            bodyWidget = UserProfile();
                            Navigator.pop(context);
                          });
                        },
                      ),
                    ),
                    PopupMenuItem(
                      child: ListTile(
                        leading: Icon(Icons.lock),
                        title: Text('Change Password'),
                        onTap: () {
                          setState(() {
                            bodyWidget = ChangePassword();
                            Navigator.pop(context);
                          });
                        },
                      ),
                    ),
                    const PopupMenuItem(
                      child: ListTile(
                        leading: Icon(Icons.logout),
                        title: Text('Sign out'),
                      ),
                    ),
                  ],
                ),
              ],
            ),
            drawer: displayMobileLayout
                ? Drawer(
                    // Add a ListView to the drawer. This ensures the user can scroll
                    // through the options in the drawer if there isn't enough vertical
                    // space to fit everything.
                    child: ListView(
                      // Important: Remove any padding from the ListView.
                      // padding: EdgeInsets.zero,
                      children: [
                        DrawerHeader(
                          // decoration: const BoxDecoration(
                          //   color: Colors.white,
                          // ),
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              SizedBox(
                                child: Image.asset(
                                    "assets/images/3c98d8a48cfed2f87f377ec2b30130b4b9195af4.png"),
                              ),
                            ],
                          ),
                        ),
                        ListTile(
                          hoverColor: Colors.grey,
                          leading: const Icon(
                            Icons.dashboard,
                            color: Colors.deepOrange,
                          ),
                          title: const Text(
                            'Dashboard',
                            style: TextStyle(
                              fontSize: 20.0,
                              fontWeight: FontWeight.w600,
                              color: Colors.deepOrange,
                            ),
                          ),
                          onTap: () {
                            // Update the state of the app
                            // ...
                            // Then close the drawer
                            setState(() {
                              bodyWidget = DashboardInitialContent();
                            });
                            Navigator.pop(context);
                          },
                        )
                      ],
                    ),
                  )
                : null,
            body: bodyWidget,
          ),
        )
      ],
    );
  }
}