问:
Terminology for a deterministic function with no side-effects?
I need the proper terminology for a specific type of function.

Suppose you write a function in your SQL database, whose inputs and outputs are contained within the scope of a database transaction.

That is, if you call this function in the scope of a database transaction, all the data used by the function is available within the same scope.  It can query a database table, but it can't read a file from the filesystem, or ping a web site, etc.  If you call the function twice within a single transaction with REPEATABLE READ isolation, you should get the same result, even if other clients are making changes in the database.

Likewise, the function has no side-effects, except within the same transaction scope.  Changes in state outside the scope of the database transaction are not allowed.  The function shouldn't send emails, nor write to the filesystem, nor store a value in memcached, etc.  If the function changes data within the database, that's okay because if the calling transaction is rolled back, then the effects of the function are too.

The arguments of the function are okay, since they're basically used as constants.

What would be the proper term for a function of this type?  "Deterministic" doesn't really seem to be specific enough.  How would you describe this class of function?

Thanks for your answers, but none of them is exactly what I had in mind.  Idempotent gets closest, so I marked that as the accepted answer.  But each of you got an upvote from me regardless.

Pure functions have no side-effects, and their result is based solely on their arguments.  The result given the same arguments is always identical.  This doesn't work because the database functions I have in mind can be based on the state of data, and the function can also affect the state of data.

Idempotent functions can return a result based on the state of data, and given the same state of data, the result is always identical.  But this doesn't work for what I have in mind exactly; the effects of an idempotent functions must result in an unchanging result no matter how many times the function is called.  But there's no distinction between changes made within transaction isolation and changes made external to that scope.

答:
Up to the forth paragraph, I was thinking it was just a pure function with the transaction as an implicit argument.  But when you say:

the function has no side-effects, except within the same transaction scope. Changes in state outside the scope of the database transaction are not allowed.

I'm not so sure.  Do you mean that it could make changes within the transaction but not be cognizant of them on a future call?  How do you square that with:

If you call the function twice within a single transaction with REPEATABLE READ isolation, you should get the same result

In other words, are you limiting the in-transaction side effects to assignments (such as setting a flag to true) that have the same effect if done multiple times?

OwnerDisplayName: Bill Karwin

LastEditorDisplayName: chaos

OwnerDisplayName: MarkusQ


来源: stackexchange

问:
How to make a like query to @ElementCollection of type map?
I have a class like this:

```<code>class MyEntity {
    @ElementCollection
    Map<String, String> properties;
}
</code>```

I'd like to find out which MyEntity entities have a property value that matches like query using the criteria API. By this I mean I'd like to make a like query on the values of the map entries.

For example if one of my MyEntity classes has a property named "email" and the value is "example@mail.com", how do I make a query that finds the entity with a query parameter "example%" using criteria API?

答:
Okay, I found a solution. There is a joinMap(String) method in Path API which can be used in this case:

```<code>builder.like(
    root.<MyEntity, String, String>joinMap("properties").value(), "example%");
</code>```

That piece of code will create a like predicate against the values of the properties map. This would probably been easier to find out if I had generated the MetaModel of the MyEntity...

ContentLicense: CC BY-SA 3.0

Body:
I have a class like this:

class MyEntity {
    @ElementCollection
    Map<String, String> properties;
}

I'd like to find out which MyEntity entities have a property value that matches like query using the criteria API. By this I mean I'd like to make a like query on the values of the map entries.

For example if one of my MyEntity classes has a property named "email" and the value is "example@mail.com", how do I make a query that finds the entity with a query parameter "example%" using criteria API?

Body:
Okay, I found a solution. There is a joinMap(String) method in Path API which can be used in this case:

builder.like(
    root.<MyEntity, String, String>joinMap("properties").value(), "example%");

That piece of code will create a like predicate against the values of the properties map. This would probably been easier to find out if I had generated the MetaModel of the MyEntity...


问:
How can I create every combination possible for the contents of two arrays?
I have two arrays:

```<code>var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];
</code>```

How can I set another array to contain every combination of the above, so that:

```<code>var combos = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];
</code>```

答:
Arbitrary number of arrays, arbitrary number of elements.

Sort of using number base theory I guess - the j-th array changes to the next element every time the number of combinations of the j-1 arrays has been exhausted. Calling these arrays 'vectors' here.

```<code>let vectorsInstance = [
  [1, 2],
  [6, 7, 9],
  [10, 11],
  [1, 5, 8, 17]]

function getCombos(vectors) {
  function countComb(vectors) {
    let numComb = 1
    for (vector of vectors) {
      numComb *= vector.length
    }
    return numComb
  }
  let allComb = countComb(vectors)

  let combos = []
  for (let i = 0; i < allComb; i++) {
    let thisCombo = []
    for (j = 0; j < vectors.length; j++) {
      let vector = vectors[j]
      let prevComb = countComb(vectors.slice(0, j))
      thisCombo.push(vector[Math.floor(i / prevComb) % vector.length])
    }
    combos.push(thisCombo)
  }
  return combos
}

console.log(getCombos(vectorsInstance))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have two arrays:

var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];

How can I set another array to contain every combination of the above, so that:

var combos = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];

Body:
Arbitrary number of arrays, arbitrary number of elements.

Sort of using number base theory I guess - the j-th array changes to the next element every time the number of combinations of the j-1 arrays has been exhausted. Calling these arrays 'vectors' here.

let vectorsInstance = [
  [1, 2],
  [6, 7, 9],
  [10, 11],
  [1, 5, 8, 17]]

function getCombos(vectors) {
  function countComb(vectors) {
    let numComb = 1
    for (vector of vectors) {
      numComb *= vector.length
    }
    return numComb
  }
  let allComb = countComb(vectors)

  let combos = []
  for (let i = 0; i < allComb; i++) {
    let thisCombo = []
    for (j = 0; j < vectors.length; j++) {
      let vector = vectors[j]
      let prevComb = countComb(vectors.slice(0, j))
      thisCombo.push(vector[Math.floor(i / prevComb) % vector.length])
    }
    combos.push(thisCombo)
  }
  return combos
}

console.log(getCombos(vectorsInstance))


问:
Copy JSONB property data within a collection
I have a JSONB column with data as follows:

{
  "foo": {
    "bars": [
       { "propA": "abc" },
       { "propA": "def" }
    ]
  }
}
```
<p>For each element in <code>bars</code>, I'm trying to copy the value from <code>propA</code> into a new <code>propB</code> property. Basically the resulting JSON needs to look like this:</p>
<pre class="lang-json prettyprint-override"><code>{
  "foo": {
    "bars": [
       { "propA": "abc", "propB": "abc" },
       { "propA": "def", "propB": "def" }
    ]
  }
}
</code>```

Is this possible to do via an UPDATE statement?

Thank you.

答:
dbfiddle link for demonstration.

SQL that will change the jsonb object:

```<code>SELECT id,
       Jsonb_set(final_inline_view.contentx, '{foo,bars}',
       final_inline_view.synthesized_jsonb_agg) changed_jsonb
FROM   (SELECT id,
               contentx,
               Jsonb_agg (Jsonb_build_object('PropA', z.x, 'PropB', z.x))
                      synthesized_jsonb_agg
        FROM   (SELECT jsonsettest.id,
                       jsonsettest.content contentx,
                       Jsonb_array_elements(Jsonb_path_query_array(content,
                                            '$.foo.bars[0,1]'))
                               ->>
                       'propA'             x
                FROM   jsonsettest) z
        GROUP  BY id,
                  contentx) final_inline_view;
</code>```

Update (final):

```<code>UPDATE jsonsettest a
SET    content = b.changed_jsonb
FROM   (SELECT id,
               Jsonb_set(final_inline_view.contentx, '{foo,bars}',
               final_inline_view.synthesized_jsonb_agg) changed_jsonb
        FROM   (SELECT id,
                       contentx,
                       Jsonb_agg (Jsonb_build_object('PropA', z.x, 'PropB',
                       z.x))
                               synthesized_jsonb_agg
                FROM   (SELECT jsonsettest.id,
                               jsonsettest.content contentx,
                               Jsonb_array_elements(Jsonb_path_query_array(
                                                    content,
                                                    '$.foo.bars[0,1]'))
                                       ->>
                               'propA'             x
                        FROM   jsonsettest) z
                GROUP  BY id,
                          contentx) final_inline_view) b
WHERE  a.id = b.id;
</code>```

Body:
I have a JSONB column with data as follows:

{
  "foo": {
    "bars": [
       { "propA": "abc" },
       { "propA": "def" }
    ]
  }
}

For each element in bars, I'm trying to copy the value from propA into a new propB property. Basically the resulting JSON needs to look like this:

{
  "foo": {
    "bars": [
       { "propA": "abc", "propB": "abc" },
       { "propA": "def", "propB": "def" }
    ]
  }
}

Is this possible to do via an UPDATE statement?

Thank you.

Body:
dbfiddle link for demonstration.

SQL that will change the jsonb object:

SELECT id,
       Jsonb_set(final_inline_view.contentx, '{foo,bars}',
       final_inline_view.synthesized_jsonb_agg) changed_jsonb
FROM   (SELECT id,
               contentx,
               Jsonb_agg (Jsonb_build_object('PropA', z.x, 'PropB', z.x))
                      synthesized_jsonb_agg
        FROM   (SELECT jsonsettest.id,
                       jsonsettest.content contentx,
                       Jsonb_array_elements(Jsonb_path_query_array(content,
                                            '$.foo.bars[0,1]'))
                               ->>
                       'propA'             x
                FROM   jsonsettest) z
        GROUP  BY id,
                  contentx) final_inline_view;

Update (final):

UPDATE jsonsettest a
SET    content = b.changed_jsonb
FROM   (SELECT id,
               Jsonb_set(final_inline_view.contentx, '{foo,bars}',
               final_inline_view.synthesized_jsonb_agg) changed_jsonb
        FROM   (SELECT id,
                       contentx,
                       Jsonb_agg (Jsonb_build_object('PropA', z.x, 'PropB',
                       z.x))
                               synthesized_jsonb_agg
                FROM   (SELECT jsonsettest.id,
                               jsonsettest.content contentx,
                               Jsonb_array_elements(Jsonb_path_query_array(
                                                    content,
                                                    '$.foo.bars[0,1]'))
                                       ->>
                               'propA'             x
                        FROM   jsonsettest) z
                GROUP  BY id,
                          contentx) final_inline_view) b
WHERE  a.id = b.id;


问:
Using qsort()/qsort_r() on btrlib didn't work
im trying to use the C standard library qsort() function to sort an
array of bstring and didn't work,
according to bstrlib:

    typedef struct tagbstring * bstring;
    typedef const struct tagbstring * const_bstring;
```
<p>my comparator callback is:</p>
<pre class="lang-c prettyprint-override"><code>int cmp_bstring(const void *a, const void *b, void *unused) {
  (void)unused;
    return bstrcmp((const_bstring)a, (const bstring)b);
}
```c

then i setup some simple code to test, call `qsort\_r()` on this data and the array
remains unsorted:

```c
  bstring strings[] = {
    bfromcstr("Three"),
    bfromcstr("One"),
    bfromcstr("Two"),
  };

  printf("-- Unordered Array --\n");
  print_array(strings, SizeArray(strings));

  qsort_r(strings, SizeArray(strings), sizeof(bstring), cmp_bstring, NULL);

  printf("\n-- Ordered Array --\n");
  print_array(strings, SizeArray(strings));
}
</code>```

the full code is:

 #ifndef _GNU_SOURCE
 #define _GNU_SOURCE
 #endif

 #include <stdio.h>
 #include <stdlib.h>

 #include "bstrlib.h"

 #define SizeArray(arr) (sizeof((arr)) / sizeof((arr)[0]))

int cmp_bstring(const void *a, const void *b, void *unused) {
  (void)unused;
    return bstrcmp((const_bstring)a, (const bstring)b);
}

void print_array(bstring array[], unsigned array_len) {
    for (unsigned i=0; i < array_len; i++)
        printf("[%d] = %s\n", i, array[i]->data);
}

int main(void) {
  bstring strings[] = {
    bfromcstr("Three"),
    bfromcstr("One"),
    bfromcstr("Two"),
  };

  printf("-- Unordered Array --\n");
  print_array(strings, SizeArray(strings));

  qsort_r(strings, SizeArray(strings), sizeof(bstring), cmp_bstring, NULL);

  printf("\n-- Ordered Array --\n");
  print_array(strings, SizeArray(strings));
}
```
<p>The expected output is:</p>
```-- Unordered Array --
[0] = Three
[1] = One
[2] = Two

-- Ordered Array --
[0] = One
[2] = Three
[3] = Two
```
<p>but i get:</p>
```-- Unordered Array --
[0] = Three
[1] = One
[2] = Two

-- Ordered Array --
[0] = Three
[1] = One
[2] = Two
```

by the way, why SizeArray macro didn't work if i use it into print_array()
function (returns 1), and from main() returns correct array size?

Built with GCC on Linux

答:
You have become confused about levels of indirection.  Pretend that you don't know the definition of bstring, and in particular, you don't know that it is a pointer type.  Would you then think it made sense to convert pointers into bstrings?

qsort()'s comparison function receives pointers to the values being compared, not the values themselves.  Therefore, you appear to be looking for this variation:

```<code>int cmp_bstring(const void *a, const void *b, void *unused) {
  (void)unused;
    return bstrcmp(*(const_bstring *)a, *(const bstring *)b);
}
</code>```

Body:
im trying to use the C standard library qsort() function to sort an
array of bstring and didn't work,
according to bstrlib:

    typedef struct tagbstring * bstring;
    typedef const struct tagbstring * const_bstring;

my comparator callback is:

int cmp_bstring(const void *a, const void *b, void *unused) {
  (void)unused;
    return bstrcmp((const_bstring)a, (const bstring)b);
}
```c

then i setup some simple code to test, call `qsort\_r()` on this data and the array
remains unsorted:

```c
  bstring strings[] = {
    bfromcstr("Three"),
    bfromcstr("One"),
    bfromcstr("Two"),
  };

  printf("-- Unordered Array --\n");
  print_array(strings, SizeArray(strings));

  qsort_r(strings, SizeArray(strings), sizeof(bstring), cmp_bstring, NULL);

  printf("\n-- Ordered Array --\n");
  print_array(strings, SizeArray(strings));
}

the full code is:

 #ifndef _GNU_SOURCE
 #define _GNU_SOURCE
 #endif

 #include <stdio.h>
 #include <stdlib.h>

 #include "bstrlib.h"

 #define SizeArray(arr) (sizeof((arr)) / sizeof((arr)[0]))

int cmp_bstring(const void *a, const void *b, void *unused) {
  (void)unused;
    return bstrcmp((const_bstring)a, (const bstring)b);
}

void print_array(bstring array[], unsigned array_len) {
    for (unsigned i=0; i < array_len; i++)
        printf("[%d] = %s\n", i, array[i]->data);
}

int main(void) {
  bstring strings[] = {
    bfromcstr("Three"),
    bfromcstr("One"),
    bfromcstr("Two"),
  };

  printf("-- Unordered Array --\n");
  print_array(strings, SizeArray(strings));

  qsort_r(strings, SizeArray(strings), sizeof(bstring), cmp_bstring, NULL);

  printf("\n-- Ordered Array --\n");
  print_array(strings, SizeArray(strings));
}

The expected output is:

-- Unordered Array --
[0] = Three
[1] = One
[2] = Two

-- Ordered Array --
[0] = One
[2] = Three
[3] = Two

but i get:

-- Unordered Array --
[0] = Three
[1] = One
[2] = Two

-- Ordered Array --
[0] = Three
[1] = One
[2] = Two

by the way, why SizeArray macro didn't work if i use it into print_array()
function (returns 1), and from main() returns correct array size?

Built with GCC on Linux

Body:
You have become confused about levels of indirection.  Pretend that you don't know the definition of bstring, and in particular, you don't know that it is a pointer type.  Would you then think it made sense to convert pointers into bstrings?

qsort()'s comparison function receives pointers to the values being compared, not the values themselves.  Therefore, you appear to be looking for this variation:

int cmp_bstring(const void *a, const void *b, void *unused) {
  (void)unused;
    return bstrcmp(*(const_bstring *)a, *(const bstring *)b);
}


问:
Playframework Secure module and Internationalization
I'm using the standard Secure module from Play! 1.2.2.

In this discussion I've seen how to copy the view template for the Secure module:

```<code>play secure:ov --css
play secure:ov --login
play secure:ov --layout
</code>```

or one can just copy yourself the relevant files to app/views/Secure and /public/stylesheets.

But my authentication should be in a different language than English. The error messages are in the module source, in the Play! distribution: models/secure/conf/messages.

Is there any proper way of customising that file without touching the module source itself? Creating a conf/secure/messages in my application does not have any effect.

The message catalogue is not only used by the view - which I could easily change - but also by the Secure controller, when generating an error message. I'd like to avoid forking the Secure module just for these six messages.

Thanks for reading, Viktor.

答:
The Secure module is usually "forked" and customized for many applications, don't be afraid to do so. In theory removing the keys from the models/secure/conf/messages and moving them to the app conf/messages should do it.

But if you have problems, just copy the contents of the module to your project. You are already customizing most of it (the look and feel) so copying 1 class, 1 annotation and 1 tag should be a bug deal :)

Body:
I'm using the standard Secure module from Play! 1.2.2.

In this discussion I've seen how to copy the view template for the Secure module:

play secure:ov --css
play secure:ov --login
play secure:ov --layout

or one can just copy yourself the relevant files to app/views/Secure and /public/stylesheets.

But my authentication should be in a different language than English. The error messages are in the module source, in the Play! distribution: models/secure/conf/messages.

Is there any proper way of customising that file without touching the module source itself? Creating a conf/secure/messages in my application does not have any effect.

The message catalogue is not only used by the view - which I could easily change - but also by the Secure controller, when generating an error message. I'd like to avoid forking the Secure module just for these six messages.

Thanks for reading, Viktor.


问:
Selenium: Open browsers one at a time from Array of IWebDriver
We are doing a Proof of Concept with Selenium and MS Test at our company. We are supporting only three browsers for the POC; Chrome, Firefox, and Edge.

I have created an array of IWebDriver and added the browsers to it in this way:

```<code>    private IWebDriver[] drivers = { new ChromeDriver(), new FirefoxDriver(), new EdgeDriver() };

    [TestMethod]
    [TestCategory("SmokeTest")]
    public void LoadHomePageWhenInitiated()
    {

        foreach (var driver in drivers)
        {
            using (driver)
            {
                // arrange (do prep work here, if needed)
                var searchPage = new SearchPage(driver);

                // act  (perform the actual test)
                driver.Manage().Window.Maximize();
                searchPage.NavigateTo();

                // assert (determine pass/fail outcome)

                // doesn't seem to be closing the browser like it should
                driver.Close();
            }

        }
    }
</code>```

What I'd hoped for is that each browser would initialize in succession (at the foreach or the using), each run the tests, and the close. At that point the next browser would initialize and run the same tests.

What's happening is that all three browsers are opening at the time the array is created.

I'm thinking there must be a way to do this with [ClassInitialize()] or [TestInitialize()] but at the moment cannot determine how to accomplish what I'm looking for.

I appreciate any insights on a better way to accomplish this with Selenium and MS Test.

答:
I will advice against doing this. If you want to run all your tests in succession, schedule your tests and run them that way. One good way of managing this is by using a CI/CD platform like Jenkins.

In Jenkins, you can easily create all kinds of jobs, scheduled them at whatever intervals/frequency you need, deliver reports to whoever, all without the need to do what you are trying to do.

Here is a 50-minute video you can watch to setup Jenkins configure it to run your tests and integrate with GitHub (if you need to do that as well).

If the video doesn't help, reach out to me and I should be able to get you going. You don't have to become an expert on Jenkins to use it effectively to create all kinds of scheduled tasks that can be executed automatically or manually.

Body:
We are doing a Proof of Concept with Selenium and MS Test at our company. We are supporting only three browsers for the POC; Chrome, Firefox, and Edge.

I have created an array of IWebDriver and added the browsers to it in this way:

    private IWebDriver[] drivers = { new ChromeDriver(), new FirefoxDriver(), new EdgeDriver() };

    [TestMethod]
    [TestCategory("SmokeTest")]
    public void LoadHomePageWhenInitiated()
    {

        foreach (var driver in drivers)
        {
            using (driver)
            {
                // arrange (do prep work here, if needed)
                var searchPage = new SearchPage(driver);

                // act  (perform the actual test)
                driver.Manage().Window.Maximize();
                searchPage.NavigateTo();

                // assert (determine pass/fail outcome)

                // doesn't seem to be closing the browser like it should
                driver.Close();
            }

        }
    }

What I'd hoped for is that each browser would initialize in succession (at the foreach or the using), each run the tests, and the close. At that point the next browser would initialize and run the same tests.

What's happening is that all three browsers are opening at the time the array is created.

I'm thinking there must be a way to do this with [ClassInitialize()] or [TestInitialize()] but at the moment cannot determine how to accomplish what I'm looking for.

I appreciate any insights on a better way to accomplish this with Selenium and MS Test.


问:
Condition IF is_search() Results Page for Default Post Type only
The built in wordpress function is_search() determines whether the query is for a search (source). In this form, the function does not distinguish between post types.

What im trying is to load a script only on the search results page for posts but not the search results for products. For example:

```<code>    function child_theme_search_custom_js_script() {
        if ( is_search() ) { // But only for default post type?
            wp_enqueue_script( 'child-theme-cart-js', get_stylesheet_directory_uri() . '/js/child-search-custom-js.js', array('abc-core'), '1.0.0', true );
        }
    }
    add_action( 'wp_enqueue_scripts', 'child_theme_search_custom_js_script' );
</code>```

Any way to check if it is the results page for the default post type?

答:
So i played around with different wordpress conditions and found a solution to target only the search results page for the default post type.</p>
```<code>    // If it is "Post" Post Type Search Results Page only
    if ( ! is_post_type_archive() && is_search()  )  {
</code>```

Body:
The built in wordpress function is_search() determines whether the query is for a search (source). In this form, the function does not distinguish between post types.

What im trying is to load a script only on the search results page for posts but not the search results for products. For example:

    function child_theme_search_custom_js_script() {
        if ( is_search() ) { // But only for default post type?
            wp_enqueue_script( 'child-theme-cart-js', get_stylesheet_directory_uri() . '/js/child-search-custom-js.js', array('abc-core'), '1.0.0', true );
        }
    }
    add_action( 'wp_enqueue_scripts', 'child_theme_search_custom_js_script' );

Any way to check if it is the results page for the default post type?

Body:
So i played around with different wordpress conditions and found a solution to target only the search results page for the default post type.

    // If it is "Post" Post Type Search Results Page only
    if ( ! is_post_type_archive() && is_search()  )  {


问:
Code can't reverse the string. It prins empty
```<code>#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "input";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = 0; i <= y-1; i++){

    f[i] = x[y-(1+i)];
    f[y] = '\0';

    }

    cout << f << endl;
    return 0;

}
</code>```

As the code above shows, I am trying to reverse the string user's input.

cin >> x; stores the string input as x.

int y = x.size(); gets the size of the string.

f[i] = x[y-(1+i)]; reverses the string input.

Example:

```<code>Let the input be "hello",
So y=5.
f[0] = x[4] = o;
...
f[3] = x[1] = e;
f[4] = x[0] = h;
</code>```

cout << f << endl; should print f.

BUT the code does not work.

I fear that it is because this:

```<code>f[i] = x[y-(1+i)];
f[y] = '\0';
</code>```

is inside of keys {} and so does not change the value of f. Is that the problem? How to fix it?

答:
To create a reversed copy of the source string you could just write

```<code>string f( x.rbegin(), x.rend() );
</code>```

If to use the approach with the for loop then the loop can look the following way

```<code>for ( auto n = x.size(), i = 0; i < n; i++ )
{
    f += x[n - i - 1];
}
</code>```

Before the for loop you could reserve required memory for the string f like

```<code>f.reserve( x.size() );
</code>```

As for your code then at least you may not use the subscript operator with the empty string f. And there is no need to add explicitly the terminating zero character '\0'.

Moreover if before the for loop you will write

```<code>string f(y,' ');
</code>```

as it was advised nevertheless this statement

```<code>f[y] = '\0';
</code>```

invokes undefined behavior.

Body:
#include <iostream>
#include <string.h>

using namespace std;

int main()
{
    string x;
    cout << "input";
    cin >> x;

    int y = x.size();

    string f;

    for (int i = 0; i <= y-1; i++){

    f[i] = x[y-(1+i)];
    f[y] = '\0';

    }

    cout << f << endl;
    return 0;

}

As the code above shows, I am trying to reverse the string user's input.

cin >> x; stores the string input as x.

int y = x.size(); gets the size of the string.

f[i] = x[y-(1+i)]; reverses the string input.

Example:

Let the input be "hello",
So y=5.
f[0] = x[4] = o;
...
f[3] = x[1] = e;
f[4] = x[0] = h;

cout << f << endl; should print f.

BUT the code does not work.

I fear that it is because this:

f[i] = x[y-(1+i)];
f[y] = '\0';

is inside of keys {} and so does not change the value of f. Is that the problem? How to fix it?

Body:
To create a reversed copy of the source string you could just write

string f( x.rbegin(), x.rend() );

If to use the approach with the for loop then the loop can look the following way

for ( auto n = x.size(), i = 0; i < n; i++ )
{
    f += x[n - i - 1];
}

Before the for loop you could reserve required memory for the string f like

f.reserve( x.size() );

As for your code then at least you may not use the subscript operator with the empty string f. And there is no need to add explicitly the terminating zero character '\0'.

Moreover if before the for loop you will write

string f(y,' ');

as it was advised nevertheless this statement

f[y] = '\0';

invokes undefined behavior.


问:
marginRight property of imageview not working
I have an image view whose background is a xml shape  drawable i.e. a rectangle shape drawable.My app's orientation   is fixed to landscape view.

The imageview is in relative layout.

I  am trying to move it to  the right of the screen by setting the appropriate value of layout_marginRight but this does not work .The imageView always stays in its's original position.

I have tried the following other options also but none helped.

The other options which I tried are:

Creating a new relative layout params and  setting the right margin

Creating new margin layout params and setting the position

Trying padding option

Setting the imageview to  right position relative to another imageview...

Using display metrics to get width of screen and accordingly setting the margin....

I am stuck since a week setting the position of this imageview...

I was thinking the best approach is to  set this imageview in between two imageview as I am not able to move it by setting margin but that does not work either...

Here is the current xml of my imageview in main.xml:-

```<code><ImageView
            android:id="@+id/rect1"
            android:background="@drawable/rect"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginRight="70dp"
            android:scaleType="fitCenter"/>
</code>```

答: put the image view in a linearlayout, then use   android:layout_marginRight="70dp</p>

Body:
I have an image view whose background is a xml shape  drawable i.e. a rectangle shape drawable.My app's orientation   is fixed to landscape view.

The imageview is in relative layout.

I  am trying to move it to  the right of the screen by setting the appropriate value of layout_marginRight but this does not work .The imageView always stays in its's original position.

I have tried the following other options also but none helped.

The other options which I tried are:

Creating a new relative layout params and  setting the right margin

Creating new margin layout params and setting the position

Trying padding option

Setting the imageview to  right position relative to another imageview...

Using display metrics to get width of screen and accordingly setting the margin....

I am stuck since a week setting the position of this imageview...

I was thinking the best approach is to  set this imageview in between two imageview as I am not able to move it by setting margin but that does not work either...

Here is the current xml of my imageview in main.xml:-

<ImageView
            android:id="@+id/rect1"
            android:background="@drawable/rect"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_marginRight="70dp"
            android:scaleType="fitCenter"/>


问:
cufflinks remove gaps in candlestick charts
I am using cufflinks for plotting candlestick charts in jupyter notebook.
How to remove gaps of non trading days in chart.
In plotly we can update layout ['xaxis']['type'] to 'category'.
How can we update the same for a QuantFig in cufflinks.
Follwowing is my code.</p>
```<code>import cufflinks as cf
import pandas as pd
import plotly
from plotly import tools
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
print("List of Cufflinks Themes : ", cf.getThemes())

cf.set_config_file(theme='pearl',sharing='public',offline=True)
daily = pd.read_csv('data.csv',index_col=0,parse_dates=True)

qf=cf.QuantFig(daily,title='my test chart',legend='left',name='Test')
qf.add_volume()

qf.iplot()
</code>```

答:
This did the trick for me:

```<code>fig = qf.iplot(kind='candle')
fig.update_xaxes(
    rangebreaks=[
        dict(bounds=["sat", "mon"]), #hide weekends
    ]
)
</code>```

(described here: https://plotly.com/python/time-series/#hiding-weekends-and-holidays)

Body:
I am using cufflinks for plotting candlestick charts in jupyter notebook.
How to remove gaps of non trading days in chart.
In plotly we can update layout ['xaxis']['type'] to 'category'.
How can we update the same for a QuantFig in cufflinks.
Follwowing is my code.

import cufflinks as cf
import pandas as pd
import plotly
from plotly import tools
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
print("List of Cufflinks Themes : ", cf.getThemes())

cf.set_config_file(theme='pearl',sharing='public',offline=True)
daily = pd.read_csv('data.csv',index_col=0,parse_dates=True)

qf=cf.QuantFig(daily,title='my test chart',legend='left',name='Test')
qf.add_volume()

qf.iplot()

Body:
This did the trick for me:

fig = qf.iplot(kind='candle')
fig.update_xaxes(
    rangebreaks=[
        dict(bounds=["sat", "mon"]), #hide weekends
    ]
)

(described here: https://plotly.com/python/time-series/#hiding-weekends-and-holidays)


问:
Tabbed Content Tabs
I'm using this method from W3schools for tabbed content and it's working well except for one minor detail that is overlooked in their example.  When the tab is closed by clicking on the X in the content, the tab remains in the active presentation, a darker color in this instance.  I want the tabs to revert to their original appearance when the X is clicked (i.e. the lighter color).  I contacted W3schools to point out their example is missing this feature but did not hear back.  Can someone enlighten me on the code needed to achieve this?

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

/* Style the close button */
.topright {
  float: right;
  cursor: pointer;
  font-size: 28px;
}

.topright:hover {color: red;}</code>```

Tabs

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  &times

London

London is the capital city of England.

  &times

Paris

Paris is the capital of France.

  &times

Tokyo

Tokyo is the capital of Japan.

```

答:
Try add this to your script:</p>
```<code>document.querySelectorAll('.topright').forEach(item => {
    item.addEventListener('click', event => {
        let elems = document.querySelectorAll(".tablinks");

        [].forEach.call(elems, el => {
            el.classList.remove("active");
        });
    });
});
</code>```

Title: Tabbed Content Tabs

Body:
I'm using this method from W3schools for tabbed content and it's working well except for one minor detail that is overlooked in their example.  When the tab is closed by clicking on the X in the content, the tab remains in the active presentation, a darker color in this instance.  I want the tabs to revert to their original appearance when the X is clicked (i.e. the lighter color).  I contacted W3schools to point out their example is missing this feature but did not hear back.  Can someone enlighten me on the code needed to achieve this?

function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();

body {font-family: Arial;}

/* Style the tab */
.tab {
  overflow: hidden;
  border: 1px solid #ccc;
  background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
  background-color: inherit;
  float: left;
  border: none;
  outline: none;
  cursor: pointer;
  padding: 14px 16px;
  transition: 0.3s;
  font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
  background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
  background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
  display: none;
  padding: 6px 12px;
  border: 1px solid #ccc;
  border-top: none;
}

/* Style the close button */
.topright {
  float: right;
  cursor: pointer;
  font-size: 28px;
}

.topright:hover {color: red;}

Tabs

Click on the x button in the top right corner to close the current tab:

  <button class="tablinks" onclick="openCity(event, 'London')" id="defaultOpen">London</button>
  <button class="tablinks" onclick="openCity(event, 'Paris')">Paris</button>
  <button class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</button>

  &times

London

London is the capital city of England.

  &times

Paris

Paris is the capital of France.

  &times

Tokyo

Tokyo is the capital of Japan.

Body:
Try add this to your script:

document.querySelectorAll('.topright').forEach(item => {
    item.addEventListener('click', event => {
        let elems = document.querySelectorAll(".tablinks");

        [].forEach.call(elems, el => {
            el.classList.remove("active");
        });
    });
});


问:
How can I stop a css background resizing to fit the browser window?
When using a css background such as in the footer on the page below (in the elements div.footer_head and div.footer_footer), if the browser window is resized to less than about 1000px the divs themselves remain at the full width but scrolling right in the browser causes whitespace to appear where the background should be.

I was sure I'd find a similar question on here but can't seem to word it correctly enough to find it in search.

If someone could point me in the right direction I'm sure I can figure this out.

Look at how the divs with class footer_head and footer_footer behave when you resize the browser to be quite thin and scroll to the right.

screenshot http://printanomics.unbranded-nomads.co.uk/picture-2.jpg

答:
You need to add a min-width:1000px to .footer-container.

```<code>.footer-container {
    float: left;
    line-height: 1.5;
    margin-top: 20px;
    width: 100%;
    min-width: 1000px; /* add this */
}
</code>```

This will mean the smallest width the .footer-container will get is 1000px. Though after that it will expand to 100%.

Body:
You need to add a min-width:1000px to .footer-container.

.footer-container {
    float: left;
    line-height: 1.5;
    margin-top: 20px;
    width: 100%;
    min-width: 1000px; /* add this */
}

This will mean the smallest width the .footer-container will get is 1000px. Though after that it will expand to 100%.


问:
Rstudio -Error: Client error: (401) Unauthorized No such user, can't open files.credentials, ./config etc
When i run the R code in Rstudio, I get below error. what's wrong?'

```<code>Error: Client error: (401) Unauthorized     No such user In addition: Warning messages: 1: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.credentials': No such file or directory 2: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.config': No such file or directory 3: You need a plotly username. See help(signup, package = 'plotly')  4: Couldn't find username  5: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.credentials': No such file or directory 6: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.config': No such file or directory 7: You need an api_key. See help(signup, package = 'plotly')  8: Couldn't find api_key
</code>```

R code:

```<code>library("plotly")
a = read.csv('cleanSankey.csv', header=TRUE, sep=',')
node_names <- unique(c(as.character(a$source), as.character(a$target)))
nodes <- data.frame(name = node_names)
links <- data.frame(source = match(a$source, node_names) - 1,
                    target = match(a$target, node_names) - 1,
                    value = a$value)

#Plot
p <- plot_ly(type='sankey',
        orientation = "h",

        node = list(
          label = node_names,
          color = "grey",
          pad = 15,
          thinkness = 20,
          line = list(color = "grey", width = 0.5)),

         link = list(
           source = links$source,
           target = links$target,
           value = links$value))

plotly_IMAGE(p, out_file="out.png")
</code>```

If I remove last row code plotly_IMAGE(p, out_file="out.png"), there is no error.

答:
plotly_IMAGE is used to export graphs as static images using plotly chart studio. You need an api_key for this to work. See this or help(signup, package = 'plotly').

If you want to export static images on your local PC you can use plotly::save_image(p, "plot.png").

For save_image to work please consider the following:

kaleido() requires the kaleido python package to be usable via the
reticulate package. Here is a recommended way to do the installation:

install.packages('reticulate') reticulate::install_miniconda()
reticulate::conda_install('r-reticulate', 'python-kaleido')
reticulate::conda_install('r-reticulate', 'plotly', channel =
'plotly') reticulate::use_miniconda('r-reticulate')

As an alternative you could use

htmlwidgets::saveWidget(partial_bundle(p), file = "plot.HTML", selfcontained = TRUE)

to save your chart as a standalone HTML file (e.g. as done here)

Body:
When i run the R code in Rstudio, I get below error. what's wrong?'

Error: Client error: (401) Unauthorized     No such user In addition: Warning messages: 1: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.credentials': No such file or directory 2: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.config': No such file or directory 3: You need a plotly username. See help(signup, package = 'plotly')  4: Couldn't find username  5: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.credentials': No such file or directory 6: In open.connection(con, "rb") :   cannot open file '/Users/i073341/.plotly/.config': No such file or directory 7: You need an api_key. See help(signup, package = 'plotly')  8: Couldn't find api_key

R code:

library("plotly")
a = read.csv('cleanSankey.csv', header=TRUE, sep=',')
node_names <- unique(c(as.character(a$source), as.character(a$target)))
nodes <- data.frame(name = node_names)
links <- data.frame(source = match(a$source, node_names) - 1,
                    target = match(a$target, node_names) - 1,
                    value = a$value)

#Plot
p <- plot_ly(type='sankey',
        orientation = "h",

        node = list(
          label = node_names,
          color = "grey",
          pad = 15,
          thinkness = 20,
          line = list(color = "grey", width = 0.5)),

         link = list(
           source = links$source,
           target = links$target,
           value = links$value))

plotly_IMAGE(p, out_file="out.png")

If I remove last row code plotly_IMAGE(p, out_file="out.png"), there is no error.


问:
Unable to reach AWS Glue to get connection in DataBrew
I'm trying to get started with AWS Databrew using connection to Redshift. I did add connection to AWS Glue and it is working while testing. When databrew tries to use this connection it gives following error. Both databrew and glue are on same region.

```<code>{"error":"Failure reading from input connection AwsGlueDataBrew-databrew-to-redshift with \"public.table\": Unable to reach AWS Glue to get connection AwsGlueDataBrew-databrew-to-redshift. Exception: Connect timeout on endpoint URL: \"https://glue.us-west-2.amazonaws.com/\""}
</code>```

Policy attached with projects is like this:

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "glue:GetDatabases",
                "glue:GetPartitions",
                "glue:GetTable",
                "glue:GetTables",
                "glue:GetConnection"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::databrew-public-datasets-*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeVpcEndpoints",
                "ec2:DescribeRouteTables",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcAttribute",
                "ec2:CreateNetworkInterface"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "ec2:DeleteNetworkInterface",
            "Condition": {
                "StringLike": {
                    "aws:ResourceTag/aws-glue-service-resource": "*"
                }
            },
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:CreateTags",
                "ec2:DeleteTags"
            ],
            "Condition": {
                "ForAllValues:StringEquals": {
                    "aws:TagKeys": [
                        "aws-glue-service-resource"
                    ]
                }
            },
            "Resource": [
                "arn:aws:ec2:*:*:network-interface/*",
                "arn:aws:ec2:*:*:security-group/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:*:*:log-group:/aws-glue-databrew/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "lakeformation:GetDataAccess"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetSecretValue"
            ],
            "Resource": "arn:aws:secretsmanager:*:*:secret:databrew!default-*"
        }
    ]
}
</code>```

Can someone please help me resolve this issue?

Thank you.

答:
This happens because the DataBrew service is trying to reach the AWS Glue service endpoint when you are trying to use a project/job. (AWS Glue test connection functionality works differently)

You have two ways to resolve this issue

Attach a VPC Endpoint for AWS Glue service in your VPC. This will ensure a way to reach the Glue service, but securely.

Open your VPC to public internet, so any traffic from your VPC can travel via internet and the API calls to the Glue service succeeds.

I recommend option #1 since it is more secure (and simpler), but it comes with an overhead of some cost.

Body:
I'm trying to get started with AWS Databrew using connection to Redshift. I did add connection to AWS Glue and it is working while testing. When databrew tries to use this connection it gives following error. Both databrew and glue are on same region.

{"error":"Failure reading from input connection AwsGlueDataBrew-databrew-to-redshift with \"public.table\": Unable to reach AWS Glue to get connection AwsGlueDataBrew-databrew-to-redshift. Exception: Connect timeout on endpoint URL: \"https://glue.us-west-2.amazonaws.com/\""}

Policy attached with projects is like this:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "glue:GetDatabases",
                "glue:GetPartitions",
                "glue:GetTable",
                "glue:GetTables",
                "glue:GetConnection"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket",
                "s3:GetObject"
            ],
            "Resource": [
                "arn:aws:s3:::databrew-public-datasets-*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeVpcEndpoints",
                "ec2:DescribeRouteTables",
                "ec2:DescribeNetworkInterfaces",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcAttribute",
                "ec2:CreateNetworkInterface"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": "ec2:DeleteNetworkInterface",
            "Condition": {
                "StringLike": {
                    "aws:ResourceTag/aws-glue-service-resource": "*"
                }
            },
            "Resource": [
                "*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:CreateTags",
                "ec2:DeleteTags"
            ],
            "Condition": {
                "ForAllValues:StringEquals": {
                    "aws:TagKeys": [
                        "aws-glue-service-resource"
                    ]
                }
            },
            "Resource": [
                "arn:aws:ec2:*:*:network-interface/*",
                "arn:aws:ec2:*:*:security-group/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:*:*:log-group:/aws-glue-databrew/*"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "lakeformation:GetDataAccess"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "secretsmanager:GetSecretValue"
            ],
            "Resource": "arn:aws:secretsmanager:*:*:secret:databrew!default-*"
        }
    ]
}

Can someone please help me resolve this issue?

Thank you.


问:
How to break the Parallel.ForEachAsync loop, not cancel it?
In .NET 5 we had Parallel.ForEach which you were able to use ParallelLoopState.Break() method to stop additional iterations from processing. Allowing current ones to complete processing.

But the new .NET 6 Parallel.ForEachAsync does not have the ParallelLoopState class so we can't break it like we could with Parallel.ForEach. So is there a way to perform the same break functionality in ForEachAsync? CancellationToken passed to the func I don't believe is the right way since your not trying to cancel the running loop but preventing additional iterations from starting.

Something like this functionality but for the async version:

```<code>int count = 0;
Parallel.ForEach(enumerateFiles, new ParallelOptions() { CancellationToken = cancellationToken},
    (file, state) =>
    {
        Interlocked.Increment(ref count);
        if (count >= MaxFilesToProcess)
        {
            state.Break();
        }
...
</code>```

As a workaround I can probably use .Take([xx]) on the TSource before it is passed into the parallel loop but that might not be an option for a complex condition to break on.

答:
The asynchronous API Parallel.ForEachAsync does not offer the Stop/Break functionality of its synchronous counterpart.

One way to replicate this functionality is to use a bool flag in combination with the TakeWhile LINQ operator:

```<code>bool breakFlag = false;
await Parallel.ForEachAsync(
    source.TakeWhile(_ => !Volatile.Read(ref breakFlag)),
    async (item, ct) =>
{
    // ...
    if (condition) Volatile.Write(ref breakFlag, true);
    // ...
});
</code>```

The Parallel.ForEachAsync does not buffer aggressively elements from the source sequence¹, like the Parallel.ForEach does, so as soon as the condition is met, no more asynchronous operations are going to start.

Is case the source is an asynchronous enumerable (IAsyncEnumerable<T>), there is a compatible TakeWhile operator with identical functionality in the System.Linq.Async package.

¹ At least not today (.NET 6). This behavior is not documented or guaranteed.

Body:
In .NET 5 we had Parallel.ForEach which you were able to use ParallelLoopState.Break() method to stop additional iterations from processing. Allowing current ones to complete processing.

But the new .NET 6 Parallel.ForEachAsync does not have the ParallelLoopState class so we can't break it like we could with Parallel.ForEach. So is there a way to perform the same break functionality in ForEachAsync? CancellationToken passed to the func I don't believe is the right way since your not trying to cancel the running loop but preventing additional iterations from starting.

Something like this functionality but for the async version:

int count = 0;
Parallel.ForEach(enumerateFiles, new ParallelOptions() { CancellationToken = cancellationToken},
    (file, state) =>
    {
        Interlocked.Increment(ref count);
        if (count >= MaxFilesToProcess)
        {
            state.Break();
        }
...

As a workaround I can probably use .Take([xx]) on the TSource before it is passed into the parallel loop but that might not be an option for a complex condition to break on.

Body:
The asynchronous API Parallel.ForEachAsync does not offer the Stop/Break functionality of its synchronous counterpart.

One way to replicate this functionality is to use a bool flag in combination with the TakeWhile LINQ operator:

bool breakFlag = false;
await Parallel.ForEachAsync(
    source.TakeWhile(_ => !Volatile.Read(ref breakFlag)),
    async (item, ct) =>
{
    // ...
    if (condition) Volatile.Write(ref breakFlag, true);
    // ...
});

The Parallel.ForEachAsync does not buffer aggressively elements from the source sequence¹, like the Parallel.ForEach does, so as soon as the condition is met, no more asynchronous operations are going to start.

Is case the source is an asynchronous enumerable (IAsyncEnumerable<T>), there is a compatible TakeWhile operator with identical functionality in the System.Linq.Async package.

¹ At least not today (.NET 6). This behavior is not documented or guaranteed.


问:
PL/pgSQL: finding all groups person belongs to (also indirectly)
Simple intro:

I have a database with users and groups.
Every user might be a member of one or more groups.
Every group might have one or more parent groups.

Schema:

```<code>CREATE TABLE users(
  username VARCHAR(64) NOT NULL PRIMARY KEY,
  password VARCHAR(64) NOT NULL,
  enabled BOOLEAN NOT NULL);

CREATE TABLE groups (
  id bigserial NOT NULL PRIMARY KEY,
  group_name VARCHAR(64) NOT NULL);

CREATE TABLE groups_inheritance (
  group_id bigint NOT NULL,
  parent_group_id bigint NOT NULL,
  CONSTRAINT fk_group_inheritance_group FOREIGN KEY(group_id) REFERENCES groups(id),
  CONSTRAINT fk_group_inheritance_group_2 FOREIGN KEY(parent_group_id) REFERENCES groups(id),
  CONSTRAINT unique_uk_groups_inheritance UNIQUE(group_id, parent_group_id));

CREATE TABLE group_members (
  id bigint PRIMARY KEY,
  username VARCHAR(64) NOT NULL,
  group_id bigint NOT NULL,
  CONSTRAINT fk_group_members_username FOREIGN KEY(username) REFERENCES users(username),
  CONSTRAINT fk_group_members_group FOREIGN KEY(group_id) REFERENCES groups(id));
</code>```

I'm looking for a PL/pgSQL function which finds all groups (their names) particular user belongs to.

Example:

group name: People,
group parent: null

group name: Students,
group parent: People

group name: Football_players,
group parent: People

group name: Basketball_players,
group parent: People

user name: Maciej,
groups : Students, Football_players

f("Maciej") = {"Students", "People", "Football_players"}

He belongs to "People" just because he belongs to "Students" or "Football_players". He is not a direct member of "People" group.

Thanks in advance!

答:
```<code>WITH RECURSIVE group_ancestry AS (
SELECT group_id, username
FROM group_members
UNION
SELECT groups_inheritance.parent_group_id, username
FROM group_ancestry
     JOIN groups_inheritance ON groups_inheritance.group_id = group_ancestry.group_id
)
SELECT username, group_id
FROM group_ancestry
</code>```

Body:
Simple intro:

I have a database with users and groups.
Every user might be a member of one or more groups.
Every group might have one or more parent groups.

Schema:

CREATE TABLE users(
  username VARCHAR(64) NOT NULL PRIMARY KEY,
  password VARCHAR(64) NOT NULL,
  enabled BOOLEAN NOT NULL);

CREATE TABLE groups (
  id bigserial NOT NULL PRIMARY KEY,
  group_name VARCHAR(64) NOT NULL);

CREATE TABLE groups_inheritance (
  group_id bigint NOT NULL,
  parent_group_id bigint NOT NULL,
  CONSTRAINT fk_group_inheritance_group FOREIGN KEY(group_id) REFERENCES groups(id),
  CONSTRAINT fk_group_inheritance_group_2 FOREIGN KEY(parent_group_id) REFERENCES groups(id),
  CONSTRAINT unique_uk_groups_inheritance UNIQUE(group_id, parent_group_id));

CREATE TABLE group_members (
  id bigint PRIMARY KEY,
  username VARCHAR(64) NOT NULL,
  group_id bigint NOT NULL,
  CONSTRAINT fk_group_members_username FOREIGN KEY(username) REFERENCES users(username),
  CONSTRAINT fk_group_members_group FOREIGN KEY(group_id) REFERENCES groups(id));

I'm looking for a PL/pgSQL function which finds all groups (their names) particular user belongs to.

Example:

group name: People,
group parent: null

group name: Students,
group parent: People

group name: Football_players,
group parent: People

group name: Basketball_players,
group parent: People

user name: Maciej,
groups : Students, Football_players

f("Maciej") = {"Students", "People", "Football_players"}

He belongs to "People" just because he belongs to "Students" or "Football_players". He is not a direct member of "People" group.

Thanks in advance!


问:
"Calendar is not defined" when attempting to run Google's "Vacation Calendar" sample code
I'm trying to run Google's sample code for a vacation calendar. When I attempt to do so, I get the following error:

Calendar is not defined

I looked at the code and it stems from this line of code:

```<code>    try {
      response = Calendar.Events.list(user.getEmail(), params);
    } catch (e) {
      console.error('Error retriving events for %s, %s: %s; skipping',
          user, keyword, e.toString());
      continue;
    }
</code>```

How do I get this line of code to not error out?

答:
TL;DR

Since it's using Calendar instead of CalendarApp in the script, it's using the advanced service, so you must explicitly enable the Calendar service. Don't forget to name it Calendar so you don't need to tweak the code.

Long answer...

Each service has two methods of invocation: FooApp and Foo. For example, CalendarApp and Calendar.

Here are the differences:

CalendarApp

The default mechanism for interacting with a service.

Automatically enabled by default.

Simple API with arguments / code completion:

```<code>var events = CalendarApp.getDefaultCalendar().getEvents(now, twoHoursFromNow);
</code>```

Access documentation via Support > Documentation > Google Apps Scripts > Reference > Calendar

Calendar (also called Calendar API)

The "advanced" method of interacting with a service.

Must be enabled via an Advanced Service (where you will also give it the name Calendar).

Advanced API with dictionary parameters:

```<code>let params = {
  q: keyword,
  timeMin: formatDateAsRFC3339(start),
  timeMax: formatDateAsRFC3339(end),
  showDeleted: true,
};
response = Calendar.Events.list(user.getEmail(), params);
</code>```

Access documentation via Support > Documentation > Google Apps Scripts > Reference > Calendar > Calendar API > Google Calendar API > Calendar API > Reference Documentation

Note that in the above example, I used Calendar everywhere, but the same applies to all the other services (e.g. Gmail and GmailApp).

If you go to the reference for Calendar > Calendar API, you can see this documented by Google:

The advanced Calendar service allows you to use the public Google Calendar API in Apps Script. Much like Apps Script's built-in Calendar service, this API allows scripts to access and modify the user's Google Calendar, including additional calendars that the user is subscribed to. In most cases, the built-in service is easier to use, but this advanced service provides a few extra features, including setting the background color for individual events.

Body:
I'm trying to run Google's sample code for a vacation calendar. When I attempt to do so, I get the following error:

Calendar is not defined

I looked at the code and it stems from this line of code:

    try {
      response = Calendar.Events.list(user.getEmail(), params);
    } catch (e) {
      console.error('Error retriving events for %s, %s: %s; skipping',
          user, keyword, e.toString());
      continue;
    }

How do I get this line of code to not error out?

Body:
TL;DR

Since it's using Calendar instead of CalendarApp in the script, it's using the advanced service, so you must explicitly enable the Calendar service. Don't forget to name it Calendar so you don't need to tweak the code.

Long answer...

Each service has two methods of invocation: FooApp and Foo. For example, CalendarApp and Calendar.

Here are the differences:

CalendarApp

The default mechanism for interacting with a service.

Automatically enabled by default.

Simple API with arguments / code completion:

var events = CalendarApp.getDefaultCalendar().getEvents(now, twoHoursFromNow);

Access documentation via Support > Documentation > Google Apps Scripts > Reference > Calendar

Calendar (also called Calendar API)

The "advanced" method of interacting with a service.

Must be enabled via an Advanced Service (where you will also give it the name Calendar).

Advanced API with dictionary parameters:

let params = {
  q: keyword,
  timeMin: formatDateAsRFC3339(start),
  timeMax: formatDateAsRFC3339(end),
  showDeleted: true,
};
response = Calendar.Events.list(user.getEmail(), params);

Access documentation via Support > Documentation > Google Apps Scripts > Reference > Calendar > Calendar API > Google Calendar API > Calendar API > Reference Documentation

Note that in the above example, I used Calendar everywhere, but the same applies to all the other services (e.g. Gmail and GmailApp).

If you go to the reference for Calendar > Calendar API, you can see this documented by Google:

The advanced Calendar service allows you to use the public Google Calendar API in Apps Script. Much like Apps Script's built-in Calendar service, this API allows scripts to access and modify the user's Google Calendar, including additional calendars that the user is subscribed to. In most cases, the built-in service is easier to use, but this advanced service provides a few extra features, including setting the background color for individual events.


问:
What is the performance impact of Python profiling?
I am considering profiling a Python application in production (such as a Django website). I've found many options that self-describe as lightweight and demonstrate how they are used (including cProfile, vmprof, yappi and DTrace/SystemTap) but I am struggling to get a sense of what kind of negative performance impact I can expect while the profiler is in operation. This would be an important factor in identifying whether a particular tool is suitable for profiling in production.

Is it possible to anticipate the performance impact of a particular profiler, without experimentation in a test environment?

答:
A profiler will not in itself speed up you program  what it does is tell you  where the program spends most time.  Suppose that you profiler tells you that the program is in func1 1% of the time and in func2  80% of the time.  If you make func1 run twice as fast you will speed up your progrram by about .5%.  If you make func2 run twice as fast you will speed up you program by 40%.   Spend your time and effort on func2.

How do you make functions faster?   There is no simple answer, but there are lots of sites that talk about this  (search for Python Performance).  What sort of performance increase can you expect?  Again there is no simple answer.  My rule of thumb is a factor of two increase, but your mileage will probably vary?


问:
How to parse json array of objects inside object using Retrofit
I am trying to parse JSON (https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json) to show data in RecyclerView, but I get an error:

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 13534
    java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
        at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
        at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39)
        at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
        at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
        at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
</code>```

I see that the problem is that JSON contains just 1 object (pokemon) and inside this object there is array of different pokemons. I don't know how to parse array inside the upper level object in JSON. What should I change to make it work?
I suppose that I should save this pokemon object and then parse it but I don't know hot to get inside it.
Thanks.

API interface:

```<code>interface SimpleApi {
    @GET("pokedex.json")
    suspend fun getCustomPosts(): Response<List<Post>>
}
</code>```

Repository:

```<code>class Repository {
    suspend fun getCustomPosts(): Response<List<Post>>{
        return RetrofitInstance.api.getCustomPosts()
    }
}
</code>```

ViewModel:

```<code>class MainViewModel(val repository: Repository) : ViewModel() {

    val myCustomPosts = MutableLiveData<Response<List<Post>>>()

    fun getCustomPosts() {
        viewModelScope.launch {
            val response: Response<List<Post>> = repository.getCustomPosts()
            myCustomPosts.value = response
        }
    }
}
</code>```

MainActivity:

```<code>class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: MainViewModel
    private lateinit var binding: ActivityMainBinding
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: MyAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        setRecyclerView()

        val repository = Repository()
        val viewModelFactory = MainViewModelFactory(repository)
        viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)

        viewModel.getCustomPosts()

        viewModel.myCustomPosts.observe(this, Observer { response ->
            if (response.isSuccessful) {
                response.body()?.let { adapter.setData(it) }
            } else {
                Toast.makeText(this, response.code(), Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun setRecyclerView() {
        adapter = MyAdapter()
        recyclerView = binding.recyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
    }
}
</code>```

RecyclerView Adapter:

```<code>class MyAdapter() : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    private var postList = emptyList<Post>()

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val idView: TextView = view.findViewById(R.id.id_txt)
        val nameView: TextView = view.findViewById(R.id.name_txt)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false)
        )
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val currentItem = postList[position]
        holder.idView.text = currentItem.id.toString()
        holder.nameView.text = currentItem.name
    }

    override fun getItemCount(): Int = postList.size

    fun setData(newList: List<Post>){
        postList = newList
        notifyDataSetChanged()
    }
}
</code>```

Post:

```<code>data class Post(
    @SerializedName("id")
    val id: Int,
    @SerializedName("name")
    val name: String
)
</code>```

答:
Try to use next class in response object:

```<code>data class PokedexResponse (
    @SerializedName("pokemon")
    val pokemons: List<Post>
)

interface SimpleApi {
    @GET("pokedex.json")
    suspend fun getCustomPosts(): Response<PokedexResponse>
}
</code>```

My guess is that you missed to parse pokemon object:

```<code>{
  "pokemon": [{ ... }]
}
</code>```

Body:
I am trying to parse JSON (https://raw.githubusercontent.com/Biuni/PokemonGO-Pokedex/master/pokedex.json) to show data in RecyclerView, but I get an error:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 13534
    java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 path $
        at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:350)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:80)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
        at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:39)
        at retrofit2.converter.gson.GsonResponseBodyConverter.convert(GsonResponseBodyConverter.java:27)
        at retrofit2.OkHttpCall.parseResponse(OkHttpCall.java:243)
        at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:153)
        at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

I see that the problem is that JSON contains just 1 object (pokemon) and inside this object there is array of different pokemons. I don't know how to parse array inside the upper level object in JSON. What should I change to make it work?
I suppose that I should save this pokemon object and then parse it but I don't know hot to get inside it.
Thanks.

API interface:

interface SimpleApi {
    @GET("pokedex.json")
    suspend fun getCustomPosts(): Response<List<Post>>
}

Repository:

class Repository {
    suspend fun getCustomPosts(): Response<List<Post>>{
        return RetrofitInstance.api.getCustomPosts()
    }
}

ViewModel:

class MainViewModel(val repository: Repository) : ViewModel() {

    val myCustomPosts = MutableLiveData<Response<List<Post>>>()

    fun getCustomPosts() {
        viewModelScope.launch {
            val response: Response<List<Post>> = repository.getCustomPosts()
            myCustomPosts.value = response
        }
    }
}

MainActivity:

class MainActivity : AppCompatActivity() {

    private lateinit var viewModel: MainViewModel
    private lateinit var binding: ActivityMainBinding
    private lateinit var recyclerView: RecyclerView
    private lateinit var adapter: MyAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        val view = binding.root
        setContentView(view)
        setRecyclerView()

        val repository = Repository()
        val viewModelFactory = MainViewModelFactory(repository)
        viewModel = ViewModelProvider(this, viewModelFactory).get(MainViewModel::class.java)

        viewModel.getCustomPosts()

        viewModel.myCustomPosts.observe(this, Observer { response ->
            if (response.isSuccessful) {
                response.body()?.let { adapter.setData(it) }
            } else {
                Toast.makeText(this, response.code(), Toast.LENGTH_SHORT).show()
            }
        })
    }

    private fun setRecyclerView() {
        adapter = MyAdapter()
        recyclerView = binding.recyclerView
        recyclerView.layoutManager = LinearLayoutManager(this)
        recyclerView.adapter = adapter
    }
}

RecyclerView Adapter:

class MyAdapter() : RecyclerView.Adapter<MyAdapter.MyViewHolder>() {

    private var postList = emptyList<Post>()

    class MyViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val idView: TextView = view.findViewById(R.id.id_txt)
        val nameView: TextView = view.findViewById(R.id.name_txt)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        return MyViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.row_layout, parent, false)
        )
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val currentItem = postList[position]
        holder.idView.text = currentItem.id.toString()
        holder.nameView.text = currentItem.name
    }

    override fun getItemCount(): Int = postList.size

    fun setData(newList: List<Post>){
        postList = newList
        notifyDataSetChanged()
    }
}

Post:

data class Post(
    @SerializedName("id")
    val id: Int,
    @SerializedName("name")
    val name: String
)

Body:
Try to use next class in response object:

data class PokedexResponse (
    @SerializedName("pokemon")
    val pokemons: List<Post>
)

interface SimpleApi {
    @GET("pokedex.json")
    suspend fun getCustomPosts(): Response<PokedexResponse>
}

My guess is that you missed to parse pokemon object:

{
  "pokemon": [{ ... }]
}


问:
aws cloudformation wordpress updates
I have a wordpress app that I need to install to aws with a cloudformation template, I initially created it using some sample template from AWS cloudformation, but when AWS rebuilds the system some changes are lost,

in particular I need to set the httpd.conf file so that:

```<code><Directory "/var/www">
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>
</code>```

and everytime aws rebuilds (they do it a few times a week) I lose this.

also I need to add a few environment variables to the elasticbeanstalk instance so that other changes will be picked up as well.

I currently have a few env variables like:

RDS_DB_NAME, RDS_HOSTNAME, RDS_PASSWORD, RDS_PORT, RDS_USERNAME

I'm not sure where they are configured in the cloudformation template, I think I remember adding them manually to the elasticbean instance configuration. I now need to add a bunch to these, like:

```<code>AUTH_KEY
SECURE_AUTH_KEY
LOGGED_IN_KEY
NONCE_KEY
AUTH_SALT
SECURE_AUTH_SALT
LOGGED_IN_SALT
NONCE_SALT
</code>```

I'm not sure how to get around to do that.

I also need to configure the cloudformation so that my wordpress has also an SSL certificate (which I have available as arn) and is accessible via https.

I think if I add it to the autoscaling configuration, then updating the stack will just recreate the autoscaling resource and reinstall the vanilla version of wordpress,

I have wordpress in an application on elasticbean stalk, I'm not sure in this case how to make it install the latest version, instead of the vanilla one.

here's my entire cloudformation yaml template: https://justpaste.it/481a7

答:
Any such changes to your EB env, should be provided with your application as explained in section "Reverse proxy configuration" of

Extending Elastic Beanstalk Linux platforms

This includes any changes to httpd or nginx. This will ensure that they are always applied when you autoscale or re-upload your EB application.

Title: aws cloudformation wordpress updates

Body:
I have a wordpress app that I need to install to aws with a cloudformation template, I initially created it using some sample template from AWS cloudformation, but when AWS rebuilds the system some changes are lost,

in particular I need to set the httpd.conf file so that:

<Directory "/var/www">
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

and everytime aws rebuilds (they do it a few times a week) I lose this.

also I need to add a few environment variables to the elasticbeanstalk instance so that other changes will be picked up as well.

I currently have a few env variables like:

RDS_DB_NAME, RDS_HOSTNAME, RDS_PASSWORD, RDS_PORT, RDS_USERNAME

I'm not sure where they are configured in the cloudformation template, I think I remember adding them manually to the elasticbean instance configuration. I now need to add a bunch to these, like:

AUTH_KEY
SECURE_AUTH_KEY
LOGGED_IN_KEY
NONCE_KEY
AUTH_SALT
SECURE_AUTH_SALT
LOGGED_IN_SALT
NONCE_SALT

I'm not sure how to get around to do that.

I also need to configure the cloudformation so that my wordpress has also an SSL certificate (which I have available as arn) and is accessible via https.

I think if I add it to the autoscaling configuration, then updating the stack will just recreate the autoscaling resource and reinstall the vanilla version of wordpress,

I have wordpress in an application on elasticbean stalk, I'm not sure in this case how to make it install the latest version, instead of the vanilla one.

here's my entire cloudformation yaml template: https://justpaste.it/481a7


问:
Could not find the correct Provider<TaskData> above this TasksScreenNew Widget
I have a problem using Flutter Provider... every time when im clicking at the widget that brings me to the Tasksscreen i'm getting this error. Im really new to Provider... got that code from a tutorial. I'm just stuck with this error for 1 hour now and i haven't found anything suitable for my problem.

If you need more code, just say it

Error:

```<code>ProviderNotFoundException (Error: Could not find the correct Provider<TaskData> above this TasksScreenNew Widget

</code>```

Code:

```<code>import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:learnon/widgets/tasks_list.dart';
import 'package:learnon/screens/addtasksscreen.dart';
import 'package:learnon/models/tasks_data.dart';
import 'package:provider/provider.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

bool theme = false;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

class TasksScreenNew extends StatelessWidget {
  static const routeName = "/tasksnewwidget";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueAccent,
      floatingActionButton: FloatingActionButton(
        heroTag: null,
        child: Icon(Icons.add),
        backgroundColor: Colors.lightBlue,
        onPressed: () {
          showModalBottomSheet(
              isScrollControlled: true,
              context: context,
              builder: (BuildContext context) => AddTaskScreen());
        },
      ),
      body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Container(
          padding: EdgeInsets.only(top: 60, left: 30, right: 30, bottom: 30),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 10,
              ),
              Text(
                'Todo',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 50,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                '${Provider.of<TaskData>(context).taskCount} Tasks',
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ],
          ),
        ),
        Expanded(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: TasksList(),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
          ),
        )
      ]),
    );
  }
}
// CircleAvatar(
// radius: 30,
// backgroundColor: Colors.white,
// child: Icon(
// Icons.list,
// color: Colors.blueAccent,
// size: 30,
// ),
// )

</code>```

答:
To access providers from context, you need to wrap any widget higher up the tree in Provider or ChangeNotifierProvider.

You can try doing the following on the current page.

```<code>Widget build(BuildContext context) {
  return ChangeNotifierProvider<TaskData>(
    create: (_) => TaskData(),
    builder: (context, __) => Scaffold(
</code>```

You can also see examples, e.g. here https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple

Body:
I have a problem using Flutter Provider... every time when im clicking at the widget that brings me to the Tasksscreen i'm getting this error. Im really new to Provider... got that code from a tutorial. I'm just stuck with this error for 1 hour now and i haven't found anything suitable for my problem.

If you need more code, just say it

Error:

ProviderNotFoundException (Error: Could not find the correct Provider<TaskData> above this TasksScreenNew Widget

Code:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:learnon/widgets/tasks_list.dart';
import 'package:learnon/screens/addtasksscreen.dart';
import 'package:learnon/models/tasks_data.dart';
import 'package:provider/provider.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

bool theme = false;
FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

class TasksScreenNew extends StatelessWidget {
  static const routeName = "/tasksnewwidget";
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blueAccent,
      floatingActionButton: FloatingActionButton(
        heroTag: null,
        child: Icon(Icons.add),
        backgroundColor: Colors.lightBlue,
        onPressed: () {
          showModalBottomSheet(
              isScrollControlled: true,
              context: context,
              builder: (BuildContext context) => AddTaskScreen());
        },
      ),
      body: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
        Container(
          padding: EdgeInsets.only(top: 60, left: 30, right: 30, bottom: 30),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 10,
              ),
              Text(
                'Todo',
                style: TextStyle(
                    color: Colors.white,
                    fontSize: 50,
                    fontWeight: FontWeight.bold),
              ),
              Text(
                '${Provider.of<TaskData>(context).taskCount} Tasks',
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ],
          ),
        ),
        Expanded(
          child: Container(
            padding: EdgeInsets.symmetric(horizontal: 20),
            child: TasksList(),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
          ),
        )
      ]),
    );
  }
}
// CircleAvatar(
// radius: 30,
// backgroundColor: Colors.white,
// child: Icon(
// Icons.list,
// color: Colors.blueAccent,
// size: 30,
// ),
// )

Body:
To access providers from context, you need to wrap any widget higher up the tree in Provider or ChangeNotifierProvider.

You can try doing the following on the current page.

Widget build(BuildContext context) {
  return ChangeNotifierProvider<TaskData>(
    create: (_) => TaskData(),
    builder: (context, __) => Scaffold(

You can also see examples, e.g. here https://docs.flutter.dev/development/data-and-backend/state-mgmt/simple


问:
Nginx Server http to https
I installed NginX to my nodeJS server and already made Certbot SSL authentication.
Everything is working fine, but when i delete cookies and going to page, its load in http.
Is there any way to redirect into https?
When i write "return 301 https://maarath.com$request_uri;", its going to error: too many redirects.
Someone any idea?
My config:

```<code>server {

listen       80;
    server_name ujhonlapod.hu www.ujhonlapod.hu;

   location / {

    proxy_pass http://localhost:3000; # Change the port if needed
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;

   }
listen 443 ssl; # managed by Certbot
    server_name ujhonlapod.hu www.ujhonlapod.hu;
    ssl_certificate /etc/letsencrypt/live/ujhonlapod.hu/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/ujhonlapod.hu/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot

    ssl_trusted_certificate /etc/letsencrypt/live/ujhonlapod.hu/chain.pem; # managed by Certbot
    ssl_stapling on; # managed by Certbot
    ssl_stapling_verify on; # managed by Certbot
    add_header Content-Security-Policy upgrade-insecure-requests;

}
</code>```

Thanks for the answers.

答:
Are you using the certbot plugin for nginx? It doesn't look like. You should remove this part

listen 443 ssl; # managed by Certbot
    server_name ujhonlapod.hu www.ujhonlapod.hu;
    ssl_certificate /etc/letsencrypt/live/ujhonlapod.hu/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/ujhonlapod.hu/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot

    ssl_trusted_certificate /etc/letsencrypt/live/ujhonlapod.hu/chain.pem; # managed by Certbot
    ssl_stapling on; # managed by Certbot
    ssl_stapling_verify on; # managed by Certbot
    add_header Content-Security-Policy upgrade-insecure-requests;

```
<p>and clean up your config to just listen on port 80.</p>
<pre class="lang-sh prettyprint-override"><code>server {

listen       80;
server_name ujhonlapod.hu www.ujhonlapod.hu;

   location / {

    proxy_pass http://localhost:3000; # Change the port if needed
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

   }
}
</code>```

Reload nginx nginx -s reload

Run certbot sudo certbot --nginx

This should create the correct configuration for you.

Personally I would always!! split the http and https traffic in two server blocks like

server {
  listen 80;
  server_name example.com;

  if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
}

server {
  listen 443;
  server_name example.com;
  .....

}
```

I would really recommend to use the plugin to manage the NGINX configuration if not a 100% aware on how to manage the configuration and certificates by your self. With certbot it is an act of 2 minutes to make it work.

Read more here: https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal

Title: Nginx Server http to https

Body:
I installed NginX to my nodeJS server and already made Certbot SSL authentication.
Everything is working fine, but when i delete cookies and going to page, its load in http.
Is there any way to redirect into https?
When i write "return 301 https://maarath.com$request_uri;", its going to error: too many redirects.
Someone any idea?
My config:

server {

listen       80;
    server_name ujhonlapod.hu www.ujhonlapod.hu;

   location / {

    proxy_pass http://localhost:3000; # Change the port if needed
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;

   }
listen 443 ssl; # managed by Certbot
    server_name ujhonlapod.hu www.ujhonlapod.hu;
    ssl_certificate /etc/letsencrypt/live/ujhonlapod.hu/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/ujhonlapod.hu/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot

    ssl_trusted_certificate /etc/letsencrypt/live/ujhonlapod.hu/chain.pem; # managed by Certbot
    ssl_stapling on; # managed by Certbot
    ssl_stapling_verify on; # managed by Certbot
    add_header Content-Security-Policy upgrade-insecure-requests;

}

Thanks for the answers.

Body:
Are you using the certbot plugin for nginx? It doesn't look like. You should remove this part

listen 443 ssl; # managed by Certbot
    server_name ujhonlapod.hu www.ujhonlapod.hu;
    ssl_certificate /etc/letsencrypt/live/ujhonlapod.hu/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/ujhonlapod.hu/privkey.pem; # managed by Certbot
    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
    ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot

    add_header Strict-Transport-Security "max-age=31536000" always; # managed by Certbot

    ssl_trusted_certificate /etc/letsencrypt/live/ujhonlapod.hu/chain.pem; # managed by Certbot
    ssl_stapling on; # managed by Certbot
    ssl_stapling_verify on; # managed by Certbot
    add_header Content-Security-Policy upgrade-insecure-requests;

and clean up your config to just listen on port 80.

server {

listen       80;
server_name ujhonlapod.hu www.ujhonlapod.hu;

   location / {

    proxy_pass http://localhost:3000; # Change the port if needed
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;

   }
}

Reload nginx nginx -s reload

Run certbot sudo certbot --nginx

This should create the correct configuration for you.

Personally I would always!! split the http and https traffic in two server blocks like

server {
  listen 80;
  server_name example.com;

  if ($host = example.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot
}

server {
  listen 443;
  server_name example.com;
  .....

}

I would really recommend to use the plugin to manage the NGINX configuration if not a 100% aware on how to manage the configuration and certificates by your self. With certbot it is an act of 2 minutes to make it work.

Read more here: https://certbot.eff.org/instructions?ws=nginx&os=ubuntufocal