问:
java split with unknown result
for the following code,

why there is empty string in position 2,3,5,6,8?

then why "b", ":andf", "1" has no empty string behind?

```<code>    String[] splitStrs = "booo:and:fooo1o".split("o", -1);
    System.out.println(splitStrs.length);
    for (int i=0; i<splitStrs.length; i++) {
        System.out.println("\"" + splitStrs[i]+ "\"");
    }
</code>```

output is:

8

"b"

""

""

":and:f"

""

""

"1"

""

答:
Public String [ ] split ( String regex, int limit ) Parameters:

regex – a delimiting regular expression

Limit – the resulting
threshold

The limit parameter can have 3 values:

limit > 0 – If this is the case, then the pattern will be applied at
most limit-1 times, the resulting array’s length will not be more
than n, and the resulting array’s last entry will contain all input
beyond the last matched pattern.

limit < 0 – In this case, the
pattern will be applied as many times as possible, and the resulting
array can be of any size.

limit = 0 – In this case, the pattern will
be applied as many times as possible, the resulting array can be of
any size, and trailing empty strings will be discarded.

please visit GeeksforGeeks site for more information regarding spliting.

"booo:and:fooo1o".split("o", -1);

why there is empty string in position 2,3,5,6,8?

Since the limit is -1 we can split it any number of times. When 'o' is used as the regex it will give all the values which are before it since there is no value it returns empty string

then why "b", ":andf", "1" has no empty string behind?

There is no empty string because there are characters after the 'o' previous match.

See this example:

```<code>class Split{
    public static void main(final String ... $){
        var out = System.out;
        final String s = "ooa";
        for(final String str : s.split("o", -1))
            out.println("\""+str+"\"");

    }
}
</code>```

Output:

```<code>$ javac Split.java && java Split
""
""
"a"
</code>```

Why this output?

When first match happens @ index 0 which is also the very first character and it returns string before it but since there is no string it returns an empty string.

Then when second match happens with o @ index 1 it returns the string after the first match and before index 1. Since there is no characters it returns an empty string.

After that it returns a.

Title: java split with unknown result

Body:
for the following code,

why there is empty string in position 2,3,5,6,8?

then why "b", ":andf", "1" has no empty string behind?

    String[] splitStrs = "booo:and:fooo1o".split("o", -1);
    System.out.println(splitStrs.length);
    for (int i=0; i<splitStrs.length; i++) {
        System.out.println("\"" + splitStrs[i]+ "\"");
    }

output is:

8

"b"

""

""

":and:f"

""

""

"1"

""

Body:
Public String [ ] split ( String regex, int limit ) Parameters:

regex – a delimiting regular expression

Limit – the resulting
threshold

The limit parameter can have 3 values:

limit > 0 – If this is the case, then the pattern will be applied at
most limit-1 times, the resulting array’s length will not be more
than n, and the resulting array’s last entry will contain all input
beyond the last matched pattern.

limit < 0 – In this case, the
pattern will be applied as many times as possible, and the resulting
array can be of any size.

limit = 0 – In this case, the pattern will
be applied as many times as possible, the resulting array can be of
any size, and trailing empty strings will be discarded.

please visit GeeksforGeeks site for more information regarding spliting.

"booo:and:fooo1o".split("o", -1);

why there is empty string in position 2,3,5,6,8?

Since the limit is -1 we can split it any number of times. When 'o' is used as the regex it will give all the values which are before it since there is no value it returns empty string

then why "b", ":andf", "1" has no empty string behind?

There is no empty string because there are characters after the 'o' previous match.

See this example:

class Split{
    public static void main(final String ... $){
        var out = System.out;
        final String s = "ooa";
        for(final String str : s.split("o", -1))
            out.println("\""+str+"\"");

    }
}

Output:

$ javac Split.java && java Split
""
""
"a"

Why this output?

When first match happens @ index 0 which is also the very first character and it returns string before it but since there is no string it returns an empty string.

Then when second match happens with o @ index 1 it returns the string after the first match and before index 1. Since there is no characters it returns an empty string.

After that it returns a.


来源: stackexchange

问:
date comparison moment js
I want to compare two dates and my date format is DD-MM-YYYY but I don't know why my output returns false when I compare my dates.

example 1

```<code>const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1) < moment(date2); // return false, should return true
</code>```

example 2

```<code>const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1).isBefore(date2); // return false, should return true
</code>```

答:
There are two issues there:

You're expecting moment to guess the format of your dates, but it can't do that reliably. Always provide a format string if your string isn't in a RFC2822 or ISO-8601 format. moment itself warns you about doing that in the dev version of the library:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/

< cannot be used to meaningfully compare objects. If you want to know if a date is before another date, use the isBefore method.

For example:

```<code>const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
</code>```

const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
console.log(result);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script></code>```

ContentLicense: CC BY-SA 4.0

Title: date comparison moment js

Body:
I want to compare two dates and my date format is DD-MM-YYYY but I don't know why my output returns false when I compare my dates.

example 1

const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1) < moment(date2); // return false, should return true

example 2

const date1 = '30-06-2021';
const date2 = '10-01-2022';
const result = moment(date1).isBefore(date2); // return false, should return true

Body:
There are two issues there:

You're expecting moment to guess the format of your dates, but it can't do that reliably. Always provide a format string if your string isn't in a RFC2822 or ISO-8601 format. moment itself warns you about doing that in the dev version of the library:

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/

< cannot be used to meaningfully compare objects. If you want to know if a date is before another date, use the isBefore method.

For example:

const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));

const date1 = "30-06-2021";
const date2 = "10-01-2022";
const format = "DD-MM-YYYY";
const result = moment(date1, format).isBefore(moment(date2, format));
console.log(result);

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>


问:
C-Lang: Segmentation Fault when working with string in for-loop
Quite recently, at the university, we began to study strings in the C programming language, and as a homework, I was given the task of writing a program to remove extra words.

While writing a program, I faced an issue with iteration through a string that I could solve in a hacky way. However, I would like to deal with the problem with your help, since I cannot find the error myself.

The problem is that when I use the strlen(buffer) function as a for-loop condition, the code compiles easily and there are no errors at runtime, although when I use the __act_buffer_len variable, which is assigned a value of strlen(buffer) there will be a segmentation fault at runtime.

I tried many more ways to solve this problem, but the only one, which I already described, worked for me.

```<code>// deletes words with <= 2 letters
char* _delete_odd(const char* buffer, char delim)
{
    int __act_buffer_len = strlen(buffer);

    // for debugging purposes
    printf("__actbuff: %d\n", __act_buffer_len);
    printf("sizeof: %d\n", sizeof(buffer));
    printf("strlen: %d\n", strlen(buffer));

    char* _newbuff = malloc(__act_buffer_len + 1); // <- new buffer without words with less than 2 unique words
    char* _tempbuff; // <- used to store current word

    int beg_point = 0;
    int curr_wlen = 0;
    for (int i = 0; i < strlen(buffer); i++)       // no errors at runtime, app runs well
    // for (int i = 0; i < __act_buffer_len; i++)  // <- segmentation fault when loop is reaching a space character
    // for (int i = 0; buffer[i] != '\0'; i++)     // <- also segmentation fault at the same spot
    // for (size_t i = 0; i < strlen(buffer); i++) // <- even this gives a segmentation fault which is totally confusing for me
    {
        printf("strlen in loop %d\n", i);
        if (buffer[i] == delim)
        {
            char* __cpy;
            memcpy(__cpy, &buffer[beg_point], curr_wlen); // <- will copy a string starting from the beginning of the word til its end

            // this may be commented for testing purposes
            __uint32_t __letters = __get_letters(__cpy, curr_wlen); // <- will return number of unique letters in word
            if (__letters > 2) // <- will remove all the words with less than 2 unique letters
            {
                strcat(_newbuff, __cpy);
                strcat(_newbuff, " ");
            }

            beg_point = i + 1; // <- will point on the first letter of the word
            curr_wlen = buffer[beg_point] == ' ' ? 0 : 1; // <- if the next symbol after space is another space, than word length should be 0
        }
        else curr_wlen++;
    }
    return _newbuff;
}
</code>```

In short, the code above just finds delimiter character in string and counts the number of unique letters of the word before this delimiter.

答:
My fault was in not initializing a __cpy variable.
Also, as @n.1.8e9-where's-my-sharem. stated, I shouldn't name vars with two underscores.

The final code:

```<code>// deletes words with <= 2 letters
char* _delete_odd(const char* buffer, char delim)
{
    size_t _act_buffer_len = strlen(buffer);
    char* _newbuff = malloc(_act_buffer_len); // <- new buffer without words with less than 2 unique words

    int beg_point = 0;
    int curr_wlen = 0;
    for (size_t i = 0; i < _act_buffer_len; i++)
    {
        if (buffer[i] == delim)
        {
            char* _cpy = malloc(curr_wlen);
            memcpy(_cpy, &buffer[beg_point], curr_wlen); // <- will copy a string starting from the beginning of the word til its end

            // this may be commented for testing purposes
            __uint32_t _letters = _get_letters(_cpy, curr_wlen); // <- will return number of unique letters in word
            if (_letters > 2) // <- will remove all the words with less than 2 unique letters
                strcat(_newbuff, _cpy);

            beg_point = i + 1; // <- will point on the first letter of the word
            curr_wlen = buffer[beg_point] == ' ' ? 0 : 1; // <- if the next symbol after space is another space, than word length should be 0

            free(_cpy);
        }
        else curr_wlen++;
    }
    return _newbuff;
}
</code>```

Thanks for helping me

Body:
Quite recently, at the university, we began to study strings in the C programming language, and as a homework, I was given the task of writing a program to remove extra words.

While writing a program, I faced an issue with iteration through a string that I could solve in a hacky way. However, I would like to deal with the problem with your help, since I cannot find the error myself.

The problem is that when I use the strlen(buffer) function as a for-loop condition, the code compiles easily and there are no errors at runtime, although when I use the __act_buffer_len variable, which is assigned a value of strlen(buffer) there will be a segmentation fault at runtime.

I tried many more ways to solve this problem, but the only one, which I already described, worked for me.

// deletes words with <= 2 letters
char* _delete_odd(const char* buffer, char delim)
{
    int __act_buffer_len = strlen(buffer);

    // for debugging purposes
    printf("__actbuff: %d\n", __act_buffer_len);
    printf("sizeof: %d\n", sizeof(buffer));
    printf("strlen: %d\n", strlen(buffer));

    char* _newbuff = malloc(__act_buffer_len + 1); // <- new buffer without words with less than 2 unique words
    char* _tempbuff; // <- used to store current word

    int beg_point = 0;
    int curr_wlen = 0;
    for (int i = 0; i < strlen(buffer); i++)       // no errors at runtime, app runs well
    // for (int i = 0; i < __act_buffer_len; i++)  // <- segmentation fault when loop is reaching a space character
    // for (int i = 0; buffer[i] != '\0'; i++)     // <- also segmentation fault at the same spot
    // for (size_t i = 0; i < strlen(buffer); i++) // <- even this gives a segmentation fault which is totally confusing for me
    {
        printf("strlen in loop %d\n", i);
        if (buffer[i] == delim)
        {
            char* __cpy;
            memcpy(__cpy, &buffer[beg_point], curr_wlen); // <- will copy a string starting from the beginning of the word til its end

            // this may be commented for testing purposes
            __uint32_t __letters = __get_letters(__cpy, curr_wlen); // <- will return number of unique letters in word
            if (__letters > 2) // <- will remove all the words with less than 2 unique letters
            {
                strcat(_newbuff, __cpy);
                strcat(_newbuff, " ");
            }

            beg_point = i + 1; // <- will point on the first letter of the word
            curr_wlen = buffer[beg_point] == ' ' ? 0 : 1; // <- if the next symbol after space is another space, than word length should be 0
        }
        else curr_wlen++;
    }
    return _newbuff;
}

In short, the code above just finds delimiter character in string and counts the number of unique letters of the word before this delimiter.

Body:
My fault was in not initializing a __cpy variable.
Also, as @n.1.8e9-where's-my-sharem. stated, I shouldn't name vars with two underscores.

The final code:

// deletes words with <= 2 letters
char* _delete_odd(const char* buffer, char delim)
{
    size_t _act_buffer_len = strlen(buffer);
    char* _newbuff = malloc(_act_buffer_len); // <- new buffer without words with less than 2 unique words

    int beg_point = 0;
    int curr_wlen = 0;
    for (size_t i = 0; i < _act_buffer_len; i++)
    {
        if (buffer[i] == delim)
        {
            char* _cpy = malloc(curr_wlen);
            memcpy(_cpy, &buffer[beg_point], curr_wlen); // <- will copy a string starting from the beginning of the word til its end

            // this may be commented for testing purposes
            __uint32_t _letters = _get_letters(_cpy, curr_wlen); // <- will return number of unique letters in word
            if (_letters > 2) // <- will remove all the words with less than 2 unique letters
                strcat(_newbuff, _cpy);

            beg_point = i + 1; // <- will point on the first letter of the word
            curr_wlen = buffer[beg_point] == ' ' ? 0 : 1; // <- if the next symbol after space is another space, than word length should be 0

            free(_cpy);
        }
        else curr_wlen++;
    }
    return _newbuff;
}

Thanks for helping me


问:
How to add an existing GitHub repository into PHP project in Eclipse?
I worked with class mates on a project to build a static website using CSS and HTML. Then we used visual studios and our work was synchronized with GitHub. Now we are asked to continue our work adding PHP files using Eclipse IDE. My question is how can I add the existing repo on eclipse and share it with my friends?</p>

答:
Git

Explanation: (Provided by google)

Git is software for tracking changes in any set of files, usually used for coordinating work among programmers collaboratively developing source code during software development. Its goals include speed, data integrity, and support for distributed, non-linear workflows.

How to use

Detailed instructions on how to install and setup are at

https://git-scm.com/downloads

Configure

You might need to restart for git to properly work.
Use git -v to prove git has been properly installed, and then run

```<code>git config user.name "Your Name"
git config user.email "name@email.com"
</code>```

Import a repository

TLDR from https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository

Run:

```<code>git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY
</code>```

You can also copy the URI

Install updates (Newer code version)

```<code>git pull origin main
</code>```

Git fetch

Updates the current local working branch (currently checked out
branch) Updates the remote tracking branches for all other branches.

Updates the remote tracking branches for all other branches.

from freeCodeCamp

TLDR;

```<code>git pull REMOTE-NAME BRANCH-NAME
</code>```

PHP Composer

https://getcomposer.org/

```<code>{
    "repositories": [
        {
            "url": "https://github.com/NAME/URI",
            "type": "git"
        }
    ]
}
</code>```

Body:
Git

Explanation: (Provided by google)

Git is software for tracking changes in any set of files, usually used for coordinating work among programmers collaboratively developing source code during software development. Its goals include speed, data integrity, and support for distributed, non-linear workflows.

How to use

Detailed instructions on how to install and setup are at

https://git-scm.com/downloads

Configure

You might need to restart for git to properly work.
Use git -v to prove git has been properly installed, and then run

git config user.name "Your Name"
git config user.email "name@email.com"

Import a repository

TLDR from https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository

Run:

git clone https://github.com/YOUR-USERNAME/YOUR-REPOSITORY

You can also copy the URI

Install updates (Newer code version)

git pull origin main

Git fetch

Updates the current local working branch (currently checked out
branch) Updates the remote tracking branches for all other branches.

Updates the remote tracking branches for all other branches.

from freeCodeCamp

TLDR;

git pull REMOTE-NAME BRANCH-NAME

PHP Composer

https://getcomposer.org/

{
    "repositories": [
        {
            "url": "https://github.com/NAME/URI",
            "type": "git"
        }
    ]
}


问:
How can I validate __slots__ in child classes?
From the python docs 3.3.2.4.1, it says  "__slots__ declared in parents are available in child classes. However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should only contain names of any additional slots)."

However, while I was testing this as below:

```<code>class A(object):
    __slots__ = ('a')

class B(A):
    __slots__ = ('b')

b = B()
B.z = 'z'
B.a = 'a'
print(B.z) #z
print(B.a) #a
print(B.__dict__) #{'__module__': '__main__', '__slots__': ('b',), 'b': <member 'b' of 'B' objects>, '__doc__': None, 'z': 'z', 'a': 'a'}
</code>```

Neither B.z nor B.__dict__ throws exception, the code manages to output.

I am confused why the __slots__ = ('b') in Class B doesn't validate. Theoretically, it should throw an exception at B.z because the keys in slots don't contain it.

Could you please help to explain this strange point? And if possible, could you please help to provide the right usage method of slots in child classes?

By the way, my python version is 3.9.7

Thank you so much.

答:
The __slots__ should be a tuple there, but you don't actually have a tuple, you have a string. Try doing __slots__ = ("a",).

Also, the slots apply to instances, not classes. You are assigning the attribute to the class object. Try the following. The instances work as expected.

a = A()
a.a = "a"
# a.b = "b"  # fails

b = B()
b.b = "b"
b.a = 'a'
# b.z = 'z'  # fails
```

Body:
From the python docs 3.3.2.4.1, it says  "__slots__ declared in parents are available in child classes. However, child subclasses will get a __dict__ and __weakref__ unless they also define __slots__ (which should only contain names of any additional slots)."

However, while I was testing this as below:

class A(object):
    __slots__ = ('a')

class B(A):
    __slots__ = ('b')

b = B()
B.z = 'z'
B.a = 'a'
print(B.z) #z
print(B.a) #a
print(B.__dict__) #{'__module__': '__main__', '__slots__': ('b',), 'b': <member 'b' of 'B' objects>, '__doc__': None, 'z': 'z', 'a': 'a'}

Neither B.z nor B.__dict__ throws exception, the code manages to output.

I am confused why the __slots__ = ('b') in Class B doesn't validate. Theoretically, it should throw an exception at B.z because the keys in slots don't contain it.

Could you please help to explain this strange point? And if possible, could you please help to provide the right usage method of slots in child classes?

By the way, my python version is 3.9.7

Thank you so much.


问:
Global Objects accessible throughout Android application
I have an application that uses a custom class. When the app is started I populate an instance of this class in the main activity with all the data it will hold.

Basic data is then shown in a ListView from which you can select a ListView item to see further information displayed in another Activity.

Currently, I am having to pass the data that is relevant to the new Activity to it by using:

```<code>intent.putExtra("NAME", value);
</code>```

I want to implement a ViewPager so the user can easily switch between ListView items. Therefore the currently use method isn't very good as I only have the data for one entry at a time and would need to get back to the original Activity to get all the data again.

Is there a way to have my class objects globally available ANYWHERE in my application? I feel my applications code is getting bloated as I am overcoming these issues in bad code methods.

I've just looked into using:

```<code>MyApp myapp = ((MyApp)context.getApplication());
</code>```

but this won't work unless I can pass the context around, which I'm not sure how to do??

In C# you'd create a static class that could handle this....

Thanks
Neil

答:
I think you are looking for a Singleton object. Create the custom class that holds all the data as a singleton object and access its data from anywhere in the code. Also, as this data may not be directly related to the UI, you should not be associating it with an Activity.

HTH,

Akshay

ContentLicense: CC BY-SA 3.0

Body:
I have an application that uses a custom class. When the app is started I populate an instance of this class in the main activity with all the data it will hold.

Basic data is then shown in a ListView from which you can select a ListView item to see further information displayed in another Activity.

Currently, I am having to pass the data that is relevant to the new Activity to it by using:

intent.putExtra("NAME", value);

I want to implement a ViewPager so the user can easily switch between ListView items. Therefore the currently use method isn't very good as I only have the data for one entry at a time and would need to get back to the original Activity to get all the data again.

Is there a way to have my class objects globally available ANYWHERE in my application? I feel my applications code is getting bloated as I am overcoming these issues in bad code methods.

I've just looked into using:

MyApp myapp = ((MyApp)context.getApplication());

but this won't work unless I can pass the context around, which I'm not sure how to do??

In C# you'd create a static class that could handle this....

Thanks
Neil


问:
list files pattern select date
Hello I have a set of daily meteo data, using the expression :

```<code>f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern= "PREC")
</code>```

I select only the files of Precipitation

I wonder how to select only files for example  of January, the one for example named 20170103 (yyyymmdd) ,  so the one named yyyy01dd....

the files are named in this way: "PREC_20010120.grd".

答:
Try pattern='PREC_\\d{4}01\\d[2].*'.

PREC_ literally

\\d{4} four digits

01 '"01" literally

\\d{2} two digits

.* any character repeatedly

Title: list files pattern select date

Body:
Hello I have a set of daily meteo data, using the expression :

f <- list.files(getwd(), include.dirs=TRUE, recursive=TRUE, pattern= "PREC")

I select only the files of Precipitation

I wonder how to select only files for example  of January, the one for example named 20170103 (yyyymmdd) ,  so the one named yyyy01dd....

the files are named in this way: "PREC_20010120.grd".


问:
Saleor-Storefront does not show up on localhost:3000. Looks like storefront port is not bound to port 3000
In MacOS, I am unable to access saleor storefront on localhost:3000. I do not see any errors when after following the installation steps but the storefront container is NOT binding to port 3000.
These are my current checked out branches for saleor-platform:
enter image description here

This is how the container setup looks like. Please note that the saleor-platform-storefront-1 does not have the port bound to 3000:
enter image description here

This is how the docker-compose.yml file looks like in saleor-platform folder:
enter image description here

This is how the console output looks like after successful compilation:
enter image description here

Now if I update the docker-compose.yml file with the following, the URL localhost:3000 is accessible but errors out:
enter image description here

I get the error below:
enter image description here

答:
Try this. Change docker-compose.yml file.</p>
```<code>  storefront:
    build:
      context: ./saleor-storefront
      dockerfile: ./Dockerfile.dev
    ports:
      - 3000:3000
    restart: unless-stopped
    #network_mode: "host"
    volumes:
      - ./saleor-storefront/:/app:cached
      - /app/node_modules/
    command: npm start -- --host 0.0.0.0
    #env_file: common.env
</code>```

Body:
Try this. Change docker-compose.yml file.

  storefront:
    build:
      context: ./saleor-storefront
      dockerfile: ./Dockerfile.dev
    ports:
      - 3000:3000
    restart: unless-stopped
    #network_mode: "host"
    volumes:
      - ./saleor-storefront/:/app:cached
      - /app/node_modules/
    command: npm start -- --host 0.0.0.0
    #env_file: common.env


问:
Swift async/await what it the replacement of DispatchQueue.main.async
How I can return to main thread when using async/await concurrency mechanism in new Swift 5.5? Should I just mark function, class with @MainActor.
Can I still use DispatchQueue.main.async? Will it be correct? As new mechanism doesn't use GCD and there is no mapping between async tasks and thread like before?

For example I am using SwiftUI List with refreshable

```<code>List { }
.refreshable {
    viewModel.fetchData()
}
</code>```

Is this ok

```<code>List { }
.refreshable {
    DispatchQueue.main.async {
      viewModel.fetchData()
    }
}
</code>```

Or I need to add @MainActor on ViewModel class?
I doesn't use async/await in project so using MainActor just for this single refreshable seems redundant, I also doesn't know how adding such attribute influance remaining methods and properties of ViewModel class, they now use Combine.

But on the other hand Xcode displays

runtime: SwiftUI: Publishing changes from background threads is not
allowed; make sure to publish values from the main thread (via
operators like receive(on:)) on model updates.

Moreover after adding @MainActor to ViewModel I am getting multiple warnings like this

Property 'title' isolated to global actor 'MainActor' can not satisfy
corresponding requirement from protocol
'OnlineBankingListViewModelProtocol'

答:
You asked:

Can I still use DispatchQueue.main.async?

If you are in an async method and want to dispatch something to the main queue, the most literal equivalent would be:

MainActor.run { ... }
```
<p>But it is more prudent to simply mark the method (or its class) with <code>@MainActor</code>. Not only will this ensure that it runs it on the main thread, but you get compile-time warnings if you attempt to call it from the wrong actor.</p>
<p>So, if your view model is marked with <code>@MainActor</code>, the manual running of the task on the <code>MainActor</code> becomes unnecessary. This is especially true when dealing with published properties of an observed object.</p>
<p>For example, consider:</p>
<pre class="lang-swift prettyprint-override"><code>@MainActor
class ViewModel: ObservableObject {
    @Published var values: [Int] = []

    func fetchData() async {
        let foo = await ...
        values = foo.values
    }
}
</code>```

And then

struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        List {
            ...
        }
        .refreshable {
            await viewModel.fetchData()
        }

    }
}
```
<p>(Note, I made <code>fetchData</code> an <code>async</code> method and <code>await</code> it within <code>refreshable</code> so that the spinner accurately reflects when the <code>async</code> process is running.)</p>
<p>See WWDC 2021 video Swift concurrency: Update a sample app. That is admittedly illustrating the transition of a UIKit app, but includes examples of <code>@MainActor</code> and <code>MainActor.run</code>.</p>
<hr />
<p>Note, while <code>@MainActor</code>, largely eliminates the need for <code>MainActor.run { … }</code>, there are still some scenarios where you might use this <code>run</code> pattern. Specifically, if you are on some other actor and want to run, for example, three separate <code>@MainActor</code> functions in succession on the main thread, you can wrap the series of them within a single <code>MainActor.run { … }</code> block, thereby running all three with a single dispatch to the main actor, rather than three separate calls.</p>
<hr />
<p>Above, I focused on the salient portions, but here is my full MCVE:</p>
<pre class="lang-swift prettyprint-override"><code>struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        List {
            ForEach(viewModel.values, id: \.self) { value in
                Text("\(value)")
            }
        }
        .refreshable {
            await viewModel.fetchData()
        }

    }
}

struct Foo: Decodable{
    let json: [Int]
}

@MainActor
class ViewModel: ObservableObject {
    @Published var values: [Int] = []

    func fetchData() async {
        do {
            let foo = try await object(Foo.self, for: request)
            values = foo.json
        } catch {
            print(error)
        }
    }

    func object<T: Decodable>(_ type: T.Type, for request: URLRequest) async throws -> T {
        let (data, response) = try await URLSession.shared.data(for: request)

        guard let response = response as? HTTPURLResponse else {
            throw URLError(.badServerResponse)
        }

        guard 200 ... 299 ~= response.statusCode else {
            throw ApiError.failure(response.statusCode, data)
        }

        return try JSONDecoder().decode(T.self, from: data)
    }

    var request: URLRequest = {
        let url = URL(string: "https://httpbin.org/anything")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "[1,2,3,4,5]".data(using: .utf8)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        return request
    }()
}

enum ApiError: Error {
    case failure(Int, Data)
}
</code>```

Body:
How I can return to main thread when using async/await concurrency mechanism in new Swift 5.5? Should I just mark function, class with @MainActor.
Can I still use DispatchQueue.main.async? Will it be correct? As new mechanism doesn't use GCD and there is no mapping between async tasks and thread like before?

For example I am using SwiftUI List with refreshable

List { }
.refreshable {
    viewModel.fetchData()
}

Is this ok

List { }
.refreshable {
    DispatchQueue.main.async {
      viewModel.fetchData()
    }
}

Or I need to add @MainActor on ViewModel class?
I doesn't use async/await in project so using MainActor just for this single refreshable seems redundant, I also doesn't know how adding such attribute influance remaining methods and properties of ViewModel class, they now use Combine.

But on the other hand Xcode displays

runtime: SwiftUI: Publishing changes from background threads is not
allowed; make sure to publish values from the main thread (via
operators like receive(on:)) on model updates.

Moreover after adding @MainActor to ViewModel I am getting multiple warnings like this

Property 'title' isolated to global actor 'MainActor' can not satisfy
corresponding requirement from protocol
'OnlineBankingListViewModelProtocol'

Body:
You asked:

Can I still use DispatchQueue.main.async?

If you are in an async method and want to dispatch something to the main queue, the most literal equivalent would be:

MainActor.run { ... }

But it is more prudent to simply mark the method (or its class) with @MainActor. Not only will this ensure that it runs it on the main thread, but you get compile-time warnings if you attempt to call it from the wrong actor.

So, if your view model is marked with @MainActor, the manual running of the task on the MainActor becomes unnecessary. This is especially true when dealing with published properties of an observed object.

For example, consider:

@MainActor
class ViewModel: ObservableObject {
    @Published var values: [Int] = []

    func fetchData() async {
        let foo = await ...
        values = foo.values
    }
}

And then

struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        List {
            ...
        }
        .refreshable {
            await viewModel.fetchData()
        }

    }
}

(Note, I made fetchData an async method and await it within refreshable so that the spinner accurately reflects when the async process is running.)

See WWDC 2021 video Swift concurrency: Update a sample app. That is admittedly illustrating the transition of a UIKit app, but includes examples of @MainActor and MainActor.run.

Note, while @MainActor, largely eliminates the need for MainActor.run { … }, there are still some scenarios where you might use this run pattern. Specifically, if you are on some other actor and want to run, for example, three separate @MainActor functions in succession on the main thread, you can wrap the series of them within a single MainActor.run { … } block, thereby running all three with a single dispatch to the main actor, rather than three separate calls.

Above, I focused on the salient portions, but here is my full MCVE:

struct ContentView: View {
    @ObservedObject var viewModel = ViewModel()

    var body: some View {
        List {
            ForEach(viewModel.values, id: \.self) { value in
                Text("\(value)")
            }
        }
        .refreshable {
            await viewModel.fetchData()
        }

    }
}

struct Foo: Decodable{
    let json: [Int]
}

@MainActor
class ViewModel: ObservableObject {
    @Published var values: [Int] = []

    func fetchData() async {
        do {
            let foo = try await object(Foo.self, for: request)
            values = foo.json
        } catch {
            print(error)
        }
    }

    func object<T: Decodable>(_ type: T.Type, for request: URLRequest) async throws -> T {
        let (data, response) = try await URLSession.shared.data(for: request)

        guard let response = response as? HTTPURLResponse else {
            throw URLError(.badServerResponse)
        }

        guard 200 ... 299 ~= response.statusCode else {
            throw ApiError.failure(response.statusCode, data)
        }

        return try JSONDecoder().decode(T.self, from: data)
    }

    var request: URLRequest = {
        let url = URL(string: "https://httpbin.org/anything")!
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        request.httpBody = "[1,2,3,4,5]".data(using: .utf8)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        return request
    }()
}

enum ApiError: Error {
    case failure(Int, Data)
}


问:
Creating Oracle Database Table with Numeric Permission Level
I am creating an Oracle database with a table called Roles.

I want the Permission_Level row to store values 1,2,3,4, or 5.  How to I limit the input to only those numbers?  Here is my attempt:

```<code>    CREATE TABLE ROLES
(
  ROLE_ID NUMBER(20) NOT NULL
, ROLE_NAME VARCHAR2(20) NOT NULL
, PERMISSION_LEVEL NUMBER(1,0) NOT NULL
, CONSTRAINT ROLES_PK PRIMARY KEY
  (
    ROLE_ID
  )
  ENABLE
);
</code>```

答:
Check constraint is one option:

```<code>SQL> create table roles
  2    (role_id         number(20)   constraint roles_pk primary key,
  3     role_name       varchar2(20) not null,
  4     permision_level int          constraint ch_lvl check
  5                                  (permision_level in (1, 2, 3, 4, 5))
  6  );

Table created.

</code>```

Testing:

```<code>SQL> insert into roles (role_id, role_name, permision_level) values (1, 'Role 1', 3);

1 row created.
</code>```

Level 10 doesn't fit:

```<code>SQL> insert into roles (role_id, role_name, permision_level) values (2, 'Role 2', 10);
insert into roles (role_id, role_name, permision_level) values (2, 'Role 2', 10)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_LVL) violated

SQL>
</code>```

Body:
I am creating an Oracle database with a table called Roles.

I want the Permission_Level row to store values 1,2,3,4, or 5.  How to I limit the input to only those numbers?  Here is my attempt:

    CREATE TABLE ROLES
(
  ROLE_ID NUMBER(20) NOT NULL
, ROLE_NAME VARCHAR2(20) NOT NULL
, PERMISSION_LEVEL NUMBER(1,0) NOT NULL
, CONSTRAINT ROLES_PK PRIMARY KEY
  (
    ROLE_ID
  )
  ENABLE
);

Body:
Check constraint is one option:

SQL> create table roles
  2    (role_id         number(20)   constraint roles_pk primary key,
  3     role_name       varchar2(20) not null,
  4     permision_level int          constraint ch_lvl check
  5                                  (permision_level in (1, 2, 3, 4, 5))
  6  );

Table created.

Testing:

SQL> insert into roles (role_id, role_name, permision_level) values (1, 'Role 1', 3);

1 row created.

Level 10 doesn't fit:

SQL> insert into roles (role_id, role_name, permision_level) values (2, 'Role 2', 10);
insert into roles (role_id, role_name, permision_level) values (2, 'Role 2', 10)
*
ERROR at line 1:
ORA-02290: check constraint (SCOTT.CH_LVL) violated

SQL>


问:
Rolling up monthly data to quarterly
I have monthly data for each company and it's associated MRR (Monthly Revenue) as of the month end date. I am trying to build a quarterly report which shows the progression of the company within the quarter. Following is the reproducible sample dataset with quarter end dates:

```<code>WITH

quarter_end_date AS
(
SELECT '2021-04-30' q_end_date
UNION ALL
SELECT '2021-07-31' q_end_date
UNION ALL
SELECT '2021-10-31' q_end_date
UNION ALL
SELECT '2022-01-31' q_end_date
),

data AS
(
SELECT '2020-05-31' as_of_date, 'A' company_id, '100' mrr,'new' category
UNION ALL
SELECT '2020-06-30' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-07-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-08-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-09-30' as_of_date, 'A' company_id, '0' mrr,'churn' category
UNION ALL
SELECT '2020-10-31' as_of_date, 'A' company_id, '100' mrr,'new' category
UNION ALL
SELECT '2020-11-30' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-12-31' as_of_date, 'A' company_id, '0' mrr,'churn' category
UNION ALL
SELECT '2021-01-31' as_of_date, 'A' company_id, '0' mrr,'new' category
UNION ALL
SELECT '2021-02-28' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-03-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-04-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-05-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-06-30' as_of_date, 'A' company_id, '70' mrr,'contraction' category
UNION ALL
SELECT '2021-07-31' as_of_date, 'A' company_id, '100' mrr,'expansion' category
UNION ALL
SELECT '2021-08-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-09-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-10-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-11-30' as_of_date, 'A' company_id, '0' mrr, 'churn' category
),
</code>```

The MRR dataset (above CTE data) doesn’t store company info once it churns (stops paying subscription or cancels the service). The approach I'm using is capable of capturing any churn which happens in the start of the quarter or the end of quarter but it doesn’t if churn happens within the quarter. My SQL:

```<code>step_1
AS(
SELECT *,
LAG(mrr,1) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m1_mrr,
LAG(mrr,2) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m2_mrr,
LAG(mrr,3) OVER (PARTITION BY company_id ORDER BY as_of_date) quarter_start_mrr,
FROM data
)

SELECT *
FROM step_1
CROSS JOIN quarter_end_date q
WHERE q.q_end_date = step_1.as_of_date
ORDER BY q.q_end_date DESC
</code>```

Output:

q_end_date
Company_id
mrr
category
prev_m1_mrr
prev_m2_mrr
quarter_start_mrr

2021-10-31
A
90
contraction
120
100
100

2021-07-31
A
100
expansion
70
90
120

2021-04-30
A
120
expansion
100
100
null

Expected Output:

q_end_date
Company_id
mrr
category
prev_m1_mrr
prev_m2_mrr
quarter_start_mrr

2022-01-31
A
null
churn
0
0
90

2021-10-31
A
90
contraction
120
100
100

2021-07-31
A
100
expansion
70
90
120

2021-04-30
A
120
expansion
100
100
null

答:
I am assuming that data of all companies are in the same table, otherwise the query will be straightforward. I added a few values with a second company ‘B’. The query works, but it will give ‘Churn’ as the category whenever data is not present in the entire quarter for that company.That also includes the period when the company did not even start using the service. That can be filtered out later with simple queries based on start date if needed.

Second thing is I added another CTE for the list of companies.

```<code>WITH
quarter_end_date AS
(
SELECT '2021-04-30' q_end_date
UNION ALL
SELECT '2021-07-31' q_end_date
UNION ALL
SELECT '2021-10-31' q_end_date
UNION ALL
SELECT '2022-01-31' q_end_date
),
companies as
(SELECT 'A'as company_id
union all
SELECT 'B'as company_id
),
data AS
(
SELECT '2021-02-28' as_of_date, 'A' company_id, '100' mrr,'new' category
UNION ALL
SELECT '2021-03-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-04-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-05-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-06-30' as_of_date, 'A' company_id, '70' mrr,'contraction' category
UNION ALL
SELECT '2021-07-31' as_of_date, 'A' company_id, '100' mrr,'expansion' category
UNION ALL
SELECT '2021-08-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-09-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-10-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-11-30' as_of_date, 'A' company_id, '0' mrr, 'churn' category
union all
SELECT '2021-10-31' as_of_date, 'B' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-11-30' as_of_date, 'B' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-12-31' as_of_date, 'B' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2022-01-31' as_of_date, 'B' company_id, '100' mrr, 'expansion' category
),
step_1
AS(
SELECT *,
LAG(mrr,1) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m1_mrr,
LAG(mrr,2) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m2_mrr,
LAG(mrr,3) OVER (PARTITION BY company_id ORDER BY as_of_date) quarter_start_mrr,
FROM data
)
SELECT q_end_date,c.company_id,
mrr,IFNULL(category,'churn') as category,IFNULL(prev_m1_mrr,'0') as prev_m1_mrr, IFNULL(prev_m2_mrr,'0') as prev_m2_mrr,IFNULL(quarter_start_mrr,lead(mrr) over (partition by c.company_id order by q_end_date desc)) as quarter_start_mrr
FROM  companies c cross join quarter_end_date q left join step_1 s  on q.q_end_date = s.as_of_date and c.company_id=s.company_id
ORDER BY company_id,q.q_end_date DESC

</code>```

Output:

Title: Rolling up monthly data to quarterly

Body:
I have monthly data for each company and it's associated MRR (Monthly Revenue) as of the month end date. I am trying to build a quarterly report which shows the progression of the company within the quarter. Following is the reproducible sample dataset with quarter end dates:

WITH

quarter_end_date AS
(
SELECT '2021-04-30' q_end_date
UNION ALL
SELECT '2021-07-31' q_end_date
UNION ALL
SELECT '2021-10-31' q_end_date
UNION ALL
SELECT '2022-01-31' q_end_date
),

data AS
(
SELECT '2020-05-31' as_of_date, 'A' company_id, '100' mrr,'new' category
UNION ALL
SELECT '2020-06-30' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-07-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-08-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-09-30' as_of_date, 'A' company_id, '0' mrr,'churn' category
UNION ALL
SELECT '2020-10-31' as_of_date, 'A' company_id, '100' mrr,'new' category
UNION ALL
SELECT '2020-11-30' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2020-12-31' as_of_date, 'A' company_id, '0' mrr,'churn' category
UNION ALL
SELECT '2021-01-31' as_of_date, 'A' company_id, '0' mrr,'new' category
UNION ALL
SELECT '2021-02-28' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-03-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-04-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-05-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-06-30' as_of_date, 'A' company_id, '70' mrr,'contraction' category
UNION ALL
SELECT '2021-07-31' as_of_date, 'A' company_id, '100' mrr,'expansion' category
UNION ALL
SELECT '2021-08-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-09-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-10-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-11-30' as_of_date, 'A' company_id, '0' mrr, 'churn' category
),

The MRR dataset (above CTE data) doesn’t store company info once it churns (stops paying subscription or cancels the service). The approach I'm using is capable of capturing any churn which happens in the start of the quarter or the end of quarter but it doesn’t if churn happens within the quarter. My SQL:

step_1
AS(
SELECT *,
LAG(mrr,1) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m1_mrr,
LAG(mrr,2) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m2_mrr,
LAG(mrr,3) OVER (PARTITION BY company_id ORDER BY as_of_date) quarter_start_mrr,
FROM data
)

SELECT *
FROM step_1
CROSS JOIN quarter_end_date q
WHERE q.q_end_date = step_1.as_of_date
ORDER BY q.q_end_date DESC

Output:

q_end_date
Company_id
mrr
category
prev_m1_mrr
prev_m2_mrr
quarter_start_mrr

2021-10-31
A
90
contraction
120
100
100

2021-07-31
A
100
expansion
70
90
120

2021-04-30
A
120
expansion
100
100
null

Expected Output:

q_end_date
Company_id
mrr
category
prev_m1_mrr
prev_m2_mrr
quarter_start_mrr

2022-01-31
A
null
churn
0
0
90

2021-10-31
A
90
contraction
120
100
100

2021-07-31
A
100
expansion
70
90
120

2021-04-30
A
120
expansion
100
100
null

Body:
I am assuming that data of all companies are in the same table, otherwise the query will be straightforward. I added a few values with a second company ‘B’. The query works, but it will give ‘Churn’ as the category whenever data is not present in the entire quarter for that company.That also includes the period when the company did not even start using the service. That can be filtered out later with simple queries based on start date if needed.

Second thing is I added another CTE for the list of companies.

WITH
quarter_end_date AS
(
SELECT '2021-04-30' q_end_date
UNION ALL
SELECT '2021-07-31' q_end_date
UNION ALL
SELECT '2021-10-31' q_end_date
UNION ALL
SELECT '2022-01-31' q_end_date
),
companies as
(SELECT 'A'as company_id
union all
SELECT 'B'as company_id
),
data AS
(
SELECT '2021-02-28' as_of_date, 'A' company_id, '100' mrr,'new' category
UNION ALL
SELECT '2021-03-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-04-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-05-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-06-30' as_of_date, 'A' company_id, '70' mrr,'contraction' category
UNION ALL
SELECT '2021-07-31' as_of_date, 'A' company_id, '100' mrr,'expansion' category
UNION ALL
SELECT '2021-08-31' as_of_date, 'A' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-09-30' as_of_date, 'A' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-10-31' as_of_date, 'A' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2021-11-30' as_of_date, 'A' company_id, '0' mrr, 'churn' category
union all
SELECT '2021-10-31' as_of_date, 'B' company_id, '100' mrr,'no change' category
UNION ALL
SELECT '2021-11-30' as_of_date, 'B' company_id, '120' mrr,'expansion' category
UNION ALL
SELECT '2021-12-31' as_of_date, 'B' company_id, '90' mrr,'contraction' category
UNION ALL
SELECT '2022-01-31' as_of_date, 'B' company_id, '100' mrr, 'expansion' category
),
step_1
AS(
SELECT *,
LAG(mrr,1) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m1_mrr,
LAG(mrr,2) OVER (PARTITION BY company_id ORDER BY as_of_date) prev_m2_mrr,
LAG(mrr,3) OVER (PARTITION BY company_id ORDER BY as_of_date) quarter_start_mrr,
FROM data
)
SELECT q_end_date,c.company_id,
mrr,IFNULL(category,'churn') as category,IFNULL(prev_m1_mrr,'0') as prev_m1_mrr, IFNULL(prev_m2_mrr,'0') as prev_m2_mrr,IFNULL(quarter_start_mrr,lead(mrr) over (partition by c.company_id order by q_end_date desc)) as quarter_start_mrr
FROM  companies c cross join quarter_end_date q left join step_1 s  on q.q_end_date = s.as_of_date and c.company_id=s.company_id
ORDER BY company_id,q.q_end_date DESC

Output:


问:
How do I identify the lowest required visibility of methods?
As part of a large refactoring project, I need to identify methods that are no longer used, or where the visibility can be reduced.

Consider the following code:

```<code>program Project1;

type
  TMyClass = class(TObject)
  private
    function Method1 : integer;
  public
    function Method2 : integer;
    function Method3 : integer;
    function Method4 : integer;
  end;

var
  vMyObject : TMyClass;

function TMyClass.Method1: integer;
begin
  Result := Method2;
end;

function TMyClass.Method2: integer;
begin
  Result := 2;
end;

function TMyClass.Method3: integer;
begin
  Result := 3;
end;

function TMyClass.Method4: integer;
begin
  Result := 4;
end;

begin
  vMyObject := TMyClass.Create;
  try
    writeln(vMyObject.Method3);
  finally
    vMyObject.Free;
  end;
end.
</code>```

The Delphi compiler gives the warning "[DCC Hint] Project1.dpr(6): H2219 Private symbol 'Method1' declared but never used", which is very helpful. But there are other issues with this code that I would like to be warned about:

Method4 is never used, but I don't get a warning since it's public.

Method2 is declared public, but only used privately.

Are there any tools I can use to identify issues like these?

答: Pascal Analyzer can do it and much more cases.</p>

Body:
As part of a large refactoring project, I need to identify methods that are no longer used, or where the visibility can be reduced.

Consider the following code:

program Project1;

type
  TMyClass = class(TObject)
  private
    function Method1 : integer;
  public
    function Method2 : integer;
    function Method3 : integer;
    function Method4 : integer;
  end;

var
  vMyObject : TMyClass;

function TMyClass.Method1: integer;
begin
  Result := Method2;
end;

function TMyClass.Method2: integer;
begin
  Result := 2;
end;

function TMyClass.Method3: integer;
begin
  Result := 3;
end;

function TMyClass.Method4: integer;
begin
  Result := 4;
end;

begin
  vMyObject := TMyClass.Create;
  try
    writeln(vMyObject.Method3);
  finally
    vMyObject.Free;
  end;
end.

The Delphi compiler gives the warning "[DCC Hint] Project1.dpr(6): H2219 Private symbol 'Method1' declared but never used", which is very helpful. But there are other issues with this code that I would like to be warned about:

Method4 is never used, but I don't get a warning since it's public.

Method2 is declared public, but only used privately.

Are there any tools I can use to identify issues like these?


问:
Adding and Removing Xmlnode using Powershell
I am trying to add and remove elements from multiple xml files. i ran into two issue. it removed empty elements automatically and second it did not remove what i wanted to

I have my xml like this

```<code><Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
   </App>
</Entity>
</code>```

what i want is

```<code><Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>

         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>
</code>```

i added newItemtoAdd element and removed itemToRemove on output xml above.

```<code>with the current script i have used what i get is this

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>
</code>```

emptyItem node is removed which i do not want to happen, newItemtoAdd is added which is good, and itemToRemove node is not removed which is not what i want

here is my script

```<code>Get-ChildItem D:\Projects\*.xml |
    % {
        [xml]$xml      = [xml](Get-Content $_.fullname)
        $newItemtoAdd = $xml.CreateElement('newItemtoAdd')
        $newItemtoAdd.PsBase.InnerText = '1900-01-01'
        $null     = $xml.Entity.App.AppendChild($newItemtoAdd)

    $xml.SelectNodes("//Entity/App/person") | ? {
    $_.name -eq "itemToRemove"   } | % {$_.ParentNode.RemoveChildNode($_) }
       $xml.Save($_.FullName)
    }
</code>```

答:
PowerShell has two nice syntax features which might be used in this case:

1. Xml dot notation

Where you might directly reference a node in your xml file.

For example, to select the itemToRemove for the first (0 based) Person:

```<code>$Xml.Entity.App.person[0].itemToRemove
true
</code>```

Unfortunately this PowerShell feature is a little overdone as you can see from the example where instead of returning an XmlElement, it returns a string with the innerText (#Text) if it concerns a leaf note, see: #16878 Decorate dot selected Xml strings (leaves) with XmlElement methods.

2. Member-Access Enumeration

You can use member enumeration to get property values from all members of a collection. When you use the member access operator (.) with a member name on a collection object, such as an array, if the collection object does not have a member of that name, the items of the collection are enumerated and PowerShell looks for that member on each item. This applies to both property and method members.

Taking the xml file in the question as an example:

```<code>$Xml.Entity.App.person.itemToRemove
true
false
false
</code>```

Note that in this example, there is no index behind the Person property, meaning that all persons are enumerated and returned.

To overcome a possible returned string (described in 1. xml dot notation) you might enumerate the SelectNodes() on each person node instead and use that to removed the concerned nodes from their parent:

```<code>$Xml.Entity.App.person.SelectNodes('itemToRemove').ForEach{ $Null = $_.ParentNode.RemoveChild($_) }
[System.Xml.Linq.XDocument]::Parse($Xml.OuterXml).ToString()
</code>```

```<code><Entity>
  <App>
    <item1>1</item1>
    <emptyItem />
    <person>
      <emptyItem />
      <otheritem>1</otheritem>
    </person>
    <person>
      <emptyItem />
      <otheritem>3</otheritem>
    </person>
    <person>
      <emptyItem />
      <otheritem>3</otheritem>
    </person>
  </App>
</Entity>
</code>```

Body:
I am trying to add and remove elements from multiple xml files. i ran into two issue. it removed empty elements automatically and second it did not remove what i wanted to

I have my xml like this

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
   </App>
</Entity>

what i want is

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>

         <emptyItem/>
         <otheritem>1</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <person>

         <emptyItem/>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>

i added newItemtoAdd element and removed itemToRemove on output xml above.

with the current script i have used what i get is this

<Entity>
   <App>
      <item1>1</item1>
      <emptyItem/>
      <person>
         <itemToRemove>true</itemToRemove>
         <otheritem>1</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <person>
         <itemToRemove>false</itemToRemove>
         <otheritem>3</otheritem>
      </person>
      <newItemtoAdd>2001-01-01</newItemtoAdd>
   </App>
</Entity>

emptyItem node is removed which i do not want to happen, newItemtoAdd is added which is good, and itemToRemove node is not removed which is not what i want

here is my script

Get-ChildItem D:\Projects\*.xml |
    % {
        [xml]$xml      = [xml](Get-Content $_.fullname)
        $newItemtoAdd = $xml.CreateElement('newItemtoAdd')
        $newItemtoAdd.PsBase.InnerText = '1900-01-01'
        $null     = $xml.Entity.App.AppendChild($newItemtoAdd)

    $xml.SelectNodes("//Entity/App/person") | ? {
    $_.name -eq "itemToRemove"   } | % {$_.ParentNode.RemoveChildNode($_) }
       $xml.Save($_.FullName)
    }

Body:
PowerShell has two nice syntax features which might be used in this case:

1. Xml dot notation

Where you might directly reference a node in your xml file.

For example, to select the itemToRemove for the first (0 based) Person:

$Xml.Entity.App.person[0].itemToRemove
true

Unfortunately this PowerShell feature is a little overdone as you can see from the example where instead of returning an XmlElement, it returns a string with the innerText (#Text) if it concerns a leaf note, see: #16878 Decorate dot selected Xml strings (leaves) with XmlElement methods.

2. Member-Access Enumeration

You can use member enumeration to get property values from all members of a collection. When you use the member access operator (.) with a member name on a collection object, such as an array, if the collection object does not have a member of that name, the items of the collection are enumerated and PowerShell looks for that member on each item. This applies to both property and method members.

Taking the xml file in the question as an example:

$Xml.Entity.App.person.itemToRemove
true
false
false

Note that in this example, there is no index behind the Person property, meaning that all persons are enumerated and returned.

To overcome a possible returned string (described in 1. xml dot notation) you might enumerate the SelectNodes() on each person node instead and use that to removed the concerned nodes from their parent:

$Xml.Entity.App.person.SelectNodes('itemToRemove').ForEach{ $Null = $_.ParentNode.RemoveChild($_) }
[System.Xml.Linq.XDocument]::Parse($Xml.OuterXml).ToString()

<Entity>
  <App>
    <item1>1</item1>
    <emptyItem />
    <person>
      <emptyItem />
      <otheritem>1</otheritem>
    </person>
    <person>
      <emptyItem />
      <otheritem>3</otheritem>
    </person>
    <person>
      <emptyItem />
      <otheritem>3</otheritem>
    </person>
  </App>
</Entity>


问:
Why does my GUI disappear as soon as I initialize an ImageIcon?
So i wanna program a Tic Tac Toe game in java.

Now uppon clicking a button, i wanna set the Image of the Button to either "cross" or "circle", but as soon as a type following code, the buttons disappear until i hover over them, then they return.

```<code>ImageIcon cross = new ImageIcon("Cross.png");
</code>```

What it looks like without the code above
What it looks like with the code above

Project Structure here

答:
I did in fact use null layot for the window

That's the problem. For a 3 x 3 grid, I'd use a GridLayout. See How to Use GridLayout for further details.

Body:
So i wanna program a Tic Tac Toe game in java.

Now uppon clicking a button, i wanna set the Image of the Button to either "cross" or "circle", but as soon as a type following code, the buttons disappear until i hover over them, then they return.

ImageIcon cross = new ImageIcon("Cross.png");

What it looks like without the code above
What it looks like with the code above

Project Structure here


问:
set_index does not effectively set the index
I have imported a timeseries dataset in pandas from a csv file.

```<code>data = pd.read_csv('djia_data.csv')
data.set_index('date')
</code>```

When I print the header withdata.head(), I correctly get

If instead I visualize the dataframe (double click on the variable in VS code with Jupiter), I get this

I do not understand while I do not get date as the new index anymore.
If instead I type

```<code>data = pd.read_csv('djia_data.csv')
data.set_index('date',inplace=True)
data.head()
</code>```

I get this

When I visualize again the dataframe as a variable instead I obtain

In this case, date column is empty. I've searched on the net but I wasn't able to solve it. Can you please explain what I am doing wrong?

答:
Try to set index earlier:</p>
```<code>data = pd.read_csv('djia_data.csv', index_col='date', parse_dates=['date'])
</code>```

Body:
I have imported a timeseries dataset in pandas from a csv file.

data = pd.read_csv('djia_data.csv')
data.set_index('date')

When I print the header withdata.head(), I correctly get

If instead I visualize the dataframe (double click on the variable in VS code with Jupiter), I get this

I do not understand while I do not get date as the new index anymore.
If instead I type

data = pd.read_csv('djia_data.csv')
data.set_index('date',inplace=True)
data.head()

I get this

When I visualize again the dataframe as a variable instead I obtain

In this case, date column is empty. I've searched on the net but I wasn't able to solve it. Can you please explain what I am doing wrong?

Body:
Try to set index earlier:

data = pd.read_csv('djia_data.csv', index_col='date', parse_dates=['date'])


问:
How to hide connection string of postgresql in DbContext ... EF 6(not core)
I have a web application. if I use Npgsql.EntityFrameworkCore I can hide connection string in appsettings.json file but I want to use EntityFramework6.I followed the instructions at npgsql entityframework documentation. so my first problem is that .net 6 doesnt generate default web.config or app.config file,it only has appsettings.json. In documentation there is info like this;

so first I added connection string to appsettings.json it didnt worked it gave the same error  I tried to create my own app.config file and copy-paste that configuration provided at documentation made the changes (connection name,npgsql version,public key etc).
here is my dbcontext class

when I try to enable migrations it gives me this error I

I think it doesnt recognize the app.config file that I created so my question is how can I hide connection string I dont want to use it on dbcontext class

答:
Of course you can still use your custom app.config file. However, I think you should move all the configs into appsettings.json to make it conventional since you moved to .Net 6.

To get the correct connection string section you can access it using public IConfiguration Configuration { get; } in Startup.cs/Program.cs

Notice that the the connection string name in your config is BlogDbContext, you can change it to dbcontext or input the correct name in services.AddDbContext in Startup.cs/Program.cs


问:
Fluentd + azure data explorer cluster
I'm working on fluentd setup in kubernetes. In kubernetes I have a number of applications which are writing some logs into stdout. I can filter, parse, and send logs to azure blob storage. But I want the logs from blob storage to be ingested into azure data explorer cluster. In data explorer cluster I have a database and table which has some schema defined, already. The question is how do I modify event from fluentd in such a way that it's going to meet the table schema? Is it possible at all? Maybe there are some alternative ways of creating such setup?</p>

答: Consider using the ability to listen on blobs landing in storage using the event grid mechanism. Check out https://learn.microsoft.com/en-us/azure/data-explorer/ingest-data-event-grid-overview</p>

Title: Fluentd + azure data explorer cluster


问:
Some of my console.log aren't getting to the console. Is it because of PWA Builder?
I am trying to figure out how a WebRTC demo runs.  ( https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Build_a_phone_with_peerjs )  Some of my console.log's print to the developer's console, and some don't.  They are both in the global space, right next to each other.  I can make all the console.log's print by holding the mouse down on the refresh swirl, and picking Empty Cache and Hard Reload.  But then the next regular refresh only prints some of the console.log's.

I see that the program has something in it I am not familiar with.  Pwabuilder.

```<code>    <script type="module">
        import 'https://cdn.jsdelivr.net/npm/@pwabuilder/pwaupdate';

        const el = document.createElement('pwa-update');
        document.body.appendChild(el);
    </script>
</code>```

When I comment this out, the program doesn't run at all.  Does somebody know what is going on?

答:
I figured this out.  I needed to go to my Application tab (Chrome) and unregister the service worker.

It was so frustrating!  I removed all those bits of code from the application, and restarted everything, but the strange logging behavior still persisted.  Hadn't encounter extra-persistent service worker before.

Body:
I am trying to figure out how a WebRTC demo runs.  ( https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Build_a_phone_with_peerjs )  Some of my console.log's print to the developer's console, and some don't.  They are both in the global space, right next to each other.  I can make all the console.log's print by holding the mouse down on the refresh swirl, and picking Empty Cache and Hard Reload.  But then the next regular refresh only prints some of the console.log's.

I see that the program has something in it I am not familiar with.  Pwabuilder.

When I comment this out, the program doesn't run at all.  Does somebody know what is going on?


问:
Mongo group query does not used indexes or slow down queries
I have used mongodb 1.8.1. In which I have collection which contains more than 1.8 million records. In this collections all records are simple object means not nested objects or array

Like as follows

```<code>{ name : "xyz" , "id" : 123 ,"a" : "na" , "c" : "in" , "cmp" : "pq" , "ttl" : "sd"}
</code>```

All records are like this.

On this collections at time more 5 queries fire in which 2 is simple queries one contains exists in it and another one is simple query which uses index properly.

Another 2 are group queries which in which condition fields are in indexes and one contains exists.

Another one 1 distinct query with proper condition which is also index.

And order of query fire is first qroup queries then 1 simple query then distinct query and last simple query.

So data loads slowly.

If such 2 -3 calls make then it loads very lowly sometimes gives error read time out.

The collections have more than 1 index.

答:
$exists queries do not use indexes (fixed from 1.9.1 onwards)

group commands use the JS context of mongodb which is exclusively locked while it's being used. This will affect performance of concurrent group queries. A new aggregation framework is under development that should help with this (2.1 onwards). Monitor https://jira.mongodb.org/browse/SERVER-447 for progress. In my experience it's usually more performant to do "group" like aggregation app-side.

Body:
I have used mongodb 1.8.1. In which I have collection which contains more than 1.8 million records. In this collections all records are simple object means not nested objects or array

Like as follows

{ name : "xyz" , "id" : 123 ,"a" : "na" , "c" : "in" , "cmp" : "pq" , "ttl" : "sd"}

All records are like this.

On this collections at time more 5 queries fire in which 2 is simple queries one contains exists in it and another one is simple query which uses index properly.

Another 2 are group queries which in which condition fields are in indexes and one contains exists.

Another one 1 distinct query with proper condition which is also index.

And order of query fire is first qroup queries then 1 simple query then distinct query and last simple query.

So data loads slowly.

If such 2 -3 calls make then it loads very lowly sometimes gives error read time out.

The collections have more than 1 index.


问:
Function declaration vs function definition JS
What is difference between function declaration and function definition in JavaScript? I read chapter 5.3.2 from this book

When nested, however, function declarations may
  only appear at the top level of the function they are nested within. That is, function
  definitions may not appear within if statements, while loops, or any other statements.

but don't understand difference between declaration and definition... Please, explain it ( note: I understand difference between function expression and function declaration!)

答:
```<code>function isEven(num){
     if(num%2 === 0){
return true;
}else{
return false;
}
}
</code>```

In the above code function isEven(num) is called as function declaration, its like in that line of code you declare that isEven you are using is a function.

And the remaining part of the code inside the curly braces is called function definition. Where you provide defintion for the function isEven.

In js, we don't seperate the declaration and defintion, because we have hoisting. Hoisting makes your function declaration & definition to be hoisted to the top, so you can use the function even before defining it.

In other programming languages like 'C', you don't have hoisting. So the declarations of functions are made before usage and defintions can be placed where ever we want, inside the file.

And thus the reason for two names and what they mean.

Body:
function isEven(num){
     if(num%2 === 0){
return true;
}else{
return false;
}
}

In the above code function isEven(num) is called as function declaration, its like in that line of code you declare that isEven you are using is a function.

And the remaining part of the code inside the curly braces is called function definition. Where you provide defintion for the function isEven.

In js, we don't seperate the declaration and defintion, because we have hoisting. Hoisting makes your function declaration & definition to be hoisted to the top, so you can use the function even before defining it.

In other programming languages like 'C', you don't have hoisting. So the declarations of functions are made before usage and defintions can be placed where ever we want, inside the file.

And thus the reason for two names and what they mean.


问:
set access-control-allow-origin response header only for static files in IIS
I'm using IIS to serve static files and also to send API requests to a python backend server.
for API requests the backend correctly sets CORS-related headers but for static files, I get errors. additionally, I can't set these in Response Headers in IIS because it conflicts with those set with the backend app.
So is there any way in IIS to check if some certain header is empty or requested response is a file or even check URI for a pattern like /static/ and then modify the response header?
I've reached to URLRewrite so far but I doubt it could modify the header.

答: after a little bit of digging it turned out you can set Response Header specific to each directory. so I set the CORS-related headers in my ./static/ sub-directories and it works fine.


问:
Add Maven repository to build.gradle
I added a custom maven repository to build.gradle in Android Studio but the dependency is not being found

Maven repository and dependency

```<code><repository>
    <id>achartengine</id>
    <name>Public AChartEngine repository</name>
    <url>https://repository-achartengine.forge.cloudbees.com/snapshot/</url>
</repository>

<dependency>
    <groupId>org.achartengine</groupId>
    <artifactId>achartengine</artifactId>
    <version>1.2.0</version>
</dependency>
</code>```

build.gradle

```<code>buildscript {
    repositories {
        mavenCentral()
        maven {
            url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}
apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile group: 'org.achartengine', name: 'achartengine', version: '1.2.0'
}

android {
    compileSdkVersion 19
    buildToolsVersion "19"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}
</code>```

Error message in Android Studio:

```<code>A problem occurred configuring root project 'My-MobileAndroid'.
> Failed to notify project evaluation listener.
> Could not resolve all dependencies for configuration ':_DebugCompile'.
  > Could not find org.achartengine:achartengine:1.2.0.
    Required by:
        :My-MobileAndroid:unspecified
</code>```

What am I missing in build.gradle?

答:
This is for Kotlin DSL (build.gradle.kts):

repositories {
    mavenCentral()
    maven("https://jitpack.io")
    // OR another notation:
    // maven {
    //     url = uri("https://jitpack.io")
    // }
}
```
<p>You can also centralize your repository declaration for all your subprojects in <em>settings.gradle[.kts]</em> file in newer versions of Gradle (Gradle 7.4):</p>
<pre class="lang-kotlin prettyprint-override"><code>dependencyResolutionManagement {
    repositories {
        mavenCentral()
        maven("https://jitpack.io")
    }
}
</code>```

See the full guide here in Gradle documentation website.

Title: Add Maven repository to build.gradle

Body:
I added a custom maven repository to build.gradle in Android Studio but the dependency is not being found

Maven repository and dependency

<repository>
    <id>achartengine</id>
    <name>Public AChartEngine repository</name>
    <url>https://repository-achartengine.forge.cloudbees.com/snapshot/</url>
</repository>

<dependency>
    <groupId>org.achartengine</groupId>
    <artifactId>achartengine</artifactId>
    <version>1.2.0</version>
</dependency>

build.gradle

buildscript {
    repositories {
        mavenCentral()
        maven {
            url "https://repository-achartengine.forge.cloudbees.com/snapshot/"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.6.+'
    }
}
apply plugin: 'android'

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')
    compile group: 'org.achartengine', name: 'achartengine', version: '1.2.0'
}

android {
    compileSdkVersion 19
    buildToolsVersion "19"

    sourceSets {
        main {
            manifest.srcFile 'AndroidManifest.xml'
            java.srcDirs = ['src']
            resources.srcDirs = ['src']
            aidl.srcDirs = ['src']
            renderscript.srcDirs = ['src']
            res.srcDirs = ['res']
            assets.srcDirs = ['assets']
        }

        // Move the tests to tests/java, tests/res, etc...
        instrumentTest.setRoot('tests')

        // Move the build types to build-types/<type>
        // For instance, build-types/debug/java, build-types/debug/AndroidManifest.xml, ...
        // This moves them out of them default location under src/<type>/... which would
        // conflict with src/ being used by the main source set.
        // Adding new build types or product flavors should be accompanied
        // by a similar customization.
        debug.setRoot('build-types/debug')
        release.setRoot('build-types/release')
    }
}

Error message in Android Studio:

A problem occurred configuring root project 'My-MobileAndroid'.
> Failed to notify project evaluation listener.
> Could not resolve all dependencies for configuration ':_DebugCompile'.
  > Could not find org.achartengine:achartengine:1.2.0.
    Required by:
        :My-MobileAndroid:unspecified

What am I missing in build.gradle?

Body:
This is for Kotlin DSL (build.gradle.kts):

repositories {
    mavenCentral()
    maven("https://jitpack.io")
    // OR another notation:
    // maven {
    //     url = uri("https://jitpack.io")
    // }
}

You can also centralize your repository declaration for all your subprojects in settings.gradle[.kts] file in newer versions of Gradle (Gradle 7.4):

dependencyResolutionManagement {
    repositories {
        mavenCentral()
        maven("https://jitpack.io")
    }
}

See the full guide here in Gradle documentation website.


问:
Fixed List is not updating with for loop - Flutter
I've a fixed list reservedGuest. After checking the condition in for loop I want to update the seats if the membership date has expired. The list is not updating. The code is as follows. PS. The List is filled through API on init().</p>
```<code>class MyClubController extends GetxController {

    List goldLane = List.filled(3, null, growable: false);

    void _alterLanesOnContractEnds() {
    for (var i in goldLane) {
      print("\n\n I: $i");
      if (i == null ||
          DateTime.parse(i['contractEnds']).isBefore(
            DateTime.now(),
          )) {
        i = null;
        print('Can be removed');
      } else {
        print('Cannot be removed');
      }
    }
    update();
  }

}
</code>```

答:
You can just create a new List where unqualified guests are nullified. For example,

```<code>void _alterLanesOnContractEnds() {
  goldLane = goldLane.map(
    (guest) => guest == null || DateTime.parse(guest['contractEnds']).isBefore(DateTime.now()) ? null: guest
  ).toList(growable: false);
  update();
}
</code>```

You should not and cannot modify a list while iterating with its iterator.

Elaborated by Jamesdlin,

Modifying the elements of a List while iterating is fine. Modifying
the length of the List while iterating is not, but that won't be a
problem for a non-growable List.

The bottom line is you should not mutate the size of the list while iterating.

Body:
I've a fixed list reservedGuest. After checking the condition in for loop I want to update the seats if the membership date has expired. The list is not updating. The code is as follows. PS. The List is filled through API on init().

class MyClubController extends GetxController {

    List goldLane = List.filled(3, null, growable: false);

    void _alterLanesOnContractEnds() {
    for (var i in goldLane) {
      print("\n\n I: $i");
      if (i == null ||
          DateTime.parse(i['contractEnds']).isBefore(
            DateTime.now(),
          )) {
        i = null;
        print('Can be removed');
      } else {
        print('Cannot be removed');
      }
    }
    update();
  }

}

Body:
You can just create a new List where unqualified guests are nullified. For example,

void _alterLanesOnContractEnds() {
  goldLane = goldLane.map(
    (guest) => guest == null || DateTime.parse(guest['contractEnds']).isBefore(DateTime.now()) ? null: guest
  ).toList(growable: false);
  update();
}

You should not and cannot modify a list while iterating with its iterator.

Elaborated by Jamesdlin,

Modifying the elements of a List while iterating is fine. Modifying
the length of the List while iterating is not, but that won't be a
problem for a non-growable List.

The bottom line is you should not mutate the size of the list while iterating.


问:
java.lang.ClassNotFoundException in a simple HelloWorld
I get the message after I try to start "java -cp . "HelloWorld"

Fehler: Hauptklasse .\HelloWorld konnte nicht gefunden oder geladen werden
Ursache: java.lang.ClassNotFoundException: /\HelloWorld

It's only a simple programm to check out, if the IDE is runnng correctly.

答: I used the Powershell to run the command. Inside of the cmd-Window it runs correctly. Thank you for the extensive help</p>


问:
Query large volume of data for web page display
I am new to Oracle (know some basic SQL), but the task is somehow assigned to me.

My task is to optimize a query. It joins some large tables (query is time consuming) and returns the result to a webpage (paging can be used).

My question is what direction should I look into? It would be better if links can be provided.

Here is some details:

Optimized methods taken

```<code>index on dayNum, timeNum, entityID columns
</code>```

Number of rows:

time_seq:  100,000

indicator_set: 50,000,000

tity amount: 1,000

Query:

```<code>select *
  from time_seq seq,
       (
        select entityID,
               dayNum,
               timeNum,
               sum(ind1) sum_ind1,
               avg(ind2) avg_ind2,
               max(ind3) max_ind3
          from indicator_set
         group by entityID, dayNum, timeNum
         -- the dayNum timeNum are grouped to the time sequence standard
         -- in time_seq table
        ) sum
where seq.entityID=sum.entityID
  and seq.dayNum=sum.dayNum
  and seq.timeNum=sum.timeNum
</code>```

Table time_seq

```<code>entityID, dayNum, timeNum
--------------------------------
object1, 20110818, 220000
object1, 20110818, 223000
object1, 20100818, 230000
object1, 20110819, 220000
object1, 20110819, 223000
object1, 20100819, 230000
object2, 20110818, 220000
object2, 20110818, 223000
object2, 20100818, 230000
object2, 20110819, 220000
object2, 20110819, 223000
object2, 20100819, 230000
</code>```

Table indicator_set

```<code>entityID, dayNum, timeNUm, ind1, ind2, ind3
--------------------------------------------
object1, 20110818, 220000, 23,34,23
object1, 20110818, 220500, 23,54,543
object1, 20110818, 220530, 23,54,543
object1, 20110818, 220610, 23,54,543
object1, 20110818, 222900, 23,54,543
...
</code>```

PS: sorry I didn't provide exact format/detail of the table and query. Just too complicated.

cheers~

答:
Would linking the indicator_set and time_seq tables within the subquery limit the amount of rows to be grouped in the large indicator_set table?

```<code>SELECT *
  FROM time_seq seq,
       (  SELECT ind.entityid,
                 ind.dayNum,
                 ind.timeNum,
                 SUM( ind.ind1 ),
                 AVG( ind.ind2 ),
                 MAX( ind.ind3 )
            FROM indicator_set ind,
                 time_seq ts
           WHERE ind.entity_id = ts.entityid
             AND ind.daynum    = ts.daynum
             AND ind.timenum   = ts.timenum
        GROUP BY ind.entityid,
                 ind.daynum,
                 ind.timenum) SUM
 WHERE seq.entityid = SUM.entityid
   AND seq.daynum   = SUM.daynum
   AND seq.timenum  = SUM.timenum
</code>```

The outher query would still ensure that only the records from the time_seq table would be returned from the query though.

Is this helpful?

EDIT: By the way, i'd use a better table alias than SUM as it is an oracle function.

Body:
I am new to Oracle (know some basic SQL), but the task is somehow assigned to me.

My task is to optimize a query. It joins some large tables (query is time consuming) and returns the result to a webpage (paging can be used).

My question is what direction should I look into? It would be better if links can be provided.

Here is some details:

Optimized methods taken

index on dayNum, timeNum, entityID columns

Number of rows:

time_seq:  100,000

indicator_set: 50,000,000

tity amount: 1,000

Query:

select *
  from time_seq seq,
       (
        select entityID,
               dayNum,
               timeNum,
               sum(ind1) sum_ind1,
               avg(ind2) avg_ind2,
               max(ind3) max_ind3
          from indicator_set
         group by entityID, dayNum, timeNum
         -- the dayNum timeNum are grouped to the time sequence standard
         -- in time_seq table
        ) sum
where seq.entityID=sum.entityID
  and seq.dayNum=sum.dayNum
  and seq.timeNum=sum.timeNum

Table time_seq

entityID, dayNum, timeNum
--------------------------------
object1, 20110818, 220000
object1, 20110818, 223000
object1, 20100818, 230000
object1, 20110819, 220000
object1, 20110819, 223000
object1, 20100819, 230000
object2, 20110818, 220000
object2, 20110818, 223000
object2, 20100818, 230000
object2, 20110819, 220000
object2, 20110819, 223000
object2, 20100819, 230000

Table indicator_set

entityID, dayNum, timeNUm, ind1, ind2, ind3
--------------------------------------------
object1, 20110818, 220000, 23,34,23
object1, 20110818, 220500, 23,54,543
object1, 20110818, 220530, 23,54,543
object1, 20110818, 220610, 23,54,543
object1, 20110818, 222900, 23,54,543
...

PS: sorry I didn't provide exact format/detail of the table and query. Just too complicated.

cheers~

Body:
Would linking the indicator_set and time_seq tables within the subquery limit the amount of rows to be grouped in the large indicator_set table?

SELECT *
  FROM time_seq seq,
       (  SELECT ind.entityid,
                 ind.dayNum,
                 ind.timeNum,
                 SUM( ind.ind1 ),
                 AVG( ind.ind2 ),
                 MAX( ind.ind3 )
            FROM indicator_set ind,
                 time_seq ts
           WHERE ind.entity_id = ts.entityid
             AND ind.daynum    = ts.daynum
             AND ind.timenum   = ts.timenum
        GROUP BY ind.entityid,
                 ind.daynum,
                 ind.timenum) SUM
 WHERE seq.entityid = SUM.entityid
   AND seq.daynum   = SUM.daynum
   AND seq.timenum  = SUM.timenum

The outher query would still ensure that only the records from the time_seq table would be returned from the query though.

Is this helpful?

EDIT: By the way, i'd use a better table alias than SUM as it is an oracle function.


问:
Private Variable access
Why am I able to directly access p's private number attribute within Striker's implementation of the hasSameNumber method? Seems as though using the getter should be the only (if not, best-practice) way to access it. What am I missing?

```<code>public class Football {

    public static abstract class FootballPlayer {
        private final int number;

        FootballPlayer(int num) {
            number = num;
        }

        int getNumber() {
            return number;
        }

        abstract boolean hasSameNumber(FootballPlayer p );
    }

    public static class Striker extends FootballPlayer {
        Striker(int num) {
            super(num);
        }
        boolean hasSameNumber(FootballPlayer p ) {
            return this.getNumber() == p.number;
        }
    }

}
</code>```

Edit:

The accepted answer shows why this is permissible - thanks! What would be the preferred/best-practice way to access number though - by getter or direct?

答:
Java - the access to number occurs within the body of Football, thus is allowed.

JLS 6.6.1

I admit I was surprised by this specific example.

Title: Private Variable access

Body:
Why am I able to directly access p's private number attribute within Striker's implementation of the hasSameNumber method? Seems as though using the getter should be the only (if not, best-practice) way to access it. What am I missing?

public class Football {

    public static abstract class FootballPlayer {
        private final int number;

        FootballPlayer(int num) {
            number = num;
        }

        int getNumber() {
            return number;
        }

        abstract boolean hasSameNumber(FootballPlayer p );
    }

    public static class Striker extends FootballPlayer {
        Striker(int num) {
            super(num);
        }
        boolean hasSameNumber(FootballPlayer p ) {
            return this.getNumber() == p.number;
        }
    }

}

Edit:

The accepted answer shows why this is permissible - thanks! What would be the preferred/best-practice way to access number though - by getter or direct?