问:
How to combine two tables into one using my sql statement
i'm new in Database, i want to get a result from both sql table.
Here is the example

Table 1

Item Code
Price

A001
5 Dollar

A002
6 Dollar

Table 2 - Item Code Information

Item Code
Item Description

A001
Fish

A002
Chicken

And my question i want to get result with table 1 combine with 2 with item code, item description and price

Item Code
Item Description
Price

A001
Fish
5 Dollar

A002
Chicken
6 Dollar

Does anyone know how to do the SQL statement? Please help Thank you

答:
You are looking for a Join. In this case you can use a star to Retrieve ALL items of both tables:

```<code>SELECT * FROM table1 t1 JOIN table2 t2 ON t1.item code = t2.item code.
</code>```

The "item_code" is primary Key in t1 and a foreign Key in t2.

On this YouTube video you can learn about table joins:
https://youtu.be/0OQJDd3QqQM

Body:
You are looking for a Join. In this case you can use a star to Retrieve ALL items of both tables:

SELECT * FROM table1 t1 JOIN table2 t2 ON t1.item code = t2.item code.

The "item_code" is primary Key in t1 and a foreign Key in t2.

On this YouTube video you can learn about table joins:
https://youtu.be/0OQJDd3QqQM


来源: stackexchange

问:
Print per 2 char in java arraylist (non static arraylist)
Im new with java. im getting struggle with printin something, this is my arraylist

```<code>arraylist = ['a','u','o','e']
</code>```

If my arraylist isnt a static length arraylist. How could I print that list into this

"Your Value: au, oe"

Im kinda confused

Thanks for advance

答:
You can concatenate String with character "+" like this.

```<code>System.out.println("Your Value: " + arraylist.get(0) + arraylist.get(1) + ", " + arraylist.get(2) + arraylist.get(3));
</code>```

or you can use a smarter way, using static method inside String class called "format" like this:

```<code>System.out.println(String.format("Your Value: %s%s, %s%s", arraylist.get(0), arraylist.get(1), arraylist.get(2), arraylist.get(3)));
</code>```

You can learn more about String.format() reading this post:

https://www.javatpoint.com/java-string-format

ContentLicense: CC BY-SA 4.0

Body:
Im new with java. im getting struggle with printin something, this is my arraylist

arraylist = ['a','u','o','e']

If my arraylist isnt a static length arraylist. How could I print that list into this

"Your Value: au, oe"

Im kinda confused

Thanks for advance

Body:
You can concatenate String with character "+" like this.

System.out.println("Your Value: " + arraylist.get(0) + arraylist.get(1) + ", " + arraylist.get(2) + arraylist.get(3));

or you can use a smarter way, using static method inside String class called "format" like this:

System.out.println(String.format("Your Value: %s%s, %s%s", arraylist.get(0), arraylist.get(1), arraylist.get(2), arraylist.get(3)));

You can learn more about String.format() reading this post:

https://www.javatpoint.com/java-string-format


问:
User comments on course page on frontend in Tutor LMS
In wordpress, on the frontend, in Tutor LMS on a course page, how can we have a section(at the bottom) where users can comment; like in Learpress?

Please help!

答:
By default, the Tutor LMS doesn’t have a comment form for the course details page. The comments is removed based on majority customer’s feedback because this is not a blog post page but a product page. However, you still can add a comment form very easily just by editing two files and following the steps:

Open this file /tutor/classes/Post_types.php,

-In this file, you will find this code array( 'title', 'editor', 'thumbnail', 'excerpt', 'author'),

-You need to replace the code with this code array( 'title', 'editor', 'thumbnail', 'excerpt', 'author', 'comments'),

Now you need to edit this file
/tutor/templates/single/course/instructors.php

-In this file before this code <?php } do_action( 'tutor_course/single/enrolled/after/instructors' );

-You need to add this code <?php comments_template( '', true ); ?>

Now you need to edit your course and enable comments for the course. to enable comments check the provided screenshot https://prnt.sc/26q0usm

Thank you


问:
SQL schema design question around relating 2 different types of ID's to one piece of information
I'm working on redesigning some parts of our schema, and I'm running into a problem where I just don't know a good clean way of doing something.  I have an event table such as:

```<code>Events
--------
event_id
</code>```

for each event, there could be n groups or users associated with it.  So there's a table relating Events to Users to reflect that one to many relationship such as:

```<code>EventUsers
----------
event_id
user_id
</code>```

The problem is that we also have a concept of groups.  We want to potentially tie n groups to an event in addition to users.  So, that user_id column isn't sufficient, because we need to store potentially either a user_id or a group_id.

I've thought of a variety of ways to handle this, but they all seem like a big hack.  For example, I could make that a participant_id and put in a participant_type column such as:

```<code>EventUsers
----------
event_id
participant_id
participant_type
</code>```

and if I wanted to get the events that user_id 10 was a part of, it could be something like:

```<code>select event_id
from EventUsers
where participant_id = 10
and participant_type = 1
</code>```

(assuming that somewhere participant_type 1 was defined to be a User).  But I don't like that from a philosophical point of view because when I look at the data, I don't know what the number in participant_id means unless I also look at the value in particpant_type.

I could also change EventUsers to be something like:

```<code>EventParticipants
-----------------
event_id
user_id
group_id
</code>```

and allow the values of user_id and group_id to be NULL if that record is dealing with the other type of information.

Of course, I could just break EventUsers and we'll call it EventGroups into 2 different tables but I'd like to keep who is tied to an event stored in one single place if there's a good logical way to do it.

So, am I overlooking a good way to accomplish this?

答:
Tables Events, Users and Groups represent the basic entities.  They are related by EventUsers, GroupUsers and EventGroups.  You need to union results together, e.g. the attendees for an event are:

```<code>select user_id
  from EventUsers
  where event_id = @event_id
union
select GU.user_id
  from EventGroups as EG inner join
    GroupUsers as GU on GU.group_id = EG.group_id
  where EG.event_id = @event_id
</code>```

Don't be shy about creating additional tables to represent different types of things.  It is often easier to combine them, e.g. with union, than to try to sort out a mess of vague data.

ContentLicense: CC BY-SA 3.0

Body:
I'm working on redesigning some parts of our schema, and I'm running into a problem where I just don't know a good clean way of doing something.  I have an event table such as:

Events
--------
event_id

for each event, there could be n groups or users associated with it.  So there's a table relating Events to Users to reflect that one to many relationship such as:

EventUsers
----------
event_id
user_id

The problem is that we also have a concept of groups.  We want to potentially tie n groups to an event in addition to users.  So, that user_id column isn't sufficient, because we need to store potentially either a user_id or a group_id.

I've thought of a variety of ways to handle this, but they all seem like a big hack.  For example, I could make that a participant_id and put in a participant_type column such as:

EventUsers
----------
event_id
participant_id
participant_type

and if I wanted to get the events that user_id 10 was a part of, it could be something like:

select event_id
from EventUsers
where participant_id = 10
and participant_type = 1

(assuming that somewhere participant_type 1 was defined to be a User).  But I don't like that from a philosophical point of view because when I look at the data, I don't know what the number in participant_id means unless I also look at the value in particpant_type.

I could also change EventUsers to be something like:

EventParticipants
-----------------
event_id
user_id
group_id

and allow the values of user_id and group_id to be NULL if that record is dealing with the other type of information.

Of course, I could just break EventUsers and we'll call it EventGroups into 2 different tables but I'd like to keep who is tied to an event stored in one single place if there's a good logical way to do it.

So, am I overlooking a good way to accomplish this?

Body:
Tables Events, Users and Groups represent the basic entities.  They are related by EventUsers, GroupUsers and EventGroups.  You need to union results together, e.g. the attendees for an event are:

select user_id
  from EventUsers
  where event_id = @event_id
union
select GU.user_id
  from EventGroups as EG inner join
    GroupUsers as GU on GU.group_id = EG.group_id
  where EG.event_id = @event_id

Don't be shy about creating additional tables to represent different types of things.  It is often easier to combine them, e.g. with union, than to try to sort out a mess of vague data.


问:
Storing an JWT for a Spring API client service
I have a Service that is calling a remote API to fetch data.
It is authorized with a service account, and I store the JWT-Token for my requests inside the service as a class variable.

When one of the methods gets a 401 response, the service tries to authenticate and stores the new JWT inside the old variable.
I could make the Service a Bean with a request scope, but I would like to avoid that.

Can somebody help me to make the JWT class variable thread-safe?
e.g. what happens if 2 requests try to update the JWT token at the same time?

答:
If the JWT token is the same for all requests then you could use AtomicReference. Before making a remote call use the getToken()
and apply the value to the request headers.

For example:

```<code>/**
 * Initialize it with an expired {@link OAuthToken} so we don't ever need to make a '{@code null}' check.
 */
private final AtomicReference<OAuthToken> atomicRefToken = new AtomicReference<>(OAuthToken.expiredToken());

public OAuthToken getToken() {
    if (atomicRefToken.get().isExpired()) {
        atomicRefToken.set(this.fetchToken());
    }
    return atomicRefToken.get();
}

private OAuthToken fetchToken() {
    // fetch token via some call
    return new OAuthToken(....)
}
</code>```

Example of the OAuthToken class.

```<code>public class OAuthToken implements Serializable {

    public static final String TOKEN_TYPE_BEARER = "bearer";

    public static final Long SPARE_SECONDS = 100L;

    private final String tokenType;
    private final String accessToken;
    private final Long expiresIn;
    private final LocalDateTime expiresAt;

    public OAuthToken(@JsonProperty("token_type") @NonNull String tokenType,
                      @JsonProperty("access_token") @NonNull String accessToken,
                      @JsonProperty("expires_in") @NonNull Long expiresIn) {
        this.tokenType = tokenType;
        this.accessToken = accessToken;
        this.expiresIn = expiresIn;
        this.expiresAt = LocalDateTime.now().plus(expiresIn - SPARE_SECONDS, ChronoUnit.SECONDS);
    }

    /**
     * Create a new instance where the token is expired.
     *
     * @return new instance
     */
    public static OAuthToken expiredToken() {
        return new OAuthToken(TOKEN_TYPE_BEARER, "expired", 0L);
    }

    public boolean isExpired() {
        return LocalDateTime.now().isAfter(expiresAt);
    }

    public String value() {
        return this.accessToken;
    }

}
</code>```

Body:
If the JWT token is the same for all requests then you could use AtomicReference. Before making a remote call use the getToken()
and apply the value to the request headers.

For example:

/**
 * Initialize it with an expired {@link OAuthToken} so we don't ever need to make a '{@code null}' check.
 */
private final AtomicReference<OAuthToken> atomicRefToken = new AtomicReference<>(OAuthToken.expiredToken());

public OAuthToken getToken() {
    if (atomicRefToken.get().isExpired()) {
        atomicRefToken.set(this.fetchToken());
    }
    return atomicRefToken.get();
}

private OAuthToken fetchToken() {
    // fetch token via some call
    return new OAuthToken(....)
}

Example of the OAuthToken class.

public class OAuthToken implements Serializable {

    public static final String TOKEN_TYPE_BEARER = "bearer";

    public static final Long SPARE_SECONDS = 100L;

    private final String tokenType;
    private final String accessToken;
    private final Long expiresIn;
    private final LocalDateTime expiresAt;

    public OAuthToken(@JsonProperty("token_type") @NonNull String tokenType,
                      @JsonProperty("access_token") @NonNull String accessToken,
                      @JsonProperty("expires_in") @NonNull Long expiresIn) {
        this.tokenType = tokenType;
        this.accessToken = accessToken;
        this.expiresIn = expiresIn;
        this.expiresAt = LocalDateTime.now().plus(expiresIn - SPARE_SECONDS, ChronoUnit.SECONDS);
    }

    /**
     * Create a new instance where the token is expired.
     *
     * @return new instance
     */
    public static OAuthToken expiredToken() {
        return new OAuthToken(TOKEN_TYPE_BEARER, "expired", 0L);
    }

    public boolean isExpired() {
        return LocalDateTime.now().isAfter(expiresAt);
    }

    public String value() {
        return this.accessToken;
    }

}


问:
Dash suppress_callback_exceptions not working
Here is how I implement it in my code. I have tried each way individually and using all of them as uncommented lines of code. No matter the combination of methods I use, I still have to manually turn suppress errors once my dashboard loads.

```<code>app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = 'TEST'

app.config['suppress_callback_exceptions'] = True
app.config.suppress_callback_exceptions = True
</code>```

I have also tried (without any luck):

```<code>app = dash.Dash(__name__, external_stylesheets=external_stylesheets,
                suppress_callback_exceptions = True)
</code>```

and

```<code>import sys
class HaltCallback(Exception):
    pass

@app.server.errorhandler(HaltCallback)
def handle_error(error):
    print(error, file=sys.stderr)
    return ('', 204)
</code>```

Are there any other possible ways I can try to suppress the callback exceptions? I'm making a dashboard for my boss, so I'd really like automate the error suppression upon loading it.

答:
Just to complete the answers given:

app = dash.Dash( ... , suppress_callback_exceptions=True) works well for normal callbacks. If you have a long_callback you also need to provide a validation_layout that contains all of the components referenced by callbacks in the app and set the prevent_initial_call=True argument of app.long_callback.

For more information and examples please refer to the official documentation of long callbacks:

https://dash.plotly.com/long-callbacks#limitations

Body:
Here is how I implement it in my code. I have tried each way individually and using all of them as uncommented lines of code. No matter the combination of methods I use, I still have to manually turn suppress errors once my dashboard loads.

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.title = 'TEST'

app.config['suppress_callback_exceptions'] = True
app.config.suppress_callback_exceptions = True

I have also tried (without any luck):

app = dash.Dash(__name__, external_stylesheets=external_stylesheets,
                suppress_callback_exceptions = True)

and

import sys
class HaltCallback(Exception):
    pass

@app.server.errorhandler(HaltCallback)
def handle_error(error):
    print(error, file=sys.stderr)
    return ('', 204)

Are there any other possible ways I can try to suppress the callback exceptions? I'm making a dashboard for my boss, so I'd really like automate the error suppression upon loading it.


问:
Can I create GCP API keys using Terraform?
I'd like to create Google Cloud API keys using Terraform.

Is this possible?

答:
It seems they’ve declined the ask for Terraform support here:
https://github.com/hashicorp/terraform-provider-google/issues/6413

However there's now this issue for tracking the desire for this again:
https://github.com/hashicorp/terraform-provider-google/issues/8959 ❔


问:
How to get the file's path from file input?
please tell me how to get a full file path from an <input type="file">

i have tried fileinput.value but it shows fakepath.

i have also tried mozFullPath.

答: Due to major security reasons, most browsers don't allow getting it so JavaScript when ran in the browser doesn't have access to the user file system. having said that,  the Firefox is exceptional and provides the mozFullPath property but it will only return an empty string.


问:
Does SQL server 2019 allows to commit the data changes as similar to GIT
I am doing an analysis to check in MSSQL 2019 to confirm whether it allows to take data backup of recent changes as similar to Git.

I need to go back to older data version if there is an need.
Any way to do this ?

答:
Primarily you would use backup and restore database or restore with no-recovery and apply transaction log backups to get to a point-in-time restore.

There is also system versioning which has in-built support for logging changes to data in a table to capture historical changes.

Other options would be to roll your own bespoke solution using something like change tracking or change-data-capture, or even triggers for specific tables.


问:
Maven building only changed files
Lets say i have module structure like below

```<code>     Modules
       ->utils
       ->domain
       ->client
       ->services
       ->deploy (this is at the module level)
</code>```

Now to lauch the client i need to make a build of all the modules, i.e utils, domain, client, services, because i am loading the jars of all the above modules to fianlly lanch the client

And all the jars gets assembled in the module deploy.

My question is if i change anything in services for example, then is there a way when running a build from deploy maven could recognise it has to build only services and hence build it and deploy it in deploy folder?

答:
mvn clean install to run full build

mvn install to compile only changed and prepare war/jars other binaries

mvn compile to compile only changed files...

So mvn compile is the fastest. but if run/debug your project with war/jars it might not show those changes.

Title: Maven building only changed files

Body:
Lets say i have module structure like below

     Modules
       ->utils
       ->domain
       ->client
       ->services
       ->deploy (this is at the module level)

Now to lauch the client i need to make a build of all the modules, i.e utils, domain, client, services, because i am loading the jars of all the above modules to fianlly lanch the client

And all the jars gets assembled in the module deploy.

My question is if i change anything in services for example, then is there a way when running a build from deploy maven could recognise it has to build only services and hence build it and deploy it in deploy folder?


问:
Django Custom Field - Boolean -> CHAR YN
Due to a legacy system I'm trying to get Django boolean fields to save in the dB as a simple 'Y' or 'N' char field (VARCHAR not supported in said legacy system).

Using a django custom field I have it working but struggling to get Django admin to work with the field.

```<code>class BooleanYN(models.BooleanField):
    """ We need to save boolean variables as CHAR Y/N

    """

    description = _("Boolean field stored as Y or N in the dB")

    def from_db_value(self, value, expression, connection):
        if value in ('Y', 'y'):
            return True
        if value in ('N', 'n'):
            return True
        raise ValidationError(_(f"Value in dB is not Y or N - {value}"))

    def get_prep_value(self, value):
        if value is True:
            return 'Y'
        if value is False:
            return 'N'
        return value

    def db_type(self, connection):
        return char(1)
</code>```

In Django admin, single record view + list view, the checkbox widget is always flagged as true even though 'N' is correctly saved in the dB and "to_python" is correctly being passed 'False' or 'True' as the value when its called by the modelform code depending on whether 'Y' or 'N' in the dB.

Any help appreciated!

答:
I spent so much time concentrating on the Django source code, I missed a stupid bug in my own code which I hid from myself with invalid logging!

Changed :

```<code>    def from_db_value(self, value, expression, connection):
        if value in ('Y', 'y'):
            return True
        if value in ('N', 'n'):
            return True
        raise ValidationError(_(f"Value in dB is not Y or N - {value}"))
</code>```

to :

```<code>    def from_db_value(self, value, expression, connection):
        if value in ('Y', 'y'):
            return True
        if value in ('N', 'n'):
            return False
        raise ValidationError(_(f"Value in dB is not Y or N - {value}"))
</code>```

Then no issues anymore.  Thanks for your reply nigel222

Body:
Due to a legacy system I'm trying to get Django boolean fields to save in the dB as a simple 'Y' or 'N' char field (VARCHAR not supported in said legacy system).

Using a django custom field I have it working but struggling to get Django admin to work with the field.

class BooleanYN(models.BooleanField):
    """ We need to save boolean variables as CHAR Y/N

    """

    description = _("Boolean field stored as Y or N in the dB")

    def from_db_value(self, value, expression, connection):
        if value in ('Y', 'y'):
            return True
        if value in ('N', 'n'):
            return True
        raise ValidationError(_(f"Value in dB is not Y or N - {value}"))

    def get_prep_value(self, value):
        if value is True:
            return 'Y'
        if value is False:
            return 'N'
        return value

    def db_type(self, connection):
        return char(1)

In Django admin, single record view + list view, the checkbox widget is always flagged as true even though 'N' is correctly saved in the dB and "to_python" is correctly being passed 'False' or 'True' as the value when its called by the modelform code depending on whether 'Y' or 'N' in the dB.

Any help appreciated!

Body:
I spent so much time concentrating on the Django source code, I missed a stupid bug in my own code which I hid from myself with invalid logging!

Changed :

    def from_db_value(self, value, expression, connection):
        if value in ('Y', 'y'):
            return True
        if value in ('N', 'n'):
            return True
        raise ValidationError(_(f"Value in dB is not Y or N - {value}"))

to :

    def from_db_value(self, value, expression, connection):
        if value in ('Y', 'y'):
            return True
        if value in ('N', 'n'):
            return False
        raise ValidationError(_(f"Value in dB is not Y or N - {value}"))

Then no issues anymore.  Thanks for your reply nigel222


问:
Why is this code printing a line after reading one line of content
```<code>file = 'pi'
with open(file) as object:
    for line in object:
        print(line)
</code>```

The file content includes the first 30 digits of pi, and I don't understand why it is printing a line after reading a particular line. As in, how can print(line) actually print a line?

The contents of the file are henceforth:

```<code>3.1415926535
8979323846
2643383279
</code>```

And this is the output:

```<code>3.1415926535

8979323846

2643383279
</code>```

答:
Because by default, print add a newline after a print, you can change this by adding the end parameter to your print statement :

print(line, end='')

Body:
file = 'pi'
with open(file) as object:
    for line in object:
        print(line)

The file content includes the first 30 digits of pi, and I don't understand why it is printing a line after reading a particular line. As in, how can print(line) actually print a line?

The contents of the file are henceforth:

3.1415926535
8979323846
2643383279

And this is the output:

3.1415926535

8979323846

2643383279


问:
Creating an application registration to access Azure REST API under enterprise agreement
Sorry if this is off-topic but I haven't been able to find any information on it anywhere else. I'm trying to create an application registration that will allow a batch process to access the Azure REST API on my behalf.

Normally, this is pretty simple: just create the user, give it API permissions to what you need, add a secret and then insert the tenant ID, application ID and secret into a request against the /token endpoint, as described here.

I have done that and gotten the access token but, when I try to get all the billing accounts associated with the enterprise agreement, by calling https://management.azure.com/providers/Microsoft.Billing/billingAccounts?api-version=2020-05-01 I get no information back. Also, when I try to access a particular billing account back, by calling https://management.azure.com/providers/Microsoft.Billing/billingAccounts/{account_id}?api-version=2020-05-01, I get the following error and a 403 response code:

```<code>{
    "error": {
        "code": "Forbidden",
        "message": "User is not authorized to access billing account '{account_id}'."
    }
}
</code>```

So, essentially the application user was created from an enterprise agreement account but can't access enterprise agreement resources from the API. What's going on here?

答:
The application registration should have any of the below roles to access the billing accounts information:

Service Administrator

Co-administrator

Owner

Contributor

Reader

Billing reader

You can assign any of the above roles from the Access Control (IAM) to the application registration

Body:
Sorry if this is off-topic but I haven't been able to find any information on it anywhere else. I'm trying to create an application registration that will allow a batch process to access the Azure REST API on my behalf.

Normally, this is pretty simple: just create the user, give it API permissions to what you need, add a secret and then insert the tenant ID, application ID and secret into a request against the /token endpoint, as described here.

I have done that and gotten the access token but, when I try to get all the billing accounts associated with the enterprise agreement, by calling https://management.azure.com/providers/Microsoft.Billing/billingAccounts?api-version=2020-05-01 I get no information back. Also, when I try to access a particular billing account back, by calling https://management.azure.com/providers/Microsoft.Billing/billingAccounts/{account_id}?api-version=2020-05-01, I get the following error and a 403 response code:

{
    "error": {
        "code": "Forbidden",
        "message": "User is not authorized to access billing account '{account_id}'."
    }
}

So, essentially the application user was created from an enterprise agreement account but can't access enterprise agreement resources from the API. What's going on here?


问:
Xamarin Forms CollectionView OnScroll Hide/Show Element
I'm trying to create a scroll aware header that hide or show header depending on scroll up or down.

I have a grid with a header menu and a collection view :

```<code><Grid RowDefinitions="Auto, *">
    <ContentView x:Name="Header"> ... </ContentView>
    <CollectionView Grid.Row="1"
                    Scrolled="CollectionView_OnScrolled" ... />
</Grid>
</code>```

In the scrolled event i tried to perform something like :

```<code>void OperationList_Scrolled(object sender, ItemsViewScrolledEventArgs e)
{
    if (Header.IsVisible && e.VerticalDelta > 0)
    {
        Header.IsVisible = false;
    }
    else if (!Header.IsVisible && e.VerticalDelta < 0)
    {
        Header.IsVisible = true;
    }
}
</code>```

But it's not very smooth and it blinks. Do you have any ideas to accomplish this properly ?

答:
You could use animations to simulate the header visible or not to avoid blinking.

Xaml:

```<code>  <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <CollectionView x:Name="collectionView" ItemsSource="{Binding Monkeys}"   AbsoluteLayout.LayoutBounds="0,0,1,1"
    AbsoluteLayout.LayoutFlags="All" Scrolled="CollectionView_OnScrolled">
            <CollectionView.Header>
                <ContentView>
                    <StackLayout x:Name="HeaderView" />
                </ContentView>
            </CollectionView.Header>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Label Text="{Binding Name}" FontSize="Large"></Label>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        <Frame
    x:Name="HeaderLabelView"
    Margin="16,8,16,8"
    Padding="3"
    AbsoluteLayout.LayoutBounds="0.5, 0, AutoSize, AutoSize"
    AbsoluteLayout.LayoutFlags="PositionProportional"
    CornerRadius="6"
    HasShadow="True">
            <Label HorizontalOptions="FillAndExpand" />
        </Frame>
    </AbsoluteLayout>
</code>```

Code behind:

```<code>   public partial class Page10 : ContentPage
{
    public Page10()
    {
        InitializeComponent();

        this.BindingContext = new MonkeyViewModel();
    }

    private void CollectionView_OnScrolled(object sender, ItemsViewScrolledEventArgs e)
    {
        var transY = Convert.ToInt32(HeaderLabelView.TranslationY);
        if (transY == 0 &&
            e.VerticalDelta > 15)
        {
            var trans = HeaderLabelView.Height + HeaderLabelView.Margin.Top;

            Task.WhenAll(
                HeaderLabelView.TranslateTo(0, -(trans), 200, Easing.CubicIn),
                HeaderLabelView.FadeTo(0.25, 200));
        }
        else if (transY != 0 &&
                 e.VerticalDelta < 0 &&
                 Math.Abs(e.VerticalDelta) > 10)
        {
            Task.WhenAll(
                HeaderLabelView.TranslateTo(0, 0, 200, Easing.CubicOut),
                HeaderLabelView.FadeTo(1, 200));
        }
    }
}
public class MonkeyViewModel
{
    public ObservableCollection<Monkey> Monkeys { get; set; }
    public MonkeyViewModel()
    {
        Monkeys = new ObservableCollection<Monkey>()
        {
            new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"},
             new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="g"},
        };
    }
}

public class Monkey
{
    public string Name { get; set; }
}
</code>```

Body:
I'm trying to create a scroll aware header that hide or show header depending on scroll up or down.

I have a grid with a header menu and a collection view :

<Grid RowDefinitions="Auto, *">
    <ContentView x:Name="Header"> ... </ContentView>
    <CollectionView Grid.Row="1"
                    Scrolled="CollectionView_OnScrolled" ... />
</Grid>

In the scrolled event i tried to perform something like :

void OperationList_Scrolled(object sender, ItemsViewScrolledEventArgs e)
{
    if (Header.IsVisible && e.VerticalDelta > 0)
    {
        Header.IsVisible = false;
    }
    else if (!Header.IsVisible && e.VerticalDelta < 0)
    {
        Header.IsVisible = true;
    }
}

But it's not very smooth and it blinks. Do you have any ideas to accomplish this properly ?

Body:
You could use animations to simulate the header visible or not to avoid blinking.

Xaml:

  <AbsoluteLayout HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">

        <CollectionView x:Name="collectionView" ItemsSource="{Binding Monkeys}"   AbsoluteLayout.LayoutBounds="0,0,1,1"
    AbsoluteLayout.LayoutFlags="All" Scrolled="CollectionView_OnScrolled">
            <CollectionView.Header>
                <ContentView>
                    <StackLayout x:Name="HeaderView" />
                </ContentView>
            </CollectionView.Header>
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Label Text="{Binding Name}" FontSize="Large"></Label>
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
        <Frame
    x:Name="HeaderLabelView"
    Margin="16,8,16,8"
    Padding="3"
    AbsoluteLayout.LayoutBounds="0.5, 0, AutoSize, AutoSize"
    AbsoluteLayout.LayoutFlags="PositionProportional"
    CornerRadius="6"
    HasShadow="True">
            <Label HorizontalOptions="FillAndExpand" />
        </Frame>
    </AbsoluteLayout>

Code behind:

   public partial class Page10 : ContentPage
{
    public Page10()
    {
        InitializeComponent();

        this.BindingContext = new MonkeyViewModel();
    }

    private void CollectionView_OnScrolled(object sender, ItemsViewScrolledEventArgs e)
    {
        var transY = Convert.ToInt32(HeaderLabelView.TranslationY);
        if (transY == 0 &&
            e.VerticalDelta > 15)
        {
            var trans = HeaderLabelView.Height + HeaderLabelView.Margin.Top;

            Task.WhenAll(
                HeaderLabelView.TranslateTo(0, -(trans), 200, Easing.CubicIn),
                HeaderLabelView.FadeTo(0.25, 200));
        }
        else if (transY != 0 &&
                 e.VerticalDelta < 0 &&
                 Math.Abs(e.VerticalDelta) > 10)
        {
            Task.WhenAll(
                HeaderLabelView.TranslateTo(0, 0, 200, Easing.CubicOut),
                HeaderLabelView.FadeTo(1, 200));
        }
    }
}
public class MonkeyViewModel
{
    public ObservableCollection<Monkey> Monkeys { get; set; }
    public MonkeyViewModel()
    {
        Monkeys = new ObservableCollection<Monkey>()
        {
            new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"},
             new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="D"}, new Monkey(){ Name="A"},
            new Monkey(){ Name="B"},
            new Monkey(){ Name="C"},
            new Monkey(){ Name="g"},
        };
    }
}

public class Monkey
{
    public string Name { get; set; }
}


问:
R - Finding duplicates in list entries
I am trying to figure out how to get duplicates out of list objects in R.
So my example list:

```<code>examplelist <- list(a = c("blue", "red", "yellow"),
                    b = c("red", "black", "green"),
                    c = c("black", "green", "brown"))
</code>```

What I would like to get as a result:

duplicates: c("red", "black", "green")

vector of all entries, without double entries: c("blue", "red", "yellow", "black", "green", "brown")

I was not able to find a function for that other than duplicated() which just checks my list objects in total but not the entries itselves.

Thank you for your help :)

答:
You can unlist first:

unlisted <- unlist(examplelist)
unlisted[duplicated(unlisted)]
#     b1      c1      c2
#  "red" "black" "green"

unlisted[!duplicated(unlisted)]
#      a1       a2       a3       b2       b3       c3
#  "blue"    "red" "yellow"  "black"  "green"  "brown"
```
<p>If you only want the vector (without the names), use <code>unname</code>:</p>
<pre class="lang-r prettyprint-override"><code>unlisted <- unname(unlist(examplelist))
</code>```

Title: R - Finding duplicates in list entries

Body:
I am trying to figure out how to get duplicates out of list objects in R.
So my example list:

examplelist <- list(a = c("blue", "red", "yellow"),
                    b = c("red", "black", "green"),
                    c = c("black", "green", "brown"))

What I would like to get as a result:

duplicates: c("red", "black", "green")

vector of all entries, without double entries: c("blue", "red", "yellow", "black", "green", "brown")

I was not able to find a function for that other than duplicated() which just checks my list objects in total but not the entries itselves.

Thank you for your help :)

Body:
You can unlist first:

unlisted <- unlist(examplelist)
unlisted[duplicated(unlisted)]
#     b1      c1      c2
#  "red" "black" "green"

unlisted[!duplicated(unlisted)]
#      a1       a2       a3       b2       b3       c3
#  "blue"    "red" "yellow"  "black"  "green"  "brown"

If you only want the vector (without the names), use unname:

unlisted <- unname(unlist(examplelist))


答:
Print function takes many parameters. One relevant here is end. Default value is '\n'

try print(line, end='')

Title: Why is this code printing a line after reading one line of content


问:
How can i make my navigation bar stick to the top of my screen with css
So i was creating a navigation bar for my website and it seems impossible to make it stick on the screen, its so confusing to me.

I followed Kevin Powell's tutorial on this but he didn't show how to make it stick to the top of the page.

Here is my HTML:

```<code>    <header>
        <div class="container">
            <h1 class="logo">Navigation</h1>

            <nav>
                <ul>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About us</a></li>
                    <li><a href="#">Contact us</a></li>
                </ul>
            </nav>
        </div>
    </header>
</code>```

And here is my CSS:

```<code>.container {
    width: 80%;
    margin: 0 auto;
}

header {
    background: rgb(155, 155, 155);
    border-radius: 0px 0px 25px 25px;
}

.logo {
    float: left;
    padding: 0px 0;
}
</code>```

I had to shrink the css code a bit but the ul is not really important here.

答:
Just added some css of your nav.

```<code>nav {
   overflow: hidden;
   position: fixed;
   top: 0;
   width: 100%;
}
</code>```

See a demo where I used your code:- in codepen

Also,

.container {
  width: 100%;
  margin: 0 auto;
}

header {
  background: rgb(155, 155, 155);
  border-radius: 0px 0px 25px 25px;
  height: 700px;
}
nav {
  overflow: hidden;
  position: fixed;
  top: 0;
  width: 100%;
}
.logo {
  float: left;
  padding: 0px 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <div class="container">
    <h1 class="logo">Navigation</h1>
    <nav>
      <ul>
        <li>Home</li>
        <li>About us</li>
        <li>Contact us</li>
      </ul>
    </nav>
  </div>
</header></code>```

check from here;-

Body:
So i was creating a navigation bar for my website and it seems impossible to make it stick on the screen, its so confusing to me.

I followed Kevin Powell's tutorial on this but he didn't show how to make it stick to the top of the page.

Here is my HTML:

Navigation

Home

About us

Contact us

And here is my CSS:

.container {
    width: 80%;
    margin: 0 auto;
}

header {
    background: rgb(155, 155, 155);
    border-radius: 0px 0px 25px 25px;
}

.logo {
    float: left;
    padding: 0px 0;
}

I had to shrink the css code a bit but the ul is not really important here.

Body:
Just added some css of your nav.

nav {
   overflow: hidden;
   position: fixed;
   top: 0;
   width: 100%;
}

See a demo where I used your code:- in codepen

Also,

.container {
  width: 100%;
  margin: 0 auto;
}

header {
  background: rgb(155, 155, 155);
  border-radius: 0px 0px 25px 25px;
  height: 700px;
}
nav {
  overflow: hidden;
  position: fixed;
  top: 0;
  width: 100%;
}
.logo {
  float: left;
  padding: 0px 0;
}

<header>
  <div class="container">
    <h1 class="logo">Navigation</h1>
    <nav>
      <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">About us</a></li>
        <li><a href="#">Contact us</a></li>
      </ul>
    </nav>
  </div>
</header>

check from here;-


问:
Can I query twice to get more specific value in mongoDB?
For an example, there is a group called "A" which is an array.

And there is another group called "B" which is inside of group "A" also an array.

I want to find and update group "B" elements.

I tried to query chain-like query like in jQuery.

```<code>db.collection.findOne({"group":"A"}).findOne({"society":"B"})
</code>```

something like this..

but this does not work. But main point is that I want to query group elements in group.

Any suggestion on doing this?

If you give me advice especially with PHP implementation, it will be really helpful

答:
Maybe I am misunderstanding something, but what is wrong with:

```<code>db.collection.findOne({"group":"A", "society":"B"})
</code>```

Also note that findOne only returns one document.

Body:
For an example, there is a group called "A" which is an array.

And there is another group called "B" which is inside of group "A" also an array.

I want to find and update group "B" elements.

I tried to query chain-like query like in jQuery.

db.collection.findOne({"group":"A"}).findOne({"society":"B"})

something like this..

but this does not work. But main point is that I want to query group elements in group.

Any suggestion on doing this?

If you give me advice especially with PHP implementation, it will be really helpful

Body:
Maybe I am misunderstanding something, but what is wrong with:

db.collection.findOne({"group":"A", "society":"B"})

Also note that findOne only returns one document.


问:
How to keep already chosen value in ReactJS
I have following code.

What I'm trying to do is, in the first step, select one of the elements, store it in my state, and in the last step, console.log all my data. Also, the user can go from the last step to the first and change what he chose before. But the problem is that I can't save what the user selects for the first time.

For example, if the user selects the second one, and then on the last step they go back, then the first one is displayed as selected. How can I fix this?

here is my code

App.js

```<code>     const [current, setCurrent] = useState(0);
      const [data, setData] = useState({
        firstName: "AAA",
        lastName: "BBB",
        age: 26
      });
      const steps = [
        {
       content: (
        <PackageChoose setCurrent={setCurrent} data={data} setData={setData} />
        ),
        id: 0
       },
       {
        content: <LastStep setCurrent={setCurrent} data={data} />,
        id: 1
       }
     ];
     return (
       <div className="App">
        <div>{steps[current].content}</div>
      </div>
     );
</code>```

packageChoose (or first step)

```<code>   const PackageChoose = ({ setCurrent, data, setData }) => {
     const [selected, setSelected] = useState(1);
     const [packageType, setPackageType] = useState(data.package || "choice");
     return (
        <div>
          <div
            onClick={() => {
            setPackageType("choice");
            setData({ ...data, packageType: packageType });
          }}
         >
           <SelectCard
             id={1}
             selected={selected}
             onSelect={setSelected}
             text="text 1"
          />
        </div>
        <div
          onClick={() => {
            setPackageType("select");
           setData({ ...data, packageType: packageType });
          }}
        >
         <SelectCard
           id={2}
          selected={selected}
          onSelect={setSelected}
          text="text 2"
        />
        </div>
        <button onClick={() => setCurrent(1)}>Next</button>
      </div>
     );
   };

</code>```

Last step

```<code>    const LastStep = ({ setCurrent, data }) => {
    return (
       <div>
         LastStep
         <button
           onClick={() => {
             setCurrent(0);
           }}
         >
           Previous
         </button>
         <button onClick={() => console.log("data===>", data)}> submit </button>
       </div>
     );
    };
</code>```

Selected Card reusable component

```<code>   const SelectCard = ({ id, selected, onSelect, text }) => {
     const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (
        <div className={classNames(myClassName)} onClick={() => onSelect(id)}>
          <div> {text} </div>
        </div>
      );
    };
</code>```

Please help me to fix this problem.

答:
You need to update the packageType inside onClick handler. Since setState calls are batched and enqueued inside event handler and state updates may be asynchronous. You can't access the packageType state immediately after setting it.

PackageChoose.js

Card 1

```<code>onClick={() => setData({ ...data, packageType: "choice" })}
</code>```

Card 2

```<code>onClick={() => setData({ ...data, packageType: "select" })}
</code>```

set the packageType directly on data.

Body:
I have following code.

What I'm trying to do is, in the first step, select one of the elements, store it in my state, and in the last step, console.log all my data. Also, the user can go from the last step to the first and change what he chose before. But the problem is that I can't save what the user selects for the first time.

For example, if the user selects the second one, and then on the last step they go back, then the first one is displayed as selected. How can I fix this?

here is my code

App.js

     const [current, setCurrent] = useState(0);
      const [data, setData] = useState({
        firstName: "AAA",
        lastName: "BBB",
        age: 26
      });
      const steps = [
        {
       content: (
        <PackageChoose setCurrent={setCurrent} data={data} setData={setData} />
        ),
        id: 0
       },
       {
        content: <LastStep setCurrent={setCurrent} data={data} />,
        id: 1
       }
     ];
     return (

{steps[current].content}

     );

packageChoose (or first step)

   const PackageChoose = ({ setCurrent, data, setData }) => {
     const [selected, setSelected] = useState(1);
     const [packageType, setPackageType] = useState(data.package || "choice");
     return (

 {
            setPackageType("choice");
            setData({ ...data, packageType: packageType });
          }}
         >
           <SelectCard
             id={1}
             selected={selected}
             onSelect={setSelected}
             text="text 1"
          />

 {
            setPackageType("select");
           setData({ ...data, packageType: packageType });
          }}
        >
         <SelectCard
           id={2}
          selected={selected}
          onSelect={setSelected}
          text="text 2"
        />

        <button onClick={() => setCurrent(1)}>Next</button>

     );
   };

Last step

    const LastStep = ({ setCurrent, data }) => {
    return (

         LastStep
         <button
           onClick={() => {
             setCurrent(0);
           }}
         >
           Previous
         </button>
         <button onClick={() => console.log("data===>", data)}> submit </button>

     );
    };

Selected Card reusable component

   const SelectCard = ({ id, selected, onSelect, text }) => {
     const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (

 onSelect(id)}>

 {text}

      );
    };

Please help me to fix this problem.

Body:
You need to update the packageType inside onClick handler. Since setState calls are batched and enqueued inside event handler and state updates may be asynchronous. You can't access the packageType state immediately after setting it.

PackageChoose.js

Card 1

onClick={() => setData({ ...data, packageType: "choice" })}

Card 2

onClick={() => setData({ ...data, packageType: "select" })}

set the packageType directly on data.


问:
Join a Tree Based Table
I have a fact table "Pricing" like this:

Serial
Main_Category
Group_Category
Sub_Category
Item
Location
Price

1
Clothes
Men
T Shirts
T Shirt 1
Store 1
100

2
Clothes
Men
T Shirts
T Shirt 1
All
25

3
Devices
TVs
Smart TVs
SmartTV 1
Store 1
50

4
Devices
TVs
Smart TVs
All
Store 1
75

You can note that not all items are explicitly defined, if the item is not mentioned, it should be available in the "All".

"All" could be found in any column except for Price

Another dimension table "Sales" like this:

Serial
Main_Category
Group_Category
Sub_Category
Item
Location

1
Clothes
Men
T Shirts
T Shirt 1
Store 1

2
Clothes
Men
T Shirts
T Shirt 1
Store 3

3
Devices
TVs
Smart TVs
SmartTV 3
Store 1

4
Devices
TVs
Smart TVs
SmartTV 1
Store 1

I would like to add the price from the Pricing table to the Sales table without using a join for each combination

Excepted output:

Serial
Main_Category
Group_Category
Sub_Category
Item
Location
Price

1
Clothes
Men
T Shirts
T Shirt 1
Store 1
100

2
Clothes
Men
T Shirts
T Shirt 1
Store 3
25

3
Devices
TVs
Smart TVs
SmartTV 3
Store 1
75

4
Devices
TVs
Smart TVs
SmartTV 1
Store 1
50

Update:
"All" could be found in more than one column

答:
You can do</p>
```<code>select *
from (
    select s.*, p.Price, row_number() over(partition by s.Main_Category, .., s.Location order by p.Serial) rn
    from Sales s
    join Pricing p on
      (s.Main_Category = p.Main_Category or p.Main_Category ='All')
      and ..
      and (s.Location = p.Location or p.Location ='All')
 ) t
 where rn = 1;
</code>```

Title: Join a Tree Based Table

Body:
You can do

select *
from (
    select s.*, p.Price, row_number() over(partition by s.Main_Category, .., s.Location order by p.Serial) rn
    from Sales s
    join Pricing p on
      (s.Main_Category = p.Main_Category or p.Main_Category ='All')
      and ..
      and (s.Location = p.Location or p.Location ='All')
 ) t
 where rn = 1;


问:
Flutter Error: No named parameter with the name 'displayLarge'
I am working on an app, I posted last update on git 2 days ago and haven't touched the code since. Now, I opened android studio and it was giving me this error when I tried to run it... I tried deleting repository from my computer and then cloning it again but it didn't work. I have also tried searching for similar problems, and found out there was a similar problem with speed-dial package and one comment said something about broken package versions. Anyways, this is the error I am getting after I try running my app:

These are first few lines of the error it's giving me, but there is more than a thousand lines following these.

I also tried running flutter doctor and it gave me the following:

答: set the package version to google_fonts: 2.2.0 and it should work properly</p>


问:
Non-Nullable becomes Nullable on return
I think I've seen this question answered somewhere, but I can't find it and don't remember the answer.

Assuming Nullable-Reference-Types is enabled.

There is a method that returns a string. The caller of the method stores the resulting string into a variable. The variable will be Nullable, even if the method's return value is non-nullable.

static string MyMethod()
{
   return "Hello World!";
}

public static void Main()
{
   // result is of type string? here. Hence nullable.
   var result = MyMethod();
}
```

The same does not seem to happen with primitive types, but it does happen reference types, like object. Kind of defeats the purpose of NRT for me. I'm  sure there's a reason for this and it's "by design".

答:
This is indeed by design.

The meeting notes where this design was chosen are here: https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md#var

To summarise: It was found that people were frequently having to explicitly type the variable rather than using var because after assignment from a non-null-returning method, the code went on to assign null to the variable.

To quote from the meeting notes:

At this point we've seen a large amount of code that requires people
spell out the type instead of using var, because code may assign null
later.

That is, code like the following was found to be quite frequent:

```<code>var someVariable = SomeMethodThatDoesntReturnNull();
...
someVariable = null; // or someVariable = someMethodThatCanReturnNull();
</code>```

Note that (as pointed out by Jeroen Mostert) result2 in your question is NOT nullable because it's explicitly typed as non-nullable. I'm not sure why you think it is nullable, but it definitely isn't.

For example, look at this repro on DotNetFiddle and note the warning on line 11.

Title: Non-Nullable becomes Nullable on return

Body:
I think I've seen this question answered somewhere, but I can't find it and don't remember the answer.

Assuming Nullable-Reference-Types is enabled.

There is a method that returns a string. The caller of the method stores the resulting string into a variable. The variable will be Nullable, even if the method's return value is non-nullable.

static string MyMethod()
{
   return "Hello World!";
}

public static void Main()
{
   // result is of type string? here. Hence nullable.
   var result = MyMethod();
}

The same does not seem to happen with primitive types, but it does happen reference types, like object. Kind of defeats the purpose of NRT for me. I'm  sure there's a reason for this and it's "by design".

Body:
This is indeed by design.

The meeting notes where this design was chosen are here: https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md#var

To summarise: It was found that people were frequently having to explicitly type the variable rather than using var because after assignment from a non-null-returning method, the code went on to assign null to the variable.

To quote from the meeting notes:

At this point we've seen a large amount of code that requires people
spell out the type instead of using var, because code may assign null
later.

That is, code like the following was found to be quite frequent:

var someVariable = SomeMethodThatDoesntReturnNull();
...
someVariable = null; // or someVariable = someMethodThatCanReturnNull();

Note that (as pointed out by Jeroen Mostert) result2 in your question is NOT nullable because it's explicitly typed as non-nullable. I'm not sure why you think it is nullable, but it definitely isn't.

For example, look at this repro on DotNetFiddle and note the warning on line 11.


问:
What's the accepted method for deploying a linux application that relies on shared libraries?
I have an application that relies on Qt, GDCM, and VTK, with the main build environment being Qt.  All of these libraries are cross-platform and compile on Windows, Mac, and Linux.  I need to deploy the application to Linux after deploying on Windows.  The versions of vtk and gdcm I'm using are trunk versions from git (about a month old), more recent than what I can get apt-get on Ubuntu 11.04, which is my current (and only) Linux deployment target.

What is the accepted method for deploying an application that relies on these kinds of libraries?

Should I be statically linking here, to avoid LD_LIBRARY_PATH?  I see conflicting reports on LD_LIBRARY_PATH; tutorials like this one suggest that it's the 'right way' to modify the library path to use shared libraries through system reboots.  Others suggest that I should never set LD_LIBRARY_PATH.  In the default version of GDCM, the installation already puts libraries into the /usr/local/lib directory, so those libraries get seen when I run ldd <my program>.  VTK, on the other hand, puts its libraries into /usr/local/lib/vtk-5.9, which is not part of the LD_LIBRARY_PATH on most user's machines, and so is not found unless some change is made to the system.  Copying the VTK files into '/usr/local/lib' does not allow 'ldd' to see the files.

So, how can I make my application see VTK to use the libraries?

On windows, deploying the dlls is very straightforward, because I can just include them in the installer, and the application finds them because they are in the local directory.  That approach does not work in Linux, so I was going to have the users install Qt, GDCM, and VTK from whatever appropriate source and use the default locations, and then have the application point to those default locations.  However, since VTK is putting things into a non-standard location, should I also expect users to modify LD_LIBRARY_PATH?  Should I include the specific versions of the libraries that I want and then figure out how to make the executable look in the local directory for those libraries and ignore the ones it finds in the library path?

答:
Every "serious" commercial application I have ever seen uses LD_LIBRARY_PATH.  They invariably include a shell script that looks something like this:

```<code>#!/bin/sh

here="${0%/*}"  # or you can use `dirname "$0"`

LD_LIBRARY_PATH="$here"/lib:"$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH
exec "$0".bin "$@"
</code>```

They name this script something like .wrapper and create a directory tree that looks like this:

```<code>.wrapper
lib/  (directory full of .so files)
app1 -> .wrapper (symlink)
app1.bin (executable)
app2 -> .wrapper (symlink)
app2.bin (executable)
</code>```

Now you can copy this whole tree to wherever you want, and you can run "/path/to/tree/app1" or "/path/to/tree/app2 --with --some --arguments" and it will work.  So will putting /path/to/tree in your PATH.

Incidentally, this is also how Firefox and Chrome do it, more or less.

Whoever told you not to use LD_LIBRARY_PATH is full of it, IMHO.

Which system libraries you want to put in lib depends on which Linux versions you want to officially support.

Do not even think about static linking.  The glibc developers do not like it, they do not care about supporting it, and they somehow manage to break it a little harder with every release.

Good luck.

Body:
Every "serious" commercial application I have ever seen uses LD_LIBRARY_PATH.  They invariably include a shell script that looks something like this:

#!/bin/sh

here="${0%/*}"  # or you can use `dirname "$0"`

LD_LIBRARY_PATH="$here"/lib:"$LD_LIBRARY_PATH"
export LD_LIBRARY_PATH
exec "$0".bin "$@"

They name this script something like .wrapper and create a directory tree that looks like this:

.wrapper
lib/  (directory full of .so files)
app1 -> .wrapper (symlink)
app1.bin (executable)
app2 -> .wrapper (symlink)
app2.bin (executable)

Now you can copy this whole tree to wherever you want, and you can run "/path/to/tree/app1" or "/path/to/tree/app2 --with --some --arguments" and it will work.  So will putting /path/to/tree in your PATH.

Incidentally, this is also how Firefox and Chrome do it, more or less.

Whoever told you not to use LD_LIBRARY_PATH is full of it, IMHO.

Which system libraries you want to put in lib depends on which Linux versions you want to officially support.

Do not even think about static linking.  The glibc developers do not like it, they do not care about supporting it, and they somehow manage to break it a little harder with every release.

Good luck.


答:
This is because each row in your datafile is appended with a newline character, \n. If you want to remove this from your line, you can do

```<code>line = line.rstrip()
</code>```

If you want to print without the newline character, change the args to print as

```<code>print(line, end='')
</code>```

Body:
This is because each row in your datafile is appended with a newline character, \n. If you want to remove this from your line, you can do

line = line.rstrip()

If you want to print without the newline character, change the args to print as

print(line, end='')


问:
stacked column highchart custom modifications
I attached the below photo describe the challenge that I have
hide black color value change the black color to red and decrease the black color value from the total

```<code>here is the code URL

    https://jsfiddle.net/Anasddrx/gtyhrvp3/33/
</code>```

enter image description here

答:
To set the red color for the Stop series and hide dataLabels use this config:

```<code> {
    name: 'Stop',
    data: [5000, 3000, 4000, 7000, 2000],
        color: 'red',
        dataLabels: {
            enabled: false
        },
  },
</code>```

To subtract Stop value from the stacking sum try this approach:

```<code>  formatter: function() {
            const stopSeries = this.axis.series.find(s => s.name === 'Stop');

    return this.total - stopSeries.processedYData[this.x] + " Pcs";
  },
</code>```

Demo: https://jsfiddle.net/BlackLabel/pq7tdufk/

API: https://api.highcharts.com/highcharts/yAxis.stackLabels.formatter

API: https://api.highcharts.com/highcharts/series.column.color

API: https://api.highcharts.com/highcharts/series.column.dataLabels

Body:
I attached the below photo describe the challenge that I have
hide black color value change the black color to red and decrease the black color value from the total

here is the code URL

    https://jsfiddle.net/Anasddrx/gtyhrvp3/33/

enter image description here

Body:
To set the red color for the Stop series and hide dataLabels use this config:

 {
    name: 'Stop',
    data: [5000, 3000, 4000, 7000, 2000],
        color: 'red',
        dataLabels: {
            enabled: false
        },
  },

To subtract Stop value from the stacking sum try this approach:

  formatter: function() {
            const stopSeries = this.axis.series.find(s => s.name === 'Stop');

    return this.total - stopSeries.processedYData[this.x] + " Pcs";
  },

Demo: https://jsfiddle.net/BlackLabel/pq7tdufk/

API: https://api.highcharts.com/highcharts/yAxis.stackLabels.formatter

API: https://api.highcharts.com/highcharts/series.column.color

API: https://api.highcharts.com/highcharts/series.column.dataLabels


问:
How do I return single orderid having same rank?
I have the following output:

Orderid
Time
State
Order_rank

1
10.15
mfr
1

1
10.15
delivered
1

2
12.10
picked
1

2
12.10
mfr
1

Here I have ranked the order ids wrt to the latest time and put the condition in where clause "where order_rank = 1", but I want to return a single entry for one orderjobid, i.e. for orderid 1 I want to return the delivered state entry and for orderid 2 I want mfr state entry etc.

This is just a sample data, I have more than 1000s of orderids, how do I return single entry for the same rank?

答:
Extend your ranking to include not only the time, but also an expression of state, like.

```<code>Order time desc,
     case state when 'picked' then 1
                When 'mfr' then 2
                When 'delivered' then 3
                ...
     End asc
</code>```

This way we assign a sort order 1,2,3 to each state.

Edited to make it correct as per comments from @simeon-pilgrim (thanks)

Body:
Extend your ranking to include not only the time, but also an expression of state, like.

Order time desc,
     case state when 'picked' then 1
                When 'mfr' then 2
                When 'delivered' then 3
                ...
     End asc

This way we assign a sort order 1,2,3 to each state.

Edited to make it correct as per comments from @simeon-pilgrim (thanks)


问:
How can I remove a tensor from a FilterDataset/MapDataset
I have a dataset of video_id, user_id and score tensors. I want to filter this to only positive examples with score above a threshold and then remove the score tensor.

def decode_retrieval_positive(record_bytes):
    return tf.io.parse_single_example(
        # Data
        record_bytes,
        # Schema
        {"video_id": tf.io.FixedLenFeature([], dtype=tf.int64),
        "user_id": tf.io.FixedLenFeature([], dtype=tf.int64),
        "score": tf.io.FixedLenFeature([], dtype=tf.float32)}
    )

ratings_positive = ratings.map(
            decode_retrieval_positive
        ).filter(
            lambda x: x["score"] > 0.2
        ).map(
            lambda x: {"video_id": x["video_id"], "user_id": x["user_id"]}
        )

<MapDataset element_spec={'video_id': TensorSpec(shape=(), dtype=tf.int64, name=None), 'user_id': TensorSpec(shape=(), dtype=tf.int64, name=None)}>
```
<p>This gives me this error:</p>
```2022-02-07 08:18:52.825318: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at example_parsing_ops.cc:94 : INVALID_ARGUMENT: Feature: score (data type: float) is required but could not be found.
```

One solution would be to simply make a new positive_ratings.tfrecord but that would take up more space and I'm annoyed I can't do this.

答:
You just need to make sure x['score'] has float values. Here is a working example:

import tensorflow as tf
tf.random.set_seed(111)

# Create dummy data
dataset = tf.data.Dataset.range(10)
dataset = dataset.map(lambda x: {'video_id': x, 'user_id': 2555 + x, 'score': tf.cast(x, dtype=tf.float32)*tf.random.normal(())})

dataset = dataset.filter(lambda x: x["score"] > 0.2)
dataset = dataset.map(lambda x: {"video_id": x["video_id"], "user_id": x["user_id"]})
for d in dataset:
  print(d)
```
```{'video_id': <tf.Tensor: shape=(), dtype=int64, numpy=5>, 'user_id': <tf.Tensor: shape=(), dtype=int64, numpy=2560>}
```

Body:
I have a dataset of video_id, user_id and score tensors. I want to filter this to only positive examples with score above a threshold and then remove the score tensor.

def decode_retrieval_positive(record_bytes):
    return tf.io.parse_single_example(
        # Data
        record_bytes,
        # Schema
        {"video_id": tf.io.FixedLenFeature([], dtype=tf.int64),
        "user_id": tf.io.FixedLenFeature([], dtype=tf.int64),
        "score": tf.io.FixedLenFeature([], dtype=tf.float32)}
    )

ratings_positive = ratings.map(
            decode_retrieval_positive
        ).filter(
            lambda x: x["score"] > 0.2
        ).map(
            lambda x: {"video_id": x["video_id"], "user_id": x["user_id"]}
        )

<MapDataset element_spec={'video_id': TensorSpec(shape=(), dtype=tf.int64, name=None), 'user_id': TensorSpec(shape=(), dtype=tf.int64, name=None)}>

This gives me this error:

2022-02-07 08:18:52.825318: W tensorflow/core/framework/op_kernel.cc:1745] OP_REQUIRES failed at example_parsing_ops.cc:94 : INVALID_ARGUMENT: Feature: score (data type: float) is required but could not be found.

One solution would be to simply make a new positive_ratings.tfrecord but that would take up more space and I'm annoyed I can't do this.

Body:
You just need to make sure x['score'] has float values. Here is a working example:

import tensorflow as tf
tf.random.set_seed(111)

# Create dummy data
dataset = tf.data.Dataset.range(10)
dataset = dataset.map(lambda x: {'video_id': x, 'user_id': 2555 + x, 'score': tf.cast(x, dtype=tf.float32)*tf.random.normal(())})

dataset = dataset.filter(lambda x: x["score"] > 0.2)
dataset = dataset.map(lambda x: {"video_id": x["video_id"], "user_id": x["user_id"]})
for d in dataset:
  print(d)

{'video_id': <tf.Tensor: shape=(), dtype=int64, numpy=5>, 'user_id': <tf.Tensor: shape=(), dtype=int64, numpy=2560>}


问:
Where do java packages live on a linux system? Package org.json does not exist Error using javac
I am trying to compile a library I wrote, using javac and I am getting the error: package org.json does not exist.  My program includes org.json.JSONArray and org.json.JSONException.

I have this package installed on my computer because I have successfully compiled android apps that import org.json libraries.  I'm pretty sure all I have to do is specify a -classpath but I have been unable to find where these files live on my system (ubuntu 10.10 64-bit sun-java6).

Having been unable to find these on my own system I downloaded the org.json files from here, but I was unable to compile them individually because they were co-dependent on each other.

So I have a couple questions:

Does anyone know where the org.json
package lives from android sdk
install?

Where might I find a tutorial
explaining these basic concepts
regarding compiling, and javac.

答: use "java" command instead of "javac"</p>

Body: use "java" command instead of "javac"


问:
GMB Q&A API v1 Does not return list of answers
When making a call to the Questions endpoint (https://developers.google.com/my-business/reference/qanda/rest/v1/locations.questions/list) using a URL like
https://mybusinessqanda.googleapis.com/v1/locations/7588802572969590693/questions
I get back a list of questions with top answers. However when I make a call to the Answers endpoint (https://developers.google.com/my-business/reference/qanda/rest/v1/locations.questions.answers/list) using a URL like
https://mybusinessqanda.googleapis.com/v1/locations/7588802572969590693/questions/AIe9_BExcxslmE1rr7n5jMcadSKe_cI3ZkOvVEvqa8t0FKNXgmSYiUhM_1uJsGKdkR7rDZwgFwpFSWBONLvdDvfxs5c7gNiOk4Z6MdcNBPJyLb0wBiy8uR0Ezz2aMrE3xRIW9sIysNDK/answers
to get a list of all answers for a specific question name I keep getting the below error response:

{  "error": {    "code": 404,    "message": "Requested entity was not found.",    "status": "NOT_FOUND"  }}

If I take any of the question names from the first questions list call, the answers call always returns the above error message.

答:
Update 3: fixed again as of April 14, 2022.

Update 2: this bug was reintroduced in April 2022.

Update: This bug was fixed yesterday (Feb 22, 2022).

This is a bug.

The only remediation possible right now is to continue using the GMB API v4.9 method: https://developers.google.com/my-business/reference/rest/v4/accounts.locations.questions.answers/list


问:
Azure SQL db with no data takes too much space
I set up azure sql database in free tier for testing purposes. It has 32 MB limit, but it should be fine, since my db is about 30 tables and few rows of data per each (really just for testing purposes).
After some while, I reached 32 MB limit. I was forced to delete (and drop) all the tables. Now the db takes 87.5 % WITH NO TABLES IN IT.

I followed this post about data size investigations and here are the results:

(more rows here, but each with 0.1 MB and less)

I tried to run DBCC SHRINKFILE (log, 0); but nothing has changed.

I also did sp_spaceused

Which resulted in:

The percentage form azure portal (87.5 %) changes time to time for no reason (sometimes it drops to 37.5 %)

So my question is - what am I doing wrong here? How should I proceed to not have most of the db filled without any data..?

答:
The Azure free tier account type provides 250 GB free storage with S0 instance for 12 months.

Please create another database (upto 10 databases allowed in free tier) using S0 instance. Refer the steps given by @FabioSipoliMuller in this thread to deploy the same.

Note: You need to make some changes in configuration while deploying the database in free service.


问:
How to plot data with two different timestamps in one plot?
I tried the following script, also i need add another url link with different time stamp format.

```<code>set grid
set xl "Time"
set yl "Temp(\260C)"
set xdata time
set timefmt "%b %d %H:%M:%S %Y"
set format x "%H:%M\n%d/%m"
set multiplot layout 2, 1 title "MASER Temperature data" font ",10"
plot "<wget -q -O - http://hmtmp/~elab/MaserTemperature/temp/Feb05_2022.TEMP" using 2:6 w l title "Sensor-A", \
"<wget -q -O - http://hmtmp/~elab/MaserTemperature/temp/Feb05_2022.TEMP" using 2:10 w l title "Sensor-E", \
"<wget -q -O - http://hmtmp/~elab/MaserTemperature/temp/Feb05_2022.TEMP" using 2:15 w l title "Sensor-J"
pause 2
reread
</code>```

答:
You are using the older syntax where you set the input fimeformat via set xdata time and set timefmt.
You can also set the input timeformat individually in the plot command without set xdata time.
Check help timecolumn. Note that in the first case you have to plot column 5 and in the second case column 3 as y-values.

Code:

```<code>### two different input timeformats in the same plot
reset session

$Data1 <<EOD
Feb 28 18:30:37 2022    1
Mar 29 18:30:38 2022    2
Apr 30 18:30:39 2022    3
EOD

$Data2 <<EOD
02/28/2022 18:30:37     2
03/29/2022 18:30:37     3
04/30/2022 18:30:37     4
EOD

set format x "%b %d\n%Y" time
set key top left

plot $Data1 u (timecolumn(1,"%b %d %H:%M:%S %Y")):5 w lp pt 7 lc "red"  ti "Data1", \
     $Data2 u (timecolumn(1,"%m/%d/%Y %H:%M:%S")):3 w lp pt 7 lc "blue" ti "Data2"
### end of code
</code>```

Result:

Body:
I tried the following script, also i need add another url link with different time stamp format.

set grid
set xl "Time"
set yl "Temp(\260C)"
set xdata time
set timefmt "%b %d %H:%M:%S %Y"
set format x "%H:%M\n%d/%m"
set multiplot layout 2, 1 title "MASER Temperature data" font ",10"
plot "<wget -q -O - http://hmtmp/~elab/MaserTemperature/temp/Feb05_2022.TEMP" using 2:6 w l title "Sensor-A", \
"<wget -q -O - http://hmtmp/~elab/MaserTemperature/temp/Feb05_2022.TEMP" using 2:10 w l title "Sensor-E", \
"<wget -q -O - http://hmtmp/~elab/MaserTemperature/temp/Feb05_2022.TEMP" using 2:15 w l title "Sensor-J"
pause 2
reread

Body:
You are using the older syntax where you set the input fimeformat via set xdata time and set timefmt.
You can also set the input timeformat individually in the plot command without set xdata time.
Check help timecolumn. Note that in the first case you have to plot column 5 and in the second case column 3 as y-values.

Code:

### two different input timeformats in the same plot
reset session

$Data1 <<EOD
Feb 28 18:30:37 2022    1
Mar 29 18:30:38 2022    2
Apr 30 18:30:39 2022    3
EOD

$Data2 <<EOD
02/28/2022 18:30:37     2
03/29/2022 18:30:37     3
04/30/2022 18:30:37     4
EOD

set format x "%b %d\n%Y" time
set key top left

plot $Data1 u (timecolumn(1,"%b %d %H:%M:%S %Y")):5 w lp pt 7 lc "red"  ti "Data1", \
     $Data2 u (timecolumn(1,"%m/%d/%Y %H:%M:%S")):3 w lp pt 7 lc "blue" ti "Data2"
### end of code

Result:


问:
Spring Boot: Load common config application properties file using bootstrap.yml
In our config server we have following application properties files:

```<code>helloApp-dev.properties //dev env properties
helloApp-commonConfig.properties //common properties across env
</code>```

The properties are accessible from URI like:

```<code>https://myapp.abc.com/1234/helloApp-dev.properties
https://myapp.abc.com/1234/helloApp-commonConfig.properties
</code>```

Below is our bootstrap.yml of helloApp application:

```<code>---
spring:
  application:
    name: helloApp

---
spring
  profiles: dev
  cloud:
    config:
      label: 1234
      name: {spring.application.name}
      uri: https://myapp.abc.com/
</code>```

I am using Spring boot version 2.2.4. The helloApp-dev.properties are loading successfully in application but not commonConfig.

答:
To load properties file, profiles should match.
You have 2 solutions:

Rename helloApp-commonConfig.properties -> helloApp.properties

Use multiple profiles for your application (dev, commonConfig)

Body:
In our config server we have following application properties files:

helloApp-dev.properties //dev env properties
helloApp-commonConfig.properties //common properties across env

The properties are accessible from URI like:

https://myapp.abc.com/1234/helloApp-dev.properties
https://myapp.abc.com/1234/helloApp-commonConfig.properties

Below is our bootstrap.yml of helloApp application:

---
spring:
  application:
    name: helloApp

---
spring
  profiles: dev
  cloud:
    config:
      label: 1234
      name: {spring.application.name}
      uri: https://myapp.abc.com/

I am using Spring boot version 2.2.4. The helloApp-dev.properties are loading successfully in application but not commonConfig.


问:
What is the Difference between "\" and "/"?
For Example This Both are Opening same path

C:\Users\XYZ\Pictures

C:/Users/XYZ/Pictures/

答: Actually,It's a historical problem.Traditional NT and DOS operating system uses "\" as an internal expression in VFS path.But UNIX-like system uses "/".Also,many complier considers backslash as escape character e.g."\n \r".So to facilitate the porting of different platforms and the communication across computer systems, Windows now also supports splash as a path separator.</p>


问:
Alternatives ways to getting the properties of the file?
Background:

I have a file monitoring service that watches for changes in the files on the local system using the FileSystemWatcher class and i am handling for events like Created,Deleted,Renamed. When these events are triggered,I would simply want to GET THE PROPERTIES OF THE FILE such as FileName,FileSize,CreationTime,LastAccessTime,LastWriteTime using the FileSystemInfo class.

Problem:

While this service is running, I am unable to uninstall some programs for example (Microsoft Security Essentials). I have a feeling that these service is HANGING ON TO THE RESOURCES of the files marked for deletion because I can only uninstall those programs if only this service is running.

My Question is how can I GET THE PROPERTIES OF THE FILE (as specified above) in an ALTERNATIVE & efficient way without hanging on to the resources of the file ?

Here is my code using the FileSystemInfo

```<code>public void OnCreate/OnRenamed(object source, FileSystemEventArgs e)

{ FileInfo file = new FileInfo(e.FullPath);

String output = "<Event><TimeStamp>" + currentTime + "</TimeStamp>";
            output += "<Name>" + action + "</Name>";
            output += "<Properties><FileName>" + file.Name + "</FileName>";
            output += "<FullPath>" + file.FullName + "</FullPath>";
            output += "<FileSize>" + file.Length + "</FileSize>";
            output += "<CreationTime>" + String.Format("{0:yyyyMMdd-HHmmss.fff}", file.CreationTime) + "</CreationTime>";
            output += "<LastAccess>" + String.Format("{0:yyyyMMdd-HHmmss.fff}", file.LastAccessTime) + "</LastAccess>";
            output += "<LastWriteTime>" + String.Format("{0:yyyyMMdd-HHmmss.fff}", file.LastWriteTime = DateTime.Now) + "</LastWriteTime></Properties></Event>";

}
</code>```

Sincerely,
Derek

答:
Using FileSystemInfo will not normally 'hang on' to these files. You have to first figure out what exactly is causing other programs to stuck during uninstallation. Use ProcessMonitor to see what files are being accessed during uninstallation. The tool is pretty self explanatory, you need to filter on file system activity. Read this or google around.

Try to experiment by taking out one thing at a time. I assume these programs get uninstalled successfully when your service is not running. This proves that it is indeed your service that is causing issues. First comment your FileSystemInfo code. See if the problem goes away. Then comment out FileSystemWatcher and see if it helps.

Update: looks like this is offending line:

```<code>file.LastWriteTime = DateTime.Now
</code>```

Try to comment this assignement and see if it solves the problem:

```<code>file.LastWriteTime /* = DateTime.Now */
</code>```

Was this a typo or you really need to write LastWriteTime?

Body:
Background:

I have a file monitoring service that watches for changes in the files on the local system using the FileSystemWatcher class and i am handling for events like Created,Deleted,Renamed. When these events are triggered,I would simply want to GET THE PROPERTIES OF THE FILE such as FileName,FileSize,CreationTime,LastAccessTime,LastWriteTime using the FileSystemInfo class.

Problem:

While this service is running, I am unable to uninstall some programs for example (Microsoft Security Essentials). I have a feeling that these service is HANGING ON TO THE RESOURCES of the files marked for deletion because I can only uninstall those programs if only this service is running.

My Question is how can I GET THE PROPERTIES OF THE FILE (as specified above) in an ALTERNATIVE & efficient way without hanging on to the resources of the file ?

Here is my code using the FileSystemInfo

public void OnCreate/OnRenamed(object source, FileSystemEventArgs e)

{ FileInfo file = new FileInfo(e.FullPath);

String output = "<Event><TimeStamp>" + currentTime + "</TimeStamp>";
            output += "<Name>" + action + "</Name>";
            output += "<Properties><FileName>" + file.Name + "</FileName>";
            output += "<FullPath>" + file.FullName + "</FullPath>";
            output += "<FileSize>" + file.Length + "</FileSize>";
            output += "<CreationTime>" + String.Format("{0:yyyyMMdd-HHmmss.fff}", file.CreationTime) + "</CreationTime>";
            output += "<LastAccess>" + String.Format("{0:yyyyMMdd-HHmmss.fff}", file.LastAccessTime) + "</LastAccess>";
            output += "<LastWriteTime>" + String.Format("{0:yyyyMMdd-HHmmss.fff}", file.LastWriteTime = DateTime.Now) + "</LastWriteTime></Properties></Event>";

}

Sincerely,
Derek

Body:
Using FileSystemInfo will not normally 'hang on' to these files. You have to first figure out what exactly is causing other programs to stuck during uninstallation. Use ProcessMonitor to see what files are being accessed during uninstallation. The tool is pretty self explanatory, you need to filter on file system activity. Read this or google around.

Try to experiment by taking out one thing at a time. I assume these programs get uninstalled successfully when your service is not running. This proves that it is indeed your service that is causing issues. First comment your FileSystemInfo code. See if the problem goes away. Then comment out FileSystemWatcher and see if it helps.

Update: looks like this is offending line:

file.LastWriteTime = DateTime.Now

Try to comment this assignement and see if it solves the problem:

file.LastWriteTime /* = DateTime.Now */

Was this a typo or you really need to write LastWriteTime?


答:
You can move the selected state in PackageChoose to App level.

In App.js define the selected state and pass as props.

```<code>export default function App() {
  const [selected, setSelected] = useState(1);
  ...
  ...

        <PackageChoose
          ...
          ...
          selected={selected}
          setSelected={setSelected}
        />
}
</code>```

In PackageChoose use the props passed above and remove the local selected state.

```<code>const PackageChoose = ({ setCurrent, data, setData, setSelected, selected }) => {
</code>```

Title: How to keep already chosen value in ReactJS

Body:
I have following code.

What I'm trying to do is, in the first step, select one of the elements, store it in my state, and in the last step, console.log all my data. Also, the user can go from the last step to the first and change what he chose before. But the problem is that I can't save what the user selects for the first time.

For example, if the user selects the second one, and then on the last step they go back, then the first one is displayed as selected. How can I fix this?

here is my code

App.js

     const [current, setCurrent] = useState(0);
      const [data, setData] = useState({
        firstName: "AAA",
        lastName: "BBB",
        age: 26
      });
      const steps = [
        {
       content: (
        <PackageChoose setCurrent={setCurrent} data={data} setData={setData} />
        ),
        id: 0
       },
       {
        content: <LastStep setCurrent={setCurrent} data={data} />,
        id: 1
       }
     ];
     return (

{steps[current].content}

     );

packageChoose (or first step)

   const PackageChoose = ({ setCurrent, data, setData }) => {
     const [selected, setSelected] = useState(1);
     const [packageType, setPackageType] = useState(data.package || "choice");
     return (

 {
            setPackageType("choice");
            setData({ ...data, packageType: packageType });
          }}
         >
           <SelectCard
             id={1}
             selected={selected}
             onSelect={setSelected}
             text="text 1"
          />

 {
            setPackageType("select");
           setData({ ...data, packageType: packageType });
          }}
        >
         <SelectCard
           id={2}
          selected={selected}
          onSelect={setSelected}
          text="text 2"
        />

        <button onClick={() => setCurrent(1)}>Next</button>

     );
   };

Last step

    const LastStep = ({ setCurrent, data }) => {
    return (

         LastStep
         <button
           onClick={() => {
             setCurrent(0);
           }}
         >
           Previous
         </button>
         <button onClick={() => console.log("data===>", data)}> submit </button>

     );
    };

Selected Card reusable component

   const SelectCard = ({ id, selected, onSelect, text }) => {
     const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (

 onSelect(id)}>

 {text}

      );
    };

Please help me to fix this problem.

Body:
You can move the selected state in PackageChoose to App level.

In App.js define the selected state and pass as props.

export default function App() {
  const [selected, setSelected] = useState(1);
  ...
  ...

        <PackageChoose
          ...
          ...
          selected={selected}
          setSelected={setSelected}
        />
}

In PackageChoose use the props passed above and remove the local selected state.

const PackageChoose = ({ setCurrent, data, setData, setSelected, selected }) => {


问:
Why is this code printing a line after reading one line of content
```<code>file = 'pi'
with open(file) as object:
    for line in object:
        print(line)
</code>```

The file content includes the first 30 digits of pi, and I don't understand why it is printing a line after reading a particular line. As in, how can print(line) actually print a line?

The contents of the file are henceforth:

```<code>3.1415926535
8979323846
2643383279
</code>```

And this is the output:

```<code>3.1415926535

8979323846

2643383279
</code>```

答:
The line strings that you are looping include a newline character at the end ("\n"), and print also adds a newline after the call, so you have two. Instead, you can strip the newline character before printing:

file = 'pi'
with open(file) as object:
    for line in object:
        print(line.strip("\n"))
```

Body:
file = 'pi'
with open(file) as object:
    for line in object:
        print(line)

The file content includes the first 30 digits of pi, and I don't understand why it is printing a line after reading a particular line. As in, how can print(line) actually print a line?

The contents of the file are henceforth:

3.1415926535
8979323846
2643383279

And this is the output:

3.1415926535

8979323846

2643383279


问:
How to get the BUILD_USER in Jenkins when job triggered by timer?
I wanted to show the user who triggered a Jenkins job in the post job email. This is possible by using the plugin Build User Vars Plugin and the env variable BUILD_USER.
But this variable do not get initialized when the job is triggered by a scheduler.

How can we achieve this? I know we have a plugin called - EnvInject Plugin, and that can be used...

But I just want to know how we can use this and achieve the solution...

答:
How to return Username & UserId:

UserName: currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserName()

UserId: currentBuild.rawBuild.getCause(Cause.UserIdCause).getUserId()


问:
Python BeautifulSoup: Loop through elements to strip whitespace from within a function
I am trying to write a function that I can reuse to strip whitespace from scraped elements. I am scraping h2, li and p tags; they are currently being returned as <tag>    string    </tag> and I'd like to remove the whitespace and save the content back using *.get_text(strip=True).

h_content = soup.select('h2') will store all the h2 tags found.

p_content = soup.select('p') will store all the p tags found.

And so on.

I have been trying this but am not sure how to return the items to the original location, that is to say, return them here --> *_content

```<code>def remove_whitespace(tags):
    for item in tags:
        item.get_text(strip=True)
        return item
</code>```

The ideal situation is to end up with a function that I can reuse.

remove_whitespace(*_content)

答:
Using "return" exits the function after the first iteration. You need to do something like this to stop that from happening:</p>
```<code>def remove_whitespace(tags):
    res=[]
    for item in tags:
        res.append(item.get_text(strip=True))
    return res
</code>```

Body:
I am trying to write a function that I can reuse to strip whitespace from scraped elements. I am scraping h2, li and p tags; they are currently being returned as <tag>    string    </tag> and I'd like to remove the whitespace and save the content back using *.get_text(strip=True).

h_content = soup.select('h2') will store all the h2 tags found.

p_content = soup.select('p') will store all the p tags found.

And so on.

I have been trying this but am not sure how to return the items to the original location, that is to say, return them here --> *_content

def remove_whitespace(tags):
    for item in tags:
        item.get_text(strip=True)
        return item

The ideal situation is to end up with a function that I can reuse.

remove_whitespace(*_content)

Body:
Using "return" exits the function after the first iteration. You need to do something like this to stop that from happening:

def remove_whitespace(tags):
    res=[]
    for item in tags:
        res.append(item.get_text(strip=True))
    return res


问:
iOS15 polyline does not show on mapView
I tried to add a polyline from the user's location to destination by using the following code, I am sure that I have conformed to the delegate and ensure that the user is in authorizedAlway mode in the authorization status. However, the console generated this error message saying "[UserSession] maps short session requested but session sharing is not enabled" I can not find anything related on how to solve this error.

```<code>    func generatePolyLine(toDestination destination: MKMapItem) {

    let request = MKDirections.Request()
    //start from the user's current location to find the ride
    request.source = MKMapItem.forCurrentLocation()
    request.destination = destination
    request.transportType = .automobile

    let directionRequest = MKDirections(request: request)

    directionRequest.calculate { response, error in
        if let error = error {
            print("Error calculating direction request \(error)")
        }
        guard let response = response else { return }
        self.route = response.routes.first
        guard let polyLine = self.route?.polyline else { return }
        self.mapView.addOverlay(polyLine, level: .aboveRoads)

    }
}
</code>```

答:
Did you add the delegate method to specify the renderer? Something like:</p>
```<code>func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polyline = overlay as? MKPolyline {
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.lineWidth = 3.0
        renderer.alpha = 0.5
        renderer.strokeColor = UIColor.blue

        return renderer
    }
    if let circle = overlay as? MKCircle {
        let renderer = MKCircleRenderer(circle: circle)
        renderer.lineWidth = 3.0
        renderer.alpha = 0.5
        renderer.strokeColor = UIColor.blue

        return renderer
    }
    return MKCircleRenderer()
}
</code>```

Title: iOS15 polyline does not show on mapView

Body:
I tried to add a polyline from the user's location to destination by using the following code, I am sure that I have conformed to the delegate and ensure that the user is in authorizedAlway mode in the authorization status. However, the console generated this error message saying "[UserSession] maps short session requested but session sharing is not enabled" I can not find anything related on how to solve this error.

    func generatePolyLine(toDestination destination: MKMapItem) {

    let request = MKDirections.Request()
    //start from the user's current location to find the ride
    request.source = MKMapItem.forCurrentLocation()
    request.destination = destination
    request.transportType = .automobile

    let directionRequest = MKDirections(request: request)

    directionRequest.calculate { response, error in
        if let error = error {
            print("Error calculating direction request \(error)")
        }
        guard let response = response else { return }
        self.route = response.routes.first
        guard let polyLine = self.route?.polyline else { return }
        self.mapView.addOverlay(polyLine, level: .aboveRoads)

    }
}

Body:
Did you add the delegate method to specify the renderer? Something like:

func mapView(_ mapView: MKMapView, rendererFor overlay: MKOverlay) -> MKOverlayRenderer {
    if let polyline = overlay as? MKPolyline {
        let renderer = MKPolylineRenderer(polyline: polyline)
        renderer.lineWidth = 3.0
        renderer.alpha = 0.5
        renderer.strokeColor = UIColor.blue

        return renderer
    }
    if let circle = overlay as? MKCircle {
        let renderer = MKCircleRenderer(circle: circle)
        renderer.lineWidth = 3.0
        renderer.alpha = 0.5
        renderer.strokeColor = UIColor.blue

        return renderer
    }
    return MKCircleRenderer()
}