问:
confusion for view's and viewmodel's responsibility in mvvm architecture
i asked this some days ago here but didn't get any answer

i have a confusion about what code should be placed in view and what in viewmodel

for example click events

here is a snippet code of google ToDo app example for showing application architecture (Link):

```<code>//this code is placed in view (TasksFragment)
override fun onOptionsItemSelected(item: MenuItem) =
        when (item.itemId) {
            R.id.menu_clear -> {
                viewModel.clearCompletedTasks()
                true
            }
            R.id.menu_filter -> {
                showFilteringPopUpMenu()
                true
            }
            R.id.menu_refresh -> {
                viewModel.loadTasks(true)
                true
            }
            else -> false
        }

private fun showFilteringPopUpMenu() {
    val view = activity?.findViewById<View>(R.id.menu_filter) ?: return
    PopupMenu(requireContext(), view).run {
        menuInflater.inflate(R.menu.filter_tasks, menu)

    setOnMenuItemClickListener {
        viewModel.setFiltering(
            when (it.itemId) {
                R.id.active -> TasksFilterType.ACTIVE_TASKS
                R.id.completed -> TasksFilterType.COMPLETED_TASKS
                else -> TasksFilterType.ALL_TASKS
            }
        )
        viewModel.loadTasks(false)
        true
    }
    show()
  }
}
</code>```

as you can see there are 3 three items for a menu

2 of them delegated to viewmodel and one handled in view

beside that there are some logic in view that make decision based on view's id, but in mvvm definition said there must be no condition in view

答:
Is really easy. It depends, every architecture question is not written in golden characters. But there are some best practices that should be followed. You want to maintain your classes short, readable and most important testable. Moving your business logic to the view model is really important, because then you can test your viewModel with Junit tests without mocking specific Android components.

The when you mention is in some way business logic but the it.itemId you see is really dependent by the view  and is under the scope of the run command, moving into the viewmodel as parameter of the function setFiltering would be opinable for few developers

Even advanced Clean Architecture models could have and they actually have the status that is showed with a when, for instance

```<code> private fun handleDataState(resource: Resource<List<ProjectView>>) {
        when (resource.status) {
            ResourceState.SUCCESS -> {
                progress.visibility = View.GONE
                recycler_projects.visibility = View.VISIBLE
                resource.data?.let {
                    adapter.projects = it.map { mapper.mapToView(it) }
                    adapter.notifyDataSetChanged()
                }
            }
            ResourceState.LOADING -> {
                progress.visibility = View.VISIBLE
                recycler_projects.visibility = View.GONE
            }
        }
    }
</code>```

EDIT

the first  function viewModel.clearCompletedTasks()is delegated to the view model because you are going to clear the cache in (usually)a repository layer, in other words you are eliciting what is called an use case, delegating this so called business logic outside the view that is popular today to make it "as dumb as possible", you do not want that the view clear the tasks, but want that the underlyer object that represents the tasks is cleared, and only then is showed in the view as status.

The same is for the third viewModel.loadTasks(false) this is an use case as well and furthermore you are also passing a boolean, that is going to be injected into the viewModel, or even beyond if you use clear architecture. The rule of thumb is  the view should have view components, the business logic should stay in the view model. This is a good starting point, but please be aware that the MVVM can be applied to other types of more complex architectures.

Body:
i asked this some days ago here but didn't get any answer

i have a confusion about what code should be placed in view and what in viewmodel

for example click events

here is a snippet code of google ToDo app example for showing application architecture (Link):

//this code is placed in view (TasksFragment)
override fun onOptionsItemSelected(item: MenuItem) =
        when (item.itemId) {
            R.id.menu_clear -> {
                viewModel.clearCompletedTasks()
                true
            }
            R.id.menu_filter -> {
                showFilteringPopUpMenu()
                true
            }
            R.id.menu_refresh -> {
                viewModel.loadTasks(true)
                true
            }
            else -> false
        }

private fun showFilteringPopUpMenu() {
    val view = activity?.findViewById<View>(R.id.menu_filter) ?: return
    PopupMenu(requireContext(), view).run {
        menuInflater.inflate(R.menu.filter_tasks, menu)

    setOnMenuItemClickListener {
        viewModel.setFiltering(
            when (it.itemId) {
                R.id.active -> TasksFilterType.ACTIVE_TASKS
                R.id.completed -> TasksFilterType.COMPLETED_TASKS
                else -> TasksFilterType.ALL_TASKS
            }
        )
        viewModel.loadTasks(false)
        true
    }
    show()
  }
}

as you can see there are 3 three items for a menu

2 of them delegated to viewmodel and one handled in view

beside that there are some logic in view that make decision based on view's id, but in mvvm definition said there must be no condition in view

Body:
Is really easy. It depends, every architecture question is not written in golden characters. But there are some best practices that should be followed. You want to maintain your classes short, readable and most important testable. Moving your business logic to the view model is really important, because then you can test your viewModel with Junit tests without mocking specific Android components.

The when you mention is in some way business logic but the it.itemId you see is really dependent by the view  and is under the scope of the run command, moving into the viewmodel as parameter of the function setFiltering would be opinable for few developers

Even advanced Clean Architecture models could have and they actually have the status that is showed with a when, for instance

 private fun handleDataState(resource: Resource<List<ProjectView>>) {
        when (resource.status) {
            ResourceState.SUCCESS -> {
                progress.visibility = View.GONE
                recycler_projects.visibility = View.VISIBLE
                resource.data?.let {
                    adapter.projects = it.map { mapper.mapToView(it) }
                    adapter.notifyDataSetChanged()
                }
            }
            ResourceState.LOADING -> {
                progress.visibility = View.VISIBLE
                recycler_projects.visibility = View.GONE
            }
        }
    }

EDIT

the first  function viewModel.clearCompletedTasks()is delegated to the view model because you are going to clear the cache in (usually)a repository layer, in other words you are eliciting what is called an use case, delegating this so called business logic outside the view that is popular today to make it "as dumb as possible", you do not want that the view clear the tasks, but want that the underlyer object that represents the tasks is cleared, and only then is showed in the view as status.

The same is for the third viewModel.loadTasks(false) this is an use case as well and furthermore you are also passing a boolean, that is going to be injected into the viewModel, or even beyond if you use clear architecture. The rule of thumb is  the view should have view components, the business logic should stay in the view model. This is a good starting point, but please be aware that the MVVM can be applied to other types of more complex architectures.


来源: stackexchange

问:
SQL - Updating specific rows based on group by count
I want to update a set of rows if they fall within the result of a group by + having criteria:

Example Table:

```<code>equip_id | fiber_id | new_col
-----+-------------------------------------------------------------------
A        | 1        | *update this row/col because there are (3) A's
A        | 2        | *update this row/col because there are (3) A's
A        | 3        | *update this row/col because there are (3) A's
B        | 1        | *dont update this row/col because there are (4) B's
B        | 2        | *dont update this row/col because there are (4) B's
B        | 3        | *dont update this row/col because there are (4) B's
B        | 4        | *dont update this row/col because there are (4) B's
</code>```

I want to update new_col only where GROUP BY equip_id HAVING count(equip_id) = 3

Since GROUP BY is not supported in UPDATE, how do I achieve this result?

答:
You can use the following nested table expression:</p>

```<code>update table_name
set ...
where equip_id in (
    select equip_id
    from table_name
    group by equip_id
    having count(*) = 3
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to update a set of rows if they fall within the result of a group by + having criteria:

Example Table:

equip_id | fiber_id | new_col
-----+-------------------------------------------------------------------
A        | 1        | *update this row/col because there are (3) A's
A        | 2        | *update this row/col because there are (3) A's
A        | 3        | *update this row/col because there are (3) A's
B        | 1        | *dont update this row/col because there are (4) B's
B        | 2        | *dont update this row/col because there are (4) B's
B        | 3        | *dont update this row/col because there are (4) B's
B        | 4        | *dont update this row/col because there are (4) B's

I want to update new_col only where GROUP BY equip_id HAVING count(equip_id) = 3

Since GROUP BY is not supported in UPDATE, how do I achieve this result?

Body:
You can use the following nested table expression:

update table_name
set ...
where equip_id in (
    select equip_id
    from table_name
    group by equip_id
    having count(*) = 3
)


问:
Upgrading Doctrine Migrations
I am getting this warning on my codebase, here's my composer

```<code>Package zendframework/zend-eventmanager is abandoned, you should avoid using it. Use laminas/laminas-eventmanager instead.
</code>```

So I needed to upgrade Doctrine Migrations bundle, but I can't seem to upgrade it, and I can't find an upgrade log.
First I get errors about Doctrine\DBAL\Migrations\AbstractMigration, so I replaced them all to Doctrine\Migrations\AbstractMigration. Now I'm getting

```<code>Compile Error: Declaration of Application\Migrations\Version20170927104049::up(Doctrine\DBAL\Schema\Schema $schema) must be compatible with Doctrine\Migrations\AbstractMigration::up(Doctrine\DB
  AL\Schema\Schema $schema): void
</code>```

I asked for a CHANGELOG https://github.com/doctrine/DoctrineMigrationsBundle/issues/296

But anyhelp would be greatly appreciated

答:
The error tells you your function is not compatible with the abstract function, did you forget to add the return type to your function?

make it:

public function up(Schema $schema) : void
{}

Title: Upgrading Doctrine Migrations

Body:
I am getting this warning on my codebase, here's my composer

Package zendframework/zend-eventmanager is abandoned, you should avoid using it. Use laminas/laminas-eventmanager instead.

So I needed to upgrade Doctrine Migrations bundle, but I can't seem to upgrade it, and I can't find an upgrade log.
First I get errors about Doctrine\DBAL\Migrations\AbstractMigration, so I replaced them all to Doctrine\Migrations\AbstractMigration. Now I'm getting

Compile Error: Declaration of Application\Migrations\Version20170927104049::up(Doctrine\DBAL\Schema\Schema $schema) must be compatible with Doctrine\Migrations\AbstractMigration::up(Doctrine\DB
  AL\Schema\Schema $schema): void

I asked for a CHANGELOG https://github.com/doctrine/DoctrineMigrationsBundle/issues/296

But anyhelp would be greatly appreciated


问:
Implementing a C function that splits a string on a given character and returns an array of strings after the split (along with length of array)
I'm trying to implement a C function that takes a string and then breaks that string on a certain character and returns back an array of strings after the split along with the size of that array. I'm using a data structure for this since returning a 2D array (the array of strings after the split) and its length is not possible. My code is given below:

```<code>struct charArr {
    char *arr[10000];
    int size;
};

struct charArr *stringSplitter(char *str, char c) {
    struct charArr *splitString = (struct charArr *)malloc(sizeof(struct charArr));
    if (splitString == NULL) {
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    int i = 0;
    int j = 0;

    while (str[i] != '\0') {
        if (str[i] == c) {
            splitString->arr[splitString->size][j] = '\0';

            (splitString->size)++;
            j = 0;
            i++;

            while (str[i] == c) {    /* this loop is to ignore continuous occurrences of the character c */
                i++;
            }
        } else {
            splitString->arr[splitString->size][j] = str[i];
            i++;
            j++;
        }
    }
    splitString->arr[splitString->size][j] = '\0';
    return splitString;
}

int main(int argc, char *argv[]) {

    // take input from command line
    if (argc == 1) {
        //buffer to store lines
        size_t buffer_size = 128;
        char *buffer = malloc(buffer_size * sizeof(char));
        if (buffer == NULL) {
            fprintf(stderr, "malloc failed\n");
            exit(1);
        }

        // loop continuously till user exits by ctrl+c
        while (1) {
            printf("Enter Input> ");
            getline(&buffer, &buffer_size, stdin);

            char *str = strdup(buffer);

            struct charArr *splitString = stringSplitter(str, '&');

            for (int i = 0; i<splitString->size; i++) {
                printf("%s ", splitString->arr[i]);
            }
        }
    }
    return 0;
}
</code>```

On running the code on a simple input like (the input is continuously taken from the command line):

Enter Input> this & that

I expect the output to be:

this that

But, I'm getting the error:

Segmentation fault (core dumped)

If the input is as shown below (i.e; continuous occurrences of the splitting character):

Enter Input> this &&& that

then also the output must be:

this that

Edit: I'm trying to extend this to split a string on multiple delimiters as well (in one go), so instead of char c in the above function, if char *c is passed which is a string of delimiters (example c = " \t\n" to remove all white spaces from given string), then also it should work as expected and return an array of strings after the split and length of array.
For example, if input is (multiple spaces, tabs and newline):

```<code>Enter Input>      this                               that
</code>```

Then the array returned (which is a part of the returned structure) must be of size 2 and only contain the 2 strings - "this" and "that".

答:
Here's a rewrite of your function with the corrections that you need for proper allocation of each found string using strdup(): </p>

<p>You can find my modifications preceded with comments that start 'Previously':  </p>

```<code>struct charArr* stringSplitter(char *str, char c){
    struct charArr* splitString = (struct charArr*)malloc(sizeof(struct charArr));
    char buffer[ MAX_BUFF ] ;
    if(splitString == NULL){
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    int i=0;
    int j=0;

    while(str[i] != '\0'){

        if(str[i] == c){
            //Previously:  splitString->arr[splitString->size][j] = '\0';
            splitString->arr[splitString->size] = strndup( buffer , j );

            (splitString->size)++;
            j = 0;
            i++;

            while(str[i] == c){    /* this loop is to ignore continuous occurrences of the character c */
                i++;
            }
        } else {
            // Previously:  splitString->arr[splitString->size][j] = str[i];
            buffer[j] = str[i];
            i++;
            j++;
        }

    }
    //Previously:  splitString->arr[splitString->size][j] = '\0';
    splitString->arr[splitString->size++] = strndup( buffer , j );
    return splitString;
}
</code>```

Body:
I'm trying to implement a C function that takes a string and then breaks that string on a certain character and returns back an array of strings after the split along with the size of that array. I'm using a data structure for this since returning a 2D array (the array of strings after the split) and its length is not possible. My code is given below:

struct charArr {
    char *arr[10000];
    int size;
};

struct charArr *stringSplitter(char *str, char c) {
    struct charArr *splitString = (struct charArr *)malloc(sizeof(struct charArr));
    if (splitString == NULL) {
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    int i = 0;
    int j = 0;

    while (str[i] != '\0') {
        if (str[i] == c) {
            splitString->arr[splitString->size][j] = '\0';

            (splitString->size)++;
            j = 0;
            i++;

            while (str[i] == c) {    /* this loop is to ignore continuous occurrences of the character c */
                i++;
            }
        } else {
            splitString->arr[splitString->size][j] = str[i];
            i++;
            j++;
        }
    }
    splitString->arr[splitString->size][j] = '\0';
    return splitString;
}

int main(int argc, char *argv[]) {

    // take input from command line
    if (argc == 1) {
        //buffer to store lines
        size_t buffer_size = 128;
        char *buffer = malloc(buffer_size * sizeof(char));
        if (buffer == NULL) {
            fprintf(stderr, "malloc failed\n");
            exit(1);
        }

        // loop continuously till user exits by ctrl+c
        while (1) {
            printf("Enter Input> ");
            getline(&buffer, &buffer_size, stdin);

            char *str = strdup(buffer);

            struct charArr *splitString = stringSplitter(str, '&');

            for (int i = 0; i<splitString->size; i++) {
                printf("%s ", splitString->arr[i]);
            }
        }
    }
    return 0;
}

On running the code on a simple input like (the input is continuously taken from the command line):

Enter Input> this & that

I expect the output to be:

this that

But, I'm getting the error:

Segmentation fault (core dumped)

If the input is as shown below (i.e; continuous occurrences of the splitting character):

Enter Input> this &&& that

then also the output must be:

this that

Edit: I'm trying to extend this to split a string on multiple delimiters as well (in one go), so instead of char c in the above function, if char *c is passed which is a string of delimiters (example c = " \t\n" to remove all white spaces from given string), then also it should work as expected and return an array of strings after the split and length of array.
For example, if input is (multiple spaces, tabs and newline):

Enter Input>      this                               that

Then the array returned (which is a part of the returned structure) must be of size 2 and only contain the 2 strings - "this" and "that".

Body:
Here's a rewrite of your function with the corrections that you need for proper allocation of each found string using strdup():

You can find my modifications preceded with comments that start 'Previously':

struct charArr* stringSplitter(char *str, char c){
    struct charArr* splitString = (struct charArr*)malloc(sizeof(struct charArr));
    char buffer[ MAX_BUFF ] ;
    if(splitString == NULL){
        fprintf(stderr, "malloc failed\n");
        exit(1);
    }
    splitString->size = 0;
    int i=0;
    int j=0;

    while(str[i] != '\0'){

        if(str[i] == c){
            //Previously:  splitString->arr[splitString->size][j] = '\0';
            splitString->arr[splitString->size] = strndup( buffer , j );

            (splitString->size)++;
            j = 0;
            i++;

            while(str[i] == c){    /* this loop is to ignore continuous occurrences of the character c */
                i++;
            }
        } else {
            // Previously:  splitString->arr[splitString->size][j] = str[i];
            buffer[j] = str[i];
            i++;
            j++;
        }

    }
    //Previously:  splitString->arr[splitString->size][j] = '\0';
    splitString->arr[splitString->size++] = strndup( buffer , j );
    return splitString;
}


问:
Which value of hibernate.hbm2ddl.auto property should be used in production environment?
Which value of hibernate.hbm2ddl.auto property should be used in production environment? Whether it should be create, update or create-drop????</p>

答:
You should set hibernate.hbm2ddl.auto to validate in all your environments/profiles.

You might want to check Liquibase or Flyway to update your DB in running envs and for integration testing.


问:
Mapping A simple XSD userdefined simple type to A .net class
I have a XSD I generated using xsd.exe and then created a class off the the xsd.  Everything worked great but some of the elements have common business rules.  For example all of the amounts in our xml are expressed without the decimal so 3.94$ becomes 394.  I have created a xml simple type to represent all of the attributes that are defined in this way, but haven't figured out how to map the xsd type to a .net class that can handle the business logic of how the data has to be stored in the xml.  I have created complex types before but not simple types that are used in attributes can some one point me in the right directory

A very Simplified XML snip it

```<code><Check amt="356" >
   <LNItem amt="123" />
   <LNItem amt="223" />
</Check>
</code>```

I would like a class like the following.

```<code>[XmlType(Check)]
public
{
    AmtType Amt {get;set}

}
</code>```

答:
This should do it:</p>

```<code>[XmlRoot(Check)]
public class Check
{
    [XmlElement("LNItem")]
    public List<LNItem> LNItems { get; set; }
}

[XmlRoot(LNItem)]
public class LNItem
{
    [XmlAttribute("amt")]
    public AmtType Amt { get; set; }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a XSD I generated using xsd.exe and then created a class off the the xsd.  Everything worked great but some of the elements have common business rules.  For example all of the amounts in our xml are expressed without the decimal so 3.94$ becomes 394.  I have created a xml simple type to represent all of the attributes that are defined in this way, but haven't figured out how to map the xsd type to a .net class that can handle the business logic of how the data has to be stored in the xml.  I have created complex types before but not simple types that are used in attributes can some one point me in the right directory

A very Simplified XML snip it

<Check amt="356" >
   <LNItem amt="123" />
   <LNItem amt="223" />
</Check>

I would like a class like the following.

[XmlType(Check)]
public
{
    AmtType Amt {get;set}

}

Body:
This should do it:

[XmlRoot(Check)]
public class Check
{
    [XmlElement("LNItem")]
    public List<LNItem> LNItems { get; set; }
}

[XmlRoot(LNItem)]
public class LNItem
{
    [XmlAttribute("amt")]
    public AmtType Amt { get; set; }
}


问:
Angular 6 - Validators pattern not working
I am using a reactive form in angular 6, and trying to do some validation on a password field. Basically it needs to be more than 8 characters, contain at least 1 upper case, and contain at least 1 symbol.

my regex which I have tested, is ^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})

Here is an excerpt from my login component ts:

```<code>  ngOnInit() {
        this.loginForm = this.formBuilder.group({
            userName: ['Username', [Validators.required]],
            password: ['Password', [Validators.pattern("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})")]]
        });
    }
</code>```

Here is my form group div:

```<code> <div class="form-group">
                      <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
                      <div *ngIf="submitted && f.password.errors" class="invalid-feedback">
                          <div *ngIf="f.password.errors.pattern">Password must contain more than 8 characters, 1 upper case letter, and 1 special character</div>
                      </div>
                  </div>
</code>```

Basically the password does not validate even if it appears to be correct. Any tips would be appreciated.

答:
```<code> pattern1 =  "^[0-9_-]{10,12}$";
 phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]
</code>```

Body:
I am using a reactive form in angular 6, and trying to do some validation on a password field. Basically it needs to be more than 8 characters, contain at least 1 upper case, and contain at least 1 symbol.

my regex which I have tested, is ^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})

Here is an excerpt from my login component ts:

  ngOnInit() {
        this.loginForm = this.formBuilder.group({
            userName: ['Username', [Validators.required]],
            password: ['Password', [Validators.pattern("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})")]]
        });
    }

Here is my form group div:

                      <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />

Password must contain more than 8 characters, 1 upper case letter, and 1 special character

Basically the password does not validate even if it appears to be correct. Any tips would be appreciated.


问:
Ternary inside of map returning no results
I'm trying to create a very basic filter system. I currently have the whole object displaying as a list which is great however when I try to copy the same component with a ternary statement inside of the map function it returns no results, it compiles with no errors but just does not display any items within the object.

I'm fairly new to this so please explain like I'm 5.

The filtered component:

```<code>function Torquay() {
  return (

    <div className="container">

      <div className="row">

        {spaces.map(item => {
          return item.town === 'Torquay' ?
            <div className="col-sm-12 col-md-6 col-lg-4">

              <div className="card mb-sm-5">
                  <span className="badge badge-light">{item.town}</span>
                  <h4 className="card-title">{item.name}</h4>

                  <div className="wifi">
                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-wifi"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>
                    <h6>{item.net}Mbps</h6>
                  </div>

                  <div className="amenities">
                    <ul>
                      <li>
                        {item.day === true ? <span role="img" aria-label="Open in day"></span> : null}
                      </li>
                      <li>
                        {item.night === true ? <span role="img" aria-label="Open at night"></span> : null}
                      </li>
                      <li>
                        {item.dog === true ? <span role="img" aria-label="Dog friendly"></span> : null}
                      </li>
                      <li>
                        {item.parking === true ? <span role="img" aria-label="Car parking"></span> : null}
                      </li>
                    </ul>
                  </div>

                  <img src={item.image} className="card-img-top" alt="..."/>
              </div>

            </div>
          : null}

        )}

      </div>

    </div>
  );
}
</code>```

The object structure:

```<code>const spaces = [
  {
    name: 'WeSup Torquay',
    image: '/img/wesup/1.jpg',
    town: 'Torquay',
    net: 20,
    parking: true,
    dog: true,
    day: true,
    night: true,
  },
</code>```

Thanks in advance!

答: I've now fixed this issue, it was due to not defining the path of the component when utilising react router. Thanks all for letting me know that it technically should work (although not the best approach).</p>

Body:
I'm trying to create a very basic filter system. I currently have the whole object displaying as a list which is great however when I try to copy the same component with a ternary statement inside of the map function it returns no results, it compiles with no errors but just does not display any items within the object.

I'm fairly new to this so please explain like I'm 5.

The filtered component:

function Torquay() {
  return (

        {spaces.map(item => {
          return item.town === 'Torquay' ?

                  {item.town}

{item.name}

                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-wifi"><path d="M5 12.55a11 11 0 0 1 14.08 0"></path><path d="M1.42 9a16 16 0 0 1 21.16 0"></path><path d="M8.53 16.11a6 6 0 0 1 6.95 0"></path><line x1="12" y1="20" x2="12.01" y2="20"></line></svg>

{item.net}Mbps

                        {item.day === true ?  : null}

                        {item.night === true ?  : null}

                        {item.dog === true ?  : null}

                        {item.parking === true ?  : null}

          : null}

        )}

  );
}

The object structure:

const spaces = [
  {
    name: 'WeSup Torquay',
    image: '/img/wesup/1.jpg',
    town: 'Torquay',
    net: 20,
    parking: true,
    dog: true,
    day: true,
    night: true,
  },

Thanks in advance!


问:
Best way to display a list of toggleable array of items in SwiftUI
For a something that would be simple with UIKit, I'm struggling to find the best solution using SwiftUI. I would appreciate any help / guidance.

I have an array of objects, each of which can be selected. My first attempt do display this was:

```<code>final class MeasurementSelections: ObservableObject {

    struct Measurement: Identifiable {
        let id = UUID()
        let name: String
        var isSelected: Bool = false

        init(name: String) {
            self.name = name
        }
    }

    @Published var measurements: [Measurement]

    init(measurements: [Measurement]) {
        self.measurements = measurements
    }
}

struct Readings: View {

    @ObservedObject var model: MeasurementSelections

    var body: some View {
        List(0..<model.measurements.count) { index in
            Text(self.model.measurements[index].name)
                .font(.subheadline)
            Spacer()
            Toggle(self.model.measurements[index].name, isOn: self.$model.measurements[index].isSelected)
                .labelsHidden()
        }
    }
}
</code>```

This is fairly straightforward, but the use of a Range and the replication of self.model.measurements[index] doesn't seem right… I'd rather have a separate View that takes a Measurement as a parameter.

Follow this answer, my next attempt was…

```<code>final class MeasurementSelections: ObservableObject {

    struct Measurement: Identifiable {
        let id = UUID()
        let name: String
        var isSelected: Binding<Bool>

        private var selected: Bool = false

        init(name: String) {
            self.name = name

            let selected = CurrentValueSubject<Bool, Never>(false)
            self.isSelected = Binding<Bool>(get: { selected.value }, set: { selected.value = $0 })
        }
    }

    @Published var measurements: [Measurement]

    init(measurements: [Measurement]) {
        self.measurements = measurements
    }
}

struct Readings: View {

    @ObservedObject var model: MeasurementSelections

    var body: some View {
        VStack {
            MeasurementView(measurement: measurement)
        }
    }
}

struct MeasurementView: View {
    let measurement: MeasurementSelections.Measurement
    var body: some View {
        HStack {
            Text(measurement.name)
                .font(.subheadline)
            Spacer()
            Toggle(measurement.name, isOn: measurement.isSelected)
                .labelsHidden()
        }
    }
}
</code>```

This is nicer as regards the view separation, but now the MeasurementSelections class has become significantly more complicated, and requires Combine.

Is there a solution to this problem that keeps the view separation but with a simpler model?

Additionally, I'd eventually like the MeasurementSelections to expose a bindable(?) Bool property that is set when ANY of its measurements are selected, which might inform your answer

答:
the use of a Range and the replication of
  self.model.measurements[index] doesn't seem right…

There is no replication, you manipulating data in your model directly, without any "replication"

```<code>import SwiftUI

struct Data: Identifiable {
    let id = UUID()
    var name: String
    var on_off: Bool
}

class Model: ObservableObject {
    @Published var data = [Data(name: "alfa", on_off: false), Data(name: "beta", on_off: false), Data(name: "gama", on_off: false)]
}

struct ContentView: View {
    @ObservedObject var model = Model()
    var body: some View {
        List(0 ..< model.data.count) { idx in
            HStack {
                Text(verbatim: self.model.data[idx].name)
                Toggle(isOn: self.$model.data[idx].on_off) {
                    EmptyView()
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
</code>```

Body:
For a something that would be simple with UIKit, I'm struggling to find the best solution using SwiftUI. I would appreciate any help / guidance.

I have an array of objects, each of which can be selected. My first attempt do display this was:

final class MeasurementSelections: ObservableObject {

    struct Measurement: Identifiable {
        let id = UUID()
        let name: String
        var isSelected: Bool = false

        init(name: String) {
            self.name = name
        }
    }

    @Published var measurements: [Measurement]

    init(measurements: [Measurement]) {
        self.measurements = measurements
    }
}

struct Readings: View {

    @ObservedObject var model: MeasurementSelections

    var body: some View {
        List(0..<model.measurements.count) { index in
            Text(self.model.measurements[index].name)
                .font(.subheadline)
            Spacer()
            Toggle(self.model.measurements[index].name, isOn: self.$model.measurements[index].isSelected)
                .labelsHidden()
        }
    }
}

This is fairly straightforward, but the use of a Range and the replication of self.model.measurements[index] doesn't seem right… I'd rather have a separate View that takes a Measurement as a parameter.

Follow this answer, my next attempt was…

final class MeasurementSelections: ObservableObject {

    struct Measurement: Identifiable {
        let id = UUID()
        let name: String
        var isSelected: Binding<Bool>

        private var selected: Bool = false

        init(name: String) {
            self.name = name

            let selected = CurrentValueSubject<Bool, Never>(false)
            self.isSelected = Binding<Bool>(get: { selected.value }, set: { selected.value = $0 })
        }
    }

    @Published var measurements: [Measurement]

    init(measurements: [Measurement]) {
        self.measurements = measurements
    }
}

struct Readings: View {

    @ObservedObject var model: MeasurementSelections

    var body: some View {
        VStack {
            MeasurementView(measurement: measurement)
        }
    }
}

struct MeasurementView: View {
    let measurement: MeasurementSelections.Measurement
    var body: some View {
        HStack {
            Text(measurement.name)
                .font(.subheadline)
            Spacer()
            Toggle(measurement.name, isOn: measurement.isSelected)
                .labelsHidden()
        }
    }
}

This is nicer as regards the view separation, but now the MeasurementSelections class has become significantly more complicated, and requires Combine.

Is there a solution to this problem that keeps the view separation but with a simpler model?

Additionally, I'd eventually like the MeasurementSelections to expose a bindable(?) Bool property that is set when ANY of its measurements are selected, which might inform your answer

Body:
the use of a Range and the replication of
  self.model.measurements[index] doesn't seem right…

There is no replication, you manipulating data in your model directly, without any "replication"

import SwiftUI

struct Data: Identifiable {
    let id = UUID()
    var name: String
    var on_off: Bool
}

class Model: ObservableObject {
    @Published var data = [Data(name: "alfa", on_off: false), Data(name: "beta", on_off: false), Data(name: "gama", on_off: false)]
}

struct ContentView: View {
    @ObservedObject var model = Model()
    var body: some View {
        List(0 ..< model.data.count) { idx in
            HStack {
                Text(verbatim: self.model.data[idx].name)
                Toggle(isOn: self.$model.data[idx].on_off) {
                    EmptyView()
                }
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}


问:
Are all inputs supposed to be mutable in Rust?
I wanted to input a value and assign it to a variable that is immutable (should be). How can I do that?

Currently, I am doing this:

```<code>use std::io;

fn main() {
    let mut a = 0;
    let mut b = 1;
    let mut nth_term = String::new();
    io::stdin().read_line(&mut nth_term);
}
</code>```

But without &mut, it generates an error: types differ in mutability. If I remove mut from the declaration I get an error like this:

error[E0308]: mismatched types
 --> src/main.rs:5:27
  |
5 |     io::stdin().read_line(&nth_term).expect("I/O error");
  |                           ^^^^^^^^^ types differ in mutability
  |
  = note: expected mutable reference `&mut std::string::String`
                     found reference `&std::string::String`
```

<p>How can I have something like this:</p>

```let input_var = input(); // or some other function that inputs the value and directly assigns it.
```

I tried reading the official documentation, the first few chapters, but in vain.

答:
Mutability in Rust follows the name, not the value. So if you have a value that is bound to a mutable variable, and you want it to be immutable, all you have to do is rebind it:

```<code>fn main() {
    let mut nth_term = String::new();
    io::stdin().read_line(&mut nth_term).expect("I/O error");
    let nth_term = nth_term;
    //  ^^^^^^^^-- no `mut`
}
</code>```

Rebinding a value to the same name with a different mutability is common (see What does 'let x = x' do in Rust?).

You can also put the original binding in a block expression to minimize the scope of the mut variable:

```<code>fn main() {
    let nth_term = {
        let mut nth_term = String::new();
        io::stdin().read_line(&mut nth_term).expect("I/O error");
        nth_term
    };
}
</code>```

BufRead::read_line is defined this way so that you don't need to allocate a new String for each new line read. The method has to take &mut because it can grow the string. Although you can iterate over input lines with stdin().lines(), which does yield owned Strings, there is no standard I/O function that reads a single line from stdin and returns a String (which you could simply bind to a non-mut variable). Of course, if you find yourself doing that a lot, you could just write your own function that contains the mut and returns, for instance, an io::Result<String>.

Body:
I wanted to input a value and assign it to a variable that is immutable (should be). How can I do that?

Currently, I am doing this:

use std::io;

fn main() {
    let mut a = 0;
    let mut b = 1;
    let mut nth_term = String::new();
    io::stdin().read_line(&mut nth_term);
}

But without &mut, it generates an error: types differ in mutability. If I remove mut from the declaration I get an error like this:

error[E0308]: mismatched types
 --> src/main.rs:5:27
  |
5 |     io::stdin().read_line(&nth_term).expect("I/O error");
  |                           ^^^^^^^^^ types differ in mutability
  |
  = note: expected mutable reference `&mut std::string::String`
                     found reference `&std::string::String`

How can I have something like this:

let input_var = input(); // or some other function that inputs the value and directly assigns it.

I tried reading the official documentation, the first few chapters, but in vain.

Body:
Mutability in Rust follows the name, not the value. So if you have a value that is bound to a mutable variable, and you want it to be immutable, all you have to do is rebind it:

fn main() {
    let mut nth_term = String::new();
    io::stdin().read_line(&mut nth_term).expect("I/O error");
    let nth_term = nth_term;
    //  ^^^^^^^^-- no `mut`
}

Rebinding a value to the same name with a different mutability is common (see What does 'let x = x' do in Rust?).

You can also put the original binding in a block expression to minimize the scope of the mut variable:

fn main() {
    let nth_term = {
        let mut nth_term = String::new();
        io::stdin().read_line(&mut nth_term).expect("I/O error");
        nth_term
    };
}

BufRead::read_line is defined this way so that you don't need to allocate a new String for each new line read. The method has to take &mut because it can grow the string. Although you can iterate over input lines with stdin().lines(), which does yield owned Strings, there is no standard I/O function that reads a single line from stdin and returns a String (which you could simply bind to a non-mut variable). Of course, if you find yourself doing that a lot, you could just write your own function that contains the mut and returns, for instance, an io::Result<String>.


问:
How create application backend in django and create a api so that other developers can use that as well
I just started learning Django and wanted to make an application with API (probably REST) endpoints so that other developers can use it as well (like GitHub API), and I could connect it to my react app and android app. I want my backend to be on a different server and do not want to build my react app integrated with Django backend using the REST Framework.

Can anyone just give me the general idea of what I need to do?

P.S. Sorry in advance if my question sounds silly, I am still new to backend.

答:
First off all you can start from this.
https://www.django-rest-framework.org/tutorial/quickstart/</p>


问:
Decode JSON, including array from URL paramter in JavaScript
I have this URL:

```<code>http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000
</code>```

Now I'm trying to encode the URL to an Object. This is my current attempt:

```<code>function URLToArray(url) {
  var request = {};
  var pairs = url.substring(url.indexOf('?') + 1).split('&');
  for (var i = 0; i < pairs.length; i++) {
      if(!pairs[i])
          continue;
      var pair = pairs[i].split('=');
      request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
   }
   return request;
}
</code>```

However I need this function to return the array as a JSON array, and not the way it currently does:

How do I get my function to return my object array?

答:
You could first get the object with help from this question.

Example using URLSearchParams with a regular expression loop:

const url = "http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000";

const regex = /^([a-z0-9]+)?\[([a-zA-Z0-9]+)\]*/mi;

function URLToArray(url) {
 url = decodeURIComponent(url);
  const args = new URLSearchParams(url.split('?')[1]);

  let request = {};
  args.forEach((value, key) => {
   let baseKey = key;
    let ogValue = value;
    let lastKey = '';
   while ((m = regex.exec(key)) !== null) {
     if (m[1]) {
       baseKey = m[1];
        value = request[baseKey] || {};
       request[baseKey] = value;
      }

      if (m[2]) {
       value = value[lastKey] || value;
        value[m[2]] = value[m[2]] || {};
       lastKey = m[2];
      }

      key = key.replace(m[0], '');
    }

    if (lastKey) {
     value[lastKey] = ogValue;
    } else {
     request[baseKey] = value;
    }
  });
  return request;
}

console.log(URLToArray(url));```

This isn't perfect you will be left with nested objects as opposed to proper arrays for your items, and there are likely libraries that can achieve the same result better.

Body:
I have this URL:

http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000

Now I'm trying to encode the URL to an Object. This is my current attempt:

function URLToArray(url) {
  var request = {};
  var pairs = url.substring(url.indexOf('?') + 1).split('&');
  for (var i = 0; i < pairs.length; i++) {
      if(!pairs[i])
          continue;
      var pair = pairs[i].split('=');
      request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
   }
   return request;
}

However I need this function to return the array as a JSON array, and not the way it currently does:

How do I get my function to return my object array?

Body:
You could first get the object with help from this question.

Example using URLSearchParams with a regular expression loop:

const url = "http://localhost:5000/?orderID=000000034&fullname=Leonard+Niehaus&email=test%40gmail.com&items%5B0%5D%5BitemId%5D=9&items%5B0%5D%5Btitle%5D=Joghurt&items%5B0%5D%5Bqty%5D=1.0000&items%5B1%5D%5BitemId%5D=8&items%5B1%5D%5Btitle%5D=Alpenmilch&items%5B1%5D%5Bqty%5D=1.0000";

const regex = /^([a-z0-9]+)?\[([a-zA-Z0-9]+)\]*/mi;

function URLToArray(url) {
 url = decodeURIComponent(url);
  const args = new URLSearchParams(url.split('?')[1]);

  let request = {};
  args.forEach((value, key) => {
   let baseKey = key;
    let ogValue = value;
    let lastKey = '';
   while ((m = regex.exec(key)) !== null) {
     if (m[1]) {
       baseKey = m[1];
        value = request[baseKey] || {};
       request[baseKey] = value;
      }

      if (m[2]) {
       value = value[lastKey] || value;
        value[m[2]] = value[m[2]] || {};
       lastKey = m[2];
      }

      key = key.replace(m[0], '');
    }

    if (lastKey) {
     value[lastKey] = ogValue;
    } else {
     request[baseKey] = value;
    }
  });
  return request;
}

console.log(URLToArray(url));

This isn't perfect you will be left with nested objects as opposed to proper arrays for your items, and there are likely libraries that can achieve the same result better.


问:
How can I run a protractor config file (.ts) with ts-node?
I used to compile e2e protractor tests written in TS before run, but now I figured out how to compile ts files in run-time -- ts-node appeared to be a great tool for that. As many articles say, I registered ts-node in protractor config file, so that I can run my test specs as if they are .ts files and they will be compiled in tun-time. Something like this:

```<code>beforeLaunch: () => {
        require('ts-node').register({
            compilerOptions: {
                module: 'commonjs'
            },
            disableWarnings: true,
            fast: true
          });
    },

</code>```

That's great. But all cases I met included examples with .js config files --> you don't need to compile config files, but all specs can be in TS and will be compiled with ts-node.
What I wish to have is having all my files in TypeScript: both configs and specs. How can I run my protractor tests giving config.ts and having specs.ts in there?
Something like protractor ts-node config.ts would be just awesome.

答:
Just create another .js file that will have following

launcher.js

```<code>        require('ts-node').register({
            compilerOptions: {
                module: 'commonjs'
            },
            disableWarnings: true,
            fast: true
        });
        module.export.config = require('./protractor.conf.ts').config;

</code>```

Then run protractor and pass launcher as config file:

```<code>protractor launcher.js
</code>```

Body:
I used to compile e2e protractor tests written in TS before run, but now I figured out how to compile ts files in run-time -- ts-node appeared to be a great tool for that. As many articles say, I registered ts-node in protractor config file, so that I can run my test specs as if they are .ts files and they will be compiled in tun-time. Something like this:

beforeLaunch: () => {
        require('ts-node').register({
            compilerOptions: {
                module: 'commonjs'
            },
            disableWarnings: true,
            fast: true
          });
    },

That's great. But all cases I met included examples with .js config files --> you don't need to compile config files, but all specs can be in TS and will be compiled with ts-node.
What I wish to have is having all my files in TypeScript: both configs and specs. How can I run my protractor tests giving config.ts and having specs.ts in there?
Something like protractor ts-node config.ts would be just awesome.

Body:
Just create another .js file that will have following

launcher.js

        require('ts-node').register({
            compilerOptions: {
                module: 'commonjs'
            },
            disableWarnings: true,
            fast: true
        });
        module.export.config = require('./protractor.conf.ts').config;

Then run protractor and pass launcher as config file:

protractor launcher.js


问:
Getting pyodbc to connect in AWS Lambda Layer
I have built deployment package to connect to a AWS RDS instance via pyodbc, after zipping up and uploading to AWS lambda this connection works.

When trying to connect via an AWS layer, following error is displayed.

```<code>"errorMessage": "('01000', \"[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect)\")",
  "errorType": "Error",
</code>```

Tried to change the path for the driver in the odbcinst.ini file, but with no luck

Example of text in odbcinst.ini file

```<code>[ODBC Driver 13 for SQL Server]
Description=Microsoft ODBC Driver 13 for SQL Server
Driver=/var/task/msodbcsql/lib64/libmsodbcsql-13.1.so.9.2
UsageCount=1
</code>```

答:
If you're willing to use ODBC Driver 17 then I recommend Alexander's pyodbc layer which you can find on GitHub: https://github.com/alexanderluiscampino/lambda-layers

There's also a discussion of it when it was first being constructed that can be helpful for context: https://gist.github.com/diriver63/b72a954fa0da4851d89e5086aa13c6e8

I've used this myself and had good luck with it. I originally found it after finding that pyodbc has no binary wheels and so AWS SAM can't simply install it: https://github.com/awslabs/aws-sam-cli/issues/1577

Body:
I have built deployment package to connect to a AWS RDS instance via pyodbc, after zipping up and uploading to AWS lambda this connection works.

When trying to connect via an AWS layer, following error is displayed.

"errorMessage": "('01000', \"[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 13 for SQL Server' : file not found (0) (SQLDriverConnect)\")",
  "errorType": "Error",

Tried to change the path for the driver in the odbcinst.ini file, but with no luck

Example of text in odbcinst.ini file

[ODBC Driver 13 for SQL Server]
Description=Microsoft ODBC Driver 13 for SQL Server
Driver=/var/task/msodbcsql/lib64/libmsodbcsql-13.1.so.9.2
UsageCount=1


问:
How to count IMG tags within DIV using Xpath
I want to count how many IMG tags there are under the surface div tag and echo the amount.

```<code><div id="surface" style="width: 4567px; height: 4137px; left: -1850px; top: -1152px; cursor: default;">

<img src="https://media.memories.png" data-seat="L:106|EE:5" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2221px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:6" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2237px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:7" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2253px; top: 1561px; display: block;">

<img src="https://media.memories.png" data-seat="L:106|EE:8" data-pl="1" style="position: absolute; cursor: pointer; width: 14px; height: 14px; left: 2269px; top: 1561px; display: block;">

</div>
</code>```

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

```<code>"//div[@surface='data-seat']/img"
</code>```

答:
Try:

```<code>//div[@surface='data-seat']/count(img)
</code>```

For your example html, it outputs 4.

Body:
I want to count how many IMG tags there are under the surface div tag and echo the amount.

Here is my non working attempt to get the count however its not returning the count to run my test in selenium IDE.

"//div[@surface='data-seat']/img"

Body:
Try:

//div[@surface='data-seat']/count(img)

For your example html, it outputs 4.


问:
C++ static initialization of stateless class
Suppose I have a class T where

T has no virtual functions.

T instances have no state.

T has static member instances of itself.

T itself has no other state.

Can the C++ static initialization fiasco ruin my program? I don't think so because even if one of the static instances is not initialized before use, that should not matter because T objects are stateless.

I'm interested in doing this for enum-like classes like so:

```<code>// Switch.h

class Switch {
public:
    static Switch const ON;
    static Switch const OFF;
    bool operator== (Switch const &s) const;
    bool operator!= (Switch const &s) const;
private:
    Switch () {}
    Switch (Switch const &); // no implementation
    Switch & operator= (Switch const &); // no implementation
};
</code>```

```<code>// Switch.cpp

Switch const Switch::ON;
Switch const Switch::OFF;

bool Switch::operator== (Switch const &s) const {
    return this == &s;
}

bool Switch::operator!= (Switch const &s) const {
    return this != &s;
}
</code>```

答:
Do you really intend to use pointer values to compare "state"?  I agree with @Drew, it's an interesting idea.  I'm not sure it is guaranteed by the standard to work, though, if we assume that this is a header-only implementation.

Consider what happens when multiple compilation objects contain the same definition for Switch::ON and Switch::OFF.  Since these are variables, and not functions, the linker would have to decide, arbitrarily, between them.

When you ran a test, what did the popular compilers say:  gcc 3, gcc 4, microsoft C++ 2005, 2008, and 2010, and one of the Edison Design Groups' compilers such as http://www.comeaucomputing.com/ ?

Said test would consist of:

```<code>// Switch.h
class Switch {
public:
    static Switch const ON;
    static Switch const OFF;
    bool operator== (Switch const &s) const;
    bool operator!= (Switch const &s) const;
private:
    Switch () {}
    Switch (Switch const &); // no implementation
    Switch & operator= (Switch const &); // no implementation
};

Switch const Switch::ON;
Switch const Switch::OFF;

bool Switch::operator== (Switch const &s) const {
    return this == &s;
}

bool Switch::operator!= (Switch const &s) const {
    return this != &s;
}
</code>```

and

```<code>// main.cpp
#include "Switch.h"

extern int another_test();

int main(int argc, char*argv[])
{
  another_test();
  const Switch& current_state = Switch::ON;
  const Switch& another_state = Switch::OFF;
  if (current_state == another_state) {
    return 1;
  } else if (current_state != another_state) {
    return 2;
  }
  return another_test();
}
</code>```

and

```<code>// another_test.cpp
#include "Switch.h"

int another_test()
{
  const Switch& current_state = Switch::ON;
  const Switch& another_state = Switch::OFF;
  if (current_state == another_state) {
    return 4;
  } else if (current_state != another_state) {
    return 5;
  }
  return 6;
}
</code>```

Body:
Suppose I have a class T where

T has no virtual functions.

T instances have no state.

T has static member instances of itself.

T itself has no other state.

Can the C++ static initialization fiasco ruin my program? I don't think so because even if one of the static instances is not initialized before use, that should not matter because T objects are stateless.

I'm interested in doing this for enum-like classes like so:

// Switch.h

class Switch {
public:
    static Switch const ON;
    static Switch const OFF;
    bool operator== (Switch const &s) const;
    bool operator!= (Switch const &s) const;
private:
    Switch () {}
    Switch (Switch const &); // no implementation
    Switch & operator= (Switch const &); // no implementation
};

// Switch.cpp

Switch const Switch::ON;
Switch const Switch::OFF;

bool Switch::operator== (Switch const &s) const {
    return this == &s;
}

bool Switch::operator!= (Switch const &s) const {
    return this != &s;
}

Body:
Do you really intend to use pointer values to compare "state"?  I agree with @Drew, it's an interesting idea.  I'm not sure it is guaranteed by the standard to work, though, if we assume that this is a header-only implementation.

Consider what happens when multiple compilation objects contain the same definition for Switch::ON and Switch::OFF.  Since these are variables, and not functions, the linker would have to decide, arbitrarily, between them.

When you ran a test, what did the popular compilers say:  gcc 3, gcc 4, microsoft C++ 2005, 2008, and 2010, and one of the Edison Design Groups' compilers such as http://www.comeaucomputing.com/ ?

Said test would consist of:

// Switch.h
class Switch {
public:
    static Switch const ON;
    static Switch const OFF;
    bool operator== (Switch const &s) const;
    bool operator!= (Switch const &s) const;
private:
    Switch () {}
    Switch (Switch const &); // no implementation
    Switch & operator= (Switch const &); // no implementation
};

Switch const Switch::ON;
Switch const Switch::OFF;

bool Switch::operator== (Switch const &s) const {
    return this == &s;
}

bool Switch::operator!= (Switch const &s) const {
    return this != &s;
}

and

// main.cpp
#include "Switch.h"

extern int another_test();

int main(int argc, char*argv[])
{
  another_test();
  const Switch& current_state = Switch::ON;
  const Switch& another_state = Switch::OFF;
  if (current_state == another_state) {
    return 1;
  } else if (current_state != another_state) {
    return 2;
  }
  return another_test();
}

and

// another_test.cpp
#include "Switch.h"

int another_test()
{
  const Switch& current_state = Switch::ON;
  const Switch& another_state = Switch::OFF;
  if (current_state == another_state) {
    return 4;
  } else if (current_state != another_state) {
    return 5;
  }
  return 6;
}


问:
Bootstrap 3 Gutter Size
I've only just started working with bootstrap and unsure about how to achieve my goal.

I would like the gutters to all be even, like they are in this image:

by default, they look like this, the vertical gutters in between columns (marked with blue) are double the horizontal and outside gutters:

Any help on the best way to solve this probably would be appreciated.

答:
I tried several of the options here.  For all that I tried, the spacing was uneven, or was even but when I shrank the window width enough for the subviews to stack, there was no space between stacked views.

Here is what worked for me.

.col-sm-12 {
  margin-bottom: 2em;
}
```

<pre class="lang-html prettyprint-override"><code><div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
    </div>
</div>
</code>```

Title: Bootstrap 3 Gutter Size

Body:
I tried several of the options here.  For all that I tried, the spacing was uneven, or was even but when I shrank the window width enough for the subviews to stack, there was no space between stacked views.

Here is what worked for me.

.col-sm-12 {
  margin-bottom: 2em;
}

<div class="container">
    <div class="row">
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
        <div class="col-sm-6">
            <div class="col-sm-12">

            </div>
        </div>
    </div>
</div>


问:
Feeding User Input using bash script
I have a java program where I am expecting user to give some input and I want to use bash script to test the program. Though the program is working fine but I am not able to pass user input using script.

```<code>javac -d build ParkingLot.java
cd build/
java ParkingLot
"create_parking_lot 5"
"park hy-25-ysud-23 red"
"park hy-25-gfvd-23 white"
"park hy-25-ysfd-23 green"
"park hy-25-ysfd-24 black"
"park hy-25-ysfd-25 green"
"park hy-25-asfd-23 white"
"exit"
</code>```

This 8 strings at the end is my input to program. How do I do this?

答:
You can try Bash's here-document (one form of input redirection) in the script:

java ParkingLot << END
create_parking_lot 5
park hy-25-ysud-23 red
park hy-25-gfvd-23 white
park hy-25-ysfd-23 green
park hy-25-ysfd-24 black
park hy-25-ysfd-25 green
park hy-25-asfd-23 white
exit
END
```

Title: Feeding User Input using bash script

Body:
I have a java program where I am expecting user to give some input and I want to use bash script to test the program. Though the program is working fine but I am not able to pass user input using script.

javac -d build ParkingLot.java
cd build/
java ParkingLot
"create_parking_lot 5"
"park hy-25-ysud-23 red"
"park hy-25-gfvd-23 white"
"park hy-25-ysfd-23 green"
"park hy-25-ysfd-24 black"
"park hy-25-ysfd-25 green"
"park hy-25-asfd-23 white"
"exit"

This 8 strings at the end is my input to program. How do I do this?


问:
Xamarin.Cognitive.Face API connecting problems
I tried to use this Nuget package, but I can't connect to the API. I got an error

" Rejecting re-init on previously-failed class
  java.lang.Class:
  java.lang.NoClassDefFoundError: Failed resolution of:
  Lorg/apache/http/client/methods/HttpPost;"

so I can't use any of the FaceClient functions- they're all return null.
I use Xamarin Android

答: I added the line <uses-library android:name="org.apache.http.legacy" android:required="false" /> at the <applicaion> tag in the AndroidManifest.xml file so it solved this problem.


问:
onDatachange is called and crash the app when i remove value from firebase
**i am making an app which have function of sending request request to users and i storing senders user id as key and "true"  as value whan user send the request. But when he cancel the request, value removed from the database but on dataChange is called and compare the value with null as in the code **</p>

```<code>friend_requests = FirebaseDatabase.getInstance().getReference().child("Users").child(phone)
                    .child("Friend_Requests").child(user.getPhoneNumber());
            friend_requests.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.getValue().equals("null"))
                    {

                    }
                    else
                    {
                        follow.setText("Requested");
                    }
                        Log.d("ahmed12", "onDataChange: "+dataSnapshot.getValue());

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
</code>```

答:
The simplest change is to reverse the comparison:

```<code>if("null".equals(dataSnapshot.getValue(String.class)))
</code>```

This should get rid of the error message, although it's hard to say whether it will do what you want.

The reason for the latter is that it's quite uncommon to compare to a literal "null" string. Usually code compares to null (instead of "null") to see if something has a value/is initialized.

For example, if you want to check if the snapshot has a value, you'd do that with:

```<code>if(dataSnapshot.getValue(String.class) != null)
</code>```

Or even simpler:

```<code>if(dataSnapshot.exists())
</code>```

Body:
**i am making an app which have function of sending request request to users and i storing senders user id as key and "true"  as value whan user send the request. But when he cancel the request, value removed from the database but on dataChange is called and compare the value with null as in the code **

friend_requests = FirebaseDatabase.getInstance().getReference().child("Users").child(phone)
                    .child("Friend_Requests").child(user.getPhoneNumber());
            friend_requests.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    if(dataSnapshot.getValue().equals("null"))
                    {

                    }
                    else
                    {
                        follow.setText("Requested");
                    }
                        Log.d("ahmed12", "onDataChange: "+dataSnapshot.getValue());

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }

Body:
The simplest change is to reverse the comparison:

if("null".equals(dataSnapshot.getValue(String.class)))

This should get rid of the error message, although it's hard to say whether it will do what you want.

The reason for the latter is that it's quite uncommon to compare to a literal "null" string. Usually code compares to null (instead of "null") to see if something has a value/is initialized.

For example, if you want to check if the snapshot has a value, you'd do that with:

if(dataSnapshot.getValue(String.class) != null)

Or even simpler:

if(dataSnapshot.exists())


问:
How does name resolution work in compound "with" statements?
Which instance of Ready gets tested in the following code, and why?

```<code>interface

type
  TObject1 = class
  ...
  public
    property Ready: boolean read FReady write FReady;
  end;

  TObject2 = class
  ...
  public
    property Ready: boolean read FReady write FReady;
  end;

implementation

var
  Object1: TObject1;
  Object2: TObject2;

...

procedure test;
var
  Ready: boolean;
begin
  Ready:= true;
  with Object1, Object2 do begin
    if Ready then ShowMessage('which one?');
  end; {with}
end;
</code>```

答:
The last one.

```<code>with Object1, Object2 do
</code>```

is equivalent to

```<code>with Object1 do
  with Object2 do
</code>```

and so Object2 will be the number-one priority.

The official documentation on this matter.

Body:
Which instance of Ready gets tested in the following code, and why?

interface

type
  TObject1 = class
  ...
  public
    property Ready: boolean read FReady write FReady;
  end;

  TObject2 = class
  ...
  public
    property Ready: boolean read FReady write FReady;
  end;

implementation

var
  Object1: TObject1;
  Object2: TObject2;

...

procedure test;
var
  Ready: boolean;
begin
  Ready:= true;
  with Object1, Object2 do begin
    if Ready then ShowMessage('which one?');
  end; {with}
end;

Body:
The last one.

with Object1, Object2 do

is equivalent to

with Object1 do
  with Object2 do

and so Object2 will be the number-one priority.

The official documentation on this matter.


问:
Can't connect to the socket for mysql running under docker from the host?
I have mySQL running in a container. It and my app (in a different Docker container) seem to run fine. I am now trying to use Jaspersoft's iReport to develop a report with. I have managed to get iReport up and running on the host, Ubuntu. The problem is accessing the database from the host.

This is required to use iReport and I just can't seem to get the connection working. I tried looking at the mysql socket, but it is not in the normal place, since mySQL is in a Docker Container. I am also working on getting JasperReports server to run in another container. But my problem is connecting from the host to the mySQL database running in Docker via an JDBC connection.

here is the docker-compose.yml
https://drive.google.com/open?id=1CY_tPmnot3zSab0BtLE1fJUC7sdD2tyA

The connection that iReports has chosen is jdbc:mysql://localhost/substantiator. When I try to "test" this with the iReport database test button I get a popup that asks for password. I have tried using the same user/password combo that works from my app. It fails with: SQL problems: Communication Link Failure. In researching this I am asked to update the mySQL socket path in a mysql cnf file. But in my installation the socket file doesn't exist (because it it in docker?). So I am stumped. I am considering moving over to mariaDB. Any ideas?

答: Hi your MySql container expose port 3306 from host machine you can connect using localhost,but for some external service you need to use host machine IP address and also make sure port 3306 is exposed to outside.</p>


问:
How can I query firestore by document snapshot updateTime?
Is it possible to query firestore documents by updateTime. The field that is available from the document snapshot as doc.updateTime and use it in a where query?

I am using the node.js sdk.

答:
I really need to query Firebase on document _updateTime, so I wrote a function that copies that hidden internal timestamp to a queryable field. This took some work to figure this out, so I am posting the complete solution. (Technically, this is "Cloud Firestore" rather then "Realtime Database".)

This is done using Firebase Functions, which itself took some tries to get working. This tutorial was helpful:

https://firebase.google.com/docs/functions/get-started

However, on Windows 10, the only command line that worked was the new Bash shell, available since about 2017. This was something of a runaround to install, but necessary. The GIT Bash shell, otherwise very useful, was not able to keep track of screen positions during Firebase project setup.

In my example code, I have left in all the 'console.log' statements, to show detail. Not obvious at first was where these logs go. They do not go to the command line, but to the Firebase console:

https://console.firebase.google.com/u/0/

under (yourproject) > Functions > Logs

For testing, I found it useful to, at first, deploy only one function (this is in the CLI):

```<code>firebase deploy --only functions:testFn
</code>```

Below is my working function, heavily commented, and with some redundancy for illustration. Replace 'PlantSpp' with the name of your collection of documents:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

// Firestore maintains an interal _updateTime for every document, but this is
// not queryable. This function copies that to a visible field 'Updated'
exports.makeUpdateTimeVisible = functions.firestore
      .document('PlantSpp/{sppId}')
      .onWrite((sppDoc, context) => {
  console.log("Event type: ", context.eventType);
  // context.eventType = 'google.firestore.document.write', so cannot use
  // to distinguish e.g. create from update
  const docName = context.params.sppId // this is how to get the document name
  console.log("Before: ", sppDoc.before); // if a create, a 'DocumentSnapshot',
  // otherwise a 'QueryDocumentSnapshot'
  // if a create, everything about sppDoc.before is undefined
  if (typeof sppDoc.before._fieldsProto === "undefined"){
    console.log('document "', docName, '" has been created');
    // set flags here if desired
  }
  console.log("After: ", sppDoc.after); // if a delete, a 'DocumentSnapshot',
  // otherwise a 'QueryDocumentSnapshot'
  // if a delete, everything about sppDoc.after is undefined
  if (typeof sppDoc.after._fieldsProto === "undefined"){
    console.log('document "', docName, '" has been deleted');
    // other fields could be fetched from sppDoc.before
    return null; // no need to proceed
  }
  console.log(sppDoc.after.data()); // the user defined fields:values
  // inside curly braces
  console.log(sppDoc.after._fieldsProto); // similar to previous except with
  // data types, e.g.
  // data() has { Code: 'OLDO',...
  // _fieldsProto has { Code: { stringValue: 'OLDO' },...
  const timeJustUpdated = sppDoc.after._updateTime; // this is how to get the
  // internal nonqueryable timestamp
  console.log(timeJustUpdated);
  //  e.g.      Timestamp { _seconds: 1581615533, _nanoseconds: 496655000 }
  //  later:    Timestamp { _seconds: 1581617552, _nanoseconds: 566223000 }
  // shows this is correctly updating
  // see if the doc has the 'Updated' field yet
  if (sppDoc.after._fieldsProto.hasOwnProperty('Updated')) {
    console.log("doc has the field 'Updated' with the value",
                  sppDoc.after._fieldsProto.Updated);
    console.log("sppDoc:", sppDoc);
    const secondsInternal = timeJustUpdated._seconds;
    console.log(secondsInternal, "seconds, internal timestamp");
    const secondsExternal = sppDoc.after.data().Updated._seconds;
    console.log(secondsExternal, "seconds, external timestamp");
    // Careful here. If we just update the externally visible time to the
    // internal time, we will go into an infinite loop because that update
    // will call this function again, and by then the internal time will have
    // advanced
    // the following exit will not work:
    if (secondsInternal === secondsExternal) return null; // will never exit
    // instead, allow the external time to lag the internal by a little
    const secondsLate = secondsInternal - secondsExternal;
    if (secondsLate < 120) { // two minutes sufficient for this purpose
      console.log("the field 'Updated' is", secondsLate,
                  "seconds late, good enough");
       return null;
    }
    console.log("the field 'Updated' is", secondsLate,
                  "seconds late, updating");
    // return a promise of a set operation to update the timestamp
    return sppDoc.after.ref.set({
      Updated: timeJustUpdated
    }, {merge: true}); // 'merge' prevents overwriting whole doc
    // this change will call this same function again
  } else { // field 'Updated' does not exist in the document yet
    // this illustrates how to add a field
    console.log("doc does not have the field 'Updated', adding it now.");
    // return a promise of a set operation to create the timestamp
    return sppDoc.after.ref.set({
      Updated: timeJustUpdated
    }, {merge: true}); // 'merge' prevents overwriting the whole doc
    // this change will call this same function again
  }
});```

Body:
I really need to query Firebase on document _updateTime, so I wrote a function that copies that hidden internal timestamp to a queryable field. This took some work to figure this out, so I am posting the complete solution. (Technically, this is "Cloud Firestore" rather then "Realtime Database".)

This is done using Firebase Functions, which itself took some tries to get working. This tutorial was helpful:

https://firebase.google.com/docs/functions/get-started

However, on Windows 10, the only command line that worked was the new Bash shell, available since about 2017. This was something of a runaround to install, but necessary. The GIT Bash shell, otherwise very useful, was not able to keep track of screen positions during Firebase project setup.

In my example code, I have left in all the 'console.log' statements, to show detail. Not obvious at first was where these logs go. They do not go to the command line, but to the Firebase console:

https://console.firebase.google.com/u/0/

under (yourproject) > Functions > Logs

For testing, I found it useful to, at first, deploy only one function (this is in the CLI):

firebase deploy --only functions:testFn

Below is my working function, heavily commented, and with some redundancy for illustration. Replace 'PlantSpp' with the name of your collection of documents:

// The Cloud Functions for Firebase SDK to create Cloud Functions and setup triggers.
const functions = require('firebase-functions');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp();

// Firestore maintains an interal _updateTime for every document, but this is
// not queryable. This function copies that to a visible field 'Updated'
exports.makeUpdateTimeVisible = functions.firestore
      .document('PlantSpp/{sppId}')
      .onWrite((sppDoc, context) => {
  console.log("Event type: ", context.eventType);
  // context.eventType = 'google.firestore.document.write', so cannot use
  // to distinguish e.g. create from update
  const docName = context.params.sppId // this is how to get the document name
  console.log("Before: ", sppDoc.before); // if a create, a 'DocumentSnapshot',
  // otherwise a 'QueryDocumentSnapshot'
  // if a create, everything about sppDoc.before is undefined
  if (typeof sppDoc.before._fieldsProto === "undefined"){
    console.log('document "', docName, '" has been created');
    // set flags here if desired
  }
  console.log("After: ", sppDoc.after); // if a delete, a 'DocumentSnapshot',
  // otherwise a 'QueryDocumentSnapshot'
  // if a delete, everything about sppDoc.after is undefined
  if (typeof sppDoc.after._fieldsProto === "undefined"){
    console.log('document "', docName, '" has been deleted');
    // other fields could be fetched from sppDoc.before
    return null; // no need to proceed
  }
  console.log(sppDoc.after.data()); // the user defined fields:values
  // inside curly braces
  console.log(sppDoc.after._fieldsProto); // similar to previous except with
  // data types, e.g.
  // data() has { Code: 'OLDO',...
  // _fieldsProto has { Code: { stringValue: 'OLDO' },...
  const timeJustUpdated = sppDoc.after._updateTime; // this is how to get the
  // internal nonqueryable timestamp
  console.log(timeJustUpdated);
  //  e.g.      Timestamp { _seconds: 1581615533, _nanoseconds: 496655000 }
  //  later:    Timestamp { _seconds: 1581617552, _nanoseconds: 566223000 }
  // shows this is correctly updating
  // see if the doc has the 'Updated' field yet
  if (sppDoc.after._fieldsProto.hasOwnProperty('Updated')) {
    console.log("doc has the field 'Updated' with the value",
                  sppDoc.after._fieldsProto.Updated);
    console.log("sppDoc:", sppDoc);
    const secondsInternal = timeJustUpdated._seconds;
    console.log(secondsInternal, "seconds, internal timestamp");
    const secondsExternal = sppDoc.after.data().Updated._seconds;
    console.log(secondsExternal, "seconds, external timestamp");
    // Careful here. If we just update the externally visible time to the
    // internal time, we will go into an infinite loop because that update
    // will call this function again, and by then the internal time will have
    // advanced
    // the following exit will not work:
    if (secondsInternal === secondsExternal) return null; // will never exit
    // instead, allow the external time to lag the internal by a little
    const secondsLate = secondsInternal - secondsExternal;
    if (secondsLate < 120) { // two minutes sufficient for this purpose
      console.log("the field 'Updated' is", secondsLate,
                  "seconds late, good enough");
       return null;
    }
    console.log("the field 'Updated' is", secondsLate,
                  "seconds late, updating");
    // return a promise of a set operation to update the timestamp
    return sppDoc.after.ref.set({
      Updated: timeJustUpdated
    }, {merge: true}); // 'merge' prevents overwriting whole doc
    // this change will call this same function again
  } else { // field 'Updated' does not exist in the document yet
    // this illustrates how to add a field
    console.log("doc does not have the field 'Updated', adding it now.");
    // return a promise of a set operation to create the timestamp
    return sppDoc.after.ref.set({
      Updated: timeJustUpdated
    }, {merge: true}); // 'merge' prevents overwriting the whole doc
    // this change will call this same function again
  }
});


问:
Is it proper to use size_t for count in a bitshift operation?
This small, seemingly insignificant question, occurred to me recently, but after googling quite a bit, I have been unable to find even an opinion on the subject. Only loops and object sizes are referred to.

I know people like examples, so here the one that cause the question in the first place:

```<code>uint64_t deltaSwap( const uint64_t b, const size_t delta, uint64_t mask )
{
    return b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta;
}
</code>```

I've been trying too optimize this for a while, knowing full well that this is not the way to write proper code, though it has given me the best result so far, at least with GCC, and then it occurred to me. If you really want to be pedantic, shouldn't delta be of type size_t?

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

Update:
Here's the short explanation of what it does, although not how it does so, as I'm not really sure how to explain it:

It is a standard delta swap, which is not a new ideal, and the code works fine, this isn't really about the code (but since you asked), and all I've really done is experimenting with it, to achieve the best performance, and the version you see here, is my best result so far.

The purpose of the code is to swap two or more bits, fx if you wish to swap the first and the last bit, it could be done thusly:

```<code>deltaSwap(b, 63, 0x0000000000000001);
</code>```

or if you wish to reverse the order of the bits:

```<code>deltaSwap(b, 32, 0x00000000ffffffff);
deltaSwap(b, 16, 0x0000ffff0000ffff);
deltaSwap(b,  8, 0x00ff00ff00ff00ff);
deltaSwap(b,  4, 0x0f0f0f0f0f0f0f0f);
deltaSwap(b,  2, 0x3333333333333333);
deltaSwap(b,  1, 0x5555555555555555);
</code>```

though for this particular task, deltaswaps are probably not the best way to go.

Update 2:
Just for completion, this is the most correct onliner I can think of (haven gotten my answer), and the compiler apparently optimizes it perfectly.

```<code>uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, const uint64_t mask )
{
    return b ^ ( mask & ( b ^ b >> delta ) ) ^ ( mask & ( b ^ b >> delta ) ) << delta;
}
</code>```

I would've shortened the variable name to get it all to fit within the 80 character with imposed by my ocd brain (and apparently this site as well), but for you all, I'm willing to suffer.

答:
size_t is an integer type that is guaranteed to be able to store the output of any sizeof() operation. This has a couple of implications: No block of coherent memory can have more bytes than size_t can represent as number. This also means that no array can have more elements than size_t can represent as a count. Also no C string can have more characters than size_t can represent as a length.

As for when to use size_t, you should always use it for storing memory sizes, array counts, array indices, and string lengths, as only this will lead to really portable C code. Using int, long, or uintX_t for that purpose may work on some platforms but can fail on other platforms. Note that even malloc expects an argument of type size_t, printf supports it as well using %zu, and most string operations in C use it as input/output for string lengths.

As for mixing integers of different width: Only char, short, int, long, and long long (as well as their unsigned counterparts) are real native integers in C. The other integer types are just aliases to one of these native types added with later C standards. When mixing different types within a single operation, the smaller type is promoted to the larger one, unless both types are smaller than int, in which case they are both promoted to int, as C performs all operations on int or larger types, never on smaller ones:

```<code>char a = 1;
char b = 2;
char c = a + b;
// Last line is in fact: char c = (char)( (int)a + (int)b );

long l = 20;
long m = m * b;
// Last line is in fact: long m = l * (long)b;
</code>```

So if you mix uint64_t and size_t, then either both become whatever type uint64_t is as a native type or they both become whatever type size_t is as a native type, whichever type is larger, unless both are smaller than int, in which case both become int.

Thus using size_t for a shift is perfectly okay, as any integer type can be used on either side of a shift operation.

Body:
This small, seemingly insignificant question, occurred to me recently, but after googling quite a bit, I have been unable to find even an opinion on the subject. Only loops and object sizes are referred to.

I know people like examples, so here the one that cause the question in the first place:

uint64_t deltaSwap( const uint64_t b, const size_t delta, uint64_t mask )
{
    return b ^ mask ^ ( mask &=  b ^ b >> delta ) << delta;
}

I've been trying too optimize this for a while, knowing full well that this is not the way to write proper code, though it has given me the best result so far, at least with GCC, and then it occurred to me. If you really want to be pedantic, shouldn't delta be of type size_t?

I never really understood when to use size_t, so I never really do, but if I were to, wouldn't this be correct usage?

Update:
Here's the short explanation of what it does, although not how it does so, as I'm not really sure how to explain it:

It is a standard delta swap, which is not a new ideal, and the code works fine, this isn't really about the code (but since you asked), and all I've really done is experimenting with it, to achieve the best performance, and the version you see here, is my best result so far.

The purpose of the code is to swap two or more bits, fx if you wish to swap the first and the last bit, it could be done thusly:

deltaSwap(b, 63, 0x0000000000000001);

or if you wish to reverse the order of the bits:

deltaSwap(b, 32, 0x00000000ffffffff);
deltaSwap(b, 16, 0x0000ffff0000ffff);
deltaSwap(b,  8, 0x00ff00ff00ff00ff);
deltaSwap(b,  4, 0x0f0f0f0f0f0f0f0f);
deltaSwap(b,  2, 0x3333333333333333);
deltaSwap(b,  1, 0x5555555555555555);

though for this particular task, deltaswaps are probably not the best way to go.

Update 2:
Just for completion, this is the most correct onliner I can think of (haven gotten my answer), and the compiler apparently optimizes it perfectly.

uint64_t deltaSwap( const uint64_t b, const uint_fast8_t delta, const uint64_t mask )
{
    return b ^ ( mask & ( b ^ b >> delta ) ) ^ ( mask & ( b ^ b >> delta ) ) << delta;
}

I would've shortened the variable name to get it all to fit within the 80 character with imposed by my ocd brain (and apparently this site as well), but for you all, I'm willing to suffer.

Body:
size_t is an integer type that is guaranteed to be able to store the output of any sizeof() operation. This has a couple of implications: No block of coherent memory can have more bytes than size_t can represent as number. This also means that no array can have more elements than size_t can represent as a count. Also no C string can have more characters than size_t can represent as a length.

As for when to use size_t, you should always use it for storing memory sizes, array counts, array indices, and string lengths, as only this will lead to really portable C code. Using int, long, or uintX_t for that purpose may work on some platforms but can fail on other platforms. Note that even malloc expects an argument of type size_t, printf supports it as well using %zu, and most string operations in C use it as input/output for string lengths.

As for mixing integers of different width: Only char, short, int, long, and long long (as well as their unsigned counterparts) are real native integers in C. The other integer types are just aliases to one of these native types added with later C standards. When mixing different types within a single operation, the smaller type is promoted to the larger one, unless both types are smaller than int, in which case they are both promoted to int, as C performs all operations on int or larger types, never on smaller ones:

char a = 1;
char b = 2;
char c = a + b;
// Last line is in fact: char c = (char)( (int)a + (int)b );

long l = 20;
long m = m * b;
// Last line is in fact: long m = l * (long)b;

So if you mix uint64_t and size_t, then either both become whatever type uint64_t is as a native type or they both become whatever type size_t is as a native type, whichever type is larger, unless both are smaller than int, in which case both become int.

Thus using size_t for a shift is perfectly okay, as any integer type can be used on either side of a shift operation.


问:
Devise login acceptance test with capybara
There are already a few questions on stackoverflow with possible solutions, but none of them seemed to solve my problem, thus I'm asking another one, in hope it's specific enough to not be closed as duplicate.

I am trying to test a customized login form that uses devise. The environment consists of

rails 6.0

rspec-rails 3.9

capybara 3.31

selenium-webdriver 3.142.7

database_cleaner 1.8

The following spec is failing due to a 401 Unauthorized response, rendering the login form again with an error message that the credentials were wrong.

```<code>require 'rails_helper'

feature 'Logging in' do
  background do
    FactoryBot.create :user, email: 'john.doe@example.com',
                             first_name: 'John',
                             password: 'password',
                             password_confirmation: 'password'
  end

  scenario 'with correct credentials' do
    visit new_user_session_path

    within('#user-sessions--new') do
      find('#user_email').fill_in with: 'john.doe@example.com'
      find('#user_password').fill_in with: 'password'
    end

    find('input[name="commit"]').click
    expect(page).to have_content 'John'
  end
end
</code>```

Checking the test.log after temporarily disabling the parameter filters for logging, I can see that the password has been submitted properly, and the user is being created before the login attempt happens, yet the authentication fails. Entering an interactive debugging session and trying to log in manually inside the capybara's spun up browser, the login also fails. The email/password login works in development mode when creating the same user through the console, though. Right now, no other devise features that could impact the login behavior (like confirmable) are used.

Most of the questions I found so far advise the following points:

Disable transactional fixtures: My rails_helper.rb already contains this;

```<code>RSpec.configure do |config|
  config.use_transactional_fixtures = false
end
</code>```

Configure Database Cleaner: This was suggested in Failing to test Devise with Capybara and was also already the case before I started to implement capybara specs;

```<code>RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(
      :truncation,
      except: %w[ar_internal_metadata schema_migrations]
    )
  end

  config.before :each do
    DatabaseCleaner.start
  end

  config.after :each do
    DatabaseCleaner.clean
  end
end
</code>```

Right now I have no other Idea why this scenario could be failing except for maybe the environment in which the tests are run hot having a proper database connection. If someone has an idea that helps, I'd be happy to hear it.

答:
When using Rails > 5.0 it safely shares the database connection between the tests and the app under test Capybara starts. Because of that you don't need database cleaner, and you should be using transactional tests for the speed and isolation benefits. Start by removing all references to database cleaner from your project and re-enabling transactional fixtures (the default). If that doesn't solve your issue then there's a couple of other potential issues.

Your factory isn't creating a valid user - Use the FactoryBot.lint functionality to verify all your factories produce valid objects before your tests - https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#linting-factories

You have a JS error on your page that is causing issues. In development mode each JS asset is served separately which means an error in one doesn't affect the others.  In test mode, however, the assets are all concatenated which means an error in one can cause JS in other assets not to be run. Check your browser console for any JS errors and fix them.

If none of that helps please add relevant portions of your test.log to your question

Note: You're writing your tests more verbosely than they need to be. If locating fields to fill_in by id you can just pass the id to fill_in and not need to use separate find calls for every element, you should also use the more semantic click_button when the element you're attempting to click qualifies as a button

```<code> within('#user-sessions--new') do
  fill_in 'user_email', with: 'john.doe@example.com'
  fill_in 'user_password', with: 'password'
end

click_button('commit')
expect(page).to have_content 'John'
</code>```

Body:
There are already a few questions on stackoverflow with possible solutions, but none of them seemed to solve my problem, thus I'm asking another one, in hope it's specific enough to not be closed as duplicate.

I am trying to test a customized login form that uses devise. The environment consists of

rails 6.0

rspec-rails 3.9

capybara 3.31

selenium-webdriver 3.142.7

database_cleaner 1.8

The following spec is failing due to a 401 Unauthorized response, rendering the login form again with an error message that the credentials were wrong.

require 'rails_helper'

feature 'Logging in' do
  background do
    FactoryBot.create :user, email: 'john.doe@example.com',
                             first_name: 'John',
                             password: 'password',
                             password_confirmation: 'password'
  end

  scenario 'with correct credentials' do
    visit new_user_session_path

    within('#user-sessions--new') do
      find('#user_email').fill_in with: 'john.doe@example.com'
      find('#user_password').fill_in with: 'password'
    end

    find('input[name="commit"]').click
    expect(page).to have_content 'John'
  end
end

Checking the test.log after temporarily disabling the parameter filters for logging, I can see that the password has been submitted properly, and the user is being created before the login attempt happens, yet the authentication fails. Entering an interactive debugging session and trying to log in manually inside the capybara's spun up browser, the login also fails. The email/password login works in development mode when creating the same user through the console, though. Right now, no other devise features that could impact the login behavior (like confirmable) are used.

Most of the questions I found so far advise the following points:

Disable transactional fixtures: My rails_helper.rb already contains this;

RSpec.configure do |config|
  config.use_transactional_fixtures = false
end

Configure Database Cleaner: This was suggested in Failing to test Devise with Capybara and was also already the case before I started to implement capybara specs;

RSpec.configure do |config|
  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(
      :truncation,
      except: %w[ar_internal_metadata schema_migrations]
    )
  end

  config.before :each do
    DatabaseCleaner.start
  end

  config.after :each do
    DatabaseCleaner.clean
  end
end

Right now I have no other Idea why this scenario could be failing except for maybe the environment in which the tests are run hot having a proper database connection. If someone has an idea that helps, I'd be happy to hear it.

Body:
When using Rails > 5.0 it safely shares the database connection between the tests and the app under test Capybara starts. Because of that you don't need database cleaner, and you should be using transactional tests for the speed and isolation benefits. Start by removing all references to database cleaner from your project and re-enabling transactional fixtures (the default). If that doesn't solve your issue then there's a couple of other potential issues.

Your factory isn't creating a valid user - Use the FactoryBot.lint functionality to verify all your factories produce valid objects before your tests - https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md#linting-factories

You have a JS error on your page that is causing issues. In development mode each JS asset is served separately which means an error in one doesn't affect the others.  In test mode, however, the assets are all concatenated which means an error in one can cause JS in other assets not to be run. Check your browser console for any JS errors and fix them.

If none of that helps please add relevant portions of your test.log to your question

Note: You're writing your tests more verbosely than they need to be. If locating fields to fill_in by id you can just pass the id to fill_in and not need to use separate find calls for every element, you should also use the more semantic click_button when the element you're attempting to click qualifies as a button

 within('#user-sessions--new') do
  fill_in 'user_email', with: 'john.doe@example.com'
  fill_in 'user_password', with: 'password'
end

click_button('commit')
expect(page).to have_content 'John'