问:
Android RecyclerView : notifyDataSetChanged() IllegalStateException
I'm trying to update the items of a recycleview using notifyDataSetChanged().

This is my onBindViewHolder() method in the recycleview adapter.

```<code>@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

     //checkbox view listener
    viewHolder.getCheckbox().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            //update list items
            notifyDataSetChanged();
        }
    });
}
</code>```

What I want to do is update the list items, after I check a checkbox. I get an illegal exception though: "Cannot call this method while RecyclerView is computing a layout or scrolling"

```<code>java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
    at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:1462)
    at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:2982)
    at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:7493)
    at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:4338)
    at com.app.myapp.screens.RecycleAdapter.onRowSelect(RecycleAdapter.java:111)
</code>```

I also used notifyItemChanged(), same exception. Any secret way to update to notify the adapter that something changed?

答: I had the same problem using the Checkbox and the RadioButton. Replacing notifyDataSetChanged() with notifyItemChanged(position) worked. I added a Boolean field isChecked to the data model. Then I updated the Boolean value and in onCheckedChangedListener, I called notifyItemChanged(adapterPosition). This might not be the best way, but worked for me. The boolean value is used for checking whether the item is checked.

Body:
I'm trying to update the items of a recycleview using notifyDataSetChanged().

This is my onBindViewHolder() method in the recycleview adapter.

@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

     //checkbox view listener
    viewHolder.getCheckbox().setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            //update list items
            notifyDataSetChanged();
        }
    });
}

What I want to do is update the list items, after I check a checkbox. I get an illegal exception though: "Cannot call this method while RecyclerView is computing a layout or scrolling"

java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
    at android.support.v7.widget.RecyclerView.assertNotInLayoutOrScroll(RecyclerView.java:1462)
    at android.support.v7.widget.RecyclerView$RecyclerViewDataObserver.onChanged(RecyclerView.java:2982)
    at android.support.v7.widget.RecyclerView$AdapterDataObservable.notifyChanged(RecyclerView.java:7493)
    at android.support.v7.widget.RecyclerView$Adapter.notifyDataSetChanged(RecyclerView.java:4338)
    at com.app.myapp.screens.RecycleAdapter.onRowSelect(RecycleAdapter.java:111)

I also used notifyItemChanged(), same exception. Any secret way to update to notify the adapter that something changed?


来源: stackexchange

问:
How can we initialise a state in react typescript in constructor method, If it has a specific interface type
I have the below Code: Where I have an interface type for a state. How do i initialize it in constructor method. As It doesn't allow me to initialize to string/ null/ number

interface IState { selectedUser?: IUserMenu}

class AssignUser extends React.Component<IProps, IState>{
      constructor(props: IProps) {
          super(props);
          this.state = {
          selectedUser: ' what i have to put here' }}}

Also what does it mean by
this.state ={}
 in the constructor function means ?

IUserMenu is an interface, so I cannot initialize to number, '', null,

Only thing I can use Is undefined

答:
Hi @ankitjayaprakash ,

I've an example with your case where I'm initializing the object you want to pass described in the interface (but without being optional)

You can see it here

What "this.state={}" serves in the constructor is only to initialize the state of that component, even though it could be out without any builder function.

ContentLicense: CC BY-SA 4.0


问:
How do I add a loop to this program?
My homework question asked:

During the tax season, every Friday, J&J accounting firm privides assistance to people who prepare their own tax returns. Their charges are as follows.

a. If a person has low income (<=25,000) and the consulting time is less than or equal to 30 minutes, there are no charges; otherwise, the service charges are 40% of the regular hourly rate for the time over 30 minutes.

b. For others, if the consulting time is less than or equal to 20 minutes, there are no service charges; otherwise, service charges are 70% of the regular hourly rate for the time over 20 minutes.

(For example, suppose that a person has low income and spent 1 hour and 15 minutes, and the hourly rate is $70.00. Then the billing amount is 70.00 x 0.40 x (45 / 60) = $21.00.)

Write a program that prompts the user to enter the hourly rate, the total consulting time, and whether the person has low income. The program should output the billing amount. The program must contain a function that takes as input the hourly rate, the total consulting time, and a value indicating whether the person has low income. The function should return the billing amount. The program may prompt the user to enter the consulting time in minutes.

And this is the code I wrote:

```<code>#include <iostream>

using namespace std;

double calculate(char iRate, double cTime, double hRate);

int main()
{
double hRate = 0.0, cTime = 0.0;
char iRate, l('l'), h('h');

cout << "Please enter the hourly rate: ";
cin >> hRate;
cout << "Please enter total consulting time in minutes: ";
cin >> cTime;
cout << "Is the income rate low or high (l - Low | h - High): ";
cin >> iRate;

cout << calculate(iRate, cTime, hRate) << endl;

system("pause");
return 0;
}

double calculate(char iRate, double cTime, double hRate)
{
    double bAmount = 0.0;
    if (iRate == 'l' && cTime > 30)
        bAmount = (hRate * 40) * ((cTime)- 30)/6000;
    else if (iRate == 'h' && cTime > 20)
        bAmount = (hRate * 70) * ((cTime)- 30)/6000;

    return bAmount;
}
</code>```

I'm not sure how I can add a loop to this so it runs 3 times?

答:
What I would do for code clarity is separate out your logic from your main into another function

```<code>void gatherInputAndCalculate()
{
    double hRate = 0.0, cTime = 0.0;
    char iRate, l('l'), h('h');

    cout << "Please enter the hourly rate: ";
    cin >> hRate;
    cout << "Please enter total consulting time in minutes: ";
    cin >> cTime;
    cout << "Is the income rate low or high (l - Low | h - High): ";
    cin >> iRate;

    cout << calculate(iRate, cTime, hRate) << endl;

    system("pause");
}
</code>```

and then in your main, loop around it

```<code>int main()
{
    for(int i = 0; i < 3; i++)
    {
        gatherInputAndCalculate();
    }
    return 0;
}
</code>```

Now, that's not to say you couldn't just wrap the entire logic block in the for loop, but it's a good practice to wrap consolidated logic blocks into functions for clarity/debugging purposes. It won't come into play for easy assignments like this, but in the real world, where your code-base is hundreds of thousands of lines long, it really helps, so getting good practices down now will make for an easy transition!

Disclaimer I haven't checked your code for correctness in any way, shape or form. I merely took the logic you had in your main function and put it into it's own function. Any bugs preexisting in it will be in the function I've provided. Something like that would be beyond the scope of this question. (Not that I wouldn't point one out if I saw one, but there's another thing that we real-world programmers struggle with: sometimes we're not allowed to fix bugs, because we were provided enough funding to fix only a handful of them, and we were told which ones to fix. It can be frustrating when you're the type who likes to make things right, all the time, every time.)

ContentLicense: CC BY-SA 3.0

Title: How do I add a loop to this program?

Body:
My homework question asked:

During the tax season, every Friday, J&J accounting firm privides assistance to people who prepare their own tax returns. Their charges are as follows.

a. If a person has low income (<=25,000) and the consulting time is less than or equal to 30 minutes, there are no charges; otherwise, the service charges are 40% of the regular hourly rate for the time over 30 minutes.

b. For others, if the consulting time is less than or equal to 20 minutes, there are no service charges; otherwise, service charges are 70% of the regular hourly rate for the time over 20 minutes.

(For example, suppose that a person has low income and spent 1 hour and 15 minutes, and the hourly rate is $70.00. Then the billing amount is 70.00 x 0.40 x (45 / 60) = $21.00.)

Write a program that prompts the user to enter the hourly rate, the total consulting time, and whether the person has low income. The program should output the billing amount. The program must contain a function that takes as input the hourly rate, the total consulting time, and a value indicating whether the person has low income. The function should return the billing amount. The program may prompt the user to enter the consulting time in minutes.

And this is the code I wrote:

#include <iostream>

using namespace std;

double calculate(char iRate, double cTime, double hRate);

int main()
{
double hRate = 0.0, cTime = 0.0;
char iRate, l('l'), h('h');

cout << "Please enter the hourly rate: ";
cin >> hRate;
cout << "Please enter total consulting time in minutes: ";
cin >> cTime;
cout << "Is the income rate low or high (l - Low | h - High): ";
cin >> iRate;

cout << calculate(iRate, cTime, hRate) << endl;

system("pause");
return 0;
}

double calculate(char iRate, double cTime, double hRate)
{
    double bAmount = 0.0;
    if (iRate == 'l' && cTime > 30)
        bAmount = (hRate * 40) * ((cTime)- 30)/6000;
    else if (iRate == 'h' && cTime > 20)
        bAmount = (hRate * 70) * ((cTime)- 30)/6000;

    return bAmount;
}

I'm not sure how I can add a loop to this so it runs 3 times?

Body:
What I would do for code clarity is separate out your logic from your main into another function

void gatherInputAndCalculate()
{
    double hRate = 0.0, cTime = 0.0;
    char iRate, l('l'), h('h');

    cout << "Please enter the hourly rate: ";
    cin >> hRate;
    cout << "Please enter total consulting time in minutes: ";
    cin >> cTime;
    cout << "Is the income rate low or high (l - Low | h - High): ";
    cin >> iRate;

    cout << calculate(iRate, cTime, hRate) << endl;

    system("pause");
}

and then in your main, loop around it

int main()
{
    for(int i = 0; i < 3; i++)
    {
        gatherInputAndCalculate();
    }
    return 0;
}

Now, that's not to say you couldn't just wrap the entire logic block in the for loop, but it's a good practice to wrap consolidated logic blocks into functions for clarity/debugging purposes. It won't come into play for easy assignments like this, but in the real world, where your code-base is hundreds of thousands of lines long, it really helps, so getting good practices down now will make for an easy transition!

Disclaimer I haven't checked your code for correctness in any way, shape or form. I merely took the logic you had in your main function and put it into it's own function. Any bugs preexisting in it will be in the function I've provided. Something like that would be beyond the scope of this question. (Not that I wouldn't point one out if I saw one, but there's another thing that we real-world programmers struggle with: sometimes we're not allowed to fix bugs, because we were provided enough funding to fix only a handful of them, and we were told which ones to fix. It can be frustrating when you're the type who likes to make things right, all the time, every time.)


问:
Complex destroy query
I'm trying to come up with some code (other than a RAW sequelize query) that will allow me to delete all but N newest rows of a given model in one transaction/query.

I've tried the naive approach of using offset and order in the Model.detroy method.

Model.destroy({
  order: ["createdAt", "DESC"],
  offset: N,
  where: {
    parentModelId: someId,
  }
})

What I expected is that the code above constructed a query such as:

```sql
DELETE FROM model WHERE "parentModelId" = 'someId' ORDER BY "createdAt" DESC OFFSET N;
</code>```

Instead, the query generated was:

DELETE FROM model WHERE "parentModelId" = 'someId';
```

答:
Edit: Just realized the problem is not with Sequelize.js itself, but rather with PostgreSQL no allowing for such query in the first place. The appropiate way to achieve this is via the query:

DELETE FROM models WHERE is IN (
  SELECT id FROM models WHERE "parentModelId" = 'someId'
    ORDER BY "createdAt" DESC
    OFFSET N
);

```

The only way to do this in Sequelize.js is via a raw query, unfortuantely. http://docs.sequelizejs.com/manual/raw-queries.html

Title: Complex destroy query

Body:
I'm trying to come up with some code (other than a RAW sequelize query) that will allow me to delete all but N newest rows of a given model in one transaction/query.

I've tried the naive approach of using offset and order in the Model.detroy method.

Model.destroy({
  order: ["createdAt", "DESC"],
  offset: N,
  where: {
    parentModelId: someId,
  }
})

What I expected is that the code above constructed a query such as:

```sql
DELETE FROM model WHERE "parentModelId" = 'someId' ORDER BY "createdAt" DESC OFFSET N;

Instead, the query generated was:

DELETE FROM model WHERE "parentModelId" = 'someId';

Body:
Edit: Just realized the problem is not with Sequelize.js itself, but rather with PostgreSQL no allowing for such query in the first place. The appropiate way to achieve this is via the query:

DELETE FROM models WHERE is IN (
  SELECT id FROM models WHERE "parentModelId" = 'someId'
    ORDER BY "createdAt" DESC
    OFFSET N
);

The only way to do this in Sequelize.js is via a raw query, unfortuantely. http://docs.sequelizejs.com/manual/raw-queries.html


问:
TransformerFactory and Xalan Dependency Conflict
I have the following code:

```<code>javax.xml.transform.TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
javax.xml.transform.Transformer transformer = factory.newTransformer();
</code>```

This works fine normally. However, I also need to add Xalan as a dependency in my pom.xml, and when I do, the above code now throws an error:

```<code>java.lang.IllegalArgumentException: Not supported: http://javax.xml.XMLConstants/property/accessExternalDTD
</code>```

I think it has something to do with the fact that Xalan's jar has a different implementation of Transformer in it. How can I resolve this conflict without changing the above code and keeping Xalan as a dependency?

答:
It might be coming from other xalan version of your project.

Check Dependent Hierarchy in your POM for the xalan and exclude the xercesImpl in all the version of xalan.

Body:
I have the following code:

javax.xml.transform.TransformerFactory factory = TransformerFactory.newInstance();
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
javax.xml.transform.Transformer transformer = factory.newTransformer();

This works fine normally. However, I also need to add Xalan as a dependency in my pom.xml, and when I do, the above code now throws an error:

java.lang.IllegalArgumentException: Not supported: http://javax.xml.XMLConstants/property/accessExternalDTD

I think it has something to do with the fact that Xalan's jar has a different implementation of Transformer in it. How can I resolve this conflict without changing the above code and keeping Xalan as a dependency?


问:
How to replace special characters along with the text? like (.,*,/,\)
I am having a hierarchy name like a.b.c.d.e in multiple lines along with some text. Now I want to change that as a/b/c/d/e.

I tried %s/\./\//g. It did not work.

Error:Trailing Characters

答:
Plain and simple:</p>

```<code>:%substitute~\.~/~g
</code>```

Body:
Plain and simple:

:%substitute~\.~/~g


问:
How to handle JS serialized item in PHP?
Hey guys!
I am having a bit of trouble handling the data from a submitted form that is serialized with JS.
In the form there a textarea fields which users can input any text they want but when they enter & like "apples & oranges", I have trouble handling that.  As we know that JS serializes & to %26 and spaces with a "+" sign.

So now back in PHP, I am trying to put this data into the database and call it back out elsewhere but for the life of me don't know how to handle the special characters properly.

Note that I am also php exploding the data at the "&" sign to make it into an array, then is put into the database as an array.  I tried several methods like urldecode, htmlentities but those don't help because remember I need to explode at "&".

I am serializing in JS because its an AJAX submitting form.

答:
If something is serialized in JS and then sent to a PHP script - it can only be via GET or POST method, which in return means that the serialized data will be stored in one of the following arrays: $_GET if method was GET, $_POST if method was POST and $_REQUEST regardless of the method (so you can capture both POST and GET variables with a single array).

That means that you shouldn't have your custom function that creates from and to php array since it's already done for you.
If you want to store the array in string format, you should serialize that array before storing it into the db and then unserialize it when you want to use it in array format after pulling it out from db.


问:
JavaScript Error in Microsoft Edge with Telerik RadDatePicker in ASP.NET UpdatePanel
Telerik RadDatePicker inside ASP.NET UpdatePanel in Microsoft Edge browser throws JavaScript error when doing a post-back.
The error: "Unable to get property 'length' of undefined or null reference".

The RadDatePicker must be inside an UpdatePanel for the error to be thrown, and this ONLY happens in Microsoft Edge browser, all other browsers have no error.

Microsoft Edge version: 44.17763.1.0

Telerik Controls: Telerik.Web.UI, Version=2019.1.409.45

Any ideas how to fix this, or a work-around?

Here is my code:

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EdgeDatePickerIssue.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Default</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager" runat="server" ScriptMode="Release" />

        <asp:UpdatePanel runat="server" ID="upPanel">
            <ContentTemplate>
                <label>Select Date:</label>
                <telerik:RadDatePicker ID="dpStartDate" runat="server"
                    AutoPostBack="true"
                    OnSelectedDateChanged="dpStartDate_SelectedDateChanged" />

                <telerik:RadButton ID="btnSave" runat="server"
                    Text="Save" OnClick="btnSave_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>
</body>
</html>
</code>```

Here is a screen-shot of the error:
Screen-shot Error in Edge

答: You could try to use Telerik RadScriptManager and Telerik RadAjaxPanel instead of using asp.net ScriptManager and UpdatePanel. Then, refer to this article to use DatePicker control.</p>

Body:
Telerik RadDatePicker inside ASP.NET UpdatePanel in Microsoft Edge browser throws JavaScript error when doing a post-back.
The error: "Unable to get property 'length' of undefined or null reference".

The RadDatePicker must be inside an UpdatePanel for the error to be thrown, and this ONLY happens in Microsoft Edge browser, all other browsers have no error.

Microsoft Edge version: 44.17763.1.0

Telerik Controls: Telerik.Web.UI, Version=2019.1.409.45

Any ideas how to fix this, or a work-around?

Here is my code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="EdgeDatePickerIssue.Default" %>

<!DOCTYPE html>

    <title>Default</title>

    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager" runat="server" ScriptMode="Release" />

        <asp:UpdatePanel runat="server" ID="upPanel">
            <ContentTemplate>
                Select Date:
                <telerik:RadDatePicker ID="dpStartDate" runat="server"
                    AutoPostBack="true"
                    OnSelectedDateChanged="dpStartDate_SelectedDateChanged" />

                <telerik:RadButton ID="btnSave" runat="server"
                    Text="Save" OnClick="btnSave_Click" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </form>

Here is a screen-shot of the error:
Screen-shot Error in Edge


问:
How to plot data per hour, grouped by days?
Background: from a large DataFrame I filtered out entries for year=2013, month=June, week of the 3rd - 9th (Monday to Sunday). Then, I grouped the data by day, hour, and user_type, and pivoted the table to get a DataFrame which looks like:

```<code>   Day  Hour  Casual  Registered  Casual_percentage
0  3    0     14      19          42.42
1  3    1     8       8           50.00
2  3    2     1       3           25.00
3  3    3     2       1           66.67
4  3    4     1       3           25.00
5  3    5     1       17          5.56
.  .    .     .       .           .
</code>```

For each day I have 24 hours so for day 4 (Tuesday), the data starts like:

```<code>.  .    .     .       .           .
21 3    21    32      88          26.67
22 3    22    26      64          28.89
23 3    23    23      30          43.40
24 4    0     10      11          47.62
25 4    1     1       5           16.67
26 4    2     1       1           50.00
.  .    .     .       .           .
</code>```

How can I plot Casual and Registered variables per Hour, for each of the 7 Days? Would I need to create 7 different plots and align them in 1 figure?

Current code. I feel I'm way off. I also tried to create a second x-axis (for Days) using the documentation.

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.set(xlabel='Hours', ylabel='Total # of trips started')

ax1.plot(data.Hour, data.Casual, color='g')
ax1.plot(data.Hour, data.Registered, color='b')

"""This part is trying to create the 2nd x-axis (Days)"""
ax2 = ax1.twinx()
#offset the bottom spine
ax2.spines['bottom'].set_position(('axes', -.5))
make_patch_spines_invisible(ax2)
#show bottomm spine
ax2.spines['bottom'].set_visible(True)
ax2.set_xlabel("Days")

plt.show()
```

Output:

End goal

答:
I think this should be easier if you work on datetime objects rather than Day, Hour strings.

This way, you'll be able to use date tick locators and formatters
 along with major and minor ticks.

Even if you didn't mention it, I assume you can use pandas to deal with dataframes.

I created a new dataframe by copying many times data you provided and cutting some of them (this is not so important).

Here I rebuilt dates from infos you provided, but I suggest to work directly on them (I suppose the original dataframe has some kind of date-like field in it).

```<code>import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.read_csv("mydataframe.csv")
df["timestamp"] = "2013-06-" + df["Day"].astype(str).str.zfill(2) + "-" + df["Hour"].astype(str).str.zfill(2)
df["timestamp"] = pd.to_datetime(df["timestamp"], format="%Y-%m-%d-%H")

fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.set(xlabel='', ylabel='Total # of trips started')
ax1.plot(df["timestamp"], df.Casual, color='g')
ax1.plot(df["timestamp"], df.Registered, color='b')

ax1.xaxis.set(
    major_locator=mdates.DayLocator(),
    major_formatter=mdates.DateFormatter("\n\n%A"),
    minor_locator=mdates.HourLocator((0, 12)),
    minor_formatter=mdates.DateFormatter("%H"),
)
plt.show()
</code>```

Output:

Body:
Background: from a large DataFrame I filtered out entries for year=2013, month=June, week of the 3rd - 9th (Monday to Sunday). Then, I grouped the data by day, hour, and user_type, and pivoted the table to get a DataFrame which looks like:

   Day  Hour  Casual  Registered  Casual_percentage
0  3    0     14      19          42.42
1  3    1     8       8           50.00
2  3    2     1       3           25.00
3  3    3     2       1           66.67
4  3    4     1       3           25.00
5  3    5     1       17          5.56
.  .    .     .       .           .

For each day I have 24 hours so for day 4 (Tuesday), the data starts like:

.  .    .     .       .           .
21 3    21    32      88          26.67
22 3    22    26      64          28.89
23 3    23    23      30          43.40
24 4    0     10      11          47.62
25 4    1     1       5           16.67
26 4    2     1       1           50.00
.  .    .     .       .           .

How can I plot Casual and Registered variables per Hour, for each of the 7 Days? Would I need to create 7 different plots and align them in 1 figure?

Current code. I feel I'm way off. I also tried to create a second x-axis (for Days) using the documentation.

def make_patch_spines_invisible(ax):
    ax.set_frame_on(True)
    ax.patch.set_visible(False)
    for sp in ax.spines.values():
        sp.set_visible(False)

fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.set(xlabel='Hours', ylabel='Total # of trips started')

ax1.plot(data.Hour, data.Casual, color='g')
ax1.plot(data.Hour, data.Registered, color='b')

"""This part is trying to create the 2nd x-axis (Days)"""
ax2 = ax1.twinx()
#offset the bottom spine
ax2.spines['bottom'].set_position(('axes', -.5))
make_patch_spines_invisible(ax2)
#show bottomm spine
ax2.spines['bottom'].set_visible(True)
ax2.set_xlabel("Days")

plt.show()

Output:

End goal

Body:
I think this should be easier if you work on datetime objects rather than Day, Hour strings.

This way, you'll be able to use date tick locators and formatters
 along with major and minor ticks.

Even if you didn't mention it, I assume you can use pandas to deal with dataframes.

I created a new dataframe by copying many times data you provided and cutting some of them (this is not so important).

Here I rebuilt dates from infos you provided, but I suggest to work directly on them (I suppose the original dataframe has some kind of date-like field in it).

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

df = pd.read_csv("mydataframe.csv")
df["timestamp"] = "2013-06-" + df["Day"].astype(str).str.zfill(2) + "-" + df["Hour"].astype(str).str.zfill(2)
df["timestamp"] = pd.to_datetime(df["timestamp"], format="%Y-%m-%d-%H")

fig, ax1 = plt.subplots(figsize=(10, 5))
ax1.set(xlabel='', ylabel='Total # of trips started')
ax1.plot(df["timestamp"], df.Casual, color='g')
ax1.plot(df["timestamp"], df.Registered, color='b')

ax1.xaxis.set(
    major_locator=mdates.DayLocator(),
    major_formatter=mdates.DateFormatter("\n\n%A"),
    minor_locator=mdates.HourLocator((0, 12)),
    minor_formatter=mdates.DateFormatter("%H"),
)
plt.show()

Output:


问:
ARGB in tkinter ttk behaves unexpectedly
I've been trying to learn Tkinter and subsequently ttk to create a GUI. When working with ttk I noticed something peculiar happening. When I gave any colour in an ARGB format, '#80FFFFFF' for example, there was no error but the particular widget simply turned into a small square. Why does this happen?

Here is an example,

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

s = ttk.Style()

s.configure('b1.TButton', background='#FF0000')
s.configure('b2.TButton', background='#80FFFFFF')

b1 = ttk.Button(root, style='b1.TButton')
b2 = ttk.Button(root, style='b2.TButton')

b1.grid()
b2.grid()

root.mainloop()
```

This is the result of this code:

答:
Tkinter buttons do not support transparency so my thoughts is that the extra FF in your ARGB code that tells the color to be transparent is what is causing the issue.

My guess from my research is that the Button cannot format properly due to the transparency color code and thus causes this problem when displaying the button.

You can test this by adding FF to any ARGB color and see the same effect.

Body:
I've been trying to learn Tkinter and subsequently ttk to create a GUI. When working with ttk I noticed something peculiar happening. When I gave any colour in an ARGB format, '#80FFFFFF' for example, there was no error but the particular widget simply turned into a small square. Why does this happen?

Here is an example,

import tkinter as tk
from tkinter import ttk

root = tk.Tk()

s = ttk.Style()

s.configure('b1.TButton', background='#FF0000')
s.configure('b2.TButton', background='#80FFFFFF')

b1 = ttk.Button(root, style='b1.TButton')
b2 = ttk.Button(root, style='b2.TButton')

b1.grid()
b2.grid()

root.mainloop()

This is the result of this code:


问:
How to get all members on a type elegantly?
I've been through "Questions that may already have your answer" and didn't find the thing I'm looking for.
I want to get all members on a type via reflection. When I try

```<code>var type = typeof(int);
var members = type.GetMembers();
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");
</code>```

I get 19 members.

I found that some members need specific BindingFlags. Since I don't know those flags and different members have different flags I pass all flags like this:

```<code>var type = typeof(int);
var flags =
    BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance |BindingFlags.Static |
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod |
    BindingFlags.CreateInstance | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty |
    BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty | BindingFlags.ExactBinding |
    BindingFlags.SuppressChangeType | BindingFlags.OptionalParamBinding | BindingFlags.IgnoreReturn;
var members = type.GetMembers(flags);
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");
</code>```

It gives me 34 members. That's exactly what I need.

But is where a more elegant (shorter) way to get all members?

答:
You could use LINQ's Aggregate to OR all the different BindingFlags values:

```<code>var flags = Enum.GetValues(typeof(BindingFlags))
                .Cast<BindingFlags>()
                .Aggregate((x,y) => x | y);
</code>```

Body:
I've been through "Questions that may already have your answer" and didn't find the thing I'm looking for.
I want to get all members on a type via reflection. When I try

var type = typeof(int);
var members = type.GetMembers();
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");

I get 19 members.

I found that some members need specific BindingFlags. Since I don't know those flags and different members have different flags I pass all flags like this:

var type = typeof(int);
var flags =
    BindingFlags.IgnoreCase | BindingFlags.DeclaredOnly | BindingFlags.Instance |BindingFlags.Static |
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.InvokeMethod |
    BindingFlags.CreateInstance | BindingFlags.GetField | BindingFlags.SetField | BindingFlags.GetProperty |
    BindingFlags.SetProperty | BindingFlags.PutDispProperty | BindingFlags.PutRefDispProperty | BindingFlags.ExactBinding |
    BindingFlags.SuppressChangeType | BindingFlags.OptionalParamBinding | BindingFlags.IgnoreReturn;
var members = type.GetMembers(flags);
for(var i = 0; i < members.Length; i++)
    Console.WriteLine($"{i, 2} {members[i]}");

It gives me 34 members. That's exactly what I need.

But is where a more elegant (shorter) way to get all members?

Body:
You could use LINQ's Aggregate to OR all the different BindingFlags values:

var flags = Enum.GetValues(typeof(BindingFlags))
                .Cast<BindingFlags>()
                .Aggregate((x,y) => x | y);


问:
By using ledger nano s, I wanna sign a transaction and send it
I'm trying to send ethereum transaction that sends ERC20 tokens to someone with Ledger Nano S through Node.JS but I'm not able to successfully sign and send this transaction.

First of all, I signed the transaction through the method, signTransaction, of ledgerhq API and then after signing it, I sended it to the main net by using sendSignedTransaction. When I execute below code, Ledger receives request and shows details of a transaction. However, after pressing Ledger's confirm button, the console returns error 'Returned error: Invalid signature: Crypto error (Invalid EC signature)'.

import AppEth from "@ledgerhq/hw-app-eth";
import TransportU2F from "@ledgerhq/hw-transport-u2f";
import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
import EthereumTx from "ethereumjs-tx"
const Web3 = require('web3');
import { addHexPrefix, bufferToHex, toBuffer } from 'ethereumjs-util';
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

var destAddresses = ['0xa6acFa18468786473269Dc1521fd4ff40F6481D9'];
var amount = 1000000000000;
var i=0;
var contract = new web3.eth.Contract([token contract ABI... ], '0x74a...');

const data1 = contract.methods.transfer(destAddresses[0], amount).encodeABI();
const exParams = {
  gasLimit: 6e6,
  gasPrice: 3e9,
  from: '0x1A...',
  data : data1,
  to: '0x74a...',
  value: '0x00',
  nonce: "0x0",
  chainId: 1,
  v: "0x01",
  r: "0x00",
  s: "0x00"
}

async function makeSign(txParams) {
  const tx = new EthereumTx(txParams);
  const txHex = tx.serialize().toString("hex");
  const signedTransaction = '0x' + txHex;

  let transport;
  try {
    transport = await TransportNodeHid.create();

    let eth2 = new AppEth(transport);

    const result = await eth2.signTransaction("m/44'/60'/0'/0", txHex).then(result => {
      web3.eth.sendSignedTransaction('0x' + txHex)
      .then(res => {
              console.log(res);
            }).catch(err => {
            console.log('sendSignedTransaction');
            console.log(err);
          });
        }).catch(err => {
          console.log('signTransaction');
          console.log(err);
        });

            txParams.r = `0x${result.r, 'hex'}`;
            txParams.s = `0x${result.s, 'hex'}`;
            txParams.v = `0x${result.v, 'hex'}`;

    return result;

  } catch (e) {
    console.log(e);
  }
}

makeSign(exParams).then(function () {
  console.log("Promise Resolved2");
}.catch(function () {
  console.log("Promise Rejected2");
});```

When I only use signTransaction function, I can confirm the transaction in the ledger device and return txhash on the console. However, ultimately I want to broadcast a transaction to the main net. Could you please give me any idea? I want any feedback. Also, if there are any examples of creating and broadcasting a raw transaction by using the ledger, notice me please.

答:
Your code already sends the transaction to the network. However, just awaiting the "send" promise only gives you the transaction hash, not the receipt. You need to treat it as an event emitter and wait for the 'confirmation' event.

```<code>  const serializedTx = tx.serialize();
  web3.eth.sendSignedTransaction(serializedTx.toString('hex'))
    .once('transactionHash', hash => console.log('Tx hash', hash))
    .on('confirmation', (confNumber, receipt) => {
      console.log(`Confirmation #${confNumber}`, receipt);
    })
    .on('error', console.error);
</code>```

To send it to mainnet as you mention, you can either run a local geth node on port 8545 and use your code unchanged, or point web3 at infura or similar.

Body:
I'm trying to send ethereum transaction that sends ERC20 tokens to someone with Ledger Nano S through Node.JS but I'm not able to successfully sign and send this transaction.

First of all, I signed the transaction through the method, signTransaction, of ledgerhq API and then after signing it, I sended it to the main net by using sendSignedTransaction. When I execute below code, Ledger receives request and shows details of a transaction. However, after pressing Ledger's confirm button, the console returns error 'Returned error: Invalid signature: Crypto error (Invalid EC signature)'.

import AppEth from "@ledgerhq/hw-app-eth";
import TransportU2F from "@ledgerhq/hw-transport-u2f";
import TransportNodeHid from "@ledgerhq/hw-transport-node-hid";
import EthereumTx from "ethereumjs-tx"
const Web3 = require('web3');
import { addHexPrefix, bufferToHex, toBuffer } from 'ethereumjs-util';
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

var destAddresses = ['0xa6acFa18468786473269Dc1521fd4ff40F6481D9'];
var amount = 1000000000000;
var i=0;
var contract = new web3.eth.Contract([token contract ABI... ], '0x74a...');

const data1 = contract.methods.transfer(destAddresses[0], amount).encodeABI();
const exParams = {
  gasLimit: 6e6,
  gasPrice: 3e9,
  from: '0x1A...',
  data : data1,
  to: '0x74a...',
  value: '0x00',
  nonce: "0x0",
  chainId: 1,
  v: "0x01",
  r: "0x00",
  s: "0x00"
}

async function makeSign(txParams) {
  const tx = new EthereumTx(txParams);
  const txHex = tx.serialize().toString("hex");
  const signedTransaction = '0x' + txHex;

  let transport;
  try {
    transport = await TransportNodeHid.create();

    let eth2 = new AppEth(transport);

    const result = await eth2.signTransaction("m/44'/60'/0'/0", txHex).then(result => {
      web3.eth.sendSignedTransaction('0x' + txHex)
      .then(res => {
              console.log(res);
            }).catch(err => {
            console.log('sendSignedTransaction');
            console.log(err);
          });
        }).catch(err => {
          console.log('signTransaction');
          console.log(err);
        });

            txParams.r = `0x${result.r, 'hex'}`;
            txParams.s = `0x${result.s, 'hex'}`;
            txParams.v = `0x${result.v, 'hex'}`;

    return result;

  } catch (e) {
    console.log(e);
  }
}

makeSign(exParams).then(function () {
  console.log("Promise Resolved2");
}.catch(function () {
  console.log("Promise Rejected2");
});

When I only use signTransaction function, I can confirm the transaction in the ledger device and return txhash on the console. However, ultimately I want to broadcast a transaction to the main net. Could you please give me any idea? I want any feedback. Also, if there are any examples of creating and broadcasting a raw transaction by using the ledger, notice me please.

Body:
Your code already sends the transaction to the network. However, just awaiting the "send" promise only gives you the transaction hash, not the receipt. You need to treat it as an event emitter and wait for the 'confirmation' event.

  const serializedTx = tx.serialize();
  web3.eth.sendSignedTransaction(serializedTx.toString('hex'))
    .once('transactionHash', hash => console.log('Tx hash', hash))
    .on('confirmation', (confNumber, receipt) => {
      console.log(`Confirmation #${confNumber}`, receipt);
    })
    .on('error', console.error);

To send it to mainnet as you mention, you can either run a local geth node on port 8545 and use your code unchanged, or point web3 at infura or similar.


问:
How can I return vector<vector<float>> from JNI?
I have a function in C++:

std::vector<std::vector<float>> const &GetVertices() { return m_Vertices; }
```

<p>I need to return this value to Java through JNI.</p>

<p>So, because of the fact that I need to return <code>vector</code> of <code>vector</code>, I think that I have to use <code>jobjectArray</code>, like this:</p>

<pre class="lang-cpp prettyprint-override"><code>extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_
java_helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
)
</code>```

In Java, I have this method:

public native Object[] fillListWithData();
```

<p><strong>So, my question is, how to convert <code>vector<vector<float>></code> to <code>jobjectArray</code>?</strong></p>

<p>I know that there is a method that could create <code>jobjectArray</code>:</p>

<pre class="lang-cpp prettyprint-override"><code>jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);
</code>```

Then how can I put in the values ?

Full class implementation

extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_java_
helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
) {
    //verticesVec
    vector<vector<float>> verticesVec = initializer->GetVertices(); // THIS VECTOR I NEED TO CONVERT TO JOBJECTARRAY
    jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);

    //HOW TO FILL THE ARRAY HERE??

    return verticesArr;
}
```

答:
Depends a bit on how you want to operate on the data in Java, e.g. add more elements? You didn't mention this so the answer can't be more specific. But perhaps you want "java/util/ArrayList" of float.

The following answer should point you in the right direction:
return a jobjectArray which contains lists of data.

The code would look similar for other types of lists. A bit of web search will provide several solutions.

In case speed (CPU/latency) and data volume are not important, instead of all the messy handling of Java datastructures I would generally recommend serializing your data to JSON and return as string. Using e.g. JsonCpp it's easy to serialize C++ data types including objects to JSON, and on the Java side there are several packages for deserialization (web search again) and many Java frameworks come with builtin tools for this.

Body:
I have a function in C++:

std::vector<std::vector<float>> const &GetVertices() { return m_Vertices; }

I need to return this value to Java through JNI.

So, because of the fact that I need to return vector of vector, I think that I have to use jobjectArray, like this:

extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_
java_helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
)

In Java, I have this method:

public native Object[] fillListWithData();

So, my question is, how to convert vector<vector<float>> to jobjectArray?

I know that there is a method that could create jobjectArray:

jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);

Then how can I put in the values ?

Full class implementation

extern "C" JNIEXPORT jobjectArray JNICALL
Java_com_google_ar_core_examples_java_
helloar_HelloArActivity_fillListWithData(
    JNIEnv *env,
    jobject /* this */
) {
    //verticesVec
    vector<vector<float>> verticesVec = initializer->GetVertices(); // THIS VECTOR I NEED TO CONVERT TO JOBJECTARRAY
    jobjectArray verticesArr = env->NewObjectArray(verticesVec.size(), WHAT CLASS SHOULD BE HERE?,NULL);

    //HOW TO FILL THE ARRAY HERE??

    return verticesArr;
}


问:
Built-in helper for "Must" pattern in Go
Is there a more built-in wrapper to make a function that returns (X, error) successfully execute or abort, like regexp.MustCompile?

I'm talking about something like this, but more "built-in".

答:
I have encountered the same problem myself and decided to develop the following solution: https://github.com/boramalper/must

Example:

database := must.MV(sql.Open("sqlite3", "...")).(*sql.DB)
defer must.M(database.Close())

must.M(database.Ping())

// Use MustValVoid (or MVV shortly) if you don't care about
// the return value.
must.MVV(database.Exec(`
    PRAGMA foreign_key_check;
    ...
`))
```


问:
Data replacement of data A using data B and comes out data B
The teacher table has elements of teacher's name , position, userid and password. I want to replace the userid with teacher's name in the another table named Subject so that it is easier to refer. So how can I do it using PHP coding ?

```<code><?php
    include ('connection.php');
    $data1 = mysqli_query($connect,"SELECT * FROM teacher");

    while ($info1=mysqli_fetch_array($data1))
    {
        echo "<option hidden selected> -- Your Option -- </option>";
        echo "<option value=$info1[userid]>$info1[name]</option>";
    }
</code>```

I expect to have the teacher's name as an option but it came out $info1[name]

答:
You just need to do syntax changes as follows:

```<code>while ($info1=mysqli_fetch_array($data1))
{
    echo "<option hidden selected> -- Your Option -- </option>";
    echo "<option value='$info1[userid]'>'$info1[name]'</option>";
}
</code>```

Because PHP take $info1[name] as a string, you need to use single quote to interpret the variable value.

Body:
The teacher table has elements of teacher's name , position, userid and password. I want to replace the userid with teacher's name in the another table named Subject so that it is easier to refer. So how can I do it using PHP coding ?

<?php
    include ('connection.php');
    $data1 = mysqli_query($connect,"SELECT * FROM teacher");

    while ($info1=mysqli_fetch_array($data1))
    {
        echo "<option hidden selected> -- Your Option -- </option>";
        echo "<option value=$info1[userid]>$info1[name]</option>";
    }

I expect to have the teacher's name as an option but it came out $info1[name]

Body:
You just need to do syntax changes as follows:

while ($info1=mysqli_fetch_array($data1))
{
    echo "<option hidden selected> -- Your Option -- </option>";
    echo "<option value='$info1[userid]'>'$info1[name]'</option>";
}

Because PHP take $info1[name] as a string, you need to use single quote to interpret the variable value.


问:
AWS IAM User with access to a folder in an Amazon EC2 instance
I have created an ubuntu instance in Amazon EC2. The instance has 3 project folders in the root directory:

```<code>/var/www/html/project_1
/var/www/html/project_2
/var/www/html/project_3
</code>```

I would like to add an IAM user for a developer with access to only project_1 folder and not the others. The developer can connect to the folder in the instance from ssh or sftp through Filezilla or ssh client but get access to only project_1 folder.

答:
You are mixing two types of authentication.

AWS IAM Users are granted permissions to make API calls to AWS services, such as launching an Amazon EC2 instance, uploading files to Amazon S3 and sending message to an Amazon SQS queue.

However, when logging into an Amazon EC2 instance running Linux, then the operating system on the instance is responsible for security, typically using SSH Keypairs associated with users. This type of security is completely separate from IAM Users. You cannot assign permissions on an instance to IAM Users.

Instead, you will need to:

Create separate Linux users on the EC2 instance

Use your standard corporate security to authenticate to the instance (eg Active Directory or LDAP). If you do not have a central directory authentication service, then you will need to generate keypairs for each user putting their public keypair in the user's .ssh/authorized_keys file inside their home directory.

Use standard Linux techniques to assign folder/file access to users on the instance (eg chown)

Users can then ssh/scp to the instance, providing their username and private keypair. They will have access to the files based upon permissions that were granted.

Bottom line: It's standard Linux. Assign permissions as you would for on-premises computers.

Body:
I have created an ubuntu instance in Amazon EC2. The instance has 3 project folders in the root directory:

/var/www/html/project_1
/var/www/html/project_2
/var/www/html/project_3

I would like to add an IAM user for a developer with access to only project_1 folder and not the others. The developer can connect to the folder in the instance from ssh or sftp through Filezilla or ssh client but get access to only project_1 folder.


问:
Database change notifications in asp.net core using signalr and sqldependency
If I made any changes in SQL table row then UI should automatically refresh the new changes without F5 or reloading the browser.

I have already tried this in asp.net mvc and its working good but I'm unable to do in asp.net mvc core..

答: You can detect changes using the SqlDependency class and then broadcast them to registered clients using SignalR. I wrote a sample using pre-Core SignalR, which is available at https://weblogs.asp.net/ricardoperes/broadcasting-database-changes-through-signalr. In order to make it work with ASP.NET Core SignalR you need to retrieve the hub using the service locator (HttpContext.RequestServices.GetService>). Also, there is a change that you must do to the client-side code.</p>


问:
An error occurred while installing bootsnap (1.4.4), and Bundler cannot continue after rails new in win10

An error occurred while installing bootsnap (1.4.4), and Bundler
  cannot continue. Make sure that gem install bootsnap -v '1.4.4'
  --source 'https://rubygems.org/' succeeds before bundling.

In Gemfile:   bootsnap

I tried installing rails with railsinstaller & followed this, since I'm a newb to ruby and stuff.:

https://www.tutorialspoint.com/ruby-on-rails/rails-installation.htm

and after the
$ rails new app command

I encounter that error I said above

答:
I think this is because of some issues conflicting with rails and windows 10. So the immediate solution will be to downgrade bootsnap version in gemfile

```<code>gem 'bootsnap', '<= 1.1.0'
</code>```

Another solution will be to follow rails installtion using https://rubyinstaller.org/

Body:
I think this is because of some issues conflicting with rails and windows 10. So the immediate solution will be to downgrade bootsnap version in gemfile

gem 'bootsnap', '<= 1.1.0'

Another solution will be to follow rails installtion using https://rubyinstaller.org/


问:
OpenCL2.0 runtime compiler not supporting c++11
I am trying to build an OpenCL kernel using OpenCL2.0. I am calling the cl::Program build function and passing the flag -cl-std=CL2.0. The g++ compiler finishes and links with no errors. However, when I run the program, the build function throws an exception (see below). Wanted to see if anyone has seen this before and has a solution. Thank you.

I tried other flags such as -cl-std=c++11, -cl-std=CL2.2, but none of these worked.

```<code>[20:03:47.768768][info][Demosaic] CL_FLAGS = -cl-std=CL2.0 -D IMAGE_MAD_INDEXING -D AMD_GPU_ARCH -D DEVICE_WAVEFRONT_SIZE=64 -D WG_SIZE_MAX=256
terminate called after throwing an instance of 'cl::BuildError'
[20:03:47.788335][error][Demosaic] Build failed: In file included from /tmp/OCL21460T1.cl:244:
/usr/include/CL/cl2.hpp:495:2: error: Visual studio 2013 or another C++11-supporting compiler required
#error Visual studio 2013 or another C++11-supporting compiler required
</code>```

答:
Is cl2.hpp not a file that should be #included in host code rather than OpenCL kernel code?

I assume it checks the value of __cplusplus which, if I'm reading the relevant section of the OpenCL C++ specification correctly, is not defined in the C++ dialect used for OpenCL kernels.

Body:
I am trying to build an OpenCL kernel using OpenCL2.0. I am calling the cl::Program build function and passing the flag -cl-std=CL2.0. The g++ compiler finishes and links with no errors. However, when I run the program, the build function throws an exception (see below). Wanted to see if anyone has seen this before and has a solution. Thank you.

I tried other flags such as -cl-std=c++11, -cl-std=CL2.2, but none of these worked.

[20:03:47.768768][info][Demosaic] CL_FLAGS = -cl-std=CL2.0 -D IMAGE_MAD_INDEXING -D AMD_GPU_ARCH -D DEVICE_WAVEFRONT_SIZE=64 -D WG_SIZE_MAX=256
terminate called after throwing an instance of 'cl::BuildError'
[20:03:47.788335][error][Demosaic] Build failed: In file included from /tmp/OCL21460T1.cl:244:
/usr/include/CL/cl2.hpp:495:2: error: Visual studio 2013 or another C++11-supporting compiler required
#error Visual studio 2013 or another C++11-supporting compiler required


问:
Merge two multidimensional arrays in PHP
Supposing I've this array:

```<code>Array
(
    [country] => Array
        (
            [0] => France
            [1] => Canada
        )
    [capital] => Array
        (
            [0] => Paris
            [1] => Ottawa
        )
    [other] => value
)
</code>```

Is it possible to merge the country and capital arrays ?

The desired output is the following:

```<code>Array
(
    [countries] => Array
        (
            Array
                (
                    [country] => France
                    [capital] => Paris
            )
            Array
                (
                    [country] => Canada
                    [capital] => Ottawa
            )
        )
    [other] => value
)
</code>```

What I tried:

```<code>$result = array();

foreach($arr as $key=>$array) {
    $result[$key] = array_merge($array, $arr2[$key]);
}
</code>```

答:
Try to use below code it will works 100%

thank you.

```<code><?php

$arr = [
    "country"=>["France","Canada"],
    "capital"=>["Paris","Ottawa"],
    "other"=>[]
];

$result = [
    "countries"=>[]
];

for($i=0;$i<count($arr["country"]);$i++){
    $data = [
        "country"=>$arr["country"][$i],
        "capital"=>$arr["capital"][$i]
    ];
    array_push($result["countries"],$data);
}

echo "```";
print_r($result);
echo "```";
</code>```

Body:
Supposing I've this array:

Array
(
    [country] => Array
        (
            [0] => France
            [1] => Canada
        )
    [capital] => Array
        (
            [0] => Paris
            [1] => Ottawa
        )
    [other] => value
)

Is it possible to merge the country and capital arrays ?

The desired output is the following:

Array
(
    [countries] => Array
        (
            Array
                (
                    [country] => France
                    [capital] => Paris
            )
            Array
                (
                    [country] => Canada
                    [capital] => Ottawa
            )
        )
    [other] => value
)

What I tried:

$result = array();

foreach($arr as $key=>$array) {
    $result[$key] = array_merge($array, $arr2[$key]);
}

Body:
Try to use below code it will works 100%

thank you.

<?php

$arr = [
    "country"=>["France","Canada"],
    "capital"=>["Paris","Ottawa"],
    "other"=>[]
];

$result = [
    "countries"=>[]
];

for($i=0;$i<count($arr["country"]);$i++){
    $data = [
        "country"=>$arr["country"][$i],
        "capital"=>$arr["capital"][$i]
    ];
    array_push($result["countries"],$data);
}

echo "<pre>";
print_r($result);
echo "</pre>";


问:
How to handle issues with Connections cannot be made(either DB or external systems) when multiple connections are available
I have question regarding handling the multiple connections. These connections can be either DB connection, SOA connection, EMS connection etc.....

Lets say I have 1 database connection where I pull data and I have 2 EMS connections both having different data and independent. The data is sent to EMS and update the status whether the data is successfully sent or not.

1) If the database connection is down or any other issues when we cannot access database
2) Any 1 EMS connection is down, the application should continue processing the other EMS connection.
3) What happens if we are able to send data to EMS, but cannot update the DB status bcos of database issues, what are we suppose to do with all the messages that are in memory and we need to send to EMS.
4) Cannot establish connection to 1 EMS, but the other were are able to establish and therefore the application should process that EMS messages.

These are some of the -ve test cases which I have to handle. Please feel free to let me know if any other issues I have to tackle

答:
Multiple connections to different sources, sounds like a good solution for System.Transactions (if EMS supports this).

Try something like this, this way all 3 operation eithr succeed or fail as a unit of work.

```<code>        try
        {
            using (TransactionScope tran = new TransactionScope())
            {
                Method1Save(); //DB
                Method2Save(); //EMS1
                Method3Save(); //EMS2
                tran.Complete();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Problem " + ex.ToString());
        }
</code>```

If EMS does't support a TransactionScope, then you will have to handle it manaully, probably by putting the transaction on the connection itself and then committing all the transactions once the operations succeed, which means keeping the connections open longer for each data source.

Body:
Multiple connections to different sources, sounds like a good solution for System.Transactions (if EMS supports this).

Try something like this, this way all 3 operation eithr succeed or fail as a unit of work.

        try
        {
            using (TransactionScope tran = new TransactionScope())
            {
                Method1Save(); //DB
                Method2Save(); //EMS1
                Method3Save(); //EMS2
                tran.Complete();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show("Problem " + ex.ToString());
        }

If EMS does't support a TransactionScope, then you will have to handle it manaully, probably by putting the transaction on the connection itself and then committing all the transactions once the operations succeed, which means keeping the connections open longer for each data source.


问:
How can I copy a shared slice to have a boxed slice?
I have a container:

pub struct Foo<T> {
    pub data: Box<[T]>,
}
```

<p>I would like a method to initialize a new one from an existing slice:</p>

<pre class="lang-rust prettyprint-override"><code>impl<T> Foo<T> {
    fn from_slice(slice: &[T]) -> Foo<T> {
        Foo {
            data: Box::new(/* something here */),
        }
    }
}
</code>```

I'd like to create a Foo instance from any kind of slice, coming from a dynamic vector or a static string.

I suppose there is a reason why vec! is a macro, but is there a way to avoid writing one? I guess I could do slice.to_vec().into_boxed_slice(), but it doesn't seem right to create a Vec as a proxy to a clone...

I'm not using a Vec in my struct because the data isn't supposed to change in size during the lifetime of my container. It didn't feel right to use a Vec but I may be wrong.

答:
If your slice contains Copy types, you can use From / Into to perform the construction:

```<code>pub struct Foo<T> {
    pub data: Box<[T]>,
}

impl<T> Foo<T> {
    fn from_slice(slice: &[T]) -> Foo<T>
    where
        T: Copy,
    {
        Foo { data: slice.into() }
    }
}
</code>```

If your data is Clone, then you can use to_vec + into_boxed_slice:

```<code>impl<T> Foo<T> {
    fn from_slice(slice: &[T]) -> Foo<T>
    where
        T: Clone,
    {
        Foo { data: slice.to_vec().into_boxed_slice() }
    }
}
</code>```

it doesn't seem right to create a Vec as a proxy to a clone

You aren't cloning here. When you clone a type T, you get a type T back. You are starting with a &[T] and want to get a Box<[T]>, not a [T] (which you can't have).

Creating a boxed slice through a Vec means that you temporarily take up 3 machine-sized integers instead of 2; this is unlikely to be a performance problem compared to the amount of allocation performed.

I do agree with starblue's answer that keeping a Vec<T> is probably simpler for most cases, but I admit that there are times where it's useful to have a boxed slice.

See also:

Initialize boxed slice without clone or copy

What is the use of into_boxed_slice() methods?

Performance comparison of a Vec and a boxed slice

I suppose there is a reason why vec! is a macro

The implementation of vec! is public:

```<code>macro_rules! vec {
    ($elem:expr; $n:expr) => (
        $crate::vec::from_elem($elem, $n)
    );
    ($($x:expr),*) => (
        <[_]>::into_vec(box [$($x),*])
    );
    ($($x:expr,)*) => (vec![$($x),*])
}
</code>```

It's really only a macro for syntax convenience (and because it uses the unstable box keyword); it takes the arguments, creates an array, boxes it, coerces it to a boxed slice, then converts it to a Vec.

Body:
I have a container:

pub struct Foo<T> {
    pub data: Box<[T]>,
}

I would like a method to initialize a new one from an existing slice:

impl<T> Foo<T> {
    fn from_slice(slice: &[T]) -> Foo<T> {
        Foo {
            data: Box::new(/* something here */),
        }
    }
}

I'd like to create a Foo instance from any kind of slice, coming from a dynamic vector or a static string.

I suppose there is a reason why vec! is a macro, but is there a way to avoid writing one? I guess I could do slice.to_vec().into_boxed_slice(), but it doesn't seem right to create a Vec as a proxy to a clone...

I'm not using a Vec in my struct because the data isn't supposed to change in size during the lifetime of my container. It didn't feel right to use a Vec but I may be wrong.

Body:
If your slice contains Copy types, you can use From / Into to perform the construction:

pub struct Foo<T> {
    pub data: Box<[T]>,
}

impl<T> Foo<T> {
    fn from_slice(slice: &[T]) -> Foo<T>
    where
        T: Copy,
    {
        Foo { data: slice.into() }
    }
}

If your data is Clone, then you can use to_vec + into_boxed_slice:

impl<T> Foo<T> {
    fn from_slice(slice: &[T]) -> Foo<T>
    where
        T: Clone,
    {
        Foo { data: slice.to_vec().into_boxed_slice() }
    }
}

it doesn't seem right to create a Vec as a proxy to a clone

You aren't cloning here. When you clone a type T, you get a type T back. You are starting with a &[T] and want to get a Box<[T]>, not a [T] (which you can't have).

Creating a boxed slice through a Vec means that you temporarily take up 3 machine-sized integers instead of 2; this is unlikely to be a performance problem compared to the amount of allocation performed.

I do agree with starblue's answer that keeping a Vec<T> is probably simpler for most cases, but I admit that there are times where it's useful to have a boxed slice.

See also:

Initialize boxed slice without clone or copy

What is the use of into_boxed_slice() methods?

Performance comparison of a Vec and a boxed slice

I suppose there is a reason why vec! is a macro

The implementation of vec! is public:

macro_rules! vec {
    ($elem:expr; $n:expr) => (
        $crate::vec::from_elem($elem, $n)
    );
    ($($x:expr),*) => (
        <[_]>::into_vec(box [$($x),*])
    );
    ($($x:expr,)*) => (vec![$($x),*])
}

It's really only a macro for syntax convenience (and because it uses the unstable box keyword); it takes the arguments, creates an array, boxes it, coerces it to a boxed slice, then converts it to a Vec.


问:
How is possible build apk in terminal with different SIGN credentials
I have build.gradle that can have signingConfigs, but I want TO ignore this setting and use other credentials. I don't want to edit or replace values in build.gradle.

Does gradle have same command like gradle assemble -storeFile='PATH' -storePassword='password' -keyAlias='alias' -keyPassword='password'?

If it's no way create signed apk with other signingConfigs, is it possible to create unsigned apk?

答:
I suggest you using the solution reported by @Ranjan. It is the cleaner and a standard solution.

However if you would like to use the command line command, all properties passed to gradle in the command line via -P parameter are accessible in the project variable in your gradle script.
You can do something like that:

```<code>gradle assembleRelease -PmyKeyPassword='xxx' -PmyStorePassword='xxx' -PmyKeyAlias='xxx' -PmyStoreFile='...xxx.keystore'
</code>```

and then define in your build.gradle.

```<code>signingConfigs {
   release {
      storeFile project.mystoreFile
      storePassword project.myStorePassword
      keyAlias project.myKeyAlias
      keyPassword project.myKeyPassword
   }
}
</code>```

Pay attention because it can cause errors if you don't specify the keys in the gradle command (not so good in my point of view).
You can mitigate the issue doing a check on the parameter (using the project.hasProperty(xxx) method) and defining the default value in the build.gradle.

Something like that:

```<code>signingConfigs {
       release {
         storeFile project.hasProperty('myStoreFile') ? project.myStoreFile : 'default'
         //..
       }
}
</code>```

Body:
I suggest you using the solution reported by @Ranjan. It is the cleaner and a standard solution.

However if you would like to use the command line command, all properties passed to gradle in the command line via -P parameter are accessible in the project variable in your gradle script.
You can do something like that:

gradle assembleRelease -PmyKeyPassword='xxx' -PmyStorePassword='xxx' -PmyKeyAlias='xxx' -PmyStoreFile='...xxx.keystore'

and then define in your build.gradle.

signingConfigs {
   release {
      storeFile project.mystoreFile
      storePassword project.myStorePassword
      keyAlias project.myKeyAlias
      keyPassword project.myKeyPassword
   }
}

Pay attention because it can cause errors if you don't specify the keys in the gradle command (not so good in my point of view).
You can mitigate the issue doing a check on the parameter (using the project.hasProperty(xxx) method) and defining the default value in the build.gradle.

Something like that:

signingConfigs {
       release {
         storeFile project.hasProperty('myStoreFile') ? project.myStoreFile : 'default'
         //..
       }
}


问:
Events or operations in gmail add ins
I'm trying to create a Gmail web add-in using apps-script in which I am trying to do the following things:

make an API call on receiving an email.

label emails.

move emails to

spam. get all emails of a specific folder.

Is this possible? If Yes then how? Please give me the links to any documentation or tutorials for the same.

答:
It is sort of possible, but you should be aware that Gmail Add-ons can be triggered either by opening an email or opening compose Ui both by explicit user interaction with Gmail, not when an email is recieved (though, Gmail Add-ons platform is growing and this trigger can be added in the near future).

As for the actions 2-4, they are entirely possible, you should take a look at the following references:

Gmail Add-ons guide and reference;

GitHub repo with sample Add-ons from Google;

OAuth2.0 library for 3P service calls (if it authenticates via OAuth2.0);

Gmail service reference for apps script.

This should definitely help you get started, happy coding!

Title: Events or operations in gmail add ins


答:
```<code>SELECT CONVERT_TZ(`timestamp`, @@session.time_zone, '+00:00') AS `time`,
       AVG(value / 1000) as "value",
       name as "metric" -- phase / line
FROM `power`
WHERE name IN ("PhaseA_Energy", "PhaseB_Energy", "PhaseC_Energy")
AND $__timeFilter(timestamp)
GROUP BY date_format( timestamp, '%Y-%m-%d %H' ), name
</code>```

Title: mysql clculate daily kWh consumption from solar inverter

Body:
i read data from solar inverter and store it into mysql database

the table has 2 fields dtime records the date and time and AC_Output_Apparent_Power records the current load in Watts.

what i need is to calculate total daily wattage consumption like this (example):

date        kWh
2018-10-24  1.3
2018-10-10 0.700
2018-10-09 2.2

and so on...

i tried:

SELECT date(dtime),hour(dtime),((avg(AC_Output_Apparent_Power) *1)/1000) as kWh
FROM `logs`
WHERE AC_Output_Apparent_Power > 0
GROUP by date(dtime),hour(dtime)
order by dtime desc

and the result is hourly consumption:

date       hour     kWh
2018-10-25  2   0.20880952
2018-10-25  1   0.23985294
2018-10-24  18  0.29619231
2018-10-23  6   0.11400000
2018-10-22  6   0.13800000
2018-10-22  2   0.13800000
2018-10-18  1   0.13800000
2018-10-16  10  0.09200000
2018-10-15  13  0.09100000
2018-10-14  21  0.13800000
2018-10-13  22  0.13700000
2018-10-13  8   0.09200000
2018-10-12  6   0.18966667
2018-10-12  5   0.17800000
2018-10-12  4   0.13800000
2018-10-10  15  0.25100000
2018-10-10  14  0.61285714
2018-10-09  18  0.13800000
2018-10-09  1   0.15150000
2018-10-04  5   0.14728947
2018-10-04  4   0.15062500
2018-10-04  3   0.14927778
2018-10-04  2   0.14958974
2018-10-04  1   0.14726744
2018-10-04  0   0.14886207

the mysql table has these values.

Note: as you see the data is not read regularly as i am testing

SELECT dtime,AC_Output_Apparent_Power FROM `logs` WHERE AC_Output_Apparent_Power > 0 order by dtime desc

dtime                  AC_Output_Apparent_Power
2018-10-24 18:20:25     152
2018-10-24 18:20:02     174
2018-10-24 18:19:50     174
2018-10-24 18:19:38     174
2018-10-24 18:19:26     173
2018-10-24 18:19:03     174
2018-10-24 18:18:51     154
2018-10-24 18:18:04     174
2018-10-24 18:17:53     175
2018-10-24 18:17:46     174
2018-10-24 18:17:29     175
2018-10-24 18:17:17     175
2018-10-24 18:17:05     174
2018-10-24 18:16:53     174
2018-10-24 18:16:48     174
2018-10-24 18:16:18     816
2018-10-24 18:15:54     174
2018-10-24 18:15:42     174
2018-10-24 18:15:30     852
2018-10-24 18:15:18     173
2018-10-24 18:15:07     174
2018-10-24 18:14:55     1084
2018-10-24 18:14:32     174
2018-10-24 18:14:26     173
2018-10-24 18:13:33     176
2018-10-24 18:13:21     152
2018-10-24 18:13:09     175
2018-10-24 18:12:58     174
2018-10-24 18:12:47     939
2018-10-24 18:12:37     174
2018-10-24 18:12:30     175
2018-10-24 18:11:48     815
2018-10-24 18:11:01     880
2018-10-24 18:10:49     924
2018-10-24 18:10:37     753
2018-10-24 18:10:13     154
2018-10-24 18:10:01     176
2018-10-24 18:09:50     174
2018-10-24 18:09:38     175
2018-10-24 18:09:26     176
2018-10-24 18:09:15     176
2018-10-24 18:09:03     176
2018-10-24 18:08:52     154
2018-10-24 18:08:40     176
2018-10-24 18:08:27     176
2018-10-24 18:08:16     176
2018-10-24 18:08:04     928
2018-10-24 18:07:52     176
2018-10-24 18:07:41     177
2018-10-24 18:07:29     176
2018-10-24 18:07:17     177
2018-10-24 18:06:54     178
2018-10-23 06:06:12     114
2018-10-22 06:49:01     138
2018-10-22 02:00:29     138
2018-10-18 01:47:54     138
2018-10-16 10:04:14     92
2018-10-15 13:59:27     91
2018-10-14 21:59:44     138
2018-10-13 22:01:48     137
2018-10-13 08:37:37     92
2018-10-13 08:02:43     92
2018-10-12 06:05:53     190
2018-10-12 06:05:41     190
2018-10-12 06:03:08     189
2018-10-12 05:58:59     166
2018-10-12 05:58:12     190
2018-10-12 04:31:56     138
2018-10-10 15:08:31     241
2018-10-10 15:06:34     370
2018-10-10 15:05:35     239
2018-10-10 15:03:02     154
2018-10-10 14:58:41     864
2018-10-10 14:58:16     456
2018-10-10 14:58:07     415
2018-10-10 14:57:53     545
2018-10-10 14:57:41     714
2018-10-10 14:56:43     1300
2018-10-10 14:56:22     949
2018-10-10 14:55:55     608
2018-10-10 14:55:45     522
2018-10-10 14:54:45     415
2018-10-10 14:54:34     431
2018-10-10 14:54:10     503
2018-10-10 14:53:47     506
2018-10-10 14:53:35     438
2018-10-10 14:53:23     417
2018-10-10 14:45:43     874
2018-10-10 14:45:31     442
2018-10-10 14:45:08     710
2018-10-10 14:44:19     421
2018-10-10 14:44:07     604
2018-10-10 14:40:23     736
2018-10-09 18:05:58     138
2018-10-09 01:05:55     153
2018-10-09 01:05:29     153
2018-10-09 01:05:04     152
2018-10-09 01:04:40     151
2018-10-09 01:04:13     151
2018-10-09 01:03:47     152

Watts to kWh calculation
The energy E in kilowatt-hours (kWh) is equal to the power P in watts (W),
times the time period t in hours (hr) divided by 1000:

E(kWh) = P(W) × t(hr) / 1000

How to calculate total daily wattage consumption not hourly.

any suggestions are welcomed.
thanks in advance.


问:
How to add jarray Object into JObject
How to add JArray into JObject?  I am getting an exception when changing the jarrayObj into JObject.

```<code>parameterNames = "Test1,Test2,Test3";

JArray jarrayObj = new JArray();

foreach (string parameterName in parameterNames)
{
    jarrayObj.Add(parameterName);
}

JObject ObjDelParams = new JObject();
ObjDelParams["_delete"] = jarrayObj;

JObject UpdateAccProfile = new JObject(
                               ObjDelParams,
                               new JProperty("birthday", txtBday),
                               new JProperty("email", txtemail))
</code>```

I need output in this form:

```<code>{
    "_delete": ["Test1","Test2","Test3"],
    "birthday":"2011-05-06",
    "email":"dude@test.com"
}
</code>```

答:
```<code>var jObject = new JObject();
jObject.Add("birthday", "2011-05-06");
jObject.Add("email", "dude@test.com");
var items = new [] { "Item1", "Item2", "Item3" };
var jSonArray = JsonConvert.SerializeObject(items);
var jArray = JArray.Parse(jSonArray);
jObject.Add("_delete", jArray);
</code>```

Title: How to add jarray Object into JObject

Body:
How to add JArray into JObject?  I am getting an exception when changing the jarrayObj into JObject.

parameterNames = "Test1,Test2,Test3";

JArray jarrayObj = new JArray();

foreach (string parameterName in parameterNames)
{
    jarrayObj.Add(parameterName);
}

JObject ObjDelParams = new JObject();
ObjDelParams["_delete"] = jarrayObj;

JObject UpdateAccProfile = new JObject(
                               ObjDelParams,
                               new JProperty("birthday", txtBday),
                               new JProperty("email", txtemail))

I need output in this form:

{
    "_delete": ["Test1","Test2","Test3"],
    "birthday":"2011-05-06",
    "email":"dude@test.com"
}


问:
Regular expression to replace content between parentheses ()
I tried this code:

```<code>string.replaceAll("\\(.*?)","");
</code>```

But it returns null. What am I missing?

答:
First, Do you wish to remove the parentheses along with their content? Although the title of the question indicates no, I am assuming that you do wish to remove the parentheses as well.

Secondly, can the content between the parentheses contain nested matching parentheses? This solution assumes yes. Since the Java regex flavor does not support recursive expressions, the solution is to first craft a regex which matches the "innermost" set of parentheses, and then apply this regex in an iterative manner replacing them from the inside-out. Here is a tested Java program which correctly removes (possibly nested) parentheses and their contents:

import java.util.regex.*;
public class TEST {
    public static void main(String[] args) {
        String s = "stuff1 (foo1(bar1)foo2) stuff2 (bar2) stuff3";
        String re = "\\([^()]*\\)";
        Pattern p = Pattern.compile(re);
        Matcher m = p.matcher(s);
        while (m.find()) {
            s = m.replaceAll("");
            m = p.matcher(s);
        }
        System.out.println(s);
    }
}
```

<p><strong>Test Input:</strong></p>

```"stuff1 (foo1(bar1)foo2) stuff2 (bar2) stuff3"
```

<p><strong>Test Output:</strong></p>

```"stuff1  stuff2  stuff3"
```

Note that the lazy-dot-star solution will never work, because it fails to match the innermost set of parentheses when they are nested. (i.e. it erroneously matches: (foo1(bar1) in the example above.) And this is a very commonly made regex mistake: Never use the dot when there is a more precise expression! In this case, the contents between an "innermost" set of matching parentheses consists of any character that is not an opening or closing parentheses, (i.e. Use: [^()]* instead of: .*?).

Body:
I tried this code:

string.replaceAll("\\(.*?)","");

But it returns null. What am I missing?

Body:
First, Do you wish to remove the parentheses along with their content? Although the title of the question indicates no, I am assuming that you do wish to remove the parentheses as well.

Secondly, can the content between the parentheses contain nested matching parentheses? This solution assumes yes. Since the Java regex flavor does not support recursive expressions, the solution is to first craft a regex which matches the "innermost" set of parentheses, and then apply this regex in an iterative manner replacing them from the inside-out. Here is a tested Java program which correctly removes (possibly nested) parentheses and their contents:

import java.util.regex.*;
public class TEST {
    public static void main(String[] args) {
        String s = "stuff1 (foo1(bar1)foo2) stuff2 (bar2) stuff3";
        String re = "\\([^()]*\\)";
        Pattern p = Pattern.compile(re);
        Matcher m = p.matcher(s);
        while (m.find()) {
            s = m.replaceAll("");
            m = p.matcher(s);
        }
        System.out.println(s);
    }
}

Test Input:

"stuff1 (foo1(bar1)foo2) stuff2 (bar2) stuff3"

Test Output:

"stuff1  stuff2  stuff3"

Note that the lazy-dot-star solution will never work, because it fails to match the innermost set of parentheses when they are nested. (i.e. it erroneously matches: (foo1(bar1) in the example above.) And this is a very commonly made regex mistake: Never use the dot when there is a more precise expression! In this case, the contents between an "innermost" set of matching parentheses consists of any character that is not an opening or closing parentheses, (i.e. Use: [^()]* instead of: .*?).


问:
Transform Rotate Menu Item Circular Menu
I have modified a circular menu that I found on this pen
But I am having trouble rotating the menu items around the main circle. By default of this pen, the button's bottom part is perpendicular to it's relative position, but since I changed them with font icons, they look upside down or crooked.

I'm a CSS noob, so I need some help please, been at this for hours!

I've tried a couple of things like:

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}
```
<p>or something like</p>
<pre class="lang-css prettyprint-override"><code>menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
}
</code>```

None of them seems to be working. Currently my component looks like this:

Here is my full CSS and HTML...

menu {
  box-sizing: border-box;
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!--<menu>
    <li><i className="fas fa-bell"></i></li>
    <li><i className="fas fa-cog"></i></li>
    <li><i className="fas fa-terminal"></i></li>
</menu>-->

<menu>
    <li>1</li>
    <li>2</li>
    <li>3</li>
</menu></code>```

答:
This has fixed your rotation problem. please check my code.

I have added after each li and set rotation in after, here is the code what I added.

```<code>menu li i{
  content: "1";
  display: flex !important;
  align-items: center;
  justify-content: center;
  transform-origin: center;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  border-radius: 100%;
}

menu li:nth-of-type(1) i {
  transform: rotate(180deg);
}

menu li:nth-of-type(2) i {
  transform: rotate(230deg);
}

menu li:nth-of-type(3) i {
  transform: rotate(280deg);
}
</code>```

And this is your full code.

```<code>menu {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}

menu li i{
  content: "1";
  display: flex !important;
  align-items: center;
  justify-content: center;
  transform-origin: center;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  border-radius: 100%;
}

menu li:nth-of-type(1) i {
  transform: rotate(180deg);
}

menu li:nth-of-type(2) i {
  transform: rotate(230deg);
}

menu li:nth-of-type(3) i {
  transform: rotate(280deg);
}
</code>```

And here is the HTML

```<code>    <menu>
    <li><i class="fas fa-bell"></i></li>
    <li><i class="fas fa-cog"></i></li>
    <li><i class="fas fa-terminal"></i></li>
</menu>
</code>```

Body:
I have modified a circular menu that I found on this pen
But I am having trouble rotating the menu items around the main circle. By default of this pen, the button's bottom part is perpendicular to it's relative position, but since I changed them with font icons, they look upside down or crooked.

I'm a CSS noob, so I need some help please, been at this for hours!

I've tried a couple of things like:

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

or something like

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
}

None of them seems to be working. Currently my component looks like this:

Here is my full CSS and HTML...

menu {
  box-sizing: border-box;
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li::after{
  transform: rotate(0deg);
  -webkit-transform: rotate(0deg);
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}

<menu>

1

2

3

</menu>

Body:
This has fixed your rotation problem. please check my code.

I have added after each li and set rotation in after, here is the code what I added.

menu li i{
  content: "1";
  display: flex !important;
  align-items: center;
  justify-content: center;
  transform-origin: center;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  border-radius: 100%;
}

menu li:nth-of-type(1) i {
  transform: rotate(180deg);
}

menu li:nth-of-type(2) i {
  transform: rotate(230deg);
}

menu li:nth-of-type(3) i {
  transform: rotate(280deg);
}

And this is your full code.

menu {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
  background-color: #2e7bbd;
  margin: -45px 0 0 -45px;
  position: fixed;
  width: 90px;
  height: 90px;
  border-radius: 50%;
  cursor: pointer;
  right: 2%;
  bottom: 2%;
  z-index: 99999;
  -moz-box-sizing: border-box;
  -webkit-box-sizing: border-box;
  box-sizing: border-box;
}

menu:before, menu:after {
  content: "";
  z-index: 2;
  position: fixed;
  width: 3px;
  height: 22.5px;
  cursor: pointer;
  background-color: #fbfdff;
  top: 50%;
  left: 50%;
}

menu:before {
  -webkit-transform: translate(-50%, -50%) rotate(-90deg);
  transform: translate(-50%, -50%) rotate(-90deg);
}
menu:after {
  -webkit-transform: translate(-50%, -50%) rotate(0deg);
  transform: translate(-50%, -50%) rotate(0deg);
}

menu li {
  transition: all 0.25s ease-in-out;
  transition-delay: 0.75s;
  width: 59.4px;
  height: 59.4px;
  margin: -29.7px 0 0 -29.7px;
  opacity: 0;
  text-align: center;
  font-size: 18px;
  font-family: Helvetica, sans-serif;
  font-weight: 100;
  line-height: 59.4px;
  color: #fbfdff;
  border-radius: 50%;
  background-color: #428dce;
  list-style-type: none;
  position: fixed;
  z-index: 100;
  left: 50%;
  top: 50%;
}

menu li li:nth-of-type(1) {
  -webkit-transform: rotate(180deg) translate(0, 0);
  transform: rotate(180deg) translate(0, 0);
  animation-name: crazy;
  animation-duration: 2s;
  animation-delay: 1s;
  animation-iteration-count: infinite;
}

menu li li:nth-of-type(2) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu li li:nth-of-type(3) {
  -webkit-transform: rotate(0deg) translate(0, 0);
  transform: rotate(0deg) translate(0, 0);
}

menu:hover {
  -webkit-transform: rotate(-180deg);
  transform: rotate(-180deg);
  transition-delay: 0s;
}

menu:hover li {
  transition-delay: 0.1s;
  opacity: 1;
}

menu:hover li:nth-of-type(1) {
  -webkit-transform: rotate(359deg) translate(0, 90px);
  transform: rotate(359deg) translate(0, 90px);
}

menu:hover li:nth-of-type(2) {
  -webkit-transform: rotate(310deg) translate(0, 90px);
  transform: rotate(310deg) translate(0, 90px);
}

menu:hover li:nth-of-type(3) {
  -webkit-transform: rotate(260deg) translate(0, 90px);
  transform: rotate(260deg) translate(0, 90px);
}

menu li i{
  content: "1";
  display: flex !important;
  align-items: center;
  justify-content: center;
  transform-origin: center;
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  border-radius: 100%;
}

menu li:nth-of-type(1) i {
  transform: rotate(180deg);
}

menu li:nth-of-type(2) i {
  transform: rotate(230deg);
}

menu li:nth-of-type(3) i {
  transform: rotate(280deg);
}

And here is the HTML

    <menu>
    <li><i class="fas fa-bell"></i></li>
    <li><i class="fas fa-cog"></i></li>
    <li><i class="fas fa-terminal"></i></li>
</menu>


问:
Jest unable to load module vue-cookies
```<code>console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
  [Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read property 'get' of undefined"

  found in

  ---> <Anonymous>
         <Root>
console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884
  TypeError: Cannot read property 'get' of undefined
      at VueComponent.mounted (/home/ubuntu/vue-testing-skel/src/components/ChatApp.vue:66:1)
</code>```

The line that is causing the error:

```<code>    this.current_nickname = this.$cookies.get('nickname')
</code>```

this.$cookies is provided by a module called vue-cookies

I have it installed and saved in my devDependencies, but it seems jest is unable to find it or load it.

I'm not sure what I have to do to make sure Jest is loading these modules properly.

答:
Testing with Jest is meant to be self-contained. This means that global objects like this.$cookies are not available since they are interfacing with the cookies in your browser. The way to solve this is to mock the global functions. More info on how to do that here:
https://lmiller1990.github.io/vue-testing-handbook/mocking-global-objects.html#example-with-vue-i18n</p>

Title: Jest unable to load module vue-cookies

Body:
console.error node_modules/vue/dist/vue.runtime.common.dev.js:621
  [Vue warn]: Error in mounted hook (Promise/async): "TypeError: Cannot read property 'get' of undefined"

  found in

  ---> <Anonymous>
         <Root>
console.error node_modules/vue/dist/vue.runtime.common.dev.js:1884
  TypeError: Cannot read property 'get' of undefined
      at VueComponent.mounted (/home/ubuntu/vue-testing-skel/src/components/ChatApp.vue:66:1)

The line that is causing the error:

    this.current_nickname = this.$cookies.get('nickname')

this.$cookies is provided by a module called vue-cookies

I have it installed and saved in my devDependencies, but it seems jest is unable to find it or load it.

I'm not sure what I have to do to make sure Jest is loading these modules properly.


问:
How to print $1, $2 and then all remaining parameters together in AWK
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

```<code>sctl   sudo         systemctl
pac    sudo         pacman
</code>```

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

```<code>    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file
</code>```

And the end result would be something like this:

```<code>abbr sctl "sudo systemctl"
abbr pac "sudo pacman"
</code>```

But this code doesn't work when the line has many parts after the 3rd parameter:

```<code>svu    playerctl    -p spotify volume +0.05
</code>```

How can i go about printing in that format? $1 $2 ($3..$N)

答:
Substitute the two extra fields out of existence.

```<code>$ echo "svu playerctl -p spotify volume +0.05" | gawk '
  { print $1; $1 = ""
    print $2; $2 = ""
    print substr($0,3) } '
svu
playerctl
-p spotify volume +0.05
</code>```

The substr removes the output field separators from the remnants of the first two fields.

Body:
I'm making a script that generates aliases/abbreviations from a base file. The base file structure is something like this:

sctl   sudo         systemctl
pac    sudo         pacman

This works fine with the following code that reads the base file, removes comments and awks the abbreviation line on the abbreviation file:

    sed "s/\s*#.*$//;/^\s*$/d" $command_file |
    awk -v c=$cmd -v o="$comp" '{ print c" "$1""o"\""$2" "$3"\"" }' >> $file

And the end result would be something like this:

abbr sctl "sudo systemctl"
abbr pac "sudo pacman"

But this code doesn't work when the line has many parts after the 3rd parameter:

svu    playerctl    -p spotify volume +0.05

How can i go about printing in that format? $1 $2 ($3..$N)

Body:
Substitute the two extra fields out of existence.

$ echo "svu playerctl -p spotify volume +0.05" | gawk '
  { print $1; $1 = ""
    print $2; $2 = ""
    print substr($0,3) } '
svu
playerctl
-p spotify volume +0.05

The substr removes the output field separators from the remnants of the first two fields.