问:
Text in input field is smaller on form initialization, why?
When I am opening my website, input fields are filled, but text in input fields is small. If I click somewhere on the page, then it is bigger. I don't know what is going on, text in input fields should has 17px always. I am using bootstrap v3.3.6. This is my html:

.form-bg {
  background: #00b4ef;
}

.form-horizontal {
  background: #fff;
  padding-bottom: 40px;
  border-radius: 15px;
  text-align: center;
  margin-top: 100px;
  margin-bottom: 100px;
}

.form-horizontal .heading {
  display: block;
  font-size: 35px;
  font-weight: 700;
  padding: 35px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 30px;
}

.form-horizontal .form-group {
  padding: 0 40px;
  margin: 0 0 25px 0;
  position: relative;
}

.form-horizontal .form-control {
  background: #f0f0f0;
  border: none;
  border-radius: 20px;
  box-shadow: none;
  padding: 0 20px 0 45px;
  height: 40px;
  transition: all 0.3s ease 0s;
  font-size: 17px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><body>
  <div class="container body-content">

    <div class="form-bg">
      <div class="container">
        <div class="row">
          <div class="col-md-offset-3 col-md-6">

            <form method="post" class="form-horizontal" novalidate="novalidate">
              <span class="heading">Logowanie</span>

              <div class="form-group">
                <input class="form-control valid" placeholder="Email" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="" aria-describedby="Input_Email-error"
                  aria-invalid="false">
                <i class="fa fa-user"></i>
                <span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>
              </div>
            </form>

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

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

答:
There's something wrong elsewhere, it works properly the way you have it posted. Run the snippet below. Make sure that there no :focus class with a different font size.

    .form-bg {
        background: #00b4ef;
    }

    .form-horizontal {
        background: #fff;
        padding-bottom: 40px;
        border-radius: 15px;
        text-align: center;
        margin-top: 100px;
        margin-bottom: 100px;
    }

    .form-horizontal .heading {
        display: block;
        font-size: 35px;
        font-weight: 700;
        padding: 35px 0;
        border-bottom: 1px solid #f0f0f0;
        margin-bottom: 30px;
    }

    .form-horizontal .form-group {
        padding: 0 40px;
        margin: 0 0 25px 0;
        position: relative;
    }

    .form-horizontal .form-control {
        background: #f0f0f0;
        border: none;
        border-radius: 20px;
        box-shadow: none;
        padding: 0 20px 0 45px;
        height: 40px;
        transition: all 0.3s ease 0s;
        font-size: 17px;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <body>
        <div class="container body-content">

            <div class="form-bg">
                <div class="container">
                    <div class="row">
                        <div class="col-md-offset-3 col-md-6">

                            <form method="post" class="form-horizontal" novalidate="novalidate">
                                <span class="heading">Logowanie</span>

                                <div class="form-group">
                                    <input class="form-control valid" placeholder="Email" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="" aria-describedby="Input_Email-error" aria-invalid="false">
                                    <i class="fa fa-user"></i>
                                    <span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>
                                </div>
                            </form>

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

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

Body:
When I am opening my website, input fields are filled, but text in input fields is small. If I click somewhere on the page, then it is bigger. I don't know what is going on, text in input fields should has 17px always. I am using bootstrap v3.3.6. This is my html:

.form-bg {
  background: #00b4ef;
}

.form-horizontal {
  background: #fff;
  padding-bottom: 40px;
  border-radius: 15px;
  text-align: center;
  margin-top: 100px;
  margin-bottom: 100px;
}

.form-horizontal .heading {
  display: block;
  font-size: 35px;
  font-weight: 700;
  padding: 35px 0;
  border-bottom: 1px solid #f0f0f0;
  margin-bottom: 30px;
}

.form-horizontal .form-group {
  padding: 0 40px;
  margin: 0 0 25px 0;
  position: relative;
}

.form-horizontal .form-control {
  background: #f0f0f0;
  border: none;
  border-radius: 20px;
  box-shadow: none;
  padding: 0 20px 0 45px;
  height: 40px;
  transition: all 0.3s ease 0s;
  font-size: 17px;
}

            <form method="post" class="form-horizontal" novalidate="novalidate">
              Logowanie

                <input class="form-control valid" placeholder="Email" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="" aria-describedby="Input_Email-error"
                  aria-invalid="false">

            </form>

Body:
There's something wrong elsewhere, it works properly the way you have it posted. Run the snippet below. Make sure that there no :focus class with a different font size.

    .form-bg {
        background: #00b4ef;
    }

    .form-horizontal {
        background: #fff;
        padding-bottom: 40px;
        border-radius: 15px;
        text-align: center;
        margin-top: 100px;
        margin-bottom: 100px;
    }

    .form-horizontal .heading {
        display: block;
        font-size: 35px;
        font-weight: 700;
        padding: 35px 0;
        border-bottom: 1px solid #f0f0f0;
        margin-bottom: 30px;
    }

    .form-horizontal .form-group {
        padding: 0 40px;
        margin: 0 0 25px 0;
        position: relative;
    }

    .form-horizontal .form-control {
        background: #f0f0f0;
        border: none;
        border-radius: 20px;
        box-shadow: none;
        padding: 0 20px 0 45px;
        height: 40px;
        transition: all 0.3s ease 0s;
        font-size: 17px;
    }

    <body>
        <div class="container body-content">

            <div class="form-bg">
                <div class="container">
                    <div class="row">
                        <div class="col-md-offset-3 col-md-6">

                            <form method="post" class="form-horizontal" novalidate="novalidate">
                                <span class="heading">Logowanie</span>

                                <div class="form-group">
                                    <input class="form-control valid" placeholder="Email" type="email" data-val="true" data-val-email="The Email field is not a valid e-mail address." data-val-required="The Email field is required." id="Input_Email" name="Input.Email" value="" aria-describedby="Input_Email-error" aria-invalid="false">
                                    <i class="fa fa-user"></i>
                                    <span class="text-danger field-validation-valid" data-valmsg-for="Input.Email" data-valmsg-replace="true"></span>
                                </div>
                            </form>

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

        </div>
    </body>


来源: stackexchange

问:
All saved personal queries disappeared in Google BigQuery
Today I loged in to BigQuery and found all of my saved personal queries disappeared. It says No saved queries yet. Write and save a query to get started.

I had a lot of large queries that I still need and I have no desire to rewrite it from scratch.

Project queries are still there, I can perform new queries and go through query history. I tried to log out and log in several times with zero effect. Have someone encountered this kind of issue before?

I would appreciate any help!

Update: I submitted the bug to Google's Issue Tracker https://issuetracker.google.com/issues/119349142

答: As per the latest update, this is where you can find saved queries:

ContentLicense: CC BY-SA 4.0


问:
Count unique register in numpy array
I have a numpy array with letters "a", "b" or "c",

```<code>import numpy as np

my_array = np.array(["a", "a", "c", "c", "a"]) # In this example "b" is not present

</code>```

I want to fuild a function f that counts the unique records of each letter present in the array, for my example f should respond [3, 0, 2] meaning that "a" has appeared 3 times, "b" 0 times and "c" 2 times.

I'm looking for solution (if it possible) that use numpy functions and not explicit for loops over the array. Maybe a kind of group by

答:
You can also use np.unique with return_counts=True, and just convert it to a dict with dict + zip:

```<code>dct = dict(zip(*np.unique(my_array, return_counts=True)))
</code>```

Output:

```<code>>>> dct
{'a': 3, 'c': 2}
</code>```

For smaller arrays, Lucas's answer is faster, but for large arrays, numpy is much more efficient.

Title: Count unique register in numpy array

Body:
I have a numpy array with letters "a", "b" or "c",

import numpy as np

my_array = np.array(["a", "a", "c", "c", "a"]) # In this example "b" is not present

I want to fuild a function f that counts the unique records of each letter present in the array, for my example f should respond [3, 0, 2] meaning that "a" has appeared 3 times, "b" 0 times and "c" 2 times.

I'm looking for solution (if it possible) that use numpy functions and not explicit for loops over the array. Maybe a kind of group by

Body:
You can also use np.unique with return_counts=True, and just convert it to a dict with dict + zip:

dct = dict(zip(*np.unique(my_array, return_counts=True)))

Output:

>>> dct
{'a': 3, 'c': 2}

For smaller arrays, Lucas's answer is faster, but for large arrays, numpy is much more efficient.


问:
Cant see any page on magento
I am facing the following problem

http://www.theprinterdepot.net/hp-5000dn-printer-refurbished.html

all product pages are blank, but if you go to the homepage, or a category page or a search results page its working.

ini errors in enabled so I have no idea where to look for the error.

答:
I solved this my self after clearing all magento cache. I also had to put the old theme I was using, the creators of the theme told me that it only allows magento 1.4.1.1 to 1.5.1.1 and my installation was 1.4.0.1.

I think that was the problemm

ContentLicense: CC BY-SA 3.0

Title: Cant see any page on magento


问:
How to await inside RxJS subscribe method
Inside of an RxJS subject's subscribe callback, I want to await on an async function. Below is a code example which the typescript transpiler complains about saying:

Error:(131, 21) TS2304:Cannot find name 'await'.

```<code>async ngOnInit() {
  this.subscriber = dateSubscription.subscribe((date: Date) => {
    let dbKey = await this._someService.saveToDatabase(someObject);
    // wait for db write to finish before evaluating the next code
    // ... some other code here
  });
}
</code>```

Usually I see this when trying to call await inside a non async function. Do I somehow need to make the subscribe callback async or am I going about this wrong? The function saveToDatabase is async and returns a promise resolving to the database primary key that was written to.

答:
Rxjs in 2022: use pipe and concatMap

I ended up here looking for the ability to await processing expensive items before listening to the next published item. I had to alter my code from async inside the subscribe handler to use a pipe and concatMap as per this other similar SO question.

OLD code, does not wait for expensive call on item before handling new items (thus race conditions abound in my case):

```<code>myObservable$.subscribe(async (item) => { await expensiveFoo(item); })
</code>```

NEW code, does await expensive function before processing next item.

```<code>let subscription = myObservable$.pipe(
    concatMap(async (item) => { await expensiveFoo(item); })
).subscribe(
    (item) => simpleFoo(item),// can also handle sync code here if you want
    (error) => handleError(error),
    () => handleComplete()
);
</code>```

Be sure to keep around a reference to the subscription (it isn't the subscriber) until you're done with the observable.

Body:
Inside of an RxJS subject's subscribe callback, I want to await on an async function. Below is a code example which the typescript transpiler complains about saying:

Error:(131, 21) TS2304:Cannot find name 'await'.

async ngOnInit() {
  this.subscriber = dateSubscription.subscribe((date: Date) => {
    let dbKey = await this._someService.saveToDatabase(someObject);
    // wait for db write to finish before evaluating the next code
    // ... some other code here
  });
}

Usually I see this when trying to call await inside a non async function. Do I somehow need to make the subscribe callback async or am I going about this wrong? The function saveToDatabase is async and returns a promise resolving to the database primary key that was written to.

Body:
Rxjs in 2022: use pipe and concatMap

I ended up here looking for the ability to await processing expensive items before listening to the next published item. I had to alter my code from async inside the subscribe handler to use a pipe and concatMap as per this other similar SO question.

OLD code, does not wait for expensive call on item before handling new items (thus race conditions abound in my case):

myObservable$.subscribe(async (item) => { await expensiveFoo(item); })

NEW code, does await expensive function before processing next item.

let subscription = myObservable$.pipe(
    concatMap(async (item) => { await expensiveFoo(item); })
).subscribe(
    (item) => simpleFoo(item),// can also handle sync code here if you want
    (error) => handleError(error),
    () => handleComplete()
);

Be sure to keep around a reference to the subscription (it isn't the subscriber) until you're done with the observable.


问:
Outlook add-in sync events
Developing an outlook add-in you can add buttons which for example allow you to add additional meta information to a meeting event. Assume you have an add-in that links events with an external system when user presses a button.

Now that is all fine but now the user can also delete the event and in this case you also want to delete it on your external system. Now there are no easy events you can just register to.

You seem to have the option to subscribe for event web-hooks on the graph api on the behalf of the user. However such a subscription has the maximum lifetime of 3 days. Alternatively you could also use the deltaAPI to detect potential deletion of calendar events.

But your add-in does only run when the user clicks a button and only then you could renew an event subscription or execute a delta query. But then you see that there exists also event based activation possibilities that you could consider. You could use it to renew web-hook event subscriptions if needed or execute delta-queries directly to detect changes. Now it seems event-based add-in is a special kind of add-in you cannot easily distributed as the docs state:

Important

Event-based add-ins are restricted to admin-managed deployments only.
For now, users can't get event-based add-ins from AppSource or in-app
Office Store. To learn more, refer to AppSource listing options for
your event-based Outlook add-in.

And even it does not pair easily with SSO which obviously you need because you need access-tokens to subscribe for web-hooks or execute delta queries.

So in this Microsoft office add-in world: What is the idea to react on deleted events? How is this possible in a feasible way? Right now it feels like fighting a crazy three feeted drunk dragon rolling in circles around a green stone (or imagine something else that does not make sense) with nothing more than a bendable pencil made of plastic.

答:
You are absolutely right - web add-ins are limited in their functionality. All that you could do is to use Graph API. Outlook web add-ins are designed for running under the context of currently selected item only. As soon as the add-in is activated for the item you can run the code to make Graph API calls.

Unlike web add-ins, VSTO provides a rich set of API that doesn't require making Graph API calls. But in that case there is a big limitation for using such add-ins - Outlook desktop on Windows only.

Be aware, that Graph API can be called from any application, not only from web add-ins. So, may be you will think about a possible implementation without add-ins involved. Or your web add-in may call an external web service (yours) where it could make the required Graph API calls. Read  more about that in the Scenario: Implement single sign-on to your service in an Outlook add-in article.

Title: Outlook add-in sync events


问:
How can I load different images for mobile with Slick Slider?
I try to create mobile version of slick slider (it should display different images on mobile).

Is it any simple way to do that without adding second time very similar code with changes image src or I should build next div slider and hide/show on mobile version.

答:
Just a little touch of js

js

```<code>let imgs = [
  '<img class="desktop" src="./assets/joursHardtopImage.png"/>',
  '<img class="desktop" src="./assets/joursHardtopImage.png"/>',
]
let mobileImgs = [
  '<img class="mobile" src="./assets/joursMobileImage.png"/>',
  '<img class="mobile" src="./assets/joursMobileImage.png"/>',
]

if($( window ).width() < 600){
  for (let i = 0; i < mobileImgs.length; i++) {
    $('.carousel').append(mobileImgs [i])
  }
}else{
   for (let j = 0; j < imgs.length; j++) {
    $('.carousel').append(imgs[j])
  }

//carousel section

$('.carousel').slick({
  speed: 1000,
  slidesToShow: 1,
  slidesToScroll: 1,
  prevArrow: '<button class="slide-arrow prev-arrow"></button>',
  nextArrow: '<button class="slide-arrow next-arrow"></button>',
 });
</code>```

html

```<code><div class="carousel">

</div>
</code>```

Body:
Just a little touch of js

js

let imgs = [
  '<img class="desktop" src="./assets/joursHardtopImage.png"/>',
  '<img class="desktop" src="./assets/joursHardtopImage.png"/>',
]
let mobileImgs = [
  '<img class="mobile" src="./assets/joursMobileImage.png"/>',
  '<img class="mobile" src="./assets/joursMobileImage.png"/>',
]

if($( window ).width() < 600){
  for (let i = 0; i < mobileImgs.length; i++) {
    $('.carousel').append(mobileImgs [i])
  }
}else{
   for (let j = 0; j < imgs.length; j++) {
    $('.carousel').append(imgs[j])
  }

//carousel section

$('.carousel').slick({
  speed: 1000,
  slidesToShow: 1,
  slidesToScroll: 1,
  prevArrow: '<button class="slide-arrow prev-arrow"></button>',
  nextArrow: '<button class="slide-arrow next-arrow"></button>',
 });

html

<div class="carousel">

</div>


问:
How to add Row to DataGridView in Visual Basic (Visual Studio)
I want to be able to add a new row to my already existing DataGridView through the use of a button. How do I add this? (Using Visual Basic on Visual Studio)

Here is the Code Filling the DataGridView.

```<code>Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim connection As New SqlConnection(PlaceHolder for String)
    Dim Table As New DataTable()

    Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)

    Adapter.Fill(Table)

    DataGridView1.DataSource = Table
    bind_data()

End Sub
</code>```

答:
Since you are using a DataTable as a datasource, simply add a row to it before you bind

Dim toInsert = Table.NewRow()
Table.Rows.Add(toInsert)
```
<p>If you are doing in a place other than where the initial binding is done, you should first retrieve the DataTable, then add, and rebind</p>
<pre class="lang-vb prettyprint-override"><code>Dim Table = DirectCast(DataGridView1.DataSource, DataTable)
Dim toInsert = Table.NewRow()
Table.Rows.Add(toInsert)
DataGridView1.DataSource = Table
bind_data()
</code>```

Body:
I want to be able to add a new row to my already existing DataGridView through the use of a button. How do I add this? (Using Visual Basic on Visual Studio)

Here is the Code Filling the DataGridView.

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim connection As New SqlConnection(PlaceHolder for String)
    Dim Table As New DataTable()

    Dim Adapter As New SqlDataAdapter("SELECT * FROM TrackMain$", connection)

    Adapter.Fill(Table)

    DataGridView1.DataSource = Table
    bind_data()

End Sub

Body:
Since you are using a DataTable as a datasource, simply add a row to it before you bind

Dim toInsert = Table.NewRow()
Table.Rows.Add(toInsert)

If you are doing in a place other than where the initial binding is done, you should first retrieve the DataTable, then add, and rebind

Dim Table = DirectCast(DataGridView1.DataSource, DataTable)
Dim toInsert = Table.NewRow()
Table.Rows.Add(toInsert)
DataGridView1.DataSource = Table
bind_data()


问:
Git shell function (for aliasing) worked in bash with tab complete but not working in Zsh
The alias I've used with success in bash but no longer works in Zsh looks like this

In .zshrc (previously .bashrc)

```<code># custom git completions
_git_a ()
{
    _git_add
}
_git_b ()
{
    _git_branch
}
_git_c ()
{
    _git_commit
}
_git_co ()
{
    _git_checkout
}
.
.
.

# git alias function
g ()
{
    arg1=$1
    shift
    case "$arg1" in
        a)
            eval git add $@;;
        b)
            eval git branch $@;;
        c)
            eval git commit -m \"$1\";;
        co)
            eval git checkout $@;;
        .
        .
        .
        *)
            eval git $arg1 $@;;
    esac
}

zstyle ':completion:*:*:git:*' script ~/.git-completions-mingit.bash
autoload -Uz compinit && compinit -u
source ~/.mingit.sh
compdef g='git'
</code>```

It used to be the case (in bash) that typing something within the alias such as

```<code>g co<TAB><TAB>
</code>```

would result in the same behavior as

```<code>git checkout<TAB><TAB>
</code>```

but now (in Zsh) the result is that g co<TAB><TAB> cycles through folders and files in the directory.  Is there a way to get the tab completion on g co or other g commands to work the same as git ... when it comes to tab completion?

答:
This can be solved by following the instructions in git-completion.zsh (https://github.com/git/git/blob/master/contrib/completion/git-completion.zsh):

```<code># For example, create a directory '~/.zsh/', copy this file to '~/.zsh/_git',
# and then add the following to your ~/.zshrc file:
#
#  fpath=(~/.zsh $fpath)
#
# You need git's bash completion script installed. By default bash-completion's
# location will be used (e.g. pkg-config --variable=completionsdir bash-completion).
</code>```

Body:
The alias I've used with success in bash but no longer works in Zsh looks like this

In .zshrc (previously .bashrc)

# custom git completions
_git_a ()
{
    _git_add
}
_git_b ()
{
    _git_branch
}
_git_c ()
{
    _git_commit
}
_git_co ()
{
    _git_checkout
}
.
.
.

# git alias function
g ()
{
    arg1=$1
    shift
    case "$arg1" in
        a)
            eval git add $@;;
        b)
            eval git branch $@;;
        c)
            eval git commit -m \"$1\";;
        co)
            eval git checkout $@;;
        .
        .
        .
        *)
            eval git $arg1 $@;;
    esac
}

zstyle ':completion:*:*:git:*' script ~/.git-completions-mingit.bash
autoload -Uz compinit && compinit -u
source ~/.mingit.sh
compdef g='git'

It used to be the case (in bash) that typing something within the alias such as

g co<TAB><TAB>

would result in the same behavior as

git checkout<TAB><TAB>

but now (in Zsh) the result is that g co<TAB><TAB> cycles through folders and files in the directory.  Is there a way to get the tab completion on g co or other g commands to work the same as git ... when it comes to tab completion?

Body:
This can be solved by following the instructions in git-completion.zsh (https://github.com/git/git/blob/master/contrib/completion/git-completion.zsh):

# For example, create a directory '~/.zsh/', copy this file to '~/.zsh/_git',
# and then add the following to your ~/.zshrc file:
#
#  fpath=(~/.zsh $fpath)
#
# You need git's bash completion script installed. By default bash-completion's
# location will be used (e.g. pkg-config --variable=completionsdir bash-completion).


问:
Replace null values to 0 in array
I need to push 0 in users element if the array's length is less than 7.

Example: If array has 2 elements. The rest should have 0 in it's users and _id as the index number.

Please help me to acheive this

```<code> const newUsers = [
    {
        _id: 1,
        users: 8
    },
    {
        _id: 2,
        users: 6
    },
    {
        _id: 3,
        users: 1
    },
    {
        _id: 4,
        users: 8
    },
    {
        _id: 5,
        users: 0
    },
    {
        _id: 7,
        users: 0
    }
]
</code>```

答:
According to this W3Schools article, you can use map operator to change all the users property.

const newUsers = [
    {
        _id: 1,
        users: 8
    },
    {
        _id: 2,
        users: 6
    },
    {
        _id: 3,
        users: 1
    },
    {
        _id: 4,
        users: 8
    },
    {
        _id: 5,
        users: 8
    }
]

if (newUsers.length < 7)
  newUsers.map(x => x.users = 0);

console.log(newUsers)```

Title: Replace null values to 0 in array

Body:
I need to push 0 in users element if the array's length is less than 7.

Example: If array has 2 elements. The rest should have 0 in it's users and _id as the index number.

Please help me to acheive this

 const newUsers = [
    {
        _id: 1,
        users: 8
    },
    {
        _id: 2,
        users: 6
    },
    {
        _id: 3,
        users: 1
    },
    {
        _id: 4,
        users: 8
    },
    {
        _id: 5,
        users: 0
    },
    {
        _id: 7,
        users: 0
    }
]


问:
Firebase Messaging Device Groups
The FCM documentation says that one should use device groups to send to ALL of a user's devices. The API for it, though, is still a legacy API, and I can't get it to work.

I am using code like the following, where project_id is the sender ID and api_key is the Web API Key from the firebase console:

In [9]: headers = {
   ...: 'Accept': 'application/json',
   ...: 'Authorization': f'key={api_key}',
   ...: 'project_id': str(project_id),
   ...: 'Content-Type': 'application/json',
   ...: }

In [10]: response = requests.get('https://fcm.googleapis.com/fcm/notification?notification_key_name=foo-foo', headers=headers)

In [11]: response.status
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-f75033194368> in <module>
----> 1 response.status

AttributeError: 'Response' object has no attribute 'status'

In [12]: response.content
Out[12]: b'\n\n<TITLE>Internal Server Error</TITLE>\n\n\n
Internal Server Error
\n
Error 500
\n\n\n'

In [13]: response.reason
Out[13]: 'Internal Server Error'

In [14]:
```

答:
Ok, the "key" is the "server key" from the cloud messaging tab, and the "project_id" is the "Sender ID" from the same.

That seems to have solved it for me.

Title: Firebase Messaging Device Groups


问:
How to call current temperature from openweathermap with axios
I am trying to do an axios call to get the latest temperature using openweatherapi. However for some reason I cant find out why my axios call is not working. Any help would be great, here is my code:

```<code>function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{apikey}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const response = await axios.get(encodeURI(url));
        const temp = await response.data?.main?.temp;
        setTemperature(temp);
    }

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {getTemperature()}, [longitude, latitude])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"} />
                <OverviewContainer title="Time on app" value={secondsToHms(count)} />
            </View>
        </View>
    );
}
</code>```

Any advice on what im doing wrong would be great!

答:
You should change your getWeather function to the following.

```<code>const getWeather = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${api_key}`);
    setData(response.data.main.temp);
};
</code>```

Body:
I am trying to do an axios call to get the latest temperature using openweatherapi. However for some reason I cant find out why my axios call is not working. Any help would be great, here is my code:

function Overview() {
    const appState = useRef(AppState.currentState);
    const [count, setCount] = useState(0);
    const [active, setActive] = useState(false);
    const [latitude, setLatitude] = useState(0);
    const [longitude, setLongitude] = useState(0);
    const [temperature, setTemperature] = useState('');
    const API_KEY = '{apikey}';

    const getLocationAsync = async () => {
        let {status} = await Location.requestForegroundPermissionsAsync();
        if (status !== 'granted') {
            console.log('Location Permission Error')
        }

        const loc = await Location.getCurrentPositionAsync({});

        setLatitude(loc.coords.latitude);
        setLongitude(loc.coords.longitude);
    }

    const getTemperature = async () => {
        const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;
        const response = await axios.get(encodeURI(url));
        const temp = await response.data?.main?.temp;
        setTemperature(temp);
    }

    useEffect(() => {
        appState.current.match('active') ? setActive(true) : setActive(false)
        active && setInterval(() => setCount((oldCount) => oldCount + 1), 60000);
        getLocationAsync();

        return () => {
            clearInterval();
        };
    }, [active]);

    useEffect(() => {getTemperature()}, [longitude, latitude])

    return (
        <View style={{margin: 32}}>
            <View style={{marginBottom: 32}}>
                <Text style={{fontSize: 36, fontFamily: 'Roboto_400Regular'}}>Great!</Text>
                <Text style={{fontSize: 16, color: '#878787', fontFamily: 'Roboto_400Regular'}}>Average mood 23%</Text>
            </View>
            <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                <OverviewContainer title="Weather" value={temperature ? temperature : "no data"} />
                <OverviewContainer title="Time on app" value={secondsToHms(count)} />
            </View>
        </View>
    );
}

Any advice on what im doing wrong would be great!

Body:
You should change your getWeather function to the following.

const getWeather = async () => {
    const response = await axios.get(`https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${api_key}`);
    setData(response.data.main.temp);
};


问:
Selection and automatic deselection problem
as I stated above, I need help with my c# code which I'm using in unity to make a 3D game.
When I click on an object it should change color and if there was previously another object selected, I need it to be deselected automatically.
I already wrote a code which is supposed to at least help me select(change a material color) but it isn't working.
I am checking if the left mouse button is pressed down and using raycast to check if there is something under a cursor. Also wrote a Selection class with 2 methods(Select/deselect) that are supposed to change color of an object.
I'll be thankful if you can help me.
Here's the code with mouse click:

```<code>public class ClickSelect : MonoBehaviour
{

    private void Update()
    {
        Click();

    }
    public void Click()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                Selectable selectable = hit.collider.gameObject.GetComponent<Selectable>();
                if (selectable)
                {
                    hit.collider.gameObject.GetComponent<Selectable>().Select();
                }

            }
        }
    }

}
</code>```

And this is code of a selection class:

```<code>public class Selectable : MonoBehaviour
{

    public void Select()
    {
        GetComponent<Renderer>().material.color = Color.yellow;
    }

    public void Deselect()
    {
        GetComponent<Renderer>().material.color = Color.gray;
    }
}
</code>```

答:
First you should check if there is a Collider on the Selectable. If not add one. Because you are asking for a Ray that hits a collider and if there's no Collider it will return always null

then this

```<code>Selectable selectable = hit.collider.gameObject.GetComponent<Selectable>();
            if (selectable)
            {
                hit.collider.gameObject.GetComponent<Selectable>().Select();
            }
</code>```

is complete Nonsense
why you get the Selectable in First Place and then the Selectable again?
And you don't need a Collider on it to detect the Transform so you can remove the hit.collider to hit.gameObject or better is hit.transform (Because u don't need the whole GameObject)

```<code>hit.collider.gameObject.TryGetComponent(out Selectable selectable);
//hit.transform.TryGetComponent(out Selectable selectable)
if(selectable != null)
{
 selectable.Select();
}
</code>```

Then instead of

```<code>Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
</code>```

Try

```<code>Ray ray = Camera.main.ViewportPointToRay(Input.mousePosition);
</code>```

hope it helps you, if so, feel free to mark it as solved and correct Answer.

Body:
as I stated above, I need help with my c# code which I'm using in unity to make a 3D game.
When I click on an object it should change color and if there was previously another object selected, I need it to be deselected automatically.
I already wrote a code which is supposed to at least help me select(change a material color) but it isn't working.
I am checking if the left mouse button is pressed down and using raycast to check if there is something under a cursor. Also wrote a Selection class with 2 methods(Select/deselect) that are supposed to change color of an object.
I'll be thankful if you can help me.
Here's the code with mouse click:

public class ClickSelect : MonoBehaviour
{

    private void Update()
    {
        Click();

    }
    public void Click()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hit;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out hit))
            {
                Selectable selectable = hit.collider.gameObject.GetComponent<Selectable>();
                if (selectable)
                {
                    hit.collider.gameObject.GetComponent<Selectable>().Select();
                }

            }
        }
    }

}

And this is code of a selection class:

public class Selectable : MonoBehaviour
{

    public void Select()
    {
        GetComponent<Renderer>().material.color = Color.yellow;
    }

    public void Deselect()
    {
        GetComponent<Renderer>().material.color = Color.gray;
    }
}

Body:
First you should check if there is a Collider on the Selectable. If not add one. Because you are asking for a Ray that hits a collider and if there's no Collider it will return always null

then this

Selectable selectable = hit.collider.gameObject.GetComponent<Selectable>();
            if (selectable)
            {
                hit.collider.gameObject.GetComponent<Selectable>().Select();
            }

is complete Nonsense
why you get the Selectable in First Place and then the Selectable again?
And you don't need a Collider on it to detect the Transform so you can remove the hit.collider to hit.gameObject or better is hit.transform (Because u don't need the whole GameObject)

hit.collider.gameObject.TryGetComponent(out Selectable selectable);
//hit.transform.TryGetComponent(out Selectable selectable)
if(selectable != null)
{
 selectable.Select();
}

Then instead of

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

Try

Ray ray = Camera.main.ViewportPointToRay(Input.mousePosition);

hope it helps you, if so, feel free to mark it as solved and correct Answer.


问:
PM2 and Nginx: 502 Bad Gateway
I've been trying to deploy my Node project on a brand new DO droplet, but i'm having some problems with PM2.

My steps are a follows:

Node came installed on the Droplet image (Ubuntu, Node v4.4.4)

Installed PM2 globally

Setup Nginx to reverse proxy 127.0.0.1:3000

Cloned my project and did npm install

All i get is Nginx complaining about a 502 Bad Gateway.

If i look at the Nginx error.log i get this:

connect() failed (111: Connection refused) while connecting to
  upstream, client: client.ip, server: my.server, request:
  "GET / HTTP/1.1", upstream: "http://127.0.0.1:3000/", host:
  "my.server"

PM2 doesn't have much to say about anything. Nothing in pm2 logs and status is online.

I tried skipping PM2 and just doing npm start which worked perfectly. I also tried setting up a dummy hello world application instead, and using that with PM2 - it also worked.

So this is currently where i'm at:

My project + PM2: doesn't work.

My project without PM2: works.

Hello World app + PM2: works.

I'm not really sure where to go from here.. I could just skip PM2 and use node, but i do want the features of PM2.

Any ideas?

答: In my case I renamed app.js to project.js or something and it works.

Title: PM2 and Nginx: 502 Bad Gateway


问:
Angular OnPush strategy not working with ngFor - always recreates all children
i am trying to build a small framework that renders forms based on provided JSON data which is describing that form's structure. Each form element specified in the data is represented by an angular component at runtime.

Elements in the form can be nested using 'container' form elements. The corresponding component is using an *ngFor loop on an array.

I chose to use OnPush Change Detection which works well - except for the container components which will always recreate all child elements when an array item changes, so when change detection is done on the @inputs, there is nothing to compare to.

I tried to make a reduced example here, hope you get the point.

https://stackblitz.com/github/rpnoll1977/TestNgArray

To be able to tell which parts get recreated, i added some input fields. You can type in some random text. When you hit the button, a new element is added to the list. All elements in the list get recreated - not the others, especially not the input which is in parallel to the *ngfor.

I was able to debug this a bit after providing a tracking function in the *ngFor. In Angular's DefaultIterableDiffer.check it always sets mayBeDirty=true as the record to compare to is equal to null.

Actually i made another example which, instead of *ngfor uses a series of *ngIfs (with conditions about the length of the array being smaller than the position of the *ngif). That shows correct behavior, only re-rendering the added item.

答:
You should pay attention on how you're updating your model and how you use trackBy feature.

You're expecting that items in model for ngFor stay the same.

```<code>tracker(index:number, item:any):any{
  return item;
}
</code>```

That's true for deeply nested items:

```<code>controls: [
  ...this.model.controls[0].controls, <=== they stay the same
  {id:"labelX", type:"l"},
]

this.model.controls[0].controls[0] === newModel.controls[0].controls[0]); => true
</code>```

But that's not true for one container above:

```<code>var newModel = {
  ...this.model,
  controls: [ <=== here you create a completely new array with new objects
    {
    ...

this.model.controls[0] === newModel.controls[0] // false
</code>```

So the solution is to use some identificator for trackBy which is id in your case:

```<code>tracker(index:number, item:any):any{
  return item.id;
}
</code>```

Forked Stackblitz

Body:
You should pay attention on how you're updating your model and how you use trackBy feature.

You're expecting that items in model for ngFor stay the same.

tracker(index:number, item:any):any{
  return item;
}

That's true for deeply nested items:

controls: [
  ...this.model.controls[0].controls, <=== they stay the same
  {id:"labelX", type:"l"},
]

this.model.controls[0].controls[0] === newModel.controls[0].controls[0]); => true

But that's not true for one container above:

var newModel = {
  ...this.model,
  controls: [ <=== here you create a completely new array with new objects
    {
    ...

this.model.controls[0] === newModel.controls[0] // false

So the solution is to use some identificator for trackBy which is id in your case:

tracker(index:number, item:any):any{
  return item.id;
}

Forked Stackblitz


问:
WinUI3: How to sort datagrid groups?
I'm using the Windows Community Toolkit Datagrid.

I am binding the the datagrid's ItemSource to a grouped CollectionViewSource.

<ctWinUI:DataGrid
    ItemsSource="{x:Bind MyCollectioViewSourceView, Mode=OneWay}"
```

By default groups are sorted alphabetically:

How can I implement custom sorting?

(Note I know how to sort datagrid rows, this is specifically for sorting datagrid groups.)

I have seen similar questions for the WPF datagrid, but the WinUI datagrid is different.

答:
Just order the Source of the grouped MyCollectioViewSourceView, e.g.:

```<code>CollectionViewSource cvs= new CollectionViewSource();
cvs.IsSourceGrouped = true;
cvs.Source = groupedItems.OrderByDescending(x => x.Key).ToList();
</code>```

Title: WinUI3: How to sort datagrid groups?

Body:
I'm using the Windows Community Toolkit Datagrid.

I am binding the the datagrid's ItemSource to a grouped CollectionViewSource.

<ctWinUI:DataGrid
    ItemsSource="{x:Bind MyCollectioViewSourceView, Mode=OneWay}"

By default groups are sorted alphabetically:

How can I implement custom sorting?

(Note I know how to sort datagrid rows, this is specifically for sorting datagrid groups.)

I have seen similar questions for the WPF datagrid, but the WinUI datagrid is different.

Body:
Just order the Source of the grouped MyCollectioViewSourceView, e.g.:

CollectionViewSource cvs= new CollectionViewSource();
cvs.IsSourceGrouped = true;
cvs.Source = groupedItems.OrderByDescending(x => x.Key).ToList();


问:
Inserting strings every so many lines with awk
I am trying to insert command strings and having difficulty with my syntax. I'm trying to get the "mv" every other line, "sleep" every third line and "wait" every 4th line. Here is what I got and been playing with different combinations. Any help would be appreciated.</p>
```<code>awk '{ print; print "mv $NEWEST $RNAME"; }' curl.txt > mv.txt
sleep 2
wait
awk 'NR==3{ print "sleep 2"; }1' mv.txt > sleep.txt
sleep 2
wait
awk 'NR==4{ print "wait"; }1' sleep.txt > wait.txt
</code>```

答:
is this what you're trying to do?

```<code>$ seq 5 | sed '1~1a mv $NEWEST $RNAME\nsleep 2\nwait'

1
mv $NEWEST $RNAME
sleep 2
wait
2
mv $NEWEST $RNAME
sleep 2
wait
3
mv $NEWEST $RNAME
sleep 2
wait
4
mv $NEWEST $RNAME
sleep 2
wait
5
mv $NEWEST $RNAME
sleep 2
wait
</code>```

you can change the starting line number and the frequency with 1~1

Body:
I am trying to insert command strings and having difficulty with my syntax. I'm trying to get the "mv" every other line, "sleep" every third line and "wait" every 4th line. Here is what I got and been playing with different combinations. Any help would be appreciated.

awk '{ print; print "mv $NEWEST $RNAME"; }' curl.txt > mv.txt
sleep 2
wait
awk 'NR==3{ print "sleep 2"; }1' mv.txt > sleep.txt
sleep 2
wait
awk 'NR==4{ print "wait"; }1' sleep.txt > wait.txt

Body:
is this what you're trying to do?

$ seq 5 | sed '1~1a mv $NEWEST $RNAME\nsleep 2\nwait'

1
mv $NEWEST $RNAME
sleep 2
wait
2
mv $NEWEST $RNAME
sleep 2
wait
3
mv $NEWEST $RNAME
sleep 2
wait
4
mv $NEWEST $RNAME
sleep 2
wait
5
mv $NEWEST $RNAME
sleep 2
wait

you can change the starting line number and the frequency with 1~1


问:
Vaadin Layout dont Diaply Buttons
Hi am usin Vaadin to code an WebApplication.
I use this Vaadin Addon:
https://vaadin.com/directory/component/carousel-addon

My Problem is that my Button layout only display on the 3rd Carousel Slide and i dont know why.

```<code>private Component crateCarouselSlides(Image iconimage, H1 header, Label infoText) {
    HorizontalLayout buttonLayout = new HorizontalLayout(previousSlideButton,nextSlideButton);
    if(infoText != null){
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,infoText,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }else{
        HorizontalLayout textFields = new HorizontalLayout(new TextField("Name"),new TextField("Playlist"));
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,textFields,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }
}
</code>```

Thanks for your Help. :)

Slide1
Slide3

答:
After long debugging finally the solution.
A button can only be on one slide at a time. If buttons are added to multiple slides, the button is only displayed on the last one. I did not find out why.
Temporarily I will create a new button for each slide. Not nice to read but it works for now.</p>

Title: Vaadin Layout dont Diaply Buttons

Body:
Hi am usin Vaadin to code an WebApplication.
I use this Vaadin Addon:
https://vaadin.com/directory/component/carousel-addon

My Problem is that my Button layout only display on the 3rd Carousel Slide and i dont know why.

private Component crateCarouselSlides(Image iconimage, H1 header, Label infoText) {
    HorizontalLayout buttonLayout = new HorizontalLayout(previousSlideButton,nextSlideButton);
    if(infoText != null){
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,infoText,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }else{
        HorizontalLayout textFields = new HorizontalLayout(new TextField("Name"),new TextField("Playlist"));
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,textFields,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }
}

Thanks for your Help. :)

Slide1
Slide3


问:
How to send data from one screen to another
I've got this problem - I can get variables from the props (being sent from MainContainer which contains navigation and those variables. (item.name, item.coordinates.latitude and item.coordinates.longitude work fine on Primary.js, but I can't get them on Map_map.js.

What i'm trying to do is to send the coords (from MainContainer.js through Primary.js which shows names of cities) into  in Map_map.js.
When it gets there, it should place a marker only on the location of the city I clicked on.

Also, I currently have Map_map in the navigation tab and when I remove it from there, I can't navigate to it anymore so I need help with that as well.

Code:
MainContainer.js

```<code>import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
,
  {
    name: 'Plzeň',
    coordinates: {
      latitude: 49.739296,
      longitude: 13.372455
  }},

  {
    name: 'Karlovy Vary',
    coordinates: {
      latitude: 50.231656,
      longitude: 12.869226
  }},
  {
    name: 'Ústí nad Labem',
    coordinates: {
      latitude: 50.662592,
      longitude: 14.042824
  }},
  {
    name: 'Liberec',
    coordinates: {
      latitude: 50.764136,
      longitude: 15.047840
  }},
  {
    name: 'Hradec Králové',
    coordinates: {
      latitude: 50.210071,
      longitude: 15.829660
  }},
  {
    name: 'Pardubice',
    coordinates: {
      latitude: 50.032558,
      longitude: 15.773678
  }},
  {
    name: 'Jihlava',
    coordinates: {
      latitude: 49.401642,
      longitude: 15.584001
  }},
  {
    name: 'Brno',
    coordinates: {
      latitude: 49.190254,
      longitude: 16.614144
  }},
  {
    name: 'Olomouc',
    coordinates: {
      latitude: 49.590450,
      longitude: 17.259280
  }},
  {
    name: 'Ostrava',
    coordinates: {
      latitude: 49.820469,
      longitude: 18.269387
  }},
  {
    name: 'Zlín',
    coordinates: {
      latitude: 49.224215,
      longitude: 17.668567
  }},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            else if (rn === mapa_det) {
              iconName = focused ? 'locate' : 'locate-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
        <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/>

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;
</code>```

(inside "nav" folder): Primary.js, Secondary.js, Map_map.js

Primary.js

```<code>import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';

export default function Primary(props)
{
    const navigation = useNavigation();
    const map_map = "Map_map";
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.towns.map(item => (
                    <Text
                    style={styles.card}
                    onPress={() => navigation.navigate('Map_map', item.coordinates)}
                    >
                        {item.name}
                        {item.coordinates.latitude }
                        {item.coordinates.longitude}
                    </Text>
                ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });
</code>```

Map_map.js

```<code>import * as React from 'react';
import { StyleSheet, View, Text, Image } from 'react-native';
import Primary from './Primary.js';
import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps';

function ProfileScreen({ navigation: { goBack } }) {
    return (
      <View>
        <Button onPress={() => goBack()} title="Go back from ProfileScreen" />
      </View>
    );
  }

export default function Map_map({ navigation }) {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <MapView
                style={styles.map}
                provider={PROVIDER_GOOGLE}
                //specify our coordinates.
                initialRegion=
                {{
                latitude: 49.061880,
                longitude: 17.349916,
                latitudeDelta: 0.002,
                longitudeDelta: 0.002,
                }}
            >
                <Marker
                    //coordinate={navigation.getParam(item.coordinates)}
                        // latitude: 49.061880,
                        // longitude: 17.349916,

                />
            </MapView>
        </View>
    );
}
const styles = StyleSheet.create({
    map: {
      height: '100%',
      width: '100%'
    },
  });
</code>```

答:
In your Primary.js card onPress, do it like below -</p>
```<code>onPress={() => navigation.navigate('Map_map', {
     data: item.coordinates,
})}
</code>```

Body:
I've got this problem - I can get variables from the props (being sent from MainContainer which contains navigation and those variables. (item.name, item.coordinates.latitude and item.coordinates.longitude work fine on Primary.js, but I can't get them on Map_map.js.

What i'm trying to do is to send the coords (from MainContainer.js through Primary.js which shows names of cities) into  in Map_map.js.
When it gets there, it should place a marker only on the location of the city I clicked on.

Also, I currently have Map_map in the navigation tab and when I remove it from there, I can't navigate to it anymore so I need help with that as well.

Code:
MainContainer.js

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Ionicons from 'react-native-vector-icons/Ionicons';

// Screens
import Primary from './Screens/Primary';
import Secondary from './Screens/Secondary';
import Map_map from './Screens/Map_map';

// Locations
const mesta = [
  {
    name: 'Praha',
    coordinates: {
      latitude: 50.072829,
      longitude: 14.433817
  }},
  ,
  {
    name: 'České Budějovice',
    coordinates: {
      latitude: 48.975250,
      longitude: 14.479161
}},
,
  {
    name: 'Plzeň',
    coordinates: {
      latitude: 49.739296,
      longitude: 13.372455
  }},

  {
    name: 'Karlovy Vary',
    coordinates: {
      latitude: 50.231656,
      longitude: 12.869226
  }},
  {
    name: 'Ústí nad Labem',
    coordinates: {
      latitude: 50.662592,
      longitude: 14.042824
  }},
  {
    name: 'Liberec',
    coordinates: {
      latitude: 50.764136,
      longitude: 15.047840
  }},
  {
    name: 'Hradec Králové',
    coordinates: {
      latitude: 50.210071,
      longitude: 15.829660
  }},
  {
    name: 'Pardubice',
    coordinates: {
      latitude: 50.032558,
      longitude: 15.773678
  }},
  {
    name: 'Jihlava',
    coordinates: {
      latitude: 49.401642,
      longitude: 15.584001
  }},
  {
    name: 'Brno',
    coordinates: {
      latitude: 49.190254,
      longitude: 16.614144
  }},
  {
    name: 'Olomouc',
    coordinates: {
      latitude: 49.590450,
      longitude: 17.259280
  }},
  {
    name: 'Ostrava',
    coordinates: {
      latitude: 49.820469,
      longitude: 18.269387
  }},
  {
    name: 'Zlín',
    coordinates: {
      latitude: 49.224215,
      longitude: 17.668567
  }},
]

//Screen names
const lokace = "Lokace";
const mapa = "Mapa";
const mapa_det = "Mapa_det";

const Tab = createBottomTabNavigator();

function MainContainer() {
  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={lokace}
        screenOptions={({ route }) => ({
          tabBarIcon: ({ focused, color, size }) => {
            let iconName;
            let rn = route.name;

            if (rn === lokace) {
              iconName = focused ? 'home' : 'home-outline';

            } else if (rn === mapa) {
              iconName = focused ? 'map' : 'map-outline';
            }
            else if (rn === mapa_det) {
              iconName = focused ? 'locate' : 'locate-outline';
            }
            // You can return any component that you like here!
            return <Ionicons name={iconName} size={size} color={color} />;
          },
        })}
        tabBarOptions={{
          activeTintColor: '#007aff',
          inactiveTintColor: 'grey',
          labelStyle: { paddingBottom: 10, fontSize: 10 },
          style: { padding: 10, height: 70}
        }}>

        <Tab.Screen name={lokace} children={() => <Primary towns={mesta}/>}/>
        <Tab.Screen name={mapa} children={() => <Secondary towns={mesta}/>}/>
        <Tab.Screen name={mapa_det} component={Map_map}/>

      </Tab.Navigator>
    </NavigationContainer>
  );
}

export default MainContainer;

(inside "nav" folder): Primary.js, Secondary.js, Map_map.js

Primary.js

import * as React from 'react';
import { StyleSheet, ScrollView, View, Text, Image } from 'react-native';
import { useNavigation } from '@react-navigation/native';

export default function Primary(props)
{
    const navigation = useNavigation();
    const map_map = "Map_map";
    return(
        <ScrollView style=
            {{
                flex: 1,
            }}>
            <View>
                {props.towns.map(item => (
                    <Text
                    style={styles.card}
                    onPress={() => navigation.navigate('Map_map', item.coordinates)}
                    >
                        {item.name}
                        {item.coordinates.latitude }
                        {item.coordinates.longitude}
                    </Text>
                ))}
            </View>
            </ScrollView>
    );
}

const styles = StyleSheet.create({
    card:{
        backgroundColor: "#007aff",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
    card2:{
        backgroundColor: "#FF3300",
        borderRadius: 50,
        alignItems: 'center',
        margin: 5,
        padding: 10,
        color: 'white',
        fontWeight: 'bold'
    },
  });

Map_map.js

import * as React from 'react';
import { StyleSheet, View, Text, Image } from 'react-native';
import Primary from './Primary.js';
import MapView, {PROVIDER_GOOGLE, Marker} from 'react-native-maps';

function ProfileScreen({ navigation: { goBack } }) {
    return (
      <View>
        <Button onPress={() => goBack()} title="Go back from ProfileScreen" />
      </View>
    );
  }

export default function Map_map({ navigation }) {
    return (
        <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
            <MapView
                style={styles.map}
                provider={PROVIDER_GOOGLE}
                //specify our coordinates.
                initialRegion=
                {{
                latitude: 49.061880,
                longitude: 17.349916,
                latitudeDelta: 0.002,
                longitudeDelta: 0.002,
                }}
            >
                <Marker
                    //coordinate={navigation.getParam(item.coordinates)}
                        // latitude: 49.061880,
                        // longitude: 17.349916,

                />
            </MapView>
        </View>
    );
}
const styles = StyleSheet.create({
    map: {
      height: '100%',
      width: '100%'
    },
  });

Body:
In your Primary.js card onPress, do it like below -

onPress={() => navigation.navigate('Map_map', {
     data: item.coordinates,
})}


问:
Can't mock default export in tested file
I'm working on a Typescript project and I'm trying to add tests for functions that are sorting through MongoDB responses to get meaningful results. I've set up an in-memory mock of the database, now I just need to somehow get the test to use this mock database when running tests on the functions in my file.

I have a file called mongoClient.ts that is responsible for this MongoClient object that I need to mock:

import { MongoClient } from 'mongodb';

const client = new MongoClient(`${process.env.MONGO_CONNECT}`);

export default client;
```
<p>The file that I need to test, called <code>models.ts</code>, imports <code>mongoClient</code> with an ES6 import statement:</p>
<pre class="lang-js prettyprint-override"><code>import client from '../mongoClient';
</code>```

In my test I have created a MongoMemoryServer (mongodb-memory-server), and I have made a class to handle the connection to this MongoMemoryServer:

class dbConnection {
  server;
  connection;
  uri;
  async init() {
    this.server = await MongoMemoryServer.create();
    this.uri = await this.server.getUri();
    this.connection = await new MongoClient(this.uri);
    return this.connection;
  }

  connect() {
    this.connection.connect();
  }

  getClient() {
    return this.connection;
  }

  getUri() {
    return this.uri;
  }

  async stopIt() {
    await this.server.stop();
  }
}
```
<p>I cannot seem to get the models object that I create in the test (with <code>const models = require('../src/models');</code>) to mock its import of 'mongoClient'.
I've tried the following:</p>
<pre class="lang-js prettyprint-override"><code>let mock_db = new dbConnection();
jest.doMock('../src/mongoClient', () => ({
  __es6Module: true,
  default: mock_db.getClient()
}));
</code>```

I tried to use mock(...) earlier; that throws this error when I run the test:

```<code>The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
</code>```

In a beforeAll(...) I am able to fill this DB with dummy information so my functions in models will run correctly, but these functions can't see the mock in-memory database because I can't properly mock the mongoClient file that gets imported at the top of my models.ts. I don't want to have to change any code that isn't in a .test file to accomplish this, but I can't get this test environment to point at my mock in-memory database while running these tests. I must be missing something about the implementation of doMock, and I need some help to fix it.

- -EDIT_1- - I think this might have something to do with the order in which I'm declaring things. The class dbConnection is declared directly under my imports at the top of the test file. Then under that I instantiate the dbConnection class as mockDb and jest.doMock(... like in the example shown above. My tested function seems to be trying to use a mocked import that only contains the following:

{"__es6Module":true}
```
<p>The error message I'm getting at this point is <code>ERROR --- _get__(...).db is not a function</code>.</p>
<p>The problem with this could be that it's mocking the imported module correctly, but the default export used to mock (<code>mockDb.getClient()</code>)  is undefined when it's declared in that doMock statement near the top of the file. I don't know where else to move that doMock, and it breaks if I move it into the top-level beforeAll or into the describe section for these tests or into the test itself.</p>
<p>- -<strong>EDIT_2</strong>- - Changing <code>__es6Module</code> to <code>__esModule</code>  (because the compiled js file looks for __esModule) makes it so that <code>undefined</code> is the contents of the imported class in my code.</p>
<p>The compiled js code has the following at the top:</p>
<pre class="lang-js prettyprint-override"><code>var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const mongoClient_1 = __importDefault(require("../util/mongoClient"));
</code>```

- -FINAL_EDIT- - I've figured this out, it was an error on my part in how the order of the Jest tests were being executed. The default export client that I was mocking had not been initialized before the tests were being run. This required that I mock the default import in a beforeAll(...) statement inside of each 'describe' block of tests, and in each test I have to instantiate a new models at the start of the test with const models = require(...);. I have working tests now, and everything is good in life ;-)

答: I've figured this out, it was an error on my part in how the order of the Jest tests were being executed. The default export client that I was mocking had not been initialized before the tests were being run. This required that I mock the default import in a beforeAll(...) statement inside of each 'describe' block of tests, and in each test I have to instantiate a new models at the start of the test with const models = require(...);. I have working tests now</p>

Body:
I'm working on a Typescript project and I'm trying to add tests for functions that are sorting through MongoDB responses to get meaningful results. I've set up an in-memory mock of the database, now I just need to somehow get the test to use this mock database when running tests on the functions in my file.

I have a file called mongoClient.ts that is responsible for this MongoClient object that I need to mock:

import { MongoClient } from 'mongodb';

const client = new MongoClient(`${process.env.MONGO_CONNECT}`);

export default client;

The file that I need to test, called models.ts, imports mongoClient with an ES6 import statement:

import client from '../mongoClient';

In my test I have created a MongoMemoryServer (mongodb-memory-server), and I have made a class to handle the connection to this MongoMemoryServer:

class dbConnection {
  server;
  connection;
  uri;
  async init() {
    this.server = await MongoMemoryServer.create();
    this.uri = await this.server.getUri();
    this.connection = await new MongoClient(this.uri);
    return this.connection;
  }

  connect() {
    this.connection.connect();
  }

  getClient() {
    return this.connection;
  }

  getUri() {
    return this.uri;
  }

  async stopIt() {
    await this.server.stop();
  }
}

I cannot seem to get the models object that I create in the test (with const models = require('../src/models');) to mock its import of 'mongoClient'.
I've tried the following:

let mock_db = new dbConnection();
jest.doMock('../src/mongoClient', () => ({
  __es6Module: true,
  default: mock_db.getClient()
}));

I tried to use mock(...) earlier; that throws this error when I run the test:

The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.

In a beforeAll(...) I am able to fill this DB with dummy information so my functions in models will run correctly, but these functions can't see the mock in-memory database because I can't properly mock the mongoClient file that gets imported at the top of my models.ts. I don't want to have to change any code that isn't in a .test file to accomplish this, but I can't get this test environment to point at my mock in-memory database while running these tests. I must be missing something about the implementation of doMock, and I need some help to fix it.

- -EDIT_1- - I think this might have something to do with the order in which I'm declaring things. The class dbConnection is declared directly under my imports at the top of the test file. Then under that I instantiate the dbConnection class as mockDb and jest.doMock(... like in the example shown above. My tested function seems to be trying to use a mocked import that only contains the following:

{"__es6Module":true}

The error message I'm getting at this point is ERROR --- _get__(...).db is not a function.

The problem with this could be that it's mocking the imported module correctly, but the default export used to mock (mockDb.getClient())  is undefined when it's declared in that doMock statement near the top of the file. I don't know where else to move that doMock, and it breaks if I move it into the top-level beforeAll or into the describe section for these tests or into the test itself.

- -EDIT_2- - Changing __es6Module to __esModule  (because the compiled js file looks for __esModule) makes it so that undefined is the contents of the imported class in my code.

The compiled js code has the following at the top:

var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
const mongoClient_1 = __importDefault(require("../util/mongoClient"));

- -FINAL_EDIT- - I've figured this out, it was an error on my part in how the order of the Jest tests were being executed. The default export client that I was mocking had not been initialized before the tests were being run. This required that I mock the default import in a beforeAll(...) statement inside of each 'describe' block of tests, and in each test I have to instantiate a new models at the start of the test with const models = require(...);. I have working tests now, and everything is good in life ;-)


问:
All adb commands
How can I see the list of all commands that ever existed in ADB
For example a backup command is not listed on this page but I use https://web.archive.org/ I can see that once the command was written on the page but today it no longer exists

Is there a place where you can see all the commands? Even those which have been removed from the page?

答:
What you are looking for is adb man page.
You can find that here or by also typing in terminal:</p>
```<code>adb --help
</code>```

Title: All adb commands

Body:
What you are looking for is adb man page.
You can find that here or by also typing in terminal:

adb --help


问:
What is a neat way of breaking out of many for loops at once?
Suppose I need to break out of three or four nested for loops at once at the occurence of some event inside the innermost loop. What is a neat way of doing that?

what I do is use flags like this:

```<code>int i, j, k;
int flag1 = 0;
int flag2 = 0;

for (i = 0; i < 100; i++) {
    for (j = 0; j < 100; j++) {
        for (k = 0; k < 100; k++) {
            if (k == 50) {
                flag1 = 1;
                flag2 = 1;
                break;
            }
        }
        if (flag1 == 1)break;
    }
    if (flag2 == 1)break;
}
</code>```

I don't think this is particularly neat.

How would you accomplish the same thing? (w/o using jumps)

答:
If you absolutely don't want to use goto, set all loop conditions to false:

```<code>int i, j, k;

for (i = 0; i < 100; i++) {
    for (j = 0; j < 100; j++) {
        for (k = 0; k < 100; k++) {
            if (k == 50) {
                i = j = k = INT_MAX;
                break;
            }
        }
    }
}
</code>```

note: a smart optimizing compiler will turn the contents of the if in a jump to the end of the outer-most loop

ContentLicense: CC BY-SA 2.5

Body:
Suppose I need to break out of three or four nested for loops at once at the occurence of some event inside the innermost loop. What is a neat way of doing that?

what I do is use flags like this:

int i, j, k;
int flag1 = 0;
int flag2 = 0;

for (i = 0; i < 100; i++) {
    for (j = 0; j < 100; j++) {
        for (k = 0; k < 100; k++) {
            if (k == 50) {
                flag1 = 1;
                flag2 = 1;
                break;
            }
        }
        if (flag1 == 1)break;
    }
    if (flag2 == 1)break;
}

I don't think this is particularly neat.

How would you accomplish the same thing? (w/o using jumps)

Body:
If you absolutely don't want to use goto, set all loop conditions to false:

int i, j, k;

for (i = 0; i < 100; i++) {
    for (j = 0; j < 100; j++) {
        for (k = 0; k < 100; k++) {
            if (k == 50) {
                i = j = k = INT_MAX;
                break;
            }
        }
    }
}

note: a smart optimizing compiler will turn the contents of the if in a jump to the end of the outer-most loop


问:
Icon-fonts: ligatures in fonts vs font-classes
It's a trend using font-ligatures in icon fonts.
The icon names are stored in the font files as ligatures.

The advantage is: You don't need to create css classes for each icon, and the html code is shorter.

So you can write

arrow-left
```
<p>instead of</p>
<pre class="lang-html prettyprint-override"><code><i class="fa fa-arrow-left"></i>
</code>```

Which version of both has the better browser performance?
(in the 1st example, the CSS file does not contain the additional classes, in the 2nd example, the font does not have any ligatures).

Probably a better performance than both would have this:


```

no icon classes + no ligatures, but then the char codes must not change when more icons are added to the font, and you have to know all char codes. You also could insert the char directly, but the editors probably will not display it.

答:
First what I really dont like is how the "i" tag is used as a short for icon somehow, its used for idiomatic texts.

My prefered way:

```<code><span class="icon">icon-ligature</span>
</code>```

It definetly shortens the css you have to include as you would normaly have a class for each icon.

For performance reason I wouldnt change the approach, but from a font maintainer perspective if you need an additional font icon, you simply add it to the font with the right ligature and you would be done, with the class approach you need to add a class to unicode mapping in css + patch the font.

Body:
It's a trend using font-ligatures in icon fonts.
The icon names are stored in the font files as ligatures.

The advantage is: You don't need to create css classes for each icon, and the html code is shorter.

So you can write

arrow-left

instead of

Which version of both has the better browser performance?
(in the 1st example, the CSS file does not contain the additional classes, in the 2nd example, the font does not have any ligatures).

Probably a better performance than both would have this:



no icon classes + no ligatures, but then the char codes must not change when more icons are added to the font, and you have to know all char codes. You also could insert the char directly, but the editors probably will not display it.

Body:
First what I really dont like is how the "i" tag is used as a short for icon somehow, its used for idiomatic texts.

My prefered way:

<span class="icon">icon-ligature</span>

It definetly shortens the css you have to include as you would normaly have a class for each icon.

For performance reason I wouldnt change the approach, but from a font maintainer perspective if you need an additional font icon, you simply add it to the font with the right ligature and you would be done, with the class approach you need to add a class to unicode mapping in css + patch the font.


问:
How to access has_many through relationship possible in rails?
How can I access my related records?

```<code>class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories

class Categories < ActiveRecord::Base
has_many :post_categories
has_many :post, through: :post_categories

class PostCategories < ActiveRecord::Base
belongs_to :post
belongs_to :category
</code>```

PostCategories table has id, posts_id, and categories_id columns.

```<code>id | posts_id | categories_id
1. | 2       | 3
2. | 2       | 4
</code>```

What I want is: to get posts related to a category. like: all Posts where in x category.

答:
Get the category object and you can directly fetch the related posts. Please see the following

```<code>category = Category.find(id)
posts = category.posts
</code>```

Since you have already configured the has_many_through relation, rails will fetch post records related the category.

Body:
How can I access my related records?

class Post < ActiveRecord::Base
has_many :post_categories
has_many :categories, through: :post_categories

class Categories < ActiveRecord::Base
has_many :post_categories
has_many :post, through: :post_categories

class PostCategories < ActiveRecord::Base
belongs_to :post
belongs_to :category

PostCategories table has id, posts_id, and categories_id columns.

id | posts_id | categories_id
1. | 2       | 3
2. | 2       | 4

What I want is: to get posts related to a category. like: all Posts where in x category.

Body:
Get the category object and you can directly fetch the related posts. Please see the following

category = Category.find(id)
posts = category.posts

Since you have already configured the has_many_through relation, rails will fetch post records related the category.


答:
Your tracker function used in trackBy function is wrong

it is

```<code>  tracker(index:number, item:any):any{
    return item;/// wrong
  }
</code>```

while it should be

https://stackblitz.com/edit/github-qhynwq?file=src%2Fapp%2Fapp.component.ts

```<code>  tracker(index:number, item:any):any{
    return item.id;
  }
</code>```

Title: Angular OnPush strategy not working with ngFor - always recreates all children

Body:
i am trying to build a small framework that renders forms based on provided JSON data which is describing that form's structure. Each form element specified in the data is represented by an angular component at runtime.

Elements in the form can be nested using 'container' form elements. The corresponding component is using an *ngFor loop on an array.

I chose to use OnPush Change Detection which works well - except for the container components which will always recreate all child elements when an array item changes, so when change detection is done on the @inputs, there is nothing to compare to.

I tried to make a reduced example here, hope you get the point.

https://stackblitz.com/github/rpnoll1977/TestNgArray

To be able to tell which parts get recreated, i added some input fields. You can type in some random text. When you hit the button, a new element is added to the list. All elements in the list get recreated - not the others, especially not the input which is in parallel to the *ngfor.

I was able to debug this a bit after providing a tracking function in the *ngFor. In Angular's DefaultIterableDiffer.check it always sets mayBeDirty=true as the record to compare to is equal to null.

Actually i made another example which, instead of *ngfor uses a series of *ngIfs (with conditions about the length of the array being smaller than the position of the *ngif). That shows correct behavior, only re-rendering the added item.

Body:
Your tracker function used in trackBy function is wrong

it is

  tracker(index:number, item:any):any{
    return item;/// wrong
  }

while it should be

https://stackblitz.com/edit/github-qhynwq?file=src%2Fapp%2Fapp.component.ts

  tracker(index:number, item:any):any{
    return item.id;
  }


答:
If it will be useful to you, I found svg similar to yours and I demonstrated how you can add styles

svg {
 background: #479840;
 border-radius: 50%;
}
path {
 filter: invert(99%) sepia(99%) saturate(2%) hue-rotate( 205deg)
       brightness(110%) contrast(100%);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg height="44" viewbox="0 0 24 24" width="44" xmlns="http://www.w3.org/2000/svg">
<path d="m10 15.586-3.293-3.293-1.414 1.414L10 18.414l9.707-9.707-1.414-1.414z"></path></svg></code>```

Title: How to modify the size of a <g> (SVG element)?

Body:
I can not seem to succeed at modifying the size of my  element that is rendered inside a recharts graph as X axis. I want it to be 20px height and width. I couldn't even succeed by making modifications in the console css to the element. Could anyone help me out?

Here's the element:

    <svg
          style={{ cursor: 'pointer',  }} width="20px" height="20px"
        >
          <g transform={`translate(10,10)`} fill="green" stroke="green">
            <path
              fill="current"
              fillRule="evenodd"
              d="M8,0 C3.58862306,0 0,3.58862306 0,8 C0,12.4113769 3.58862306,16 8,16 C12.4113769,16 16,12.4113769 16,8 C16,3.58862306 12.4113769,0 8,0 Z M12.0546875,6.3046875 L7.72131347,10.6379394 C7.59130859,10.7679443 7.42065431,10.833374 7.25,10.833374 C7.07934569,10.833374 6.90869141,10.7679443 6.77868653,10.6379394 L4.61206056,8.47131347 C4.35131837,8.21069338 4.35131837,7.78930663 4.61206056,7.52868653 C4.87268066,7.26794434 5.29394531,7.26794434 5.5546875,7.52868653 L7.25,9.22399903 L11.1120606,5.36206056 C11.3726807,5.10131837 11.7939453,5.10131837 12.0546875,5.36206056 C12.3153076,5.62268066 12.3153076,6.04394531 12.0546875,6.3046875 Z"
              transform="translate(.5)"
            />
          </g>
        </svg>

Body:
If it will be useful to you, I found svg similar to yours and I demonstrated how you can add styles

svg {
 background: #479840;
 border-radius: 50%;
}
path {
 filter: invert(99%) sepia(99%) saturate(2%) hue-rotate( 205deg)
       brightness(110%) contrast(100%);
}

<svg height="44" viewbox="0 0 24 24" width="44" xmlns="http://www.w3.org/2000/svg">
<path d="m10 15.586-3.293-3.293-1.414 1.414L10 18.414l9.707-9.707-1.414-1.414z"></path></svg>


答:
Ok, I figured it out. the answer lies in formatting the new month_list to the same format that my date column in the index column of my original df "df1" is in. Then, use that new "month_list" to reorder the data.

```<code>month_list=[i.strftime("%Y-%m-%d %H:%M:%S") for i in pd.date_range(start="1992-04-01",end="2022-02-02",freq="MS")]
</code>```

And, then use this -
df1.reindex(month_list)

Title: Arrange Pandas Data in 12-month Date Sequence From "Next" Month

Body:
I cannot figure out how to or know how to begin to arrange a pandas df with an index in datetime format in a 12-month sequence based on the "next" month from the current month. For example, if the current OR start month is "Feb" or in serial month form == 2 and the "next" OR target month is "Mar" or "3" then I need a 12-month date sequence arranged in the following serial month form: 4,5,6,7,8,9,10,11,12,1,2,3. My pandas data "df1" looks like this below where the index column is in datetime format. This is a small subset of 30 years of monthly data in this format.

date    month   std anomaly
2/1/1992 0:00   2   0.2
3/1/1992 0:00   3   3.2
4/1/1992 0:00   4   1.3
5/1/1992 0:00   5   0.8
6/1/1992 0:00   6   -0.3
7/1/1992 0:00   7   0.9
8/1/1992 0:00   8   1.0
9/1/1992 0:00   9   -0.4
10/1/1992 0:00  10  -0.9
11/1/1992 0:00  11  2.9
12/1/1992 0:00  12  0.8
1/1/1993 0:00   1   2.1
2/1/1993 0:00   2   1.5
3/1/1993 0:00   3   -0.7
4/1/1993 0:00   4   3.7
5/1/1993 0:00   5   1.6
6/1/1993 0:00   6   2.7
7/1/1993 0:00   7   -2.6
8/1/1993 0:00   8   3.5
9/1/1993 0:00   9   -2.9
10/1/1993 0:00  10  -2.8
11/1/1993 0:00  11  2.6
12/1/1993 0:00  12  1.3
1/1/1994 0:00   1   2.4
2/1/1994 0:00   2   2.3
3/1/1994 0:00   3   0.6

I need the newly-arranged data in "df2" to look like this:

date    month   std anomaly
4/1/1992 0:00   4   1.3
5/1/1992 0:00   5   0.8
6/1/1992 0:00   6   -0.3
7/1/1992 0:00   7   0.9
8/1/1992 0:00   8   1.0
9/1/1992 0:00   9   -0.4
10/1/1992 0:00  10  -0.9
11/1/1992 0:00  11  2.9
12/1/1992 0:00  12  0.8
1/1/1993 0:00   1   2.1
2/1/1993 0:00   2   1.5
3/1/1993 0:00   3   -0.7
4/1/1993 0:00   4   3.7
5/1/1993 0:00   5   1.6
6/1/1993 0:00   6   2.7
7/1/1993 0:00   7   -2.6
8/1/1993 0:00   8   3.5
9/1/1993 0:00   9   -2.9
10/1/1993 0:00  10  -2.8
11/1/1993 0:00  11  2.6
12/1/1993 0:00  12  1.3
1/1/1994 0:00   1   2.4
2/1/1994 0:00   2   2.3
3/1/1994 0:00   3   0.6

thank you very much on how to proceed to sort. I have tried generating a new date list based on the start and end dates that I could use to sort my original df "df1" with something like below but I get a new sorted "df1" original dataframe with all values == NaN.

month_list=[i.strftime("%b-%y") for i in pd.date_range(start="1992-04-01",end="2022-02-02",freq="MS")]

And using this -

df1.reindex(month_list)

Body:
Ok, I figured it out. the answer lies in formatting the new month_list to the same format that my date column in the index column of my original df "df1" is in. Then, use that new "month_list" to reorder the data.

month_list=[i.strftime("%Y-%m-%d %H:%M:%S") for i in pd.date_range(start="1992-04-01",end="2022-02-02",freq="MS")]

And, then use this -
df1.reindex(month_list)


问:
Jetpack Composable with MediaRouteActionProvider
I am currently integrating Chromcast into our app. We are using Jetpack Compose for all out UI elements. We are using a TopAppBar composable and I am trying to add the Chromecast button to it using the MediaRouteActionProvider. The only way I can find to use the MediaRouteActionProvider is by using a menu.xml and inflating the menu in onCreateOptionsMenu.

Does anyone know of a way to use an ActionProvider outside the context of a menu with Jetpack Compose or am I stuck with using a menu for now?

答:
UPDATE: Decided to take another crack at this.

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.mediarouter.app.MediaRouteDialogFactory
import androidx.mediarouter.media.MediaControlIntent
import androidx.mediarouter.media.MediaRouteSelector
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.CastState
import com.google.android.gms.cast.framework.CastStateListener

class MediaRouteViewModel(context: Context) : ViewModel(), CastStateListener {

    var isCastingAvailable = false
        private set

    val castingStateLiveData = MutableLiveData(CastingState.UNKNOWN)

    val mDialogFactory = MediaRouteDialogFactory.getDefault()

    val mSelector: MediaRouteSelector = MediaRouteSelector.Builder()
        .addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
        .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
        .build()

    init {
        try {
            isCastingAvailable = true

            val castingContext = CastContext.getSharedInstance(context)
            castingContext.addCastStateListener(this)
        } catch (e: Exception) {
            // handle me please
        }
    }

    fun shouldShowChooserFragment(): Boolean {
        return when (castingStateLiveData.value) {
            CastingState.NOT_CONNECTED -> true
            CastingState.UNKNOWN -> true
            CastingState.NO_DEVICES_AVAILABLE -> true
            CastingState.CONNECTING -> false
            CastingState.CONNECTED -> false
            else -> false
        }
    }

    enum class CastingState {
        CONNECTED,
        CONNECTING,
        NOT_CONNECTED,
        NO_DEVICES_AVAILABLE,
        UNKNOWN
    }

    class Factory(val context: Context) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return MediaRouteViewModel(context = context) as T
        }
    }

    override fun onCastStateChanged(p0: Int) {
        val castingState = when (p0) {
            CastState.CONNECTED -> CastingState.CONNECTED
            CastState.CONNECTING -> CastingState.CONNECTING
            CastState.NOT_CONNECTED -> CastingState.NOT_CONNECTED
            CastState.NO_DEVICES_AVAILABLE -> CastingState.NO_DEVICES_AVAILABLE
            else -> CastingState.UNKNOWN
        }

        castingStateLiveData.postValue(castingState)
    }
}
```
<pre class="lang-kotlin prettyprint-override"><code>@Composable
fun MediaRouter(
    modifier: Modifier,
    iconWidth: Dp,
    fragmentManager: FragmentManager
) {
    val context = LocalContext.current

    val mediaRouteProviderViewModel: MediaRouteViewModel =
        viewModel(factory = MediaRouteViewModel.Factory(context))

    // Can use the casting state to change the painter accordingly
    val castingState = mediaRouteProviderViewModel.castingStateLiveData.observeAsState()

    if (mediaRouteProviderViewModel.isCastingAvailable) {
        Box(modifier = modifier.size(iconWidth)) {
            Image(
                painter = painterResource(id = R.drawable.ic_baseline_cast_connected_24),
                contentDescription = null,
                modifier = Modifier
                    .clickable {
                        val shouldShowChooserFragment = mediaRouteProviderViewModel.shouldShowChooserFragment()
                        val fragmentTag = if (shouldShowChooserFragment) "MediaRouteChooserDialogFragment" else "MediaRouteControllerDialogFragment"

                        val fragment = if (shouldShowChooserFragment) {
                            mediaRouteProviderViewModel.mDialogFactory
                                .onCreateChooserDialogFragment()
                                .apply {
                                    routeSelector = mediaRouteProviderViewModel.mSelector
                                }
                        } else {
                            mediaRouteProviderViewModel.mDialogFactory.onCreateControllerDialogFragment()
                        }

                        val transaction = fragmentManager.beginTransaction()
                        transaction.add(fragment, fragmentTag)
                        transaction.commitAllowingStateLoss()
                    },
                contentScale = ContentScale.FillBounds
            )
        }
    }
}
</code>```

Old Post:

I'm sure there's a better way of doing this in compose but this at least gets the job done.

```<code>class MediaRouteViewModel(context: Context) : ViewModel() {
    private val mediaRouteActionProvider = MediaRouteActionProvider(context)

    val buttonView: View

    init {
        buttonView = mediaRouteActionProvider.onCreateActionView()
        mediaRouteActionProvider.routeSelector = MediaRouteSelector.Builder()
            .addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
            .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
            .build()
    }

    fun onClick() {
        mediaRouteActionProvider.onPerformDefaultAction()
    }
}
</code>```
```<code>@Composable
fun MediaRouter(modifier: Modifier, iconWidth: Dp) {
    val context = LocalContext.current

    val mediaRouteProviderViewModel = MediaRouteViewModel(context)

    Box(modifier = modifier.size(iconWidth)) {
        AndroidView(factory = {
            mediaRouteProviderViewModel.buttonView
        }, modifier = Modifier.fillMaxSize())

        Box(modifier = Modifier
            .fillMaxSize()
            .clickable { mediaRouteProviderViewModel.onClick() })
    }
}
</code>```

Body:
UPDATE: Decided to take another crack at this.

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.mediarouter.app.MediaRouteDialogFactory
import androidx.mediarouter.media.MediaControlIntent
import androidx.mediarouter.media.MediaRouteSelector
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.CastState
import com.google.android.gms.cast.framework.CastStateListener

class MediaRouteViewModel(context: Context) : ViewModel(), CastStateListener {

    var isCastingAvailable = false
        private set

    val castingStateLiveData = MutableLiveData(CastingState.UNKNOWN)

    val mDialogFactory = MediaRouteDialogFactory.getDefault()

    val mSelector: MediaRouteSelector = MediaRouteSelector.Builder()
        .addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
        .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
        .build()

    init {
        try {
            isCastingAvailable = true

            val castingContext = CastContext.getSharedInstance(context)
            castingContext.addCastStateListener(this)
        } catch (e: Exception) {
            // handle me please
        }
    }

    fun shouldShowChooserFragment(): Boolean {
        return when (castingStateLiveData.value) {
            CastingState.NOT_CONNECTED -> true
            CastingState.UNKNOWN -> true
            CastingState.NO_DEVICES_AVAILABLE -> true
            CastingState.CONNECTING -> false
            CastingState.CONNECTED -> false
            else -> false
        }
    }

    enum class CastingState {
        CONNECTED,
        CONNECTING,
        NOT_CONNECTED,
        NO_DEVICES_AVAILABLE,
        UNKNOWN
    }

    class Factory(val context: Context) : ViewModelProvider.Factory {
        override fun <T : ViewModel?> create(modelClass: Class<T>): T {
            return MediaRouteViewModel(context = context) as T
        }
    }

    override fun onCastStateChanged(p0: Int) {
        val castingState = when (p0) {
            CastState.CONNECTED -> CastingState.CONNECTED
            CastState.CONNECTING -> CastingState.CONNECTING
            CastState.NOT_CONNECTED -> CastingState.NOT_CONNECTED
            CastState.NO_DEVICES_AVAILABLE -> CastingState.NO_DEVICES_AVAILABLE
            else -> CastingState.UNKNOWN
        }

        castingStateLiveData.postValue(castingState)
    }
}

@Composable
fun MediaRouter(
    modifier: Modifier,
    iconWidth: Dp,
    fragmentManager: FragmentManager
) {
    val context = LocalContext.current

    val mediaRouteProviderViewModel: MediaRouteViewModel =
        viewModel(factory = MediaRouteViewModel.Factory(context))

    // Can use the casting state to change the painter accordingly
    val castingState = mediaRouteProviderViewModel.castingStateLiveData.observeAsState()

    if (mediaRouteProviderViewModel.isCastingAvailable) {
        Box(modifier = modifier.size(iconWidth)) {
            Image(
                painter = painterResource(id = R.drawable.ic_baseline_cast_connected_24),
                contentDescription = null,
                modifier = Modifier
                    .clickable {
                        val shouldShowChooserFragment = mediaRouteProviderViewModel.shouldShowChooserFragment()
                        val fragmentTag = if (shouldShowChooserFragment) "MediaRouteChooserDialogFragment" else "MediaRouteControllerDialogFragment"

                        val fragment = if (shouldShowChooserFragment) {
                            mediaRouteProviderViewModel.mDialogFactory
                                .onCreateChooserDialogFragment()
                                .apply {
                                    routeSelector = mediaRouteProviderViewModel.mSelector
                                }
                        } else {
                            mediaRouteProviderViewModel.mDialogFactory.onCreateControllerDialogFragment()
                        }

                        val transaction = fragmentManager.beginTransaction()
                        transaction.add(fragment, fragmentTag)
                        transaction.commitAllowingStateLoss()
                    },
                contentScale = ContentScale.FillBounds
            )
        }
    }
}

Old Post:

I'm sure there's a better way of doing this in compose but this at least gets the job done.

class MediaRouteViewModel(context: Context) : ViewModel() {
    private val mediaRouteActionProvider = MediaRouteActionProvider(context)

    val buttonView: View

    init {
        buttonView = mediaRouteActionProvider.onCreateActionView()
        mediaRouteActionProvider.routeSelector = MediaRouteSelector.Builder()
            .addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO)
            .addControlCategory(MediaControlIntent.CATEGORY_REMOTE_PLAYBACK)
            .build()
    }

    fun onClick() {
        mediaRouteActionProvider.onPerformDefaultAction()
    }
}

@Composable
fun MediaRouter(modifier: Modifier, iconWidth: Dp) {
    val context = LocalContext.current

    val mediaRouteProviderViewModel = MediaRouteViewModel(context)

    Box(modifier = modifier.size(iconWidth)) {
        AndroidView(factory = {
            mediaRouteProviderViewModel.buttonView
        }, modifier = Modifier.fillMaxSize())

        Box(modifier = Modifier
            .fillMaxSize()
            .clickable { mediaRouteProviderViewModel.onClick() })
    }
}


问:
C# SQLite: Can you use a parameter in place of a table name?
I have a database with tables that are similar in name and want to access their data based on a parameter.  The SQL string I am trying to use looks like this:

string sql = "SELECT * FROM @table WHERE EntryID = @ID"

and then have the parameter add the table name as such

cmd.Parameters.Add("@table", DbType.String).Value = tableName;

this is just pseudo for my actual code but this is a very close representation of what I am using.

答:
You can, since you control the content of the string.

You can construct the string by adding the table name within.

Example:
string sql = $"SELECT * FROM {tableName} WHERE EntryID = @ID"

This is called string interpolation. I use a similar approach in my Base Classes for CRUD operations.

Edit:

There is mention that is is open to SQL injection. If the parameter named tableName in OP's example, is controlled by the developer and does not take user input, this is safe. If for some very odd reason the parameter takes user input, this can be open to SQL injection and should NOT be done.