问:
Why won't my nav lis display horizontally with floats?
I'm new to coding and trying to figure out why my nav li's will not display horizontally? I've tried a few things which I've noted in the code below.

The catch here is, I must use floats instead of flexbox.

header nav>* {
  float: left;
  width: 7%;
  margin: 0 5%;
  padding-bottom: 30px;
  list-style: none;
  text-decoration: none;
}

header nav ul li {
  width: 100px;
  float: right;
  display: block;
  text-decoration: none;
  /*margin-left: 2px;
  display: inline; not working*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    Courses
    <form action="">
      <input type="text" placeholder="Search">
    </form>
    <img class="icon" src="#">
    <h2>Tech Academy</h2>
    <ul id="SideBar">
      <li>Donate</li>
      <li>Login</li>
      <li>Sign up</li>
    </ul>
  </nav>
</header></code>```

I have tried changing the specificity to a class or id and that hasn't fixed anything. I should also note that 'text-decoration' is not working for the li but is working for the a 'courses'? * border: box-sizing is also at the top of the css sheet.

This is what it looks like on the browser

I am very new to coding and this one has had me stumped for hours. T

答:
You can use flexbox to arrange them either column or row. Declaring display: flex; should apply what you're trying to do. See the snippet below:

header nav>* {
  float: left;
  width: 7%;
  margin: 0 5%;
  padding-bottom: 30px;
  list-style: none;
  text-decoration: none;
}

header nav ul li {
  width: 100px;
  float: right;
  display: block;
  text-decoration: none;
  /*margin-left: 2px;
  display: inline; not working*/
}

#SideBar{
  display: flex;
  gap: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <nav>
    Courses
    <form action="">
      <input type="text" placeholder="Search">
    </form>
    <img class="icon" src="#">
    <h2>Tech Academy</h2>
    <ul id="SideBar">
      <li>Donate</li>
      <li>Login</li>
      <li>Sign up</li>
    </ul>
  </nav>
</header></code>```

More on flexbox here.

Body:
I'm new to coding and trying to figure out why my nav li's will not display horizontally? I've tried a few things which I've noted in the code below.

The catch here is, I must use floats instead of flexbox.

header nav>* {
  float: left;
  width: 7%;
  margin: 0 5%;
  padding-bottom: 30px;
  list-style: none;
  text-decoration: none;
}

header nav ul li {
  width: 100px;
  float: right;
  display: block;
  text-decoration: none;
  /*margin-left: 2px;
  display: inline; not working*/
}

    Courses
    <form action="">
      <input type="text" placeholder="Search">
    </form>

Tech Academy

Donate

Login

Sign up

I have tried changing the specificity to a class or id and that hasn't fixed anything. I should also note that 'text-decoration' is not working for the li but is working for the a 'courses'? * border: box-sizing is also at the top of the css sheet.

This is what it looks like on the browser

I am very new to coding and this one has had me stumped for hours. T

Body:
You can use flexbox to arrange them either column or row. Declaring display: flex; should apply what you're trying to do. See the snippet below:

header nav>* {
  float: left;
  width: 7%;
  margin: 0 5%;
  padding-bottom: 30px;
  list-style: none;
  text-decoration: none;
}

header nav ul li {
  width: 100px;
  float: right;
  display: block;
  text-decoration: none;
  /*margin-left: 2px;
  display: inline; not working*/
}

#SideBar{
  display: flex;
  gap: 5px;
}

<header>
  <nav>
    <a href="#">Courses</a>
    <form action="">
      <input type="text" placeholder="Search">
    </form>
    <img class="icon" src="#">
    <h2>Tech Academy</h2>
    <ul id="SideBar">
      <li><a href="#">Donate</a></li>
      <li><a href="#">Login</a></li>
      <li><a href="#">Sign up</a></li>
    </ul>
  </nav>
</header>

More on flexbox here.


来源: stackexchange

问:
How can I put separate row of dictionary into Dataframe and export to csv file?
Data is Dictionary in a separate line.
How can I put it together into Dataframe and export to civ file?</p>
```<code>json_responses = response.text.split('\n')
for item in json_responses:
    if item != '':
        dic = json.loads(item)
        print(dic)
</code>```
```<code>{'sku_id': 'A', 'primary_category_code': 'AA52103320001', 'primary_store': 'F0001001'}
{'sku_id': 'B', 'primary_category_code': 'AA52103320001', 'primary_store': 'F0001001'}
{'sku_id': 'C', 'primary_category_code': 'AA52103320002', 'primary_store': 'F0001002'}
{'sku_id': 'D', 'primary_category_code': 'AA52103320002', 'primary_store': 'F0001002'}
</code>```

答:
You can collect the dicts in a list and pass it to DataFrame constructor.

```<code>import json
lst_of_dic = [json.loads(item) for item in response.text.split('\n') if item != '']
df = pd.DataFrame(lst_of_dic)
</code>```

Output:

```<code>  sku_id primary_category_code primary_store
0      A         AA52103320001      F0001001
1      B         AA52103320001      F0001001
2      C         AA52103320002      F0001002
3      D         AA52103320002      F0001002
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Data is Dictionary in a separate line.
How can I put it together into Dataframe and export to civ file?

json_responses = response.text.split('\n')
for item in json_responses:
    if item != '':
        dic = json.loads(item)
        print(dic)

{'sku_id': 'A', 'primary_category_code': 'AA52103320001', 'primary_store': 'F0001001'}
{'sku_id': 'B', 'primary_category_code': 'AA52103320001', 'primary_store': 'F0001001'}
{'sku_id': 'C', 'primary_category_code': 'AA52103320002', 'primary_store': 'F0001002'}
{'sku_id': 'D', 'primary_category_code': 'AA52103320002', 'primary_store': 'F0001002'}

Body:
You can collect the dicts in a list and pass it to DataFrame constructor.

import json
lst_of_dic = [json.loads(item) for item in response.text.split('\n') if item != '']
df = pd.DataFrame(lst_of_dic)

Output:

  sku_id primary_category_code primary_store
0      A         AA52103320001      F0001001
1      B         AA52103320001      F0001001
2      C         AA52103320002      F0001002
3      D         AA52103320002      F0001002


问:
How to use fa-plus-circle icon next to a text field using CSS and HTML?
I want to use fa-plus-circle item next to the text field as below. How can I achieve that using CSS and HTMl. I haven't use any CSS right now since it's affecting to all the other places that using fa-plus-circle.

.html

```<code> <div class="col-sm-6">
        <label class="col-sm-3 col-form-label" >My Name <span class="fa fa-star required-field"></span> </label>
         <input type="text" class="form-control"><span
             class="fa fa-plus-circle text-success cursor-point"></span>
    </div>
</code>```

答:
https://getbootstrap.com/docs/5.0/forms/input-group/

You can use input group for this

```<code><div class="input-group mb-3">
  <input type="text" class="form-control">
  <span class="input-group-text">
    <span class="fa fa-plus-circle text-success cursor-point"></span>
  </span>
</div>
</code>```

Body:
I want to use fa-plus-circle item next to the text field as below. How can I achieve that using CSS and HTMl. I haven't use any CSS right now since it's affecting to all the other places that using fa-plus-circle.

.html

        My Name
         <input type="text" class="form-control">

Body:
https://getbootstrap.com/docs/5.0/forms/input-group/

You can use input group for this

<div class="input-group mb-3">
  <input type="text" class="form-control">
  <span class="input-group-text">
    <span class="fa fa-plus-circle text-success cursor-point"></span>
  </span>
</div>


问:
Display REST API content in Azure DevOps Pipelines
Im new to Azure and Postman.

Is there a way to display the content of a (GET)Rest API in Azure DevOPS.
The content should be displayed inside the "Run Cake script" in the Pipeline.

Right now i have this:

```<code>Task("Deploy")
    .IsDependentOn("Pack")
    .Does(() =>
    {
        //Code to print the content of the API packages.
    });
</code>```

How do i proceed?
Once again, im new to this so i might be missing a lot of information that you need in order to help me. In that case, let me know! :)

答:
I'm not familar with Cake script, there are 2 ways to do authentication for Azure DevOps API.

Private PAT

Environment Variable: System.AccessToken

if you want to call Azure DevOps API in your pipeline, you can conside use System.AccessToken.

Here is Powershell Script for your reference, the field of Authorization is different.

```<code>function Http-Request {
    param (
        [Parameter(Mandatory=$true)]
        [string] $Url,
        [Parameter(Mandatory=$false)]
        [string] $SystemToken
    )
    if([string]::IsNullOrEmpty($SystemToken)) {
        $pat = 'YOUR_PAT'
        $username = 'YOUR_USERNAME'
        $auth = '{0}:{1}' -f $username, $pat
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($auth)
        $encoded = [Convert]::ToBase64String($bytes)
        $auth = 'Basic ' + $encoded
    } else {
        $auth = 'Bearer ' + $SystemToken
    }
    $headers = @{
      'Content-Type' = 'application/json'
      'Authorization' = $auth
    }

    Write-Host -ForegroundColor Green 'Http Request:'$Url
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
    $response = Invoke-RestMethod -Uri $Url -Method Get -Headers $headers
    Write-Host ($reponse | Format-List | Out-String)
    return $response
}
</code>```

Body:
Im new to Azure and Postman.

Is there a way to display the content of a (GET)Rest API in Azure DevOPS.
The content should be displayed inside the "Run Cake script" in the Pipeline.

Right now i have this:

Task("Deploy")
    .IsDependentOn("Pack")
    .Does(() =>
    {
        //Code to print the content of the API packages.
    });

How do i proceed?
Once again, im new to this so i might be missing a lot of information that you need in order to help me. In that case, let me know! :)

Body:
I'm not familar with Cake script, there are 2 ways to do authentication for Azure DevOps API.

Private PAT

Environment Variable: System.AccessToken

if you want to call Azure DevOps API in your pipeline, you can conside use System.AccessToken.

Here is Powershell Script for your reference, the field of Authorization is different.

function Http-Request {
    param (
        [Parameter(Mandatory=$true)]
        [string] $Url,
        [Parameter(Mandatory=$false)]
        [string] $SystemToken
    )
    if([string]::IsNullOrEmpty($SystemToken)) {
        $pat = 'YOUR_PAT'
        $username = 'YOUR_USERNAME'
        $auth = '{0}:{1}' -f $username, $pat
        $bytes = [System.Text.Encoding]::UTF8.GetBytes($auth)
        $encoded = [Convert]::ToBase64String($bytes)
        $auth = 'Basic ' + $encoded
    } else {
        $auth = 'Bearer ' + $SystemToken
    }
    $headers = @{
      'Content-Type' = 'application/json'
      'Authorization' = $auth
    }

    Write-Host -ForegroundColor Green 'Http Request:'$Url
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
    $response = Invoke-RestMethod -Uri $Url -Method Get -Headers $headers
    Write-Host ($reponse | Format-List | Out-String)
    return $response
}


问:
Set a tag for a Fragment - ViewPager2 and FragmentStateAdapter in Android (Java)
Code from MainActivity.java declaring Viewpager2:

```<code>        viewPager = findViewById(R.id.pager);
        tabLayout = findViewById(R.id.tabs);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        pagerAdapter = new ScreenSlidePagerAdapter(MainActivity.this);
        viewPager.setAdapter(pagerAdapter);
        new TabLayoutMediator(tabLayout, viewPager,
                new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        if (position == 0) {
                            tab.setText("Home");
                        } else if (position == 1) {
                            tab.setText("Stats");
                        } else {
                            tab.setText("Top");
                        }
                    }
                }).attach();
        viewPager.setCurrentItem(0);
</code>```

Code from ScreenSlidePagerAdapter which extends FragmentStateAdapter:

```<code>public class ScreenSlidePagerAdapter extends FragmentStateAdapter {
    private static final int NUM_PAGES = 3;

    public ScreenSlidePagerAdapter(FragmentActivity fa) {
        super(fa);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        if (position == 0) {
            return new MyCoinsFragment();
        }else if (position == 1) {
            return new StatsFragment();
        }else {
            return new TopFragment();
        }
    }

    @Override
    public int getItemCount() {
        return NUM_PAGES;
    }

}
</code>```

My Layout file for a Fragment:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/layoutData"
    android:layout_marginStart="6dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="6dp"
    android:layout_marginBottom="10dp"
    android:padding="6dp"
    android:weightSum="1">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="16dp"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.1"/>

    <TextView
        style="@style/subHeadings"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.5"
        android:singleLine="true"
        android:text="sadsda" />

    <TextView
        style="@style/subHeadings"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.4"
        android:text="17.2 TH/s"
        android:textAlignment="textEnd" />
</LinearLayout>
</code>```

I need to set the tag programatically for fragment. Would appreciate some help in which direction to go into. I understand it will be done in Fragment State Adapter, where i need to set the tag, but not sure how?

答:
You can set tag in adapter like this

```<code>public class HomePageAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public HomePageAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                MyFragment myFragment = new MyFragment();
                myFragment.setTag("tag");
                return myFragment;
            case 1:
                MyFragment1 myFragment1 = new MyFragment1();
                myFragment1.setTag("tag1");
                return myFragment1;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}
</code>```

and then you can get tag:

```<code>List fragments = getSupportFragmentManager().getFragments();
Fragment disFrag = null;
for (int i = 0; i < fragments.size(); i++) {
    if (((Fragment) fragments.get(i)).getTag() == "tag")
        disFrag = (Fragment) fragments.get(i);
}
</code>```

Body:
Code from MainActivity.java declaring Viewpager2:

        viewPager = findViewById(R.id.pager);
        tabLayout = findViewById(R.id.tabs);
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        pagerAdapter = new ScreenSlidePagerAdapter(MainActivity.this);
        viewPager.setAdapter(pagerAdapter);
        new TabLayoutMediator(tabLayout, viewPager,
                new TabLayoutMediator.TabConfigurationStrategy() {
                    @Override
                    public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                        if (position == 0) {
                            tab.setText("Home");
                        } else if (position == 1) {
                            tab.setText("Stats");
                        } else {
                            tab.setText("Top");
                        }
                    }
                }).attach();
        viewPager.setCurrentItem(0);

Code from ScreenSlidePagerAdapter which extends FragmentStateAdapter:

public class ScreenSlidePagerAdapter extends FragmentStateAdapter {
    private static final int NUM_PAGES = 3;

    public ScreenSlidePagerAdapter(FragmentActivity fa) {
        super(fa);
    }

    @NonNull
    @Override
    public Fragment createFragment(int position) {
        if (position == 0) {
            return new MyCoinsFragment();
        }else if (position == 1) {
            return new StatsFragment();
        }else {
            return new TopFragment();
        }
    }

    @Override
    public int getItemCount() {
        return NUM_PAGES;
    }

}

My Layout file for a Fragment:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:id="@+id/layoutData"
    android:layout_marginStart="6dp"
    android:layout_marginTop="10dp"
    android:layout_marginEnd="6dp"
    android:layout_marginBottom="10dp"
    android:padding="6dp"
    android:weightSum="1">

    <ImageView
        android:layout_width="0dp"
        android:layout_height="16dp"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.1"/>

    <TextView
        style="@style/subHeadings"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.5"
        android:singleLine="true"
        android:text="sadsda" />

    <TextView
        style="@style/subHeadings"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:layout_weight="0.4"
        android:text="17.2 TH/s"
        android:textAlignment="textEnd" />
</LinearLayout>

I need to set the tag programatically for fragment. Would appreciate some help in which direction to go into. I understand it will be done in Fragment State Adapter, where i need to set the tag, but not sure how?

Body:
You can set tag in adapter like this

public class HomePageAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    public HomePageAdapter(FragmentManager fm, int NumOfTabs) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
    }

    @Override
    public Fragment getItem(int position) {

        switch (position) {
            case 0:
                MyFragment myFragment = new MyFragment();
                myFragment.setTag("tag");
                return myFragment;
            case 1:
                MyFragment1 myFragment1 = new MyFragment1();
                myFragment1.setTag("tag1");
                return myFragment1;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return mNumOfTabs;
    }
}

and then you can get tag:

List fragments = getSupportFragmentManager().getFragments();
Fragment disFrag = null;
for (int i = 0; i < fragments.size(); i++) {
    if (((Fragment) fragments.get(i)).getTag() == "tag")
        disFrag = (Fragment) fragments.get(i);
}


问:
String Indices Must be Integers - Fetching data from API
Here is the data i want to get from

```<code>import json

url = "https://api.opensea.io/api/v1/collection/elonpunkyachtclub/stats"

headers = {"Accept": "application/json"}

response = requests.request("GET", url, headers=headers)
data = response.json
decoded = json.loads(data)

{
  "stats": {
    "one_day_volume": 3.4598559686941988,
    "one_day_change": -0.26082160690977335,
    "one_day_sales": 167,
    "one_day_average_price": 0.020717700411342507,
    "seven_day_volume": 24.111522658583088,
    "seven_day_change": 60.74608045431068,
    "seven_day_sales": 1284,
    "seven_day_average_price": 0.01877844443814882,
    "thirty_day_volume": 24.502017447583082,
    "thirty_day_change": 0,
    "thirty_day_sales": 1370,
    "thirty_day_average_price": 0.017884684268308818,
    "total_volume": 24.50201744758308,
    "total_sales": 1370,
    "total_supply": 6969,
    "count": 6969,
    "num_owners": 1854,
    "average_price": 0.017884684268308818,
    "num_reports": 4,
    "market_cap": 130.86697928945915,
    "floor_price": 0.022
  }
}

</code>```

print(data)
print(data['stats']['floor_price'])
```

I want to fetch the floor price from the data

Getting error, what I am doing wrong?

Any help is appreciated, thanks.......

答:
From the error, it seems that you are operating on a string, not decoded data. Try decoding first:

import json

# ... get data

decoded = json.loads(data)
print(decoded['stats']['floor_price'])
```

Body:
Here is the data i want to get from

import json

url = "https://api.opensea.io/api/v1/collection/elonpunkyachtclub/stats"

headers = {"Accept": "application/json"}

response = requests.request("GET", url, headers=headers)
data = response.json
decoded = json.loads(data)

{
  "stats": {
    "one_day_volume": 3.4598559686941988,
    "one_day_change": -0.26082160690977335,
    "one_day_sales": 167,
    "one_day_average_price": 0.020717700411342507,
    "seven_day_volume": 24.111522658583088,
    "seven_day_change": 60.74608045431068,
    "seven_day_sales": 1284,
    "seven_day_average_price": 0.01877844443814882,
    "thirty_day_volume": 24.502017447583082,
    "thirty_day_change": 0,
    "thirty_day_sales": 1370,
    "thirty_day_average_price": 0.017884684268308818,
    "total_volume": 24.50201744758308,
    "total_sales": 1370,
    "total_supply": 6969,
    "count": 6969,
    "num_owners": 1854,
    "average_price": 0.017884684268308818,
    "num_reports": 4,
    "market_cap": 130.86697928945915,
    "floor_price": 0.022
  }
}

print(data)
print(data['stats']['floor_price'])

I want to fetch the floor price from the data

Getting error, what I am doing wrong?

Any help is appreciated, thanks.......


问:
Under what circumstances is it safe to release the python GIL?
I have written a C++ library which runs machine learning inference. These inference functions generally use 8 threads each to optimize for low latency (though it can still take upwards of 100ms to complete the inference call). I have used synchronization primitives such as std::mutex to ensure the library is threadsafe.

I have also written python bindings for this library using pybind11.

The current problem is that on a 16 core / thread CPU, it is optimal to run two inference function calls in parallel, thus utilizing all 16 available threads. This is fine in C++, but in python (with threading), due to the GIL, one inference call ends up holding the lock and the other cannot run in parallel. Note, I know I can solve this problem using multi processing, but I'd like to use threading instead due to the design of my library.

Can I therefore release the GIL when making the call to the C++ API function (in the python binding layer) since the C++ library implements the necessary thread safety? Are there any other considerations I need to make when releasing the GIL?

答: The GIL protects every Python object.  If you aren’t accessing any, or it’s read-only access to an immutable object for which you have an owning reference, then it’s fine to release it.  Do be sure to keep an owning reference to anything you’ll use after reacquiring the lock, lest it have been destroyed while it was released.


问:
Square Every Digit of a Number in Python?
Square Every Digit of a Number in Python?
if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
write a code but this not working.

```<code>def sq(num):
words = num.split()  # split the text
for word in words:  # for each word in the line:
    print(word**2) # print the word

num = 9119
sq(num)
</code>```

答:
```<code>number=str(input("Enter the number :"))

def pc(number):

      digits = list(number)

      for j in digits:

      print(int(j)**2,end="")

pc(number)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Square Every Digit of a Number in Python?
if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
write a code but this not working.

def sq(num):
words = num.split()  # split the text
for word in words:  # for each word in the line:
    print(word**2) # print the word

num = 9119
sq(num)


问:
sorting some data
I am trying to sort some data in bash. Data looks like below.

```<code>    20110724.gz   1347
    20110724.gz   2128
    20110725.gz   1315
    20110725.gz   2334
    20110726.gz   808
    20110726.gz   1088
    -bash-3.2$
</code>```

After sorting, it should look like

```<code>    20110724.gz 3475
    20110725.gz 3649
    20110726.gz 1896
</code>```

Basically, for a given date, the data are summed up. Can somebody help? Thanks.

hmm, hopefully I figure it out in a few days.

答:
Here's a perl solution.

Usage: script.pl input.txt > output.txt

Code:

```<code>use warnings;
use strict;
use ARGV::readonly;

my %sums;
while (<>) {
    my ($date, $num) = split;
    $sums{$date} += $num;
}
for my $date (sort keys %sums) {
    print "$date $sums{$date}\n";
}
</code>```

Or as a one-liner:

```<code>$ perl -we 'my %h; while(<>) { ($d,$n)=split; $h{$d}+=$n; } print "$_ $h{$_}\n" for sort keys %h;' data2.txt
</code>```

In case you do need a numerical sort on the dates:

```<code>sort { substr($a,0,8) <=> substr($b,0,8) } keys %sums;
</code>```

Title: sorting some data

Body:
I am trying to sort some data in bash. Data looks like below.

    20110724.gz   1347
    20110724.gz   2128
    20110725.gz   1315
    20110725.gz   2334
    20110726.gz   808
    20110726.gz   1088
    -bash-3.2$

After sorting, it should look like

    20110724.gz 3475
    20110725.gz 3649
    20110726.gz 1896

Basically, for a given date, the data are summed up. Can somebody help? Thanks.

hmm, hopefully I figure it out in a few days.

Body:
Here's a perl solution.

Usage: script.pl input.txt > output.txt

Code:

use warnings;
use strict;
use ARGV::readonly;

my %sums;
while (<>) {
    my ($date, $num) = split;
    $sums{$date} += $num;
}
for my $date (sort keys %sums) {
    print "$date $sums{$date}\n";
}

Or as a one-liner:

$ perl -we 'my %h; while(<>) { ($d,$n)=split; $h{$d}+=$n; } print "$_ $h{$_}\n" for sort keys %h;' data2.txt

In case you do need a numerical sort on the dates:

sort { substr($a,0,8) <=> substr($b,0,8) } keys %sums;


问:
filter icon in material-ui's v5 DataGrid
The default behavior for the new DataGrid is to hide a filter icon unless you hover over the column header (and have a filter applied). In the previous version the icon remained visible.

Codesandbox https://codesandbox.io/s/mui-datagrid-filter-icon-7rbrk

When a filter is applied it adds a new iconButtonContainer div. The classes are: MuiDataGrid-iconButtonContainer css-ltf0zy-MuiDataGrid-iconButtonContainer

Is there a way to override this behavior? All I'd like to do is set visibility to always be visible when that div is generated by the library.

答:
The answer here was to create a separate styled component of the data grid and use the global classnames imported from mui to reference the correct one for the style you wish to override. In my case it was something like:</p>
```<code> const MyStyledGrid = styled(DataGrid, () => ({
    [`& .${gridClasses.iconButtonContainer}`] : {
       visibility: "visible",
       width: "auto"
     }
 }))

 function MyComponent() {
    return (
       <MyStyledDataGrid {...props} />
    )
 }
</code>```

Body:
The answer here was to create a separate styled component of the data grid and use the global classnames imported from mui to reference the correct one for the style you wish to override. In my case it was something like:

 const MyStyledGrid = styled(DataGrid, () => ({
    [`& .${gridClasses.iconButtonContainer}`] : {
       visibility: "visible",
       width: "auto"
     }
 }))

 function MyComponent() {
    return (
       <MyStyledDataGrid {...props} />
    )
 }


问:
PhpStorm can not parse PHPUnit version output. Very strange error
I'm trying to set up PHPUnit in PhpStorm 2017.1 on Windows 10 using a Vagrant box for a Laravel project. I've set up a remote interpreter, and I've been using it for a couple of months now, everything working fine.

I've been asked to do some unit testing so I've set up PhpStorm with PHPUnit, following my coworkers' instructions (PhpStorm on Mac) but when I select autoload.php in my vendor folder I receive the error message

"Can not parse PHPUnit version output: Could not open input file: /vagrant/vendorphpunitphpunitphpunit" (no slashes).

If I run PHPUnit via vagrant ssh in the command line, my tests execute fine, and I can manually select the PHPUnit phar in PhpStorm, but then I'm missing the autoloaded classes, so everything fails.

答:
In case you configure remote PHP cli interpreter by Docker Compose, if you get a similar bug of parsing PHPUnit version output like this, the reason may comes from using variables in docker-compose.yaml (e.g using $PWD in volume binding).

For instance, if you mount your current directory like this:

```<code>...
  volumes:
    - $PWD:/var/www/html
</code>```

PHPStorm do not know what $PWD really is, therefore it cannot parse PHPUnit output due to volume binding. You should change the variables to a specific value (e.g to ./ in this case):

```<code>...
  volumes:
    - ./:/var/www/html
</code>```

Body:
In case you configure remote PHP cli interpreter by Docker Compose, if you get a similar bug of parsing PHPUnit version output like this, the reason may comes from using variables in docker-compose.yaml (e.g using $PWD in volume binding).

For instance, if you mount your current directory like this:

...
  volumes:
    - $PWD:/var/www/html

PHPStorm do not know what $PWD really is, therefore it cannot parse PHPUnit output due to volume binding. You should change the variables to a specific value (e.g to ./ in this case):

...
  volumes:
    - ./:/var/www/html


问:
R: Recode cells in matrix with no symmetric match
I have an adjacency matrix of 0s and 1s that indicate tie nominations. Some nominations are not reciprocated, so the matrix is asymmetrical.

I would like to recode the cell values from 1 to 0 if they do not have a symmetrical match.

Sample small matrix:

```<code>     [,1] [,2] [,3] [,4]
[1,]    0    1    0    1
[2,]    0    0    1    0
[3,]    0    0    0    1
[4,]    1    0    1    0
</code>```

Output desired:

```<code>     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0
</code>```

答:
Here is another way for this specific case. This is slower than @ThomasIsCoding's solution, and would not work for numbers other than 1, 0. If your matrix allows an inverse, then:</p>
```<code>A <- structure(c(0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0), .Dim = c(4L, 4L))

A_inv <- solve(A)
A_inv + t(A_inv)

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0
</code>```

Body:
I have an adjacency matrix of 0s and 1s that indicate tie nominations. Some nominations are not reciprocated, so the matrix is asymmetrical.

I would like to recode the cell values from 1 to 0 if they do not have a symmetrical match.

Sample small matrix:

     [,1] [,2] [,3] [,4]
[1,]    0    1    0    1
[2,]    0    0    1    0
[3,]    0    0    0    1
[4,]    1    0    1    0

Output desired:

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0

Body:
Here is another way for this specific case. This is slower than @ThomasIsCoding's solution, and would not work for numbers other than 1, 0. If your matrix allows an inverse, then:

A <- structure(c(0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0), .Dim = c(4L, 4L))

A_inv <- solve(A)
A_inv + t(A_inv)

     [,1] [,2] [,3] [,4]
[1,]    0    0    0    1
[2,]    0    0    0    0
[3,]    0    0    0    1
[4,]    1    0    1    0


问:
Upstream git tag is not showing in forked repository
I have the 1.11.57 tag in the upstream which i pushed with master branch code. I am using bitbucket and git bash

I forked above repository and locally use the fork repository as my local master branch. But in my forked repository the 1.11.57 tag is not showing.

I check the repository sync also having no problem. What is the cause of this and how to get the upstream tag to my fork and then to my local too.

答:
Just to add to what was written above, I also had to run:

```<code>git fetch upstream --tags
</code>```

To get it to actually pull the tags from upstream.

So if like me, the tag were not showing up, add this after the previously mentioned git fetch upstream

Body:
Just to add to what was written above, I also had to run:

git fetch upstream --tags

To get it to actually pull the tags from upstream.

So if like me, the tag were not showing up, add this after the previously mentioned git fetch upstream


问:
Postman API update collections
I am using Postman to test the Rest service with swagger 2.0 specs. I want to update the existing collection with multiple test cases with the new API specs.
Can anyone suggest a solution that will keep all existing requests and update the collection?</p>

答: if you want to keep that collection and update that with some test cases then you can duplicate that collection and update that duplicated one. It will let you have a backup of that previous collection and work on that same collection as well.</p>

Title: Postman API update collections


问:
problem understanding c++ namespace and using-declaration in terms of inheritance
```<code>struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};
</code>```

It seems like I specified to use i from A from B, but compiler says

error: 'A' is an ambiguous base of 'D'

To be honest, I don't really understand what using B::i does. As far as I know, it brings i from namespace B, to namespace D. But does namespace B contain i because it inherits i from A, or is it only namespace A that contains i? If latter, why

```<code>//A, B, C is same with above
struct D: B, C {
    void f() {
        B::i = 0;
    }
};
</code>```

this just compiles with no problem?

As you can see, I'm confusing with whole concept of namespaces in terms of class inheritance. Can anyone explain how rules of namespaces, inheritance, etc. works with these examples?

答:
using B::i is not useful there because there is no i in B. It is useful for function resolutions. i = 0; is this->i = 0;. Due to the multiple inheritance this->i = 0; is either static_cast(this)->i = 0; or static_cast<C*>(this)->i = 0;, that causes ambiguity.

In other words, using B::i brings the name i to the immediate scope of the class D and does not resolve the ambiguity.

The example of the useful using:

```<code>struct A { void f(); };
struct D: A {
    void f(int) { f(); }  // error: no matching function for call to 'D::f()'
};
</code>```
```<code>struct A { void f(); };
struct D: A {
    using A::f;
    void f(int) { f(); }  // ok
};
</code>```

Body:
struct A { int i; };
struct B: A {};
struct C: A {};
struct D: B, C {
    using B::i;
    void f() {
        i = 0;
    }
};

It seems like I specified to use i from A from B, but compiler says

error: 'A' is an ambiguous base of 'D'

To be honest, I don't really understand what using B::i does. As far as I know, it brings i from namespace B, to namespace D. But does namespace B contain i because it inherits i from A, or is it only namespace A that contains i? If latter, why

//A, B, C is same with above
struct D: B, C {
    void f() {
        B::i = 0;
    }
};

this just compiles with no problem?

As you can see, I'm confusing with whole concept of namespaces in terms of class inheritance. Can anyone explain how rules of namespaces, inheritance, etc. works with these examples?

Body:
using B::i is not useful there because there is no i in B. It is useful for function resolutions. i = 0; is this->i = 0;. Due to the multiple inheritance this->i = 0; is either static_cast<B*>(this)->i = 0; or static_cast<C*>(this)->i = 0;, that causes ambiguity.

In other words, using B::i brings the name i to the immediate scope of the class D and does not resolve the ambiguity.

The example of the useful using:

struct A { void f(); };
struct D: A {
    void f(int) { f(); }  // error: no matching function for call to 'D::f()'
};

struct A { void f(); };
struct D: A {
    using A::f;
    void f(int) { f(); }  // ok
};


问:
What devices have LDPI resolution with Android 2.2/2.3 version?
What devices have LDPI(Low resolution) with Android 2.2\2.3 version?</p>

答:
Normally ldpi is ordinary screen, mdpi is 120, hdpi 240, 160, xhdpi is 320.
 I know also that Motorola's  small screen devices are low density.</p>


问:
Handling long running database calls in nodejs
I have an endpoint which send out response to client and based on response I want to do database calls(creating data of users)? How to achieve this after sending out response?

```<code>router.post('/',(req,res) => {
  Policy.findOneAndUpdate({ _id: id, isActive: true }, { $set: req.body }, { new:true })
 .then(result => {
      // here i do not want to block the client so sending response
      res.status(200).json({message: 'Action taken Successfully'})
     /* After policy gets approved, My task here is to fetch all the list of
        users and create data(policy data) for them so that they can fetch the policies and take action. */
})
</code>```

答:
Of course you can call it asynchronously. Just call it before/after sending the response. But you can't send the headers again, it will generate errors.

Try the following code:

```<code>router.post('/', (req, res) => {
    Policy.findOneAndUpdate({ _id: id, isActive: true }, { $set: req.body }, { new:true })
        .then(result => {
            res.status(200).json({message: 'Action taken Successfully'});
            your_function_to_execute_other_operations();
        });
});
</code>```

The above code will immediately send response after executing the res.send. After that, it will take care of the your_function_to_execute_other_operations function.

Body:
I have an endpoint which send out response to client and based on response I want to do database calls(creating data of users)? How to achieve this after sending out response?

router.post('/',(req,res) => {
  Policy.findOneAndUpdate({ _id: id, isActive: true }, { $set: req.body }, { new:true })
 .then(result => {
      // here i do not want to block the client so sending response
      res.status(200).json({message: 'Action taken Successfully'})
     /* After policy gets approved, My task here is to fetch all the list of
        users and create data(policy data) for them so that they can fetch the policies and take action. */
})

Body:
Of course you can call it asynchronously. Just call it before/after sending the response. But you can't send the headers again, it will generate errors.

Try the following code:

router.post('/', (req, res) => {
    Policy.findOneAndUpdate({ _id: id, isActive: true }, { $set: req.body }, { new:true })
        .then(result => {
            res.status(200).json({message: 'Action taken Successfully'});
            your_function_to_execute_other_operations();
        });
});

The above code will immediately send response after executing the res.send. After that, it will take care of the your_function_to_execute_other_operations function.


问:
Can an 80386 run modern x86 executables?
If I compile a 32 bit executable to run on my modern i5, can I run it on an 80386? Assume I'm using the same operating system for both CPUs.</p>

答:
No, most modern compilers default to assuming PPro new instructions like cmov and fcomi.  Also 486 instructions like bswap.  Depending on your compiler config, it might even default to using SSE2 instructions in 32-bit mode.  (Pentium 4 / Pentium-M / AMD K8 from the early 2000s.)

If you want to override that default, e.g. for GCC or clang, you can use -m32 -march=i386

For example:

```<code>int foo(int a, int b)
{
    return (a > 3) ? 4 : b;
}
</code>```

GCC -O3 -m32 (with a standard / default config on Godolt) compiles to

```<code>foo(int, int):
        cmp     DWORD PTR [esp+4], 3
        mov     eax, 4
        cmovle  eax, DWORD PTR [esp+8]
        ret
</code>```

vs. with -march=i386 -O3 -Wall -m32

```<code>foo(int, int):
        mov     eax, DWORD PTR [esp+8]
        cmp     DWORD PTR [esp+4], 3
        jg      .L4
        ret
.L4:
        mov     eax, 4
        ret
</code>```

Body:
No, most modern compilers default to assuming PPro new instructions like cmov and fcomi.  Also 486 instructions like bswap.  Depending on your compiler config, it might even default to using SSE2 instructions in 32-bit mode.  (Pentium 4 / Pentium-M / AMD K8 from the early 2000s.)

If you want to override that default, e.g. for GCC or clang, you can use -m32 -march=i386

For example:

int foo(int a, int b)
{
    return (a > 3) ? 4 : b;
}

GCC -O3 -m32 (with a standard / default config <a href="https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1DIApACYAQuYukl9ZATwDKjdAGFUtAK4sGIM6SuADJ4DJgAcj4ARpjEINIADqgKhE4MHt6%2B/qRJKY4CIWGRLDFx0naYDmlCBEzEBBk%2Bfly2mPb5DDV1BIUR0bF6CrX1jVktQ929xaUSAJS2qF7EyOwcoQQA1PyoEOsbTKQbe1GzJhoAgiYA7FYXG/cbxJgESwwbEEwbJgDM2Bvfsy%2B3wAYhtJBsQBsoj9bpcrgARDjzWicACsvD8HC0pFQnDc1msGwUi2WmC%2BZm%2BPFIBE0SPmAGsQN9JAA6ZlXABsZlRHO%2B3wAnN8zFd9JxJLwWBINBpSJjsbiOLwFCAZTSsUjSHBYEg0CwEnRYuRKLr9fQ4sAuFwAjRaARYsqIFFaaQoqE6gBPThU3VsQQAeQYtE96tIWBYhmA4hD%2BCeVQAbphlSHMKpKl47V7eOs2s7aHgosQPR4sM6CMQ8JLuBqqAZgAoAGp4TAAdz9CUYmZkghEYnYUi78iUamduhaBiMKAJln0%2BeVkHmqASHSTAFpw8sED94XhvgAODkbFd%2B76HgDqYloh5YQqVbUqHRcDHcniaEgCwVCfRKA13OWSqQEUZmgCXIAIYKZ%2BjiX8KiqAQuhGF8xladpqmGHpP2mAZxjQoDBjQiDvziLh5mJJYVj0MtMFWHhkTRDFnQVVR9xXDlwWAZBkA2S0WTMd58UsaxDlwQgSHJSlDg8PUDWIMTiN4NUtFmBkmTMNkuH5DRJC4DQhSuPl%2BV3VFRQ4cVSElbSZTlXgFSVFVqVpeYtUQFBUCks0jQgE1pJAC0rT4Og7WIB0nRDV1mGIYNvVc30CADINnTDCMo2xGN7zwBMk2xFM0wzKtyEEHMQzzAsiwwVZsTLCtM3mGsmDrRsWzbDs8v4btRHEftWsHFR1BDXQAnHYwpxsYq5wgBclzSVdr14o8TxXc9aFoW8UOcCBXFwvyPyKSCQCM0COk2kD/w6AiZiMmCOnghpEOaZC0rg/CMN27Duk22wnp2wi5gWMi%2B2pJ5qI1FEOHRWUGM4JiORYtiOK4rgeL44ahPwIgZPMcSNkk01YjEsxZnkhzlL5Nk%2BTJ8nyeM0yrJxThbNVInjLMeiQxs%2Bz1SU0gEyCtJ4iAA%3D%3D%3D" rel="nofollow noreferrer">on Godolt) compiles to

foo(int, int):
        cmp     DWORD PTR [esp+4], 3
        mov     eax, 4
        cmovle  eax, DWORD PTR [esp+8]
        ret

vs. with -march=i386 -O3 -Wall -m32

foo(int, int):
        mov     eax, DWORD PTR [esp+8]
        cmp     DWORD PTR [esp+4], 3
        jg      .L4
        ret
.L4:
        mov     eax, 4
        ret


问:
Flutter web shows a blank screen in build mode
After finishing my web app on flutter I tried to release it on the server by flutter build web command. I uploaded my files to the server but I am getting a blank screen.
In the debugging mode on Android Studio, it works fine.
I am also getting the same blank screen when I use the command flutter run -d chrome --profile --verbose I found similar questions here but the root cause seems to be different every time and nothing worked for me, can you please advice?

Below is a simplified version of my flutter code, suffering from the same issue:

```<code>import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_signin_button/flutter_signin_button.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  //await Firebase.initializeApp();
  ErrorWidget.builder = (FlutterErrorDetails details) {
    bool inDebug = false;
    assert(() { inDebug = true; return true; }());
    // In debug mode, use the normal error widget which shows
    // the error message:
    if (inDebug)
      return ErrorWidget(details.exception);
    // In release builds, show a yellow-on-blue message instead:
    return Container(
      alignment: Alignment.center,
      child: Text(
        'Error! ${details.exception}',
        style: TextStyle(color: Colors.yellow),
        textDirection: TextDirection.ltr,
      ),
    );
  };
  // Here we would normally runApp() the root widget, but to demonstrate
  // the error handling we artificially fail:
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
          scrollBehavior: MyCustomScrollBehavior(), //fixing the scrolling for web
          home:LoginScreen(),

          theme: ThemeData(
            cupertinoOverrideTheme: CupertinoThemeData( // <---------- this
              textTheme: CupertinoTextThemeData(
                pickerTextStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.w900),
              ),
            ),

          ),
        );

//
  }
}
class MyCustomScrollBehavior extends MaterialScrollBehavior {
  // Override behavior methods and getters like dragDevices
  @override
  Set<PointerDeviceKind> get dragDevices => {
    PointerDeviceKind.touch,
    PointerDeviceKind.mouse,
    // etc.
  };
}
class LoginScreen extends StatefulWidget {

  @override
  State<LoginScreen> createState() => _LoginScreenState();

}

class _LoginScreenState extends State<LoginScreen> {
  late String em;
  late String pa;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }
  @override
  Widget build(BuildContext context) {
    return Material(
        child: Scaffold(
              body: buildHomeScreen()
          ),
        );
  }

  Widget buildHomeScreen(){
   return Container(
      decoration: BoxDecoration(color: Colors.amberAccent),
      child: Flexible(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Align(alignment: Alignment.centerLeft,
                  child: WelcomeText('Get to know the highest rated cars,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('good and bad things for each car,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('best car mechanics near you,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('best car agencies,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('and more..')),
              SizedBox(height: 100,),
              Text('Welcome to Car of your Dreams', style: GoogleFonts.ubuntu(
                  textStyle: TextStyle(fontSize: 35,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                      decoration: TextDecoration.none))),
              SizedBox(height: 8,),
              Text('Sign in to continue', style: GoogleFonts.ubuntu(
                  textStyle: TextStyle(fontSize: 14,
                      color: Colors.white,
                      fontWeight: FontWeight.w300,
                      decoration: TextDecoration.none))),
              SizedBox(height: 12,),
              FractionallySizedBox(
                widthFactor: 0.6,
                child: TextField(
                  onChanged: (value){
                  }
                  ,
                  decoration: InputDecoration(
                    hintText: "Email",
                    border: OutlineInputBorder(),
                    icon:Icon(Icons.email),
                    contentPadding: EdgeInsets.symmetric(horizontal: 20),
                  ),
                ),
              ),
              SizedBox(height: 5,),
              FractionallySizedBox(
                  widthFactor: 0.6,
                  child: TextField(
                      obscureText:true ,
                      onChanged: (value){
                      },
                      decoration: InputDecoration(
                        hintText: "Password",

                        border: OutlineInputBorder(),
                        icon:Icon(Icons.vpn_key_outlined),
                        contentPadding: EdgeInsets.symmetric(horizontal: 20),))
              ),
              SizedBox(height: 10,),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(onPressed: () {},
                    child: Text('Sign in', style: GoogleFonts.londrinaSolid(
                        textStyle: TextStyle(fontSize: 25,
                            color: Colors.white,
                            fontWeight: FontWeight.w300,
                            decoration: TextDecoration.none))),),
                  SizedBox(width: 10,),
                  Icon(Icons.arrow_forward, color: Colors.white,)
                ],
              ),
              SizedBox(height: 10,),
              SignInButton(Buttons.Google,
                  text: "Sign in with Google",
                  onPressed:(){}),
              SizedBox(height: 7,),
              SignInButton(Buttons.Facebook,
                  text: "Sign in with Facebook",
                  onPressed: (){}),
              SizedBox(height: 7,),
              TextButton(
                onPressed: (){
                  Navigator.pushNamed(context, '-1');
                },
                child: Text('New user? Register..', style: GoogleFonts.londrinaSolid(
                    textStyle: TextStyle(fontSize: 20,
                        color: Colors.white,
                        fontWeight: FontWeight.w300,
                        decoration: TextDecoration.none))),),
              SizedBox(height: 50,),

            ],
          ),
        ),
      ),
    );
  }

}

class WelcomeText extends StatelessWidget {
  WelcomeText(this.welcomeText) ;
  String welcomeText;
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20.0,0,0,0),
      child: Text(welcomeText,
          style: GoogleFonts.permanentMarker(
              textStyle: TextStyle(fontSize: 30,
                  color: Colors.white70,
                  fontWeight: FontWeight.w100,
                  decoration: TextDecoration.none))),
    );
  }
}
</code>```

Edit: I added the log after running the code in debugging mode please see below. I can see that it runs but complains about Flexible widget, could this be the problem?
Launching lib\main.dart on Chrome in debug mode...
Waiting for connection from debug service on Chrome...
This app is linked to the debug service: ws://127.0.0.1:60918/FkBvyNxPDmI=/ws
Debug service listening on ws://127.0.0.1:60918/FkBvyNxPDmI=/ws

Running with sound null safety
Debug service listening on ws://127.0.0.1:60918/FkBvyNxPDmI=/ws

======== Exception caught by widgets library =======================================================
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.

The ParentDataWidget Flexible(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.

Usually, this means that the Flexible widget has the wrong ancestor RenderObjectWidget. Typically, Flexible widgets are placed directly inside Flex widgets.
The offending Flexible is currently placed inside a DecoratedBox widget.

The ownership chain for the RenderObject that received the incompatible parent data was:
RepaintBoundary ← NotificationListener ← NotificationListener ← _MaterialScrollbar ← Scrollbar ← Scrollable ← PrimaryScrollController ← SingleChildScrollView ← Flexible ← DecoratedBox ← ⋯
When the exception was thrown, this was the stack:
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49  throw
packages/flutter/src/widgets/framework.dart 5753:11
packages/flutter/src/widgets/framework.dart 5768:14                                                                        [_updateParentData]

答:
I fixed this by changing the location of Flexible widget in the widget tree, so the buildHomeScreen widget now becomes as follows:

```<code>Widget buildHomeScreen(){
    return Container(
  decoration: BoxDecoration(color: Colors.amberAccent),
  child: Column(
    children: [
      Flexible(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Align(alignment: Alignment.centerLeft,
                  child: WelcomeText('Get to know the highest rated cars,')),
</code>```

Body:
After finishing my web app on flutter I tried to release it on the server by flutter build web command. I uploaded my files to the server but I am getting a blank screen.
In the debugging mode on Android Studio, it works fine.
I am also getting the same blank screen when I use the command flutter run -d chrome --profile --verbose I found similar questions here but the root cause seems to be different every time and nothing worked for me, can you please advice?

Below is a simplified version of my flutter code, suffering from the same issue:

import 'dart:ui';
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_signin_button/flutter_signin_button.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  //await Firebase.initializeApp();
  ErrorWidget.builder = (FlutterErrorDetails details) {
    bool inDebug = false;
    assert(() { inDebug = true; return true; }());
    // In debug mode, use the normal error widget which shows
    // the error message:
    if (inDebug)
      return ErrorWidget(details.exception);
    // In release builds, show a yellow-on-blue message instead:
    return Container(
      alignment: Alignment.center,
      child: Text(
        'Error! ${details.exception}',
        style: TextStyle(color: Colors.yellow),
        textDirection: TextDirection.ltr,
      ),
    );
  };
  // Here we would normally runApp() the root widget, but to demonstrate
  // the error handling we artificially fail:
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
          scrollBehavior: MyCustomScrollBehavior(), //fixing the scrolling for web
          home:LoginScreen(),

          theme: ThemeData(
            cupertinoOverrideTheme: CupertinoThemeData( // <---------- this
              textTheme: CupertinoTextThemeData(
                pickerTextStyle: TextStyle(color: Colors.white, fontWeight: FontWeight.w900),
              ),
            ),

          ),
        );

//
  }
}
class MyCustomScrollBehavior extends MaterialScrollBehavior {
  // Override behavior methods and getters like dragDevices
  @override
  Set<PointerDeviceKind> get dragDevices => {
    PointerDeviceKind.touch,
    PointerDeviceKind.mouse,
    // etc.
  };
}
class LoginScreen extends StatefulWidget {

  @override
  State<LoginScreen> createState() => _LoginScreenState();

}

class _LoginScreenState extends State<LoginScreen> {
  late String em;
  late String pa;
  @override
  void initState() {
    // TODO: implement initState
    super.initState();

  }
  @override
  Widget build(BuildContext context) {
    return Material(
        child: Scaffold(
              body: buildHomeScreen()
          ),
        );
  }

  Widget buildHomeScreen(){
   return Container(
      decoration: BoxDecoration(color: Colors.amberAccent),
      child: Flexible(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Align(alignment: Alignment.centerLeft,
                  child: WelcomeText('Get to know the highest rated cars,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('good and bad things for each car,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('best car mechanics near you,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('best car agencies,')),
              Align(alignment: Alignment.centerLeft,child: WelcomeText('and more..')),
              SizedBox(height: 100,),
              Text('Welcome to Car of your Dreams', style: GoogleFonts.ubuntu(
                  textStyle: TextStyle(fontSize: 35,
                      color: Colors.white,
                      fontWeight: FontWeight.w500,
                      decoration: TextDecoration.none))),
              SizedBox(height: 8,),
              Text('Sign in to continue', style: GoogleFonts.ubuntu(
                  textStyle: TextStyle(fontSize: 14,
                      color: Colors.white,
                      fontWeight: FontWeight.w300,
                      decoration: TextDecoration.none))),
              SizedBox(height: 12,),
              FractionallySizedBox(
                widthFactor: 0.6,
                child: TextField(
                  onChanged: (value){
                  }
                  ,
                  decoration: InputDecoration(
                    hintText: "Email",
                    border: OutlineInputBorder(),
                    icon:Icon(Icons.email),
                    contentPadding: EdgeInsets.symmetric(horizontal: 20),
                  ),
                ),
              ),
              SizedBox(height: 5,),
              FractionallySizedBox(
                  widthFactor: 0.6,
                  child: TextField(
                      obscureText:true ,
                      onChanged: (value){
                      },
                      decoration: InputDecoration(
                        hintText: "Password",

                        border: OutlineInputBorder(),
                        icon:Icon(Icons.vpn_key_outlined),
                        contentPadding: EdgeInsets.symmetric(horizontal: 20),))
              ),
              SizedBox(height: 10,),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  TextButton(onPressed: () {},
                    child: Text('Sign in', style: GoogleFonts.londrinaSolid(
                        textStyle: TextStyle(fontSize: 25,
                            color: Colors.white,
                            fontWeight: FontWeight.w300,
                            decoration: TextDecoration.none))),),
                  SizedBox(width: 10,),
                  Icon(Icons.arrow_forward, color: Colors.white,)
                ],
              ),
              SizedBox(height: 10,),
              SignInButton(Buttons.Google,
                  text: "Sign in with Google",
                  onPressed:(){}),
              SizedBox(height: 7,),
              SignInButton(Buttons.Facebook,
                  text: "Sign in with Facebook",
                  onPressed: (){}),
              SizedBox(height: 7,),
              TextButton(
                onPressed: (){
                  Navigator.pushNamed(context, '-1');
                },
                child: Text('New user? Register..', style: GoogleFonts.londrinaSolid(
                    textStyle: TextStyle(fontSize: 20,
                        color: Colors.white,
                        fontWeight: FontWeight.w300,
                        decoration: TextDecoration.none))),),
              SizedBox(height: 50,),

            ],
          ),
        ),
      ),
    );
  }

}

class WelcomeText extends StatelessWidget {
  WelcomeText(this.welcomeText) ;
  String welcomeText;
  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(20.0,0,0,0),
      child: Text(welcomeText,
          style: GoogleFonts.permanentMarker(
              textStyle: TextStyle(fontSize: 30,
                  color: Colors.white70,
                  fontWeight: FontWeight.w100,
                  decoration: TextDecoration.none))),
    );
  }
}

Edit: I added the log after running the code in debugging mode please see below. I can see that it runs but complains about Flexible widget, could this be the problem?
Launching lib\main.dart on Chrome in debug mode...
Waiting for connection from debug service on Chrome...
This app is linked to the debug service: ws://127.0.0.1:60918/FkBvyNxPDmI=/ws
Debug service listening on ws://127.0.0.1:60918/FkBvyNxPDmI=/ws

Running with sound null safety
Debug service listening on ws://127.0.0.1:60918/FkBvyNxPDmI=/ws

======== Exception caught by widgets library =======================================================
The following assertion was thrown while applying parent data.:
Incorrect use of ParentDataWidget.

The ParentDataWidget Flexible(flex: 1) wants to apply ParentData of type FlexParentData to a RenderObject, which has been set up to accept ParentData of incompatible type ParentData.

Usually, this means that the Flexible widget has the wrong ancestor RenderObjectWidget. Typically, Flexible widgets are placed directly inside Flex widgets.
The offending Flexible is currently placed inside a DecoratedBox widget.

The ownership chain for the RenderObject that received the incompatible parent data was:
RepaintBoundary ← NotificationListener ← NotificationListener ← _MaterialScrollbar ← Scrollbar ← Scrollable ← PrimaryScrollController ← SingleChildScrollView ← Flexible ← DecoratedBox ← ⋯
When the exception was thrown, this was the stack:
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/internal/js_dev_runtime/private/ddc_runtime/errors.dart 251:49  throw
packages/flutter/src/widgets/framework.dart 5753:11
packages/flutter/src/widgets/framework.dart 5768:14                                                                        [_updateParentData]

Body:
I fixed this by changing the location of Flexible widget in the widget tree, so the buildHomeScreen widget now becomes as follows:

Widget buildHomeScreen(){
    return Container(
  decoration: BoxDecoration(color: Colors.amberAccent),
  child: Column(
    children: [
      Flexible(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Align(alignment: Alignment.centerLeft,
                  child: WelcomeText('Get to know the highest rated cars,')),


问:
Apache Camel - Context getting closed before job ends
I am creating a basic route to copy files from one folder to another.

My ultimate goal, if to have a multiple routes in my application, and every route will be invoked as a step in batch process, one after the other. So I will have to start and stop camel context for each route.

I have written following code.

But camel context end's before completing the job.

I can't put thread sleep, as I am not sure how much time job will take.

Any help in this regard will be great help.

```<code>public class FileTransporter {

public static void main(String[] args) {

    HdfsRouteBuilder1 anotherRouteBuilder =new HdfsRouteBuilder1();

    CamelContext ctx = new DefaultCamelContext();

    try{
        ctx.addRoutes(anotherRouteBuilder);

        ctx.start();

        ctx.stop();
    } catch(Exception e){
        e.printStackTrace();
    }
}//end of main method
}

public class HdfsRouteBuilder1 extends RouteBuilder{

@Override
public void configure() throws Exception {

    from("file://E:/test/?noop=true")
    .threads(1)
    .to("file://E:/test1/");
}
}
</code>```

I also tried using oncompletion() option, in route, but that also doesn't help.

Thanks

答:
You can use Thread.sleep(Time_in_millisecond) after starting camel context.
Or else you can use camel main instead of DefaultCamelContext.</p>
```<code>Main main = new Main();
main.configure().addRoutesBuilder(anotherRouteBuilder);
main.run();
</code>```

Body:
I am creating a basic route to copy files from one folder to another.

My ultimate goal, if to have a multiple routes in my application, and every route will be invoked as a step in batch process, one after the other. So I will have to start and stop camel context for each route.

I have written following code.

But camel context end's before completing the job.

I can't put thread sleep, as I am not sure how much time job will take.

Any help in this regard will be great help.

public class FileTransporter {

public static void main(String[] args) {

    HdfsRouteBuilder1 anotherRouteBuilder =new HdfsRouteBuilder1();

    CamelContext ctx = new DefaultCamelContext();

    try{
        ctx.addRoutes(anotherRouteBuilder);

        ctx.start();

        ctx.stop();
    } catch(Exception e){
        e.printStackTrace();
    }
}//end of main method
}

public class HdfsRouteBuilder1 extends RouteBuilder{

@Override
public void configure() throws Exception {

    from("file://E:/test/?noop=true")
    .threads(1)
    .to("file://E:/test1/");
}
}

I also tried using oncompletion() option, in route, but that also doesn't help.

Thanks

Body:
You can use Thread.sleep(Time_in_millisecond) after starting camel context.
Or else you can use camel main instead of DefaultCamelContext.

Main main = new Main();
main.configure().addRoutesBuilder(anotherRouteBuilder);
main.run();


问:
Sort and create new columns by specific values using Pandas
How to sort or group by dataframe by specific values from multiple columns with Pandas?

The dataframe that I am working with looks like below. I have 3 type columns with corresponding parameters count and param. For each type accordingly count and param column. I need to sort them based on type value, so the result would be new columns with its parameters for type = '1', type = '3', type = '3' and type = '6'.

The desired result looks like this:

What I tried is this, however, I  really not sure that this will do what I want, also with I would sort only type columns and not count and param as well:

```<code>import pandas as pd

dataframe = pd.read_csv(r'W:\...file.csv')

type_col = 1
new_column = 'group_1'

dataframe.loc[dataframe[type_1'] == type_col, group_1] = type_col
dataframe.loc[dataframe['type_2'] == type_col, group_1] = type_col
dataframe.loc[dataframe['type_3'] == type_col, group_1] = type_col
</code>```

Here is the print output of dataframe.head(20):

```<code>print(dataframe.head(20).to_dict('list'))
{'type_1': [1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 4, 3, 3, 3, 3, 3, 3, 3, 3], 'count_1': [465, 254, 154, 16, 254, 261, 595, 119, 119, 751, 314, 68, 108, 118, 121, 58, 126, 87, 143, 43], 'param_1': [22, 21, 19, 21, 22, 21, 21, 20, 21, 21, 20, 17, 15, 24, 20, 23, 23, 21, 18, 18], 'type_2': [3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 1, 4, 6, 6, 4, 6, 1, 1, 4], 'count_2': [49, 15, 5, 16, 74, 3, 122, 38, 1, 63, 178, 67, 82, 3, 85, 27, 33, 74, 35, 35], 'param_2': [20, 19, 18, 21, 21, 17, 20, 20, 9, 23, 21, 14, 15, 17, 19, 23, 23, 21, 17, 19], 'type_3': [4, 0, 0, 4, 4, 0, 6, 0, 0, 4, 4, 3, 1, 1, 1, 6, 1, 4, 4, 1], 'count_3': [3, 0, 0, 7, 39, 0, 8, 0, 0, 46, 4, 58, 44, 1, 18, 11, 31, 10, 20, 20], 'param_3': [18, 0, 0, 20, 21, 0, 17, 0, 0, 21, 18, 12, 14, 17, 19, 21, 22, 21, 17, 19]}
</code>```

And the full dataframe:
print(dataframe)

```<code>    type_1  count_1  param_1  type_2  count_2  param_2  type_3  count_3  \
0        1      465       22       3       49       20       4        3
1        1      254       21       3       15       19       0        0
2        1      154       19       3        5       18       0        0
3        3       16       21       1       16       21       4        7
4        1      254       22       3       74       21       4       39
5        1      261       21       3        3       17       0        0
6        1      595       21       3      122       20       6        8
7        1      119       20       3       38       20       0        0
8        1      119       21       3        1        9       0        0
9        1      751       21       3       63       23       4       46
10       1      314       20       3      178       21       4        4
11       4       68       17       1       67       14       3       58
12       3      108       15       4       82       15       1       44
13       3      118       24       6        3       17       1        1
14       3      121       20       6       85       19       1       18
15       3       58       23       4       27       23       6       11
16       3      126       23       6       33       23       1       31
17       3       87       21       1       74       21       4       10
18       3      143       18       1       35       17       4       20
19       3       43       18       4       35       19       1       20
20       3      732       24       1      236       24       4       17
21       3      175       16       1       37       16       0        0
22       3      101       19       1       16       17       6        1
23       3       45       19       1       24       18       4       15
    param_3
0        18
1         0
2         0
3        20
4        21
5         0
6        17
7         0
8         0
9        21
10       18
11       12
12       14
13       17
14       19
15       21
16       22
17       21
18       17
19       19
20       22
21        0
22        6
23       20
</code>```

答:
Use wide_to_long for reshape first, then create helper column type1 used for groups by add to MultiIndex in DataFrame.set_index, remove second level by DataFrame.droplevel and reshape by DataFrame.unstack, last sorting by second level and flatten MultiIndex in columns:

```<code>df = (pd.wide_to_long(df.reset_index(),
                      stubnames=['type','count','param'],
                      i = 'index',
                      j='tmp',
                      sep='_')
        .assign(type1 = lambda x: x['type'])
        .query("type != 0")
        .set_index('type1', append=True)
        .droplevel(1)
        .unstack()
        .sort_index(level=1, axis=1, sort_remaining=False)
        )

df.columns = [f'group_{b}' if a == 'type' else f'g{b}_{a}' for a, b in df.columns]

</code>```

```<code>print (df.head(10))
       group_1  g1_count  g1_param  group_3  g3_count  g3_param  group_4  \
index
0          1.0     465.0      22.0      3.0      49.0      20.0      4.0
1          1.0     254.0      21.0      3.0      15.0      19.0      NaN
2          1.0     154.0      19.0      3.0       5.0      18.0      NaN
3          1.0      16.0      21.0      3.0      16.0      21.0      4.0
4          1.0     254.0      22.0      3.0      74.0      21.0      4.0
5          1.0     261.0      21.0      3.0       3.0      17.0      NaN
6          1.0     595.0      21.0      3.0     122.0      20.0      NaN
7          1.0     119.0      20.0      3.0      38.0      20.0      NaN
8          1.0     119.0      21.0      3.0       1.0       9.0      NaN
9          1.0     751.0      21.0      3.0      63.0      23.0      4.0

       g4_count  g4_param  group_6  g6_count  g6_param
index
0           3.0      18.0      NaN       NaN       NaN
1           NaN       NaN      NaN       NaN       NaN
2           NaN       NaN      NaN       NaN       NaN
3           7.0      20.0      NaN       NaN       NaN
4          39.0      21.0      NaN       NaN       NaN
5           NaN       NaN      NaN       NaN       NaN
6           NaN       NaN      6.0       8.0      17.0
7           NaN       NaN      NaN       NaN       NaN
8           NaN       NaN      NaN       NaN       NaN
9          46.0      21.0      NaN       NaN       NaN
</code>```

EDIT:

```<code>d = {'type_1': [3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 4, 3, 3, 3, 3, 3, 3, 3, 3], 'count_1': [465, 254, 154, 16, 254, 261, 595, 119, 119, 751, 314, 68, 108, 118, 121, 58, 126, 87, 143, 43], 'param_1': [22, 21, 19, 21, 22, 21, 21, 20, 21, 21, 20, 17, 15, 24, 20, 23, 23, 21, 18, 18], 'type_2': [3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 1, 4, 6, 6, 4, 6, 1, 1, 4], 'count_2': [49, 15, 5, 16, 74, 3, 122, 38, 1, 63, 178, 67, 82, 3, 85, 27, 33, 74, 35, 35], 'param_2': [20, 19, 18, 21, 21, 17, 20, 20, 9, 23, 21, 14, 15, 17, 19, 23, 23, 21, 17, 19], 'type_3': [4, 0, 0, 4, 4, 0, 6, 0, 0, 4, 4, 3, 1, 1, 1, 6, 1, 4, 4, 1], 'count_3': [3, 0, 0, 7, 39, 0, 8, 0, 0, 46, 4, 58, 44, 1, 18, 11, 31, 10, 20, 20], 'param_3': [18, 0, 0, 20, 21, 0, 17, 0, 0, 21, 18, 12, 14, 17, 19, 21, 22, 21, 17, 19]}

df = pd.DataFrame(d)

df = (pd.wide_to_long(df.reset_index(),
                      stubnames=['type','count','param'],
                      i = 'index',
                      j='tmp',
                      sep='_')
        .assign(type1 = lambda x: x['type'])
        .set_index('type1', append=True)
        .droplevel(1)
        .reset_index())

df = df[df.duplicated(['index','type'], keep=False)]
print (df)
    index  type1  type  count  param
0       0      3     3    465     22
20      0      3     3     49     20
</code>```

Body:
How to sort or group by dataframe by specific values from multiple columns with Pandas?

The dataframe that I am working with looks like below. I have 3 type columns with corresponding parameters count and param. For each type accordingly count and param column. I need to sort them based on type value, so the result would be new columns with its parameters for type = '1', type = '3', type = '3' and type = '6'.

The desired result looks like this:

What I tried is this, however, I  really not sure that this will do what I want, also with I would sort only type columns and not count and param as well:

import pandas as pd

dataframe = pd.read_csv(r'W:\...file.csv')

type_col = 1
new_column = 'group_1'

dataframe.loc[dataframe[type_1'] == type_col, group_1] = type_col
dataframe.loc[dataframe['type_2'] == type_col, group_1] = type_col
dataframe.loc[dataframe['type_3'] == type_col, group_1] = type_col

Here is the print output of dataframe.head(20):

print(dataframe.head(20).to_dict('list'))
{'type_1': [1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 4, 3, 3, 3, 3, 3, 3, 3, 3], 'count_1': [465, 254, 154, 16, 254, 261, 595, 119, 119, 751, 314, 68, 108, 118, 121, 58, 126, 87, 143, 43], 'param_1': [22, 21, 19, 21, 22, 21, 21, 20, 21, 21, 20, 17, 15, 24, 20, 23, 23, 21, 18, 18], 'type_2': [3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 1, 4, 6, 6, 4, 6, 1, 1, 4], 'count_2': [49, 15, 5, 16, 74, 3, 122, 38, 1, 63, 178, 67, 82, 3, 85, 27, 33, 74, 35, 35], 'param_2': [20, 19, 18, 21, 21, 17, 20, 20, 9, 23, 21, 14, 15, 17, 19, 23, 23, 21, 17, 19], 'type_3': [4, 0, 0, 4, 4, 0, 6, 0, 0, 4, 4, 3, 1, 1, 1, 6, 1, 4, 4, 1], 'count_3': [3, 0, 0, 7, 39, 0, 8, 0, 0, 46, 4, 58, 44, 1, 18, 11, 31, 10, 20, 20], 'param_3': [18, 0, 0, 20, 21, 0, 17, 0, 0, 21, 18, 12, 14, 17, 19, 21, 22, 21, 17, 19]}

And the full dataframe:
print(dataframe)

    type_1  count_1  param_1  type_2  count_2  param_2  type_3  count_3  \
0        1      465       22       3       49       20       4        3
1        1      254       21       3       15       19       0        0
2        1      154       19       3        5       18       0        0
3        3       16       21       1       16       21       4        7
4        1      254       22       3       74       21       4       39
5        1      261       21       3        3       17       0        0
6        1      595       21       3      122       20       6        8
7        1      119       20       3       38       20       0        0
8        1      119       21       3        1        9       0        0
9        1      751       21       3       63       23       4       46
10       1      314       20       3      178       21       4        4
11       4       68       17       1       67       14       3       58
12       3      108       15       4       82       15       1       44
13       3      118       24       6        3       17       1        1
14       3      121       20       6       85       19       1       18
15       3       58       23       4       27       23       6       11
16       3      126       23       6       33       23       1       31
17       3       87       21       1       74       21       4       10
18       3      143       18       1       35       17       4       20
19       3       43       18       4       35       19       1       20
20       3      732       24       1      236       24       4       17
21       3      175       16       1       37       16       0        0
22       3      101       19       1       16       17       6        1
23       3       45       19       1       24       18       4       15
    param_3
0        18
1         0
2         0
3        20
4        21
5         0
6        17
7         0
8         0
9        21
10       18
11       12
12       14
13       17
14       19
15       21
16       22
17       21
18       17
19       19
20       22
21        0
22        6
23       20

Body:
Use wide_to_long for reshape first, then create helper column type1 used for groups by add to MultiIndex in DataFrame.set_index, remove second level by DataFrame.droplevel and reshape by DataFrame.unstack, last sorting by second level and flatten MultiIndex in columns:

df = (pd.wide_to_long(df.reset_index(),
                      stubnames=['type','count','param'],
                      i = 'index',
                      j='tmp',
                      sep='_')
        .assign(type1 = lambda x: x['type'])
        .query("type != 0")
        .set_index('type1', append=True)
        .droplevel(1)
        .unstack()
        .sort_index(level=1, axis=1, sort_remaining=False)
        )

df.columns = [f'group_{b}' if a == 'type' else f'g{b}_{a}' for a, b in df.columns]

print (df.head(10))
       group_1  g1_count  g1_param  group_3  g3_count  g3_param  group_4  \
index
0          1.0     465.0      22.0      3.0      49.0      20.0      4.0
1          1.0     254.0      21.0      3.0      15.0      19.0      NaN
2          1.0     154.0      19.0      3.0       5.0      18.0      NaN
3          1.0      16.0      21.0      3.0      16.0      21.0      4.0
4          1.0     254.0      22.0      3.0      74.0      21.0      4.0
5          1.0     261.0      21.0      3.0       3.0      17.0      NaN
6          1.0     595.0      21.0      3.0     122.0      20.0      NaN
7          1.0     119.0      20.0      3.0      38.0      20.0      NaN
8          1.0     119.0      21.0      3.0       1.0       9.0      NaN
9          1.0     751.0      21.0      3.0      63.0      23.0      4.0

       g4_count  g4_param  group_6  g6_count  g6_param
index
0           3.0      18.0      NaN       NaN       NaN
1           NaN       NaN      NaN       NaN       NaN
2           NaN       NaN      NaN       NaN       NaN
3           7.0      20.0      NaN       NaN       NaN
4          39.0      21.0      NaN       NaN       NaN
5           NaN       NaN      NaN       NaN       NaN
6           NaN       NaN      6.0       8.0      17.0
7           NaN       NaN      NaN       NaN       NaN
8           NaN       NaN      NaN       NaN       NaN
9          46.0      21.0      NaN       NaN       NaN

EDIT:

d = {'type_1': [3, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 4, 3, 3, 3, 3, 3, 3, 3, 3], 'count_1': [465, 254, 154, 16, 254, 261, 595, 119, 119, 751, 314, 68, 108, 118, 121, 58, 126, 87, 143, 43], 'param_1': [22, 21, 19, 21, 22, 21, 21, 20, 21, 21, 20, 17, 15, 24, 20, 23, 23, 21, 18, 18], 'type_2': [3, 3, 3, 1, 3, 3, 3, 3, 3, 3, 3, 1, 4, 6, 6, 4, 6, 1, 1, 4], 'count_2': [49, 15, 5, 16, 74, 3, 122, 38, 1, 63, 178, 67, 82, 3, 85, 27, 33, 74, 35, 35], 'param_2': [20, 19, 18, 21, 21, 17, 20, 20, 9, 23, 21, 14, 15, 17, 19, 23, 23, 21, 17, 19], 'type_3': [4, 0, 0, 4, 4, 0, 6, 0, 0, 4, 4, 3, 1, 1, 1, 6, 1, 4, 4, 1], 'count_3': [3, 0, 0, 7, 39, 0, 8, 0, 0, 46, 4, 58, 44, 1, 18, 11, 31, 10, 20, 20], 'param_3': [18, 0, 0, 20, 21, 0, 17, 0, 0, 21, 18, 12, 14, 17, 19, 21, 22, 21, 17, 19]}

df = pd.DataFrame(d)

df = (pd.wide_to_long(df.reset_index(),
                      stubnames=['type','count','param'],
                      i = 'index',
                      j='tmp',
                      sep='_')
        .assign(type1 = lambda x: x['type'])
        .set_index('type1', append=True)
        .droplevel(1)
        .reset_index())

df = df[df.duplicated(['index','type'], keep=False)]
print (df)
    index  type1  type  count  param
0       0      3     3    465     22
20      0      3     3     49     20


问:
Blazor error Could not find NativeFileReference
I am watching this Steve Sanderson's Video titled New Blazor WebAssembly capabilities in .NET 6.

I Cloned the git hub repo and tried to build the BlazeOrbital solution inside of it.

I am getting the following errors

Severity  Code    Description Project File    Line    Suppression State
Error     Could not find NativeFileReference
..\rustqr\target\wasm32-unknown-emscripten\debug\librustqr.a  BlazeOrbital.ManufacturingHub   C:\Program Files\dotnet\packs\Microsoft.NET.Runtime.WebAssembly.Sdk\6.0.1\Sdk\WasmApp.Native.targets    228

Severity  Code    Description Project File    Line    Suppression State
Error MC3066  The type reference cannot find a public type named
'Inventory'. Line 12 Position
51.   BlazeOrbital.Accounting E:\Vivek\Trials\WebApps\Blazor\BlazeOrbital\BlazeOrbital\Accounting\Inventory.xaml  12

Certainly I am missing something here as I am new to Blazor.

Can someone please nudge me whats happening here?

When I look at Solution Explorer, I see a missing file librustqr.dll

Where do I get that from, or how do I build that? Rust is Greek and Latin to me, so please help.

But the other solution Satellite Simulator runs fine.

Update

I followed the steps @Janus1986. I downloaded the rustup-init.exe as mentioned. Also installed C++ Build tools. Then installed emscripten

Then I ran cargo build from the this rustqr folder.

Now I get this error.

warning: unused manifest key: build
Compiling bmp-monochrome v1.0.0
error[E0463]: can't find crate for std
|
= note: the wasm32-unknown-emscripten target may not be installed
= help: consider downloading the target with rustup target add wasm32-unknown-emscripten

For more information about this error, try rustc --explain E0463.
error: could not compile bmp-monochrome due to previous error

:(

Stuck.

Can someone elaborate what steps are need to get this up and running.

答:
Encountered the same problem, the repository don't have all libraries you have tou build it, it's a simple rust library.
You'll have to install rust
https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe
then emscripten (I installed it from chocolatey)
https://chocolatey.org/install

```<code>choco install emscripten
</code>```

then go to the rust folder to build the libs

```<code>cargo build
</code>```

change the target to x86_64-pc-windows-msvc

```<code>rustup update
rustup install x86_64-pc-windows-msvc
</code>```

and change the
inside config.toml:

```<code>[build]
target = "x86_64-pc-windows-msvc"
</code>```

and change in cargo.toml

```<code>[lib]
crate-type = ["cdylib"]

cargo build
</code>```

you should have all libraries

Body:
Encountered the same problem, the repository don't have all libraries you have tou build it, it's a simple rust library.
You'll have to install rust
https://static.rust-lang.org/rustup/dist/x86_64-pc-windows-msvc/rustup-init.exe
then emscripten (I installed it from chocolatey)
https://chocolatey.org/install

choco install emscripten

then go to the rust folder to build the libs

cargo build

change the target to x86_64-pc-windows-msvc

rustup update
rustup install x86_64-pc-windows-msvc

and change the
inside config.toml:

[build]
target = "x86_64-pc-windows-msvc"

and change in cargo.toml

[lib]
crate-type = ["cdylib"]

cargo build

you should have all libraries


问:
How to access @EventData in a @DomEvent in a Vaadin Component
I created a Vaadin Flow v22 Component wrapping the UI5 MultiComboBox Webcomponent:

```<code>@Tag("ui5-multi-combobox")
@NpmPackage(value = "@ui5/webcomponents", version = "^1.1.2")
@JsModule("@ui5/webcomponents/dist/MultiComboBox.js")
@JsModule("@ui5/webcomponents/dist/features/InputElementsFormSupport.js")
public class Ui5MultiComboBox extends Component implements HasComponents, HasLabel, HasSize {
    …
    public void setPlaceholder(String placeholder) {
        this.getElement().setProperty("placeholder", placeholder);
    }
    …
    @DomEvent("selection-change")
    public static class SelectionChangeEvent extends ComponentEvent<Ui5MultiComboBox> {
        public SelectionChangeEvent(Ui5MultiComboBox source, boolean fromClient,
                @EventData("element.placeholder") String placeholder,
                @EventData("event.bubbles") boolean bubbles,
                @EventData("event.items") JsonArray itemsa) {
            super(source, fromClient);
            LOGGER.info("Ui5MultiComboBoxSelectionChangeEvent: placeholder=" + placeholder);
            LOGGER.info("Ui5MultiComboBoxSelectionChangeEvent: bubbles=" + bubbles);
            LOGGER.info("Ui5MultiComboBoxSelectionChangeEvent: itemsa=" + itemsa);
        }
    }
    …
    public Registration addSelectionChangeListener(ComponentEventListener<SelectionChangeEvent> listener) {
        return addListener(SelectionChangeEvent.class, listener);
    }
}
</code>```

I then use the Vaadin Component in my Vaadin View:

```<code>…
Ui5MultiComboBox multiCombo1 = new Ui5MultiComboBox();
multiCombo1.setPlaceholder("Enter or pick items");
multiCombo1.addSelectionChangeListener(e -> {
    LOGGER.info("View: Selection Changed Listener ...");
});

getContent().add(multiCombo1);

// add items:
for (ItemData d : data) {
    Ui5MultiComboBoxItem multiComboItem = new Ui5MultiComboBoxItem();
    multiComboItem.setText(d.text);
    multiComboItem.setSelected(d.selected);

    multiCombo1.add(multiComboItem);
}
</code>```

I run my Application (in Crome) and it renders as expected.
When I remove one of the Ui5MultiComboBoxItem, my Listener fires as expected.

The problem is that the Listener does not get access to the @EventData("event.items") JsonArray itemsa.

Console shows null for that itemsa variable, while accessing more simple @EventData like "element.placeholder" or "event.bubbles" perfectly works:

```<code>Ui5MultiComboBoxSelectionChangeEvent: placeholder=Enter or pick items
Ui5MultiComboBoxSelectionChangeEvent: bubbles=true
Ui5MultiComboBoxSelectionChangeEvent: itemsa=null
View: Selection Changed Listener ...
</code>```

I've also used:

```<code>@EventData("event.detail") JsonArray itemsa
</code>```
```<code>@EventData("event.detail.items") JsonArray itemsa
</code>```
```<code>@EventData("event.detail") JsonObject itemsa
</code>```
```<code>@EventData("event.detail.items") JsonObject itemsa
</code>```
```<code>@EventData("event.detail") String itemsa
</code>```
```<code>@EventData("event.detail.items") String itemsa
</code>```
```<code>@EventData("event.detail") Object itemsa
</code>```
```<code>…
Ui5MultiComboBox multiCombo1 = new Ui5MultiComboBox();
multiCombo1.setPlaceholder("Enter or pick items");
multiCombo1.addSelectionChangeListener(e -> {
    LOGGER.info("View: Selection Changed Listener ...");
});

getContent().add(multiCombo1);

// add items:
for (ItemData d : data) {
    Ui5MultiComboBoxItem multiComboItem = new Ui5MultiComboBoxItem();
    multiComboItem.setText(d.text);
    multiComboItem.setSelected(d.selected);

    multiCombo1.add(multiComboItem);
}
</code>```0

but all these raise an error in Chrome Console:

```<code>…
Ui5MultiComboBox multiCombo1 = new Ui5MultiComboBox();
multiCombo1.setPlaceholder("Enter or pick items");
multiCombo1.addSelectionChangeListener(e -> {
    LOGGER.info("View: Selection Changed Listener ...");
});

getContent().add(multiCombo1);

// add items:
for (ItemData d : data) {
    Ui5MultiComboBoxItem multiComboItem = new Ui5MultiComboBoxItem();
    multiComboItem.setText(d.text);
    multiComboItem.setSelected(d.selected);

    multiCombo1.add(multiComboItem);
}
</code>```1

The typo in "dependecy" might give a hint who is issuing that error message.

Here's the UI5 Web Component Description: MultiComboBox

Any help highly appreciated!

答:
You need to know in detail how the web component you are integrating has implemented the detail. I take one of my own projects as example here. So lets say I have web component tab-sheet, where I fire custom even called tab-changed. I need some metadata to be delivered to server side in the event, so I compose JSON object details with couple of properties.

```<code>  selectedChanged(e: CustomEvent) {
    const page = e.detail.value;
    const tab = this.getTab(page);
    this._doSelectTab(page);
    const details : JSON = <JSON><unknown>{
      "index": page,
      "caption": this.getTabCaption(tab),
      "tab": tab
    }
    const event = new CustomEvent('tab-changed', {
        detail: details,
        composed: true,
        cancelable: true,
        bubbles: true
    });
    this.dispatchEvent(event);
  }
</code>```

The full implementation of the component is here: https://github.com/TatuLund/TabSheet/blob/master/src/main/resources/META-INF/resources/frontend/tab-sheet.ts

Now, I want to observe this event on Java class that is the server side representation of the component.

I use @DomEvent for that and in constructor of the event class, I decipher the JSON using @EventData("event.detail"), which now contains the JSON object I composed.

```<code>    @DomEvent("tab-changed")
    public static class TabChangedEvent<R extends TabSheet> extends ComponentEvent<TabSheet> {
        private int index;
        private TabSheet source;
        private String caption;
        private String tab;

        public TabChangedEvent(TabSheet source, boolean fromClient, @EventData("event.detail") JsonObject details) {
            super(source, fromClient);
            this.index = (int) details.getNumber("index");
            this.tab = details.getString("tab");
            this.caption = details.getString("caption");
            this.source = source;
        }
    ...
    }
</code>```

The full code is here: https://github.com/TatuLund/TabSheet/blob/master/src/main/java/org/vaadin/addons/tatu/TabSheet.java

Body:
I created a Vaadin Flow v22 Component wrapping the UI5 MultiComboBox Webcomponent:

@Tag("ui5-multi-combobox")
@NpmPackage(value = "@ui5/webcomponents", version = "^1.1.2")
@JsModule("@ui5/webcomponents/dist/MultiComboBox.js")
@JsModule("@ui5/webcomponents/dist/features/InputElementsFormSupport.js")
public class Ui5MultiComboBox extends Component implements HasComponents, HasLabel, HasSize {
    …
    public void setPlaceholder(String placeholder) {
        this.getElement().setProperty("placeholder", placeholder);
    }
    …
    @DomEvent("selection-change")
    public static class SelectionChangeEvent extends ComponentEvent<Ui5MultiComboBox> {
        public SelectionChangeEvent(Ui5MultiComboBox source, boolean fromClient,
                @EventData("element.placeholder") String placeholder,
                @EventData("event.bubbles") boolean bubbles,
                @EventData("event.items") JsonArray itemsa) {
            super(source, fromClient);
            LOGGER.info("Ui5MultiComboBoxSelectionChangeEvent: placeholder=" + placeholder);
            LOGGER.info("Ui5MultiComboBoxSelectionChangeEvent: bubbles=" + bubbles);
            LOGGER.info("Ui5MultiComboBoxSelectionChangeEvent: itemsa=" + itemsa);
        }
    }
    …
    public Registration addSelectionChangeListener(ComponentEventListener<SelectionChangeEvent> listener) {
        return addListener(SelectionChangeEvent.class, listener);
    }
}

I then use the Vaadin Component in my Vaadin View:

…
Ui5MultiComboBox multiCombo1 = new Ui5MultiComboBox();
multiCombo1.setPlaceholder("Enter or pick items");
multiCombo1.addSelectionChangeListener(e -> {
    LOGGER.info("View: Selection Changed Listener ...");
});

getContent().add(multiCombo1);

// add items:
for (ItemData d : data) {
    Ui5MultiComboBoxItem multiComboItem = new Ui5MultiComboBoxItem();
    multiComboItem.setText(d.text);
    multiComboItem.setSelected(d.selected);

    multiCombo1.add(multiComboItem);
}

I run my Application (in Crome) and it renders as expected.
When I remove one of the Ui5MultiComboBoxItem, my Listener fires as expected.

The problem is that the Listener does not get access to the @EventData("event.items") JsonArray itemsa.

Console shows null for that itemsa variable, while accessing more simple @EventData like "element.placeholder" or "event.bubbles" perfectly works:

Ui5MultiComboBoxSelectionChangeEvent: placeholder=Enter or pick items
Ui5MultiComboBoxSelectionChangeEvent: bubbles=true
Ui5MultiComboBoxSelectionChangeEvent: itemsa=null
View: Selection Changed Listener ...

I've also used:

@EventData("event.detail") JsonArray itemsa

@EventData("event.detail.items") JsonArray itemsa

@EventData("event.detail") JsonObject itemsa

@EventData("event.detail.items") JsonObject itemsa

@EventData("event.detail") String itemsa

@EventData("event.detail.items") String itemsa

@EventData("event.detail") Object itemsa

@EventData("event.detail.items") Object itemsa

but all these raise an error in Chrome Console:

(String) : Message JsonObject contained a dom node reference which should not be sent to the server and can cause a cyclic dependecy.

The typo in "dependecy" might give a hint who is issuing that error message.

Here's the UI5 Web Component Description: MultiComboBox

Any help highly appreciated!

Body:
You need to know in detail how the web component you are integrating has implemented the detail. I take one of my own projects as example here. So lets say I have web component tab-sheet, where I fire custom even called tab-changed. I need some metadata to be delivered to server side in the event, so I compose JSON object details with couple of properties.

  selectedChanged(e: CustomEvent) {
    const page = e.detail.value;
    const tab = this.getTab(page);
    this._doSelectTab(page);
    const details : JSON = <JSON><unknown>{
      "index": page,
      "caption": this.getTabCaption(tab),
      "tab": tab
    }
    const event = new CustomEvent('tab-changed', {
        detail: details,
        composed: true,
        cancelable: true,
        bubbles: true
    });
    this.dispatchEvent(event);
  }

The full implementation of the component is here: https://github.com/TatuLund/TabSheet/blob/master/src/main/resources/META-INF/resources/frontend/tab-sheet.ts

Now, I want to observe this event on Java class that is the server side representation of the component.

I use @DomEvent for that and in constructor of the event class, I decipher the JSON using @EventData("event.detail"), which now contains the JSON object I composed.

    @DomEvent("tab-changed")
    public static class TabChangedEvent<R extends TabSheet> extends ComponentEvent<TabSheet> {
        private int index;
        private TabSheet source;
        private String caption;
        private String tab;

        public TabChangedEvent(TabSheet source, boolean fromClient, @EventData("event.detail") JsonObject details) {
            super(source, fromClient);
            this.index = (int) details.getNumber("index");
            this.tab = details.getString("tab");
            this.caption = details.getString("caption");
            this.source = source;
        }
    ...
    }

The full code is here: https://github.com/TatuLund/TabSheet/blob/master/src/main/java/org/vaadin/addons/tatu/TabSheet.java


问:
Remove newline from string output

try:
    with cx_oracle.connect(user,password,dsn,encoding ="UTF-8") as connection:
        cursor = connection.cursor()
        cursor.execute("select * from customer")
        results =cursor.fetchall()
        return json.dumps(results,indent=4,sort_keys = True,default=str)
except Exception as error:
    print ("error occurred",error)
```
<p>output</p>
```'[\n [\n 1456,\n   "ice kle",\n  "2022:02:08 8:06:01",\n  "2022-02-08 8:07:01",\n "fund"\n]'
```

答:
The indent=4 argument in json.dumps call is responsible for the pretty print(with newlines).

Remove the argument if want all of the result in single line.

@Joran 's answer is correct. I don't have the reputation to add a comment so adding it as answer.

Title: Remove newline from string output

Body:
try:
    with cx_oracle.connect(user,password,dsn,encoding ="UTF-8") as connection:
        cursor = connection.cursor()
        cursor.execute("select * from customer")
        results =cursor.fetchall()
        return json.dumps(results,indent=4,sort_keys = True,default=str)
except Exception as error:
    print ("error occurred",error)

output

'[\n [\n 1456,\n   "ice kle",\n  "2022:02:08 8:06:01",\n  "2022-02-08 8:07:01",\n "fund"\n]'