问:
Hovering Data for Choropleth maps In Folium
I am trying to make Choropleth maps in python using Folium tracking the amount of refugees into each state. My maps are running, but I want to create labels to show the state name and the amount of refugees that appear when I hover/click on each state. I am not sure if this is possible, but I would appreciate any help! Here is the code for my running map Choropleth map.</p>
```<code>import pandas as pd
import json
import folium

twentysa=pd.read_excel("State_abrv (9).xlsx")

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"

h = folium.Map(location=[48, -102], zoom_start=3)

folium.Choropleth(
    geo_data=state_geo,
    name="2013 Data",
    data=thirteensa,
    columns=["State", "Refugee Influx"],
    key_on="feature.id",
    fill_color="BuPu",
    fill_opacity=0.8,
    line_opacity=0.3,
    legend_name="2013 Refugee Influx",
).add_to(h)
h
</code>```

答:
You need to use folium.GeoJSON to use the tooltip to enable the hover functionality. I've borrowed the below code from here and it worked for me. This is a starting point to allow the state to display upon hover, but this could be improved upon to show the refugee numbers as well.</p>
```<code># hover functionality

style_function = lambda x: {'fillColor': '#ffffff',
                            'color':'#000000',
                            'fillOpacity': 0.1,
                            'weight': 0.1}
highlight_function = lambda x: {'fillColor': '#000000',
                                'color':'#000000',
                                'fillOpacity': 0.50,
                                'weight': 0.1}
NIL = folium.features.GeoJson(
    state_geo,
    style_function=style_function,
    control=False,
    highlight_function=highlight_function,
    tooltip=folium.features.GeoJsonTooltip(
        fields=['name','id'],  # use fields from the json file
        aliases=['State: ','ID: '],
        style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;")
    )
)
h.add_child(NIL)
h.keep_in_front(NIL)
folium.LayerControl().add_to(h)
</code>```

Body:
I am trying to make Choropleth maps in python using Folium tracking the amount of refugees into each state. My maps are running, but I want to create labels to show the state name and the amount of refugees that appear when I hover/click on each state. I am not sure if this is possible, but I would appreciate any help! Here is the code for my running map Choropleth map.

import pandas as pd
import json
import folium

twentysa=pd.read_excel("State_abrv (9).xlsx")

url = (
    "https://raw.githubusercontent.com/python-visualization/folium/master/examples/data"
)
state_geo = f"{url}/us-states.json"

h = folium.Map(location=[48, -102], zoom_start=3)

folium.Choropleth(
    geo_data=state_geo,
    name="2013 Data",
    data=thirteensa,
    columns=["State", "Refugee Influx"],
    key_on="feature.id",
    fill_color="BuPu",
    fill_opacity=0.8,
    line_opacity=0.3,
    legend_name="2013 Refugee Influx",
).add_to(h)
h

Body:
You need to use folium.GeoJSON to use the tooltip to enable the hover functionality. I've borrowed the below code from here and it worked for me. This is a starting point to allow the state to display upon hover, but this could be improved upon to show the refugee numbers as well.

# hover functionality

style_function = lambda x: {'fillColor': '#ffffff',
                            'color':'#000000',
                            'fillOpacity': 0.1,
                            'weight': 0.1}
highlight_function = lambda x: {'fillColor': '#000000',
                                'color':'#000000',
                                'fillOpacity': 0.50,
                                'weight': 0.1}
NIL = folium.features.GeoJson(
    state_geo,
    style_function=style_function,
    control=False,
    highlight_function=highlight_function,
    tooltip=folium.features.GeoJsonTooltip(
        fields=['name','id'],  # use fields from the json file
        aliases=['State: ','ID: '],
        style=("background-color: white; color: #333333; font-family: arial; font-size: 12px; padding: 10px;")
    )
)
h.add_child(NIL)
h.keep_in_front(NIL)
folium.LayerControl().add_to(h)


来源: stackexchange

问:
Does Pandas have a dataframe length limit?
I want to create a system where I load and analyze large amounts of data into pandas. Also, I will later use this to write back to .parquet files

when I try to test this using a simple example, I see that there is some kind of built in limit on the number of rows

```<code>import pandas as pd

# Create file with 100 000 000 rows
contents = """
Tommy;19
Karen;20
"""*50000000

open("person.csv","w").write(
f"""
Name;Age
{contents}
"""
)
print("Test generated")

df = pd.read_csv("person.csv",delimiter=";")
len(df)
</code>```

returns 10 000 000. Not 100 000 000

答:
I don't think there is a limit , but there is a limit to how much it can process at a time, but that u can go around it by making code more efficient..

currently I am working with around 1-2 million rows without any issues

ContentLicense: CC BY-SA 4.0

Body:
I want to create a system where I load and analyze large amounts of data into pandas. Also, I will later use this to write back to .parquet files

when I try to test this using a simple example, I see that there is some kind of built in limit on the number of rows

import pandas as pd

# Create file with 100 000 000 rows
contents = """
Tommy;19
Karen;20
"""*50000000

open("person.csv","w").write(
f"""
Name;Age
{contents}
"""
)
print("Test generated")

df = pd.read_csv("person.csv",delimiter=";")
len(df)

returns 10 000 000. Not 100 000 000


问:
WSS3 - setting a default value on a SPFieldType.Boolean after creation
I'm using WSS3 and C# to create site and I am creating a class to change fields on lists after they have been created.  I have already created an SPField.Boolean type with no default value, but after upgrade I need the default value to be set to true. My current code that does not work follows:

```<code>           //web is already defined as the current web
           var list = web.Site.RootWeb.Lists["ListWithFieldOnIt"];
           var field = list.Fields.GetField("booleanfield");
           field.DefaultValue = "1";
           field.Update(true);
           list.Update(true);
</code>```

I have tried to change the default value through the sharepoint instance and sharepoint manager 2007 and neither of those have worked.  Does anyone know of any way to set the default value or what I am doing wrong?

Thanks in advance

答:
Code below should be more than enough to update list field definition:

```<code>       var list = web.Site.RootWeb.Lists["ListWithFieldOnIt"];
       var field = list.Fields.GetField("booleanfield");
       field.DefaultValue = "1";
       field.Update();
</code>```

You don't need to update the list or pass 'true' to SPField.Update method.

ContentLicense: CC BY-SA 2.5

Body:
I'm using WSS3 and C# to create site and I am creating a class to change fields on lists after they have been created.  I have already created an SPField.Boolean type with no default value, but after upgrade I need the default value to be set to true. My current code that does not work follows:

           //web is already defined as the current web
           var list = web.Site.RootWeb.Lists["ListWithFieldOnIt"];
           var field = list.Fields.GetField("booleanfield");
           field.DefaultValue = "1";
           field.Update(true);
           list.Update(true);

I have tried to change the default value through the sharepoint instance and sharepoint manager 2007 and neither of those have worked.  Does anyone know of any way to set the default value or what I am doing wrong?

Thanks in advance

Body:
Code below should be more than enough to update list field definition:

       var list = web.Site.RootWeb.Lists["ListWithFieldOnIt"];
       var field = list.Fields.GetField("booleanfield");
       field.DefaultValue = "1";
       field.Update();

You don't need to update the list or pass 'true' to SPField.Update method.

ContentLicense: CC BY-SA 3.0


问:
why I cant see any output on my reactjs app?
I have started my first React lesson but I cant see any output on my localhost(3000), will you pls help me ?

this is my JS code :

```<code>import React from 'react';
import ReactDOM from 'react';

const element = React.createElement("div", { id: "title", className: "app-title" }, "this is a test text");

ReactDOM.render(element, document.getElementById("root"));
</code>```

答:
Look at the Console in your browser's developer tools. When I run this code it says:

Uncaught TypeError: _reactDefault.default.render is not a function

So something is wrong with the object you call render on. That clues us into looking at the place it is defined.

```<code>import React from 'react';
import ReactDOM from 'react';
</code>```

You've imported react twice and assigned it to different variables. That doesn't make a whole lot of sense.

So go back and check the tutorial you are working from.

You should see that ReactDOM should be imported from 'react-dom' and not 'react'.

```<code>import React from 'react';
import ReactDOM from 'react-dom';
</code>```

Body:
I have started my first React lesson but I cant see any output on my localhost(3000), will you pls help me ?

this is my JS code :

import React from 'react';
import ReactDOM from 'react';

const element = React.createElement("div", { id: "title", className: "app-title" }, "this is a test text");

ReactDOM.render(element, document.getElementById("root"));

Body:
Look at the Console in your browser's developer tools. When I run this code it says:

Uncaught TypeError: _reactDefault.default.render is not a function

So something is wrong with the object you call render on. That clues us into looking at the place it is defined.

import React from 'react';
import ReactDOM from 'react';

You've imported react twice and assigned it to different variables. That doesn't make a whole lot of sense.

So go back and check the tutorial you are working from.

You should see that ReactDOM should be imported from 'react-dom' and not 'react'.

import React from 'react';
import ReactDOM from 'react-dom';


问:
How can I encrypt url in Django Rest Framework?
I found a documentation since it is not working with python updated version so I am having this problem. I want to prevent scrapping from my application. There are some api where I am passing sensitive data and my api endpoing is like localhost:8000/api/products/1 but I want this url to be like
localhost:8000/api/products/dheudhuehdeidiwf4yfg4gfy4yf4f4fu4f84j4i this. So which procedure should I follow here?</p>

答:
You can use uuid as another unique key in your model.

```<code>import uuid

class Product(models.Model):
    uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
    # other fields ...
</code>```

For the serializers, you'll have to manually set them like:

```<code>class ProductSerializer(serializers.Serializer):
    uuid = serializers.UUIDField(format="hex", read_only=True)
    # other fields ...

    class Meta:
        model = Product
        fields = [
            "uuid",
            # other fields ...
        ]
</code>```

For the views, I'm assuming you are using ModelViewSet, so you can set the uuid as the lookup field like:

```<code>class ProductViewSet(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    lookup_field = "uuid"
</code>```

Body:
You can use uuid as another unique key in your model.

import uuid

class Product(models.Model):
    uuid = models.UUIDField(unique=True, default=uuid.uuid4, editable=False)
    # other fields ...

For the serializers, you'll have to manually set them like:

class ProductSerializer(serializers.Serializer):
    uuid = serializers.UUIDField(format="hex", read_only=True)
    # other fields ...

    class Meta:
        model = Product
        fields = [
            "uuid",
            # other fields ...
        ]

For the views, I'm assuming you are using ModelViewSet, so you can set the uuid as the lookup field like:

class ProductViewSet(viewsets.ModelViewSet):
    serializer_class = ProductSerializer
    lookup_field = "uuid"


问:
Is there a way to change height of tkinter Treeview heading?
I got a problem with changing the height of the Treeview.heading. I have found some answers about the dimensions of Treeview.column, but when I access Treeview.heading in the documentation, there is not a single word about changing the height of the heading dynamically when the text doesn't fit (and wrapping it) or even just hard-coding height of the heading in pixels.
I don't have to split the text to two rows, but when I just keep it that long the whole table (as it has many entries) takes up the whole screen. I want to keep it smaller, therefore I need to split longer entries.

Here is how it looks like:

答:
you can use font size to increase the header height for sometimes;

```<code>style = ttk.Style()
style.configure('Treeview.Heading', foreground='black', background='white', font=('Arial',25),)
</code>```

Body:
you can use font size to increase the header height for sometimes;

style = ttk.Style()
style.configure('Treeview.Heading', foreground='black', background='white', font=('Arial',25),)


问:
antd Notification in Context not opening?
I am using Notification from antd wrapped in a context as I intend to call the different notifications in other pages. However, in my development build, I encountered the following error: Error: Objects are not valid as a React child (found: Error: Request failed with status code 500). If you meant to render a collection of children, use an array instead..

What am I doing wrong? Any help would be really appreciated!

Code Sandbox

Error Message in Next.js

答: Found that I was passing in an object as a description into the notification APIs, hence React was not able to render it since it was not an Element or a string.</p>


问:
Django - include app urls
I have the following structure (Django 1.4):

```<code>containing_dir/
    myproject/
        myapp1/
        myapp2/
        myapp3/
</code>```

myproject, myapp1, myapp2, and myapp3 all have init.py, so they're all modules.

In manage.py (under containing_dir) I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

in myproject.settings i define:

```<code>[..]
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = (
    [..]
    'myproject.myapp1',
    'myproject.myapp2',
    'myproject.myapp3',
)
[..]
</code>```

In myapp1.urls.py I define:

```<code>urlpatterns = patterns('myapp1',
    url(r'^agent/$', 'views.agent',    name='agent')
)
</code>```

and I try to import it in myproject.urls I try to import myapp1 urls like this:

```<code>(r'^myapp1/', include('myproject.myapp1.urls'))
</code>```

but whenever I try lo load localhost:8000/myapp1/agent I get

```<code>Exception Value: No module named myapp1
</code>```

I think thrown from withing myapp1.urls

Any help? thanks

答:
Recently, In new versions of Django introduces path(route, view, kwargs=None, name=None) instead of old url() regular expression pattern.

You must have __init__.py file in app folders to recognize it as a package by django project i.e myproject

Django project i.e. myproject urls.py file must be updated to include examples like:

```<code>path('', include('django_app.urls'))
path('url_extension/', include('django_another_app.urls'))

</code>```

Above example includes two apps urls in it. One is without adding any extension to path in url and another is with extension to path in current url.

Also, Do not forget to add django apps in INSTALLED_APPS in settings.py file to recognise it as app by django project something like this.

```<code>ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = [
...
django_app,
django_another_app
...
]
</code>```

For more information look at documentation.

Title: Django - include app urls

Body:
I have the following structure (Django 1.4):

containing_dir/
    myproject/
        myapp1/
        myapp2/
        myapp3/

myproject, myapp1, myapp2, and myapp3 all have init.py, so they're all modules.

In manage.py (under containing_dir) I have os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings")

in myproject.settings i define:

[..]
ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = (
    [..]
    'myproject.myapp1',
    'myproject.myapp2',
    'myproject.myapp3',
)
[..]

In myapp1.urls.py I define:

urlpatterns = patterns('myapp1',
    url(r'^agent/$', 'views.agent',    name='agent')
)

and I try to import it in myproject.urls I try to import myapp1 urls like this:

(r'^myapp1/', include('myproject.myapp1.urls'))

but whenever I try lo load localhost:8000/myapp1/agent I get

Exception Value: No module named myapp1

I think thrown from withing myapp1.urls

Any help? thanks

Body:
Recently, In new versions of Django introduces path(route, view, kwargs=None, name=None) instead of old url() regular expression pattern.

You must have __init__.py file in app folders to recognize it as a package by django project i.e myproject

Django project i.e. myproject urls.py file must be updated to include examples like:

path('', include('django_app.urls'))
path('url_extension/', include('django_another_app.urls'))

Above example includes two apps urls in it. One is without adding any extension to path in url and another is with extension to path in current url.

Also, Do not forget to add django apps in INSTALLED_APPS in settings.py file to recognise it as app by django project something like this.

ROOT_URLCONF = 'myproject.urls'
INSTALLED_APPS = [
...
django_app,
django_another_app
...
]

For more information look at documentation.


问:
Preload Images for Html pages
I am new to web design,

Current I am having an issue when loading few images, the background image is flickering, I assume it takes time to load from the server.

How can you preload backgound image for html?

I found few ways from others from seraching like:

```<code><link rel="stylesheet" href="url.com/image/1251302.jpg" as="image">
</code>```

I am not sure how to use this way, if I will use a image later for an html element, how to apply this reloaded image?

If this is not the best way, how to pre-load image correctly?

any help would be greatly appreciated!

Some example of my codes.

```<code>.bgimg-1 {
  background-position: center;
  background-size: cover;
  background-image: url("image/1251302.jpg");
  min-height: 100%;

}
</code>```

later:

```<code><header class="bgimg-1">
</code>```

答:
I am not sure that this is what you are asking about … But if you mean that you need to implement a pre-loader for your website to make suer that everything loaded before showing the user any content to prevent the flickering.
Here is how you can do it
HTML, CSS, and JS:

  const preloader = document.querySelector("#preloader");
  if (preloader) {
    window.addEventListener("load", () => {
      preloader.remove();
    });
  }```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#preloader {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  overflow: hidden;
  background: #fff;
}

#preloader:before {
  content: "";
  position: fixed;
  top: calc(50% - 30px);
  left: calc(50% - 30px);
  border: 6px solid #229727;
  border-top-color: #fff;
  border-bottom-color: #fff;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  -webkit-animation: animate-preloader 1s linear infinite;
  animation: animate-preloader 1s linear infinite;
}

@-webkit-keyframes animate-preloader {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes animate-preloader {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}</code>```

```

Title: Preload Images for Html pages

Body:
I am new to web design,

Current I am having an issue when loading few images, the background image is flickering, I assume it takes time to load from the server.

How can you preload backgound image for html?

I found few ways from others from seraching like:

<link rel="stylesheet" href="url.com/image/1251302.jpg" as="image">

I am not sure how to use this way, if I will use a image later for an html element, how to apply this reloaded image?

If this is not the best way, how to pre-load image correctly?

any help would be greatly appreciated!

Some example of my codes.

.bgimg-1 {
  background-position: center;
  background-size: cover;
  background-image: url("image/1251302.jpg");
  min-height: 100%;

}

later:

Body:
I am not sure that this is what you are asking about … But if you mean that you need to implement a pre-loader for your website to make suer that everything loaded before showing the user any content to prevent the flickering.
Here is how you can do it
HTML, CSS, and JS:

  const preloader = document.querySelector("#preloader");
  if (preloader) {
    window.addEventListener("load", () => {
      preloader.remove();
    });
  }

#preloader {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 9999;
  overflow: hidden;
  background: #fff;
}

#preloader:before {
  content: "";
  position: fixed;
  top: calc(50% - 30px);
  left: calc(50% - 30px);
  border: 6px solid #229727;
  border-top-color: #fff;
  border-bottom-color: #fff;
  border-radius: 50%;
  width: 60px;
  height: 60px;
  -webkit-animation: animate-preloader 1s linear infinite;
  animation: animate-preloader 1s linear infinite;
}

@-webkit-keyframes animate-preloader {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

@keyframes animate-preloader {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

<div id="preloader"></div>


问:
How do I create a Mean Annual Rainfall table for various durations from a NetCDF4 using Python?
I have downloaded a NetCDF4 file of total hourly precipitation across Sierra Leone from 1974 to Present, and have started to create a code to analyze it.

I'm trying to form a table in Python that will display my average annual rainfall for different rainfall durations, rather like this one below:

I'm wondering if anyone has done anything similar to this before and could possibly help me out as I'm very new to programming?

Here is the script I've written so far that records the hourly data for each year. From here I need to find a way to store this information onto a table, then to change the duration to say, 2 hours, and repeat until I have a complete table:

```<code>    import glob
    import numpy as np
from netCDF4 import Dataset
import pandas as pd
import xarray as xr

all_years = []

for file in glob.glob('*.nc'):
    data = Dataset(file, 'r')
    time = data.variables['time']
    year = time.units[11:16]
    all_years.append(year)

year_start = '01-01-1979'
year_end = '31-12-2021'
date_range = pd.date_range(start = str(year_start),
                           end = str(year_end),
                           freq = 'H')

df = pd.DataFrame(0.0,columns = ['tp'], index = date_range)

lat_freetown = 8.4657
lon_freetown = 13.2317

all_years.sort()

for yr in range(1979,2021):
    data = Dataset('era5_year' + str(yr)+ '.nc', 'r')

    lat = data.variables['latitude'][:]
    lon = data.variables['longitude'][:]

    sq_diff_lat = (lat - lat_freetown)**2
    sq_diff_lon = (lon - lon_freetown)**2

    min_index_lat = sq_diff_lat.argmin()
    min_index_lon = sq_diff_lon.argmin()

    tp = data.variables['tp']

    start = str(yr) + '-01-01'
    end = str(yr) + '-12-31'
    d_range = pd.date_range(start = start,
                            end = end,
                            freq = 'H')

    for t_index in np.arange(0, len(d_range)):
        print('Recording the value for: ' + str(d_range[t_index])+str(tp[t_index, min_index_lat, min_index_lon]))
        df.loc[d_range[t_index]]['tp'] = tp[t_index, min_index_lat, min_index_lon]
</code>```

答:
I gave this a try, I hope it helps.

I downloaded two years of coarse US precip data here:
https://downloads.psl.noaa.gov/Datasets/cpc_us_hour_precip/precip.hour.2000.nc
https://downloads.psl.noaa.gov/Datasets/cpc_us_hour_precip/precip.hour.2001.nc

```<code>import xarray as xr
import pandas as pd

#   Read two datasets and append them so there are multiple years of hourly data
precip_full1 = xr.open_dataset('precip.hour.2000.nc') * 25.4
precip_full2 = xr.open_dataset('precip.hour.2001.nc') * 25.4
precip_full = xr.concat([precip_full1,precip_full2],dim='time')

#   Select only the Western half of the US
precip = precip_full.where(precip_full.lon<257,drop=True)

#   Initialize output
output = []

#   Select number of hours to sum
#   This assumes that the data is hourly
intervals = [1,2,6,12,24]

#   Loop through each desired interval
for interval in intervals:
    #   Take rolling sum
    #   This means the value at any time is the sum of the preceeding times
    #   So when interval is 6, it's the sum of the previous six values
    roll = precip.rolling(time=interval,center=False).sum()

    #   Take the annual mean and average over all space
    annual = roll.groupby('time.year').mean('time').mean(['lat','lon'])

    #   Convert output to a pandas dataframe
    #   and rename the column to correspond to the interval length
    tab = annual.to_dataframe().rename(columns={'precip':str(interval)})

    #   Keep track of the output by appending it to the output list
    output.append(tab)

#   Combine the dataframes into one, by rows
output = pd.concat(output,1)
</code>```

The output looks like this:

```<code>             1         2         6        12        24
year
2000  0.014972  0.029947  0.089856  0.179747  0.359576
2001  0.015610  0.031219  0.093653  0.187290  0.374229
</code>```

Again, this assumes that the data is already hourly. It also takes the average of any (for example) 6 hour period, so it's not just 00:00-06:00, 06:00-12:00, etc., it's 00:00-06:00, 001:00-07:00, etc., and then the annual mean. If you wanted the former you could use xarray's resample function after taking the rolling sum.

Body:
I have downloaded a NetCDF4 file of total hourly precipitation across Sierra Leone from 1974 to Present, and have started to create a code to analyze it.

I'm trying to form a table in Python that will display my average annual rainfall for different rainfall durations, rather like this one below:

I'm wondering if anyone has done anything similar to this before and could possibly help me out as I'm very new to programming?

Here is the script I've written so far that records the hourly data for each year. From here I need to find a way to store this information onto a table, then to change the duration to say, 2 hours, and repeat until I have a complete table:

    import glob
    import numpy as np
from netCDF4 import Dataset
import pandas as pd
import xarray as xr

all_years = []

for file in glob.glob('*.nc'):
    data = Dataset(file, 'r')
    time = data.variables['time']
    year = time.units[11:16]
    all_years.append(year)

year_start = '01-01-1979'
year_end = '31-12-2021'
date_range = pd.date_range(start = str(year_start),
                           end = str(year_end),
                           freq = 'H')

df = pd.DataFrame(0.0,columns = ['tp'], index = date_range)

lat_freetown = 8.4657
lon_freetown = 13.2317

all_years.sort()

for yr in range(1979,2021):
    data = Dataset('era5_year' + str(yr)+ '.nc', 'r')

    lat = data.variables['latitude'][:]
    lon = data.variables['longitude'][:]

    sq_diff_lat = (lat - lat_freetown)**2
    sq_diff_lon = (lon - lon_freetown)**2

    min_index_lat = sq_diff_lat.argmin()
    min_index_lon = sq_diff_lon.argmin()

    tp = data.variables['tp']

    start = str(yr) + '-01-01'
    end = str(yr) + '-12-31'
    d_range = pd.date_range(start = start,
                            end = end,
                            freq = 'H')

    for t_index in np.arange(0, len(d_range)):
        print('Recording the value for: ' + str(d_range[t_index])+str(tp[t_index, min_index_lat, min_index_lon]))
        df.loc[d_range[t_index]]['tp'] = tp[t_index, min_index_lat, min_index_lon]

Body:
I gave this a try, I hope it helps.

I downloaded two years of coarse US precip data here:
https://downloads.psl.noaa.gov/Datasets/cpc_us_hour_precip/precip.hour.2000.nc
https://downloads.psl.noaa.gov/Datasets/cpc_us_hour_precip/precip.hour.2001.nc

import xarray as xr
import pandas as pd

#   Read two datasets and append them so there are multiple years of hourly data
precip_full1 = xr.open_dataset('precip.hour.2000.nc') * 25.4
precip_full2 = xr.open_dataset('precip.hour.2001.nc') * 25.4
precip_full = xr.concat([precip_full1,precip_full2],dim='time')

#   Select only the Western half of the US
precip = precip_full.where(precip_full.lon<257,drop=True)

#   Initialize output
output = []

#   Select number of hours to sum
#   This assumes that the data is hourly
intervals = [1,2,6,12,24]

#   Loop through each desired interval
for interval in intervals:
    #   Take rolling sum
    #   This means the value at any time is the sum of the preceeding times
    #   So when interval is 6, it's the sum of the previous six values
    roll = precip.rolling(time=interval,center=False).sum()

    #   Take the annual mean and average over all space
    annual = roll.groupby('time.year').mean('time').mean(['lat','lon'])

    #   Convert output to a pandas dataframe
    #   and rename the column to correspond to the interval length
    tab = annual.to_dataframe().rename(columns={'precip':str(interval)})

    #   Keep track of the output by appending it to the output list
    output.append(tab)

#   Combine the dataframes into one, by rows
output = pd.concat(output,1)

The output looks like this:

             1         2         6        12        24
year
2000  0.014972  0.029947  0.089856  0.179747  0.359576
2001  0.015610  0.031219  0.093653  0.187290  0.374229

Again, this assumes that the data is already hourly. It also takes the average of any (for example) 6 hour period, so it's not just 00:00-06:00, 06:00-12:00, etc., it's 00:00-06:00, 001:00-07:00, etc., and then the annual mean. If you wanted the former you could use xarray's resample function after taking the rolling sum.


问:
How to print words from a word list that have 5 letters or less Python 2.7?
I'm sorta new to python, which you can probably see by my crappy coding below. If you were to play this game, you would probably find that it's really hard, so to make it easier, I want to make it so it only gives the user 5 letter words or less from the list. My current code for that is:

```<code>word_site = "http://www.instructables.com/files/orig/FLU/YE8L/H82UHPR8/FLUYE8LH82UHPR8.txt"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
randomword=(random.choice(WORDS))
</code>```

Currently the code above gets any random word from that word list, I would like it to only get words that have 5 or less letters in them.

Here is all my code below, if it helps you:

```<code>import random
import urllib2
loop=True
while loop==True:
    name=raw_input("Hello there! What might your name be? ")
    yesorno=raw_input("Hello " + name + ", would you like to play a friendly game of Guess the Word? Answer either 'yes' or 'no': ")
    if yesorno == "yes":
        loop=False
        print "Ok then, here we go!"
        print "\n"
        print "You have 3 guesses"
        word_site = "http://www.instructables.com/files/orig/FLU/YE8L/H82UHPR8/FLUYE8LH82UHPR8.txt"
        response = urllib2.urlopen(word_site)
        txt = response.read()
        WORDS = txt.splitlines()
        randomword=(random.choice(WORDS))
        lengthrandomword=len(randomword)
        print "I'm thinking of a word with " + str(lengthrandomword) + " letters"
        print "\n"
        if lengthrandomword==2:
            print "_ _"
            print "\n"
        elif  lengthrandomword==3:
            print "_ _ _"
            print "\n"
        elif  lengthrandomword==4:
            print "_ _ _ _"
            print "\n"
        elif  lengthrandomword==5:
            print "_ _ _ _ _"
            print "\n"
        elif  lengthrandomword==6:
            print "_ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==7:
            print "_ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==8:
            print "_ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==9:
            print "_ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==10:
            print "_ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==11:
            print "_ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==12:
            print "_ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==13:
            print "_ _ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==14:
            print "_ _ _ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==15:
            print "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        else:
            print "I thought of a word and it's reeeaaaaaly long, you would never guess it, so I'm just gonna tell you that my word was " + randomword
        print "\n"
        userguess=raw_input("Try and guess the word: ")
        input = randomword
        output = ""
        for i in input.split():
            output += i[0]
        firstletter=output
        if randomword.endswith("a"):
            lastletter="a"
        elif randomword.endswith("b"):
            lastletter="b"
        elif randomword.endswith("c"):
            lastletter="c"
        elif randomword.endswith("d"):
            lastletter="d"
        elif randomword.endswith("e"):
            lastletter="e"
        elif randomword.endswith("f"):
            lastletter="f"
        elif randomword.endswith("g"):
            lastletter="g"
        elif randomword.endswith("h"):
            lastletter="h"
        elif randomword.endswith("i"):
            lastletter="i"
        elif randomword.endswith("j"):
            lastletter="j"
        elif randomword.endswith("k"):
            lastletter="k"
        elif randomword.endswith("l"):
            lastletter="l"
        elif randomword.endswith("m"):
            lastletter="m"
        elif randomword.endswith("n"):
            lastletter="n"
        elif randomword.endswith("o"):
            lastletter="o"
        elif randomword.endswith("p"):
            lastletter="p"
        elif randomword.endswith("q"):
            lastletter="q"
        elif randomword.endswith("r"):
            lastletter="r"
        elif randomword.endswith("s"):
            lastletter="s"
        elif randomword.endswith("t"):
            lastletter="t"
        elif randomword.endswith("u"):
            lastletter="u"
        elif randomword.endswith("v"):
            lastletter="v"
        elif randomword.endswith("w"):
            lastletter="w"
        elif randomword.endswith("x"):
            lastletter="x"
        elif randomword.endswith("y"):
            lastletter="y"
        elif randomword.endswith("z"):
            lastletter="z"
        else:
            lastletter="I CODED SOMETHING WRONG!"
        if userguess != randomword:
            print "You guessed wrong..."
            print "\n"
            print "I'll give you a hint: the word STARTS with the letter " + firstletter + " and ENDS with the letter " + lastletter
            userguess=raw_input("I'll give you another chance to guess the word: ")
            if userguess != randomword:
                input = randomword
                output = ""
                for i in input.split():
                    output += i[1]
                secondletter=output
                print "You guessed wrong..."
                print "\n"
                print "I'll give you another hint: the second letter of the word is " + secondletter
                userguess=raw_input("I'll give you one last chance to guess the word: ")
                if userguess != randomword:
                    print "You guessed wrong..."
                    print "\n"
                    print "You're out of chances... the word was: " + randomword
                    print "I'm sorry to say this but..."
                    print "YOU LOST!"
                    print "\n"

                elif userguess == randomword:
                    print "You guessed right!"
                    print "YOU WON!"
                    print "\n"
                else:
                    print "I made a mistake in the code somewhere?!"
        elif userguess == randomword:
            print "You guessed right!"
            print "YOU WON!"
            print "/n"
        else:
            print "I made a mistake in the code somewhere?!"
        mindchange=raw_input("Wanna play again? If you do, just type 'Start'. If you don't then type 'Exit': ")
        if mindchange=="Exit":
            loop=False
        elif mindchange=="Start":
            loop=True
        else:
            print "You didn't type either 'Start' or 'Exit' : remember to include the Capitals!"
            print "\n"
    elif yesorno == "no":
        mindchange=raw_input("Well that's too bad, I was looking forward to beating you... well if you change your mind just type 'Start' but if you still don't want to play just type 'Exit':")
        if mindchange=="Exit":
            loop=False
        elif mindchange=="Start":
            loop=True
        else:
            print "You didn't type either 'no' or 'yes' : remember to not use capitals! "
            print "\n"
</code>```

This is what is returned:

```<code>Hello there! What might your name be? Alex
Hello Alex, would you like to play a friendly game of Guess the Word? Answer either 'yes' or 'no': yes
Ok then, here we go!

You have 3 guesses
I'm thinking of a word with 14 letters

_ _ _ _ _ _ _ _ _ _ _ _ _ _

Try and guess the word: SOMEWORD
You guessed wrong...

I'll give you a hint: the word STARTS with the letter o and ENDS with the letter g
I'll give you another chance to guess the word: SOMEOTHERWORD
You guessed wrong...

I'll give you another hint: the second letter of the word is v
I'll give you one last chance to guess the word: SOMEOTHERWORD
You guessed wrong...

You're out of chances... the word was: overregulating
I'm sorry to say this but...
YOU LOST!

Wanna play again? If you do, just type 'Start'. If you don't then type 'Exit':
</code>```

If you could also point out where I've been inefficient (which is probably everywhere) as well, that would be appreciated.

答:
I would personally use regex, particularly the re.findall() function in Python, which is fantastic. It can parse through the entire dataset almost instantly and return a super handy list.. something like this. Regex may be intimidating starting out but with a little practice, Python makes it easy and fun.

```<code>import re
with open('word_list.txt') as input_file:
    data = input_file.read()

word_list = re.findall(r'\b\w{1,5}\b', data)
sample_list = word_list[0:10]

print('Total 3-5 Letter Words: {}'.format(len(word_list)))
print(sample_list)
</code>```

Results:

Total 3-5 Letter Words: 12937

['aa', 'aah', 'aahed', 'aahs', 'aal', 'aalii', 'aals', 'aas', 'aba',
'abaca']

The regex matches:

\b, which is a word boundary. In this case, it matches the beginning of a word.

\w{1,5} matches one to 5 characters in a given word (a-z, A-Z).

\b is used at the end as another word boundary to end the search.

Now just take that list and do what you want with it!

Body:
I'm sorta new to python, which you can probably see by my crappy coding below. If you were to play this game, you would probably find that it's really hard, so to make it easier, I want to make it so it only gives the user 5 letter words or less from the list. My current code for that is:

word_site = "http://www.instructables.com/files/orig/FLU/YE8L/H82UHPR8/FLUYE8LH82UHPR8.txt"
response = urllib2.urlopen(word_site)
txt = response.read()
WORDS = txt.splitlines()
randomword=(random.choice(WORDS))

Currently the code above gets any random word from that word list, I would like it to only get words that have 5 or less letters in them.

Here is all my code below, if it helps you:

import random
import urllib2
loop=True
while loop==True:
    name=raw_input("Hello there! What might your name be? ")
    yesorno=raw_input("Hello " + name + ", would you like to play a friendly game of Guess the Word? Answer either 'yes' or 'no': ")
    if yesorno == "yes":
        loop=False
        print "Ok then, here we go!"
        print "\n"
        print "You have 3 guesses"
        word_site = "http://www.instructables.com/files/orig/FLU/YE8L/H82UHPR8/FLUYE8LH82UHPR8.txt"
        response = urllib2.urlopen(word_site)
        txt = response.read()
        WORDS = txt.splitlines()
        randomword=(random.choice(WORDS))
        lengthrandomword=len(randomword)
        print "I'm thinking of a word with " + str(lengthrandomword) + " letters"
        print "\n"
        if lengthrandomword==2:
            print "_ _"
            print "\n"
        elif  lengthrandomword==3:
            print "_ _ _"
            print "\n"
        elif  lengthrandomword==4:
            print "_ _ _ _"
            print "\n"
        elif  lengthrandomword==5:
            print "_ _ _ _ _"
            print "\n"
        elif  lengthrandomword==6:
            print "_ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==7:
            print "_ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==8:
            print "_ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==9:
            print "_ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==10:
            print "_ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==11:
            print "_ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==12:
            print "_ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==13:
            print "_ _ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==14:
            print "_ _ _ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        elif  lengthrandomword==15:
            print "_ _ _ _ _ _ _ _ _ _ _ _ _ _ _"
            print "\n"
        else:
            print "I thought of a word and it's reeeaaaaaly long, you would never guess it, so I'm just gonna tell you that my word was " + randomword
        print "\n"
        userguess=raw_input("Try and guess the word: ")
        input = randomword
        output = ""
        for i in input.split():
            output += i[0]
        firstletter=output
        if randomword.endswith("a"):
            lastletter="a"
        elif randomword.endswith("b"):
            lastletter="b"
        elif randomword.endswith("c"):
            lastletter="c"
        elif randomword.endswith("d"):
            lastletter="d"
        elif randomword.endswith("e"):
            lastletter="e"
        elif randomword.endswith("f"):
            lastletter="f"
        elif randomword.endswith("g"):
            lastletter="g"
        elif randomword.endswith("h"):
            lastletter="h"
        elif randomword.endswith("i"):
            lastletter="i"
        elif randomword.endswith("j"):
            lastletter="j"
        elif randomword.endswith("k"):
            lastletter="k"
        elif randomword.endswith("l"):
            lastletter="l"
        elif randomword.endswith("m"):
            lastletter="m"
        elif randomword.endswith("n"):
            lastletter="n"
        elif randomword.endswith("o"):
            lastletter="o"
        elif randomword.endswith("p"):
            lastletter="p"
        elif randomword.endswith("q"):
            lastletter="q"
        elif randomword.endswith("r"):
            lastletter="r"
        elif randomword.endswith("s"):
            lastletter="s"
        elif randomword.endswith("t"):
            lastletter="t"
        elif randomword.endswith("u"):
            lastletter="u"
        elif randomword.endswith("v"):
            lastletter="v"
        elif randomword.endswith("w"):
            lastletter="w"
        elif randomword.endswith("x"):
            lastletter="x"
        elif randomword.endswith("y"):
            lastletter="y"
        elif randomword.endswith("z"):
            lastletter="z"
        else:
            lastletter="I CODED SOMETHING WRONG!"
        if userguess != randomword:
            print "You guessed wrong..."
            print "\n"
            print "I'll give you a hint: the word STARTS with the letter " + firstletter + " and ENDS with the letter " + lastletter
            userguess=raw_input("I'll give you another chance to guess the word: ")
            if userguess != randomword:
                input = randomword
                output = ""
                for i in input.split():
                    output += i[1]
                secondletter=output
                print "You guessed wrong..."
                print "\n"
                print "I'll give you another hint: the second letter of the word is " + secondletter
                userguess=raw_input("I'll give you one last chance to guess the word: ")
                if userguess != randomword:
                    print "You guessed wrong..."
                    print "\n"
                    print "You're out of chances... the word was: " + randomword
                    print "I'm sorry to say this but..."
                    print "YOU LOST!"
                    print "\n"

                elif userguess == randomword:
                    print "You guessed right!"
                    print "YOU WON!"
                    print "\n"
                else:
                    print "I made a mistake in the code somewhere?!"
        elif userguess == randomword:
            print "You guessed right!"
            print "YOU WON!"
            print "/n"
        else:
            print "I made a mistake in the code somewhere?!"
        mindchange=raw_input("Wanna play again? If you do, just type 'Start'. If you don't then type 'Exit': ")
        if mindchange=="Exit":
            loop=False
        elif mindchange=="Start":
            loop=True
        else:
            print "You didn't type either 'Start' or 'Exit' : remember to include the Capitals!"
            print "\n"
    elif yesorno == "no":
        mindchange=raw_input("Well that's too bad, I was looking forward to beating you... well if you change your mind just type 'Start' but if you still don't want to play just type 'Exit':")
        if mindchange=="Exit":
            loop=False
        elif mindchange=="Start":
            loop=True
        else:
            print "You didn't type either 'no' or 'yes' : remember to not use capitals! "
            print "\n"

This is what is returned:

Hello there! What might your name be? Alex
Hello Alex, would you like to play a friendly game of Guess the Word? Answer either 'yes' or 'no': yes
Ok then, here we go!

You have 3 guesses
I'm thinking of a word with 14 letters

_ _ _ _ _ _ _ _ _ _ _ _ _ _

Try and guess the word: SOMEWORD
You guessed wrong...

I'll give you a hint: the word STARTS with the letter o and ENDS with the letter g
I'll give you another chance to guess the word: SOMEOTHERWORD
You guessed wrong...

I'll give you another hint: the second letter of the word is v
I'll give you one last chance to guess the word: SOMEOTHERWORD
You guessed wrong...

You're out of chances... the word was: overregulating
I'm sorry to say this but...
YOU LOST!

Wanna play again? If you do, just type 'Start'. If you don't then type 'Exit':

If you could also point out where I've been inefficient (which is probably everywhere) as well, that would be appreciated.

Body:
I would personally use regex, particularly the re.findall() function in Python, which is fantastic. It can parse through the entire dataset almost instantly and return a super handy list.. something like this. Regex may be intimidating starting out but with a little practice, Python makes it easy and fun.

import re
with open('word_list.txt') as input_file:
    data = input_file.read()

word_list = re.findall(r'\b\w{1,5}\b', data)
sample_list = word_list[0:10]

print('Total 3-5 Letter Words: {}'.format(len(word_list)))
print(sample_list)

Results:

Total 3-5 Letter Words: 12937

['aa', 'aah', 'aahed', 'aahs', 'aal', 'aalii', 'aals', 'aas', 'aba',
'abaca']

The regex matches:

\b, which is a word boundary. In this case, it matches the beginning of a word.

\w{1,5} matches one to 5 characters in a given word (a-z, A-Z).

\b is used at the end as another word boundary to end the search.

Now just take that list and do what you want with it!


问:
coin_change function seem to be working only for certain values
I wrote a function to calculate the different coins I will received based on the amount enter. However, the function seem to be working for certain amount only.

Example when I enter $5.1, I should be have 5($1) and 1(1cent). But my function is returning me with 5($1), 1(5cent) and 4(1cent) instead.

I cant seem to figure out what is wrong with my function.

```<code>function coin_change($amount) {
    $coinDenominations = array(
        '1$'  => 1.00,
        '50c' => 0.50,
        '20c'    => 0.20,
        '10c'   => 0.10,
        '5c'    => 0.05,
        '1c'    => 0.01
    );
    $change = [];
    foreach($coinDenominations as $denomiation => $value){
        $count = floor($amount / $value);
        $change[$denomiation] = $count;

        if($amount > 0){
            $amount -= ($count * $value);
        }else{
            return $change;
        }
    }
    return $change;
}

echo "Enter amount: $amount <br/>";
var_dump(coin_change($amount));
</code>```

答:
Your logic is fine. Your problem comes from limited precision of floating point numbers in the floor function. When calculating floor(amount / $value), floor(0.99999999) will return 0.

You can fix that with round. So your function would become:

```<code>function coin_change($amount) {

    $coinDenominations = array(
        '1$'  => 1.00,
        '50c' => 0.50,
        '20c'    => 0.20,
        '10c'   => 0.10,
        '5c'    => 0.05,
        '1c'    => 0.01
    );

    $change = [];

    foreach ($coinDenominations as $denomination => $value) {

        // Round will make sure that 0.99999 = 1
        // Then floor(1) = 1
        $count = floor(round($amount / $value, 2));

        $change[$denomination] = $count;

        $amount -= $count * $value;
        $amount = round($amount, 2); // Fixes imprecision for operation above

        if ($amount == 0.00) {
            return $change;
        }
    }
    return $change;
}

$amount = 5.1;
var_dump(coin_change($amount));
</code>```

Body:
I wrote a function to calculate the different coins I will received based on the amount enter. However, the function seem to be working for certain amount only.

Example when I enter $5.1, I should be have 5($1) and 1(1cent). But my function is returning me with 5($1), 1(5cent) and 4(1cent) instead.

I cant seem to figure out what is wrong with my function.

function coin_change($amount) {
    $coinDenominations = array(
        '1$'  => 1.00,
        '50c' => 0.50,
        '20c'    => 0.20,
        '10c'   => 0.10,
        '5c'    => 0.05,
        '1c'    => 0.01
    );
    $change = [];
    foreach($coinDenominations as $denomiation => $value){
        $count = floor($amount / $value);
        $change[$denomiation] = $count;

        if($amount > 0){
            $amount -= ($count * $value);
        }else{
            return $change;
        }
    }
    return $change;
}

echo "Enter amount: $amount
";
var_dump(coin_change($amount));

Body:
Your logic is fine. Your problem comes from limited precision of floating point numbers in the floor function. When calculating floor(amount / $value), floor(0.99999999) will return 0.

You can fix that with round. So your function would become:

function coin_change($amount) {

    $coinDenominations = array(
        '1$'  => 1.00,
        '50c' => 0.50,
        '20c'    => 0.20,
        '10c'   => 0.10,
        '5c'    => 0.05,
        '1c'    => 0.01
    );

    $change = [];

    foreach ($coinDenominations as $denomination => $value) {

        // Round will make sure that 0.99999 = 1
        // Then floor(1) = 1
        $count = floor(round($amount / $value, 2));

        $change[$denomination] = $count;

        $amount -= $count * $value;
        $amount = round($amount, 2); // Fixes imprecision for operation above

        if ($amount == 0.00) {
            return $change;
        }
    }
    return $change;
}

$amount = 5.1;
var_dump(coin_change($amount));


问:
Attachment in Laravel many-to-many relation
I'm trying to do my first attachment/ detachment. I'm using two tables, user, event, and its pivot, event_user. For this one, I needed to do a button to subscribe the user to an event, so my teacher told me to use an  and route it to the method subscribe. At this moment, the error that comes up is.

Route [subscribe] not defined.

Blade

```<code><a href="{{ route('subscribe', $event->event_id) }}"
    class="btn btn-primary btn-lg">Subscribe</a>
</code>```

Route

```<code>Route::get('/subscribe', [SubscribeController::class, 'index']);
</code>```

SubscribeController

```<code>public function index($id)
{
    $user = Auth::user();
    $user->events->attach($id);

    return view('index');
}
</code>```

I tried putting URL instead of the route in the , and it goes to /subscribe, but comes to an error that says -> Too few arguments to function 0 passed and exactly 1 expected.

I did a dd() in the component to see if the event id was the correct one, and it was. Also, apart from these errors, how can I route a method without changing the route? Can I do it using the indexController (because it's in the index where these events are located)?

答:
Firstly in your blade view file you are trying to generate url using route helper like this

```<code><a href="{{ route('subscribe', $event->event_id) }}"
class="btn btn-primary btn-lg">Subscribe</a>`
</code>```

The way you call the route helper we can supposed this

You have already define a route in your web.php file which is named subscribe

and that route have paramater

But in your web.php file you have this route

```<code>Route::get('/subscribe', [SubscribeController::class, 'index']);
</code>```

This route doesn't have any name.

And it doesn't expect any parameter

To fix that you should only change the way you have define you route in the web.php file like this

```<code>Route::get('/subscribe/{id}', [SubscribeController::class, 'index'])
    ->name('subscribe');
</code>```

With this route we define:

id as a required parameter

And the route is named subscribe

Body:
I'm trying to do my first attachment/ detachment. I'm using two tables, user, event, and its pivot, event_user. For this one, I needed to do a button to subscribe the user to an event, so my teacher told me to use an  and route it to the method subscribe. At this moment, the error that comes up is.

Route [subscribe] not defined.

Blade

event_id) }}"
    class="btn btn-primary btn-lg">Subscribe

Route

Route::get('/subscribe', [SubscribeController::class, 'index']);

SubscribeController

public function index($id)
{
    $user = Auth::user();
    $user->events->attach($id);

    return view('index');
}

I tried putting URL instead of the route in the , and it goes to /subscribe, but comes to an error that says -> Too few arguments to function 0 passed and exactly 1 expected.

I did a dd() in the component to see if the event id was the correct one, and it was. Also, apart from these errors, how can I route a method without changing the route? Can I do it using the indexController (because it's in the index where these events are located)?

Body:
Firstly in your blade view file you are trying to generate url using route helper like this

<a href="{{ route('subscribe', $event->event_id) }}"
class="btn btn-primary btn-lg">Subscribe</a>`

The way you call the route helper we can supposed this

You have already define a route in your web.php file which is named subscribe

and that route have paramater

But in your web.php file you have this route

Route::get('/subscribe', [SubscribeController::class, 'index']);

This route doesn't have any name.

And it doesn't expect any parameter

To fix that you should only change the way you have define you route in the web.php file like this

Route::get('/subscribe/{id}', [SubscribeController::class, 'index'])
    ->name('subscribe');

With this route we define:

id as a required parameter

And the route is named subscribe


问:
Error in creating a function with a trait-bounded parameter wrapped in Option enum
I want to create a method for my MyError enum (whose variants are the different error types in my program) that returns a String value that describes the given MyError variant. For example:

pub enum MyError {
    Error1,
    Error2,
}

impl MyError {
    pub fn to_str(&self) -> String {
        match self {
            Error1 => format!("Error1: bla bla bla"),
            Error2 => format!("Error2: na na na"),
        }
    }
}
```
<p>This is all well and good, but the problem is, I have a new error variant (say <code>Error3</code>) that must pass a parameter to its <code>format!()</code> macro in the method, like this:</p>
<pre class="lang-rust prettyprint-override"><code>Error3 => format!("la la la {:?}", arg),
</code>```

This parameter can be of any type as long as it can derive the Debug trait. So my solution was

pub enum MyError {
    Error1,
    Error2,
    Error3
}

impl MyError {
    pub fn to_str(&self, arg: Option<&impl fmt::Debug>) -> String {
        match self {
            Error1 => format!("bla bla bla"),
            Error2 => format!("na na na"),
            Error3 => format!("la la la {:?}", arg),
        }
    }
}
```
<p>Where I wrap the trait-bounded parameter in <code>Option</code> since some variants of <code>MyError</code> do not need it (e.g. <code>Error1</code>). This works for the <code>Error3</code> variant, I can do the following without any compilation error:</p>
<pre class="lang-rust prettyprint-override"><code>eprintln!("{}", MyError::Error3.to_str(Some(vec![1, 2, 3])));
</code>```

It prints the associated error message of Error3. But when I try to use the method to the other variants which require no additional parameter, e.g. calling

eprintln!("{}", MyError::Error1.to_str(None));
```
<p>It returns the following compilation error:</p>
<pre class="lang-none prettyprint-override"><code>type annotations needed

cannot infer type for type parameter `impl fmt::Debug` declared on the associated function `to_str`rustc(E0282)
</code>```

Why can't the compiler infer the type of None here?

答:
You need to specify the concrete type, even for None. Like this:

```<code>let n: Option<&Vec<usize>> = None;
eprintln!("{}", MyError::Error1.to_str(n));
</code>```

Even though the function (method) only specifies a trait bound, not a concrete type, the compiler needs to know exactly the type of each value a caller passes to that function.

And of course, you can call the function with values of different type (but each of those needs to be clear and must adhere to the trait bound). An example:

```<code>pub fn main() {
    let v1 = vec![1, 2, 3];
    let v2 = "A str here";
    eprintln!("{}", MyError::Error3.to_str(Some(&v1)));
    eprintln!("{}", MyError::Error3.to_str(Some(&v2)));
    let n: Option<&Vec<usize>> = None;
    eprintln!("{}", MyError::Error1.to_str(n));
    let n2: Option<&Vec<String>> = None;
    eprintln!("{}", MyError::Error1.to_str(n2));
}
</code>```

You can learn more here.

Body:
I want to create a method for my MyError enum (whose variants are the different error types in my program) that returns a String value that describes the given MyError variant. For example:

pub enum MyError {
    Error1,
    Error2,
}

impl MyError {
    pub fn to_str(&self) -> String {
        match self {
            Error1 => format!("Error1: bla bla bla"),
            Error2 => format!("Error2: na na na"),
        }
    }
}

This is all well and good, but the problem is, I have a new error variant (say Error3) that must pass a parameter to its format!() macro in the method, like this:

Error3 => format!("la la la {:?}", arg),

This parameter can be of any type as long as it can derive the Debug trait. So my solution was

pub enum MyError {
    Error1,
    Error2,
    Error3
}

impl MyError {
    pub fn to_str(&self, arg: Option<&impl fmt::Debug>) -> String {
        match self {
            Error1 => format!("bla bla bla"),
            Error2 => format!("na na na"),
            Error3 => format!("la la la {:?}", arg),
        }
    }
}

Where I wrap the trait-bounded parameter in Option since some variants of MyError do not need it (e.g. Error1). This works for the Error3 variant, I can do the following without any compilation error:

eprintln!("{}", MyError::Error3.to_str(Some(vec![1, 2, 3])));

It prints the associated error message of Error3. But when I try to use the method to the other variants which require no additional parameter, e.g. calling

eprintln!("{}", MyError::Error1.to_str(None));

It returns the following compilation error:

type annotations needed

cannot infer type for type parameter `impl fmt::Debug` declared on the associated function `to_str`rustc(E0282)

Why can't the compiler infer the type of None here?

Body:
You need to specify the concrete type, even for None. Like this:

let n: Option<&Vec<usize>> = None;
eprintln!("{}", MyError::Error1.to_str(n));

Even though the function (method) only specifies a trait bound, not a concrete type, the compiler needs to know exactly the type of each value a caller passes to that function.

And of course, you can call the function with values of different type (but each of those needs to be clear and must adhere to the trait bound). An example:

pub fn main() {
    let v1 = vec![1, 2, 3];
    let v2 = "A str here";
    eprintln!("{}", MyError::Error3.to_str(Some(&v1)));
    eprintln!("{}", MyError::Error3.to_str(Some(&v2)));
    let n: Option<&Vec<usize>> = None;
    eprintln!("{}", MyError::Error1.to_str(n));
    let n2: Option<&Vec<String>> = None;
    eprintln!("{}", MyError::Error1.to_str(n2));
}

You can learn more here.


问:
Are global variables slower in c due to virtual memory?
According to the gfg article on memory layout in c program... Global variables are stored in the data section of a c program, and the data section is a portion of the virtual memory space. So does this mean using global variables is slow since they are in the virtual memory.</p>

答:
Every address in a C program (or any other program) is in a virtual address space that is created by the OS.

None of the addresses in the program are real. (In a modern OS)

Why does it use Virtual address space? SECURITY! There is also something called 'ASLR' (Address Space Layout Randomization) which goes even further, and makes the addresses random, hence avoids attacks that target known memory locations.

Note: No matter what you change in your program, it will be given a virtual address space. No compiler option will help. (But you can disable 'ASLR' by changing some settings in the OS, but it is a security risk to do so).


问:
How to resolve weird and incomplete Uri & Path received while directly sharing image from android gallery to my flutter app
I have written a functionality in Kotlin for the flutter app to share media files directly from the android phone gallery to the app.

Working fine for many devices I have tested like Realme 3 Pro, Oneplus 6t, Samsung m40.

But, for Asus Zenfone Max Pro M2 on sharing any media file received weird and incomplete URI & path

Logs from Kotlin Code

D/URI
=====(26032) : content://com.android.providers.downloads.documents/document/624

D/Path =====(26032): /document/624

Kotlin Code

```<code>override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    this.binding = binding
    binding.addOnNewIntentListener(this)
    handleIntent(binding.activity.intent, true)
}
----------------------------------------------------------------------
private fun handleIntent(intent: Intent, initial: Boolean) {
    when {
        (intent.type?.startsWith("text") != true)
                && (intent.action == Intent.ACTION_SEND
                || intent.action == Intent.ACTION_SEND_MULTIPLE) -> { // Sharing images or videos

            val value = getMediaUris(intent)
            if (initial) initialMedia = value
            latestMedia = value
            eventSinkMedia?.success(latestMedia?.toString())
        }
...
----------------------------------------------------------------------
private fun getMediaUris(intent: Intent?): JSONArray? {
    if (intent == null) return null

    return when (intent.action) {
        Intent.ACTION_SEND -> {
            val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
            Log.d("URI =====",uri)
            val path = uri?.let{ FileDirectory.getPathFromUri(applicationContext, it) } ?: uri?.path
            Log.d("Path =====",path)
            if (path != null) {
...
</code>```

Device Info

```<code>Device Name: Asus Zenfone Max Pro M2
Android Version: 9
External SD card: present
</code>```

How to resolve this URI and get a proper path with filename and extension?

答:
You can use uri_to_file plugin to fetch the path from content://uri. To use, simply parse the uri and use toFile(uri)

```<code>import 'package:uri_to_file/uri_to_file.dart';

try {
  String uriPath = 'content://com.android.providers.downloads.documents/document/624';
  Uri uri = Uri.parse(uriPath);
  File file = await toFile(uri);
} catch (e) {
  debugPrint(e);
}
</code>```

Body:
I have written a functionality in Kotlin for the flutter app to share media files directly from the android phone gallery to the app.

Working fine for many devices I have tested like Realme 3 Pro, Oneplus 6t, Samsung m40.

But, for Asus Zenfone Max Pro M2 on sharing any media file received weird and incomplete URI & path

Logs from Kotlin Code

D/URI
=====(26032) : content://com.android.providers.downloads.documents/document/624

D/Path =====(26032): /document/624

Kotlin Code

override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    this.binding = binding
    binding.addOnNewIntentListener(this)
    handleIntent(binding.activity.intent, true)
}
----------------------------------------------------------------------
private fun handleIntent(intent: Intent, initial: Boolean) {
    when {
        (intent.type?.startsWith("text") != true)
                && (intent.action == Intent.ACTION_SEND
                || intent.action == Intent.ACTION_SEND_MULTIPLE) -> { // Sharing images or videos

            val value = getMediaUris(intent)
            if (initial) initialMedia = value
            latestMedia = value
            eventSinkMedia?.success(latestMedia?.toString())
        }
...
----------------------------------------------------------------------
private fun getMediaUris(intent: Intent?): JSONArray? {
    if (intent == null) return null

    return when (intent.action) {
        Intent.ACTION_SEND -> {
            val uri = intent.getParcelableExtra<Uri>(Intent.EXTRA_STREAM)
            Log.d("URI =====",uri)
            val path = uri?.let{ FileDirectory.getPathFromUri(applicationContext, it) } ?: uri?.path
            Log.d("Path =====",path)
            if (path != null) {
...

Device Info

Device Name: Asus Zenfone Max Pro M2
Android Version: 9
External SD card: present

How to resolve this URI and get a proper path with filename and extension?

Body:
You can use uri_to_file plugin to fetch the path from content://uri. To use, simply parse the uri and use toFile(uri)

import 'package:uri_to_file/uri_to_file.dart';

try {
  String uriPath = 'content://com.android.providers.downloads.documents/document/624';
  Uri uri = Uri.parse(uriPath);
  File file = await toFile(uri);
} catch (e) {
  debugPrint(e);
}


问:
Python Dataframe : Groupby and Transform
I have a Python pandas dataframe (df1) with 3 columns: UserId, TimeStamp, Context. This dataframe represents logs of user actions within the app. There are multiple lines for each user.

I have to merge this dataframe with an other dataframe (df2) on UserId. That dataframe (df2) contains info about users (i.e. their birthdate, account creation date, etc.). The goal is to perform machine learning. I will have to create features using time between actions in df1 and df2. But before doing that, I want everything into 1 dataframe to make it easier (hopefully?)

My initial idea is to group df1 on UserId and transform TimeStamp and Context into an array that would have objects : { timestamp, context } and then merge this new df into df2.

Is this a good idea? If not, how would you go about it?

I was originally just going to ask help on grouping and aggregating my data in df1 into a new dataframe. Here is what I have so far, the result and the desired result.

Thank you

```<code>     Raw data
     df1 = df[['UserId', 'Timestamp', 'Context']]
    ----------------------------------------------------
        UserId    TimeStamp             Context
    1   618884    2015-12-18 11:29:33   410-513-FD-10-01
    2   618884    2015-12-18 11:29:38   540-823-RE-12-01
    3   620141    2015-12-18 12:29:02   101-901-RE-10-03
    4   620141    2015-12-18 12:29:34   Other
    ----------------------------------------------------
    Current code
    gp = df1.groupby(['UserId']).agg({'UserId': 'first',
                                     'TimeStamp': ', '.join,})
    gp.head()
    ----------------------------------------------------
    Current output
    UserId  UserId  Timestamp
    585953  585953  2016-04-01 11:08:06, 2016-04-01 11:08:10
    586182  586182  2016-05-01 15:53:01
    586400  586400  2015-12-27 12:31:11, 2015-12-27 12:31:44, 2015-12-29 14:35:38, 2015-12-29 14:35:45, 2016-01-10 01:42:28
    586573  586573  2016-01-12 14:40:41, 2016-04-19 19:56:41, 2016-04-19 19:56:55
    586716  586716  2016-01-13 13:50:05
    ----------------------------------------------------
    Desired result:
    UserId                       Actions
    1                            [ { 2016-04-01 19:40:32, 410-513-FD-10-01 }
                                   { 2017-05-03 20:34:21, 320-391-RE-12-03 } ]
    2                            [ { 2019-03-12 12:08:12, Other } ]
</code>```

答:
You can't use groupby and agg or transform because the transformation applied for each column. You can't access to Context column while you are processing TimeStamp column. A classical way is to use groupby_apply:

```<code>out = df.groupby('UserId').apply(lambda x: list(zip(x['TimeStamp'], x['Context']))) \
        .rename('Actions').reset_index()
print(out)

# Output
   UserId                                            Actions
0  618884  [(2015-12-18 11:29:33, 410-513-FD-10-01), (201...
1  620141  [(2015-12-18 12:29:02, 101-901-RE-10-03), (201...
</code>```

Note: if I was you, I don't do this operation, I will merge the 2 dataframes directly. Your column Actions is now too complicated to process for ML.

Body:
I have a Python pandas dataframe (df1) with 3 columns: UserId, TimeStamp, Context. This dataframe represents logs of user actions within the app. There are multiple lines for each user.

I have to merge this dataframe with an other dataframe (df2) on UserId. That dataframe (df2) contains info about users (i.e. their birthdate, account creation date, etc.). The goal is to perform machine learning. I will have to create features using time between actions in df1 and df2. But before doing that, I want everything into 1 dataframe to make it easier (hopefully?)

My initial idea is to group df1 on UserId and transform TimeStamp and Context into an array that would have objects : { timestamp, context } and then merge this new df into df2.

Is this a good idea? If not, how would you go about it?

I was originally just going to ask help on grouping and aggregating my data in df1 into a new dataframe. Here is what I have so far, the result and the desired result.

Thank you

     Raw data
     df1 = df[['UserId', 'Timestamp', 'Context']]
    ----------------------------------------------------
        UserId    TimeStamp             Context
    1   618884    2015-12-18 11:29:33   410-513-FD-10-01
    2   618884    2015-12-18 11:29:38   540-823-RE-12-01
    3   620141    2015-12-18 12:29:02   101-901-RE-10-03
    4   620141    2015-12-18 12:29:34   Other
    ----------------------------------------------------
    Current code
    gp = df1.groupby(['UserId']).agg({'UserId': 'first',
                                     'TimeStamp': ', '.join,})
    gp.head()
    ----------------------------------------------------
    Current output
    UserId  UserId  Timestamp
    585953  585953  2016-04-01 11:08:06, 2016-04-01 11:08:10
    586182  586182  2016-05-01 15:53:01
    586400  586400  2015-12-27 12:31:11, 2015-12-27 12:31:44, 2015-12-29 14:35:38, 2015-12-29 14:35:45, 2016-01-10 01:42:28
    586573  586573  2016-01-12 14:40:41, 2016-04-19 19:56:41, 2016-04-19 19:56:55
    586716  586716  2016-01-13 13:50:05
    ----------------------------------------------------
    Desired result:
    UserId                       Actions
    1                            [ { 2016-04-01 19:40:32, 410-513-FD-10-01 }
                                   { 2017-05-03 20:34:21, 320-391-RE-12-03 } ]
    2                            [ { 2019-03-12 12:08:12, Other } ]

Body:
You can't use groupby and agg or transform because the transformation applied for each column. You can't access to Context column while you are processing TimeStamp column. A classical way is to use groupby_apply:

out = df.groupby('UserId').apply(lambda x: list(zip(x['TimeStamp'], x['Context']))) \
        .rename('Actions').reset_index()
print(out)

# Output
   UserId                                            Actions
0  618884  [(2015-12-18 11:29:33, 410-513-FD-10-01), (201...
1  620141  [(2015-12-18 12:29:02, 101-901-RE-10-03), (201...

Note: if I was you, I don't do this operation, I will merge the 2 dataframes directly. Your column Actions is now too complicated to process for ML.


答:
The reason why it can't infer this is likely due to some annoying edge cases. The main one being determining the size of the enum being passed. The size of an enum type depends on the size of its largest variant. You can see this with assert_neq(std::mem::size_of::<Option<i32>>(), std::mem::size_of::<Option<i8>>());. Without knowing what concrete type it contains, we can't know how much space the function should use when passing the argument.

The easiest way is probably to allow the user to specify a concrete type as a type parameter. Even if you pass in None, you can still specify a concrete type as an alternative (Ex: error.to_str::<()>(None)).

impl MyError {
    pub fn to_str<D: fmt::Debug>(&self, arg: Option<&D>) -> String {
        // etc.
    }
}
```
<p>Otherwise, I would suggest detaching the methods to simply avoid the issue entirely.</p>
<pre class="lang-rust prettyprint-override"><code>impl MyError {
    pub fn to_str(&self) -> String {
        match self {
            Error1 => format!("bla bla bla"),
            Error2 => format!("na na na"),
            Error3 => format!("la la la"),
        }
    }

    pub fn to_str_with_context(&self, arg: &impl fmt::Debug) -> String {
        match self {
            Error1 => format!("bla bla bla"),
            Error2 => format!("na na na"),
            Error3 => format!("la la la {:?}", arg),
        }
    }
}
</code>```

Beyond that, I can only offer general coding tips.
My first instinct is that you may find it more convenient to have a display wrapper.

pub struct MyErrorWithContext<'a, D> {
    err: &'a MyError,
    context: Option<&'a D>,
}

impl<'a, D: fmt::Debug> fmt::Display for MyErrorWithContext<'a, D> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.err {
            Error1 => write!(f, "bla bla bla"),
            Error2 => write!(f, "na na na"),
            Error3 => write!(f, "la la la {:?}", &self.context),
        }
    }
}

impl MyError {
    pub fn display<D: Debug>(&self, context: Option<&D>) -> MyErrorWithContext<D> {
        MyErrorWithContext {
            err: self,
            context,
        }
    }
}

println!("Error: {}", error.display(Some(&foo)));
```

Title: Error in creating a function with a trait-bounded parameter wrapped in Option enum

Body:
The reason why it can't infer this is likely due to some annoying edge cases. The main one being determining the size of the enum being passed. The size of an enum type depends on the size of its largest variant. You can see this with assert_neq(std::mem::size_of::<Option<i32>>(), std::mem::size_of::<Option<i8>>());. Without knowing what concrete type it contains, we can't know how much space the function should use when passing the argument.

The easiest way is probably to allow the user to specify a concrete type as a type parameter. Even if you pass in None, you can still specify a concrete type as an alternative (Ex: error.to_str::<()>(None)).

impl MyError {
    pub fn to_str<D: fmt::Debug>(&self, arg: Option<&D>) -> String {
        // etc.
    }
}

Otherwise, I would suggest detaching the methods to simply avoid the issue entirely.

impl MyError {
    pub fn to_str(&self) -> String {
        match self {
            Error1 => format!("bla bla bla"),
            Error2 => format!("na na na"),
            Error3 => format!("la la la"),
        }
    }

    pub fn to_str_with_context(&self, arg: &impl fmt::Debug) -> String {
        match self {
            Error1 => format!("bla bla bla"),
            Error2 => format!("na na na"),
            Error3 => format!("la la la {:?}", arg),
        }
    }
}

Beyond that, I can only offer general coding tips.
My first instinct is that you may find it more convenient to have a display wrapper.

pub struct MyErrorWithContext<'a, D> {
    err: &'a MyError,
    context: Option<&'a D>,
}

impl<'a, D: fmt::Debug> fmt::Display for MyErrorWithContext<'a, D> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self.err {
            Error1 => write!(f, "bla bla bla"),
            Error2 => write!(f, "na na na"),
            Error3 => write!(f, "la la la {:?}", &self.context),
        }
    }
}

impl MyError {
    pub fn display<D: Debug>(&self, context: Option<&D>) -> MyErrorWithContext<D> {
        MyErrorWithContext {
            err: self,
            context,
        }
    }
}

println!("Error: {}", error.display(Some(&foo)));


问:
i keep having subprocess.CalledProcessError while trying to run pip-compile for pip-tools
This is my code at github

i am trying to test layered requirements for setup.py using pip-tools and i keep having issues with this error about subprocess.CalledProcessError

I am not sure what i did wrong. Below is the asciicast

How do i fix this?

答:
Generally, this kind of error is emitted (as far as I saw it several times) when your setup.cfg or setup.py are broken.

In your case, your extras are not defined properly. You should change your setup.cfg like the following:

```<code>[options]
python_requires = >=3.8
setup_requires = setuptools_scm
packages = find:
zip_safe = false
install_requires =
    # direct dependencies
    # pep517 ~= 0.12
    pip-tools ~= 6.5
    pip ~= 21.3
    # indirect dependencies
    # setuptools ~= 60.8  # typically needed when pip-tools invokes setup.py
    # wheel ~= 0.37 # pip plugin needed by pip-tools

[options.extras_require]
    local = pytest
</code>```

Body:
Generally, this kind of error is emitted (as far as I saw it several times) when your setup.cfg or setup.py are broken.

In your case, your extras are not defined properly. You should change your setup.cfg like the following:

[options]
python_requires = >=3.8
setup_requires = setuptools_scm
packages = find:
zip_safe = false
install_requires =
    # direct dependencies
    # pep517 ~= 0.12
    pip-tools ~= 6.5
    pip ~= 21.3
    # indirect dependencies
    # setuptools ~= 60.8  # typically needed when pip-tools invokes setup.py
    # wheel ~= 0.37 # pip plugin needed by pip-tools

[options.extras_require]
    local = pytest


问:
Provisioning profile "iOS Team Provisioning Profile: doesn't include the currently selected device" Flutter - MacOS
I'm able to build the macOS app from Xcode and run successfully, but when I'm trying to run it from Android Studio it's giving me the following error:

Provisioning profile "mac Team Provisioning Profile:  doesn't include the currently selected device"

If I go to my apple developer account I can see my device UUID there as well.

答: You can try running the project via xcode first then running it via flutter SDK. This solved the mentioned issue for me.</p>


问:
How can I separate 3 different information in a column?
For example, in the column I have, there is a line written 'Ser25Phe'. And I want to split the column HGVS.Consequence e.g. as 'Ser 25 Phe'...

```<code>HGVS.Consequence
           Met1?
           Met1?
           Met1?
         Ala2Glu
         Ala2Ala
         Asn3Asp
         Asn3Asn
         Gly4Trp
         Gly4Arg
         Ala6Glu
           AsAsp
         Arg9Arg
        Lys10Arg
        Lys10Lys
        LeullLeu
        Phe12Ser
        Phe12Cys
        lle13Leu
        lle13Val
        lle13Phe
        Thr15Pro
</code>```

Body:
For example, in the column I have, there is a line written 'Ser25Phe'. And I want to split the column HGVS.Consequence e.g. as 'Ser 25 Phe'...

HGVS.Consequence
           Met1?
           Met1?
           Met1?
         Ala2Glu
         Ala2Ala
         Asn3Asp
         Asn3Asn
         Gly4Trp
         Gly4Arg
         Ala6Glu
           AsAsp
         Arg9Arg
        Lys10Arg
        Lys10Lys
        LeullLeu
        Phe12Ser
        Phe12Cys
        lle13Leu
        lle13Val
        lle13Phe
        Thr15Pro

Body:
Using gsub, assuming that e.g. "AsAsp" should also be split into "As Asp".

trimws(gsub('([A-Z]?[a-z]+)(\\d+)?([A-Z?]*)', '\\1 \\2 \\3', x)) |>
  gsub(pat='  ', rep=' ')  ## optional, to remove inner double whitespace
# [1] "Met 1 ?"    "Met 1 ?"    "Met 1 ?"    "Ala 2 Glu"
# [5] "Ala 2 Ala"  "Asn 3 Asp"  "Asn 3 Asn"  "Gly 4 Trp"
# [9] "Gly 4 Arg"  "Ala 6 Glu"  "As Asp"     "Arg 9 Arg"
# [13] "Lys 10 Arg" "Lys 10 Lys" "Leull Leu"  "Phe 12 Ser"
# [17] "Phe 12 Cys" "lle 13 Leu" "lle 13 Val" "lle 13 Phe"
# [21] "Thr 15 Pro"

See demo.

Edit

If your column is in a data frame like this

df <- data.frame(x1=rnorm(21), x2=runif(21), x3=x)

just wrap it in a transform:

df |>
  transform(x3=trimws(gsub('([A-Z]?[a-z]+)(\\d+)?([A-Z?]*)', '\\1 \\2 \\3', x)) |>
  gsub(pat='  ', rep=' '))

Or, probably better,

res <- trimws(gsub('([A-Z]?[a-z]+)(\\d+)?([A-Z?]*)', '\\1 \\2 \\3', x)) |>
  strsplit(' ') |>
  do.call(what=rbind) |>
  {\(.) replace(., . %in% c('', '?'), NA)}() |>
  data.frame(df[1:2]) |>
  type.convert(as.is=TRUE)
res
#       X1 X2   X3          x1         x2
# 1    Met  1 <NA>  1.33312448 0.83441710
# 2    Met  1 <NA> -0.55792615 0.48805921
# 3    Met  1 <NA>  1.38184166 0.73862824
# 4    Ala  2  Glu -0.87990439 0.42793122
# 5    Ala  2  Ala  0.59143575 0.23370509
# 6    Asn  3  Asp -0.15065801 0.92168932
# 7    Asn  3  Asn -1.59350802 0.58727950
# 8    Gly  4  Trp -0.21971055 0.69603185
# 9    Gly  4  Arg -0.14004599 0.36722717
# 10   Ala  6  Glu  0.31747188 0.54845522
# 11    As NA  Asp -0.07593689 0.41273905
# 12   Arg  9  Arg -0.54154181 0.12890089
# 13   Lys 10  Arg  1.09159765 0.19433579
# 14   Lys 10  Lys -0.71238122 0.28212593
# 15 Leull NA  Leu -0.68086189 0.89415476
# 16   Phe 12  Ser -0.05169070 0.48129061
# 17   Phe 12  Cys -0.21871795 0.06282263
# 18   lle 13  Leu -1.42723032 0.62185980
# 19   lle 13  Val  0.93924955 0.39333277
# 20   lle 13  Phe  0.71006152 0.22982191
# 21   Thr 15  Pro -0.66542079 0.66382062

where:

class(res$X2)
# [1] "integer"

Data:

x <- c("Met1?", "Met1?", "Met1?", "Ala2Glu", "Ala2Ala", "Asn3Asp",
"Asn3Asn", "Gly4Trp", "Gly4Arg", "Ala6Glu", "AsAsp", "Arg9Arg",
"Lys10Arg", "Lys10Lys", "LeullLeu", "Phe12Ser", "Phe12Cys", "lle13Leu",
"lle13Val", "lle13Phe", "Thr15Pro")


问:
How to set "parent_id" of child element of multidimensional array from parent id
I need to display the parent id in the child's array. I have the id of the parent (uuid), now I need to add a new key in the array of the child (parent_id) with the uuid of the parent.
I have the following array (PHP):

```<code>"array": [
{
    "uuid": 7,
    "nome": "Parent",
    "ativo": 1,
    "childrens": [
        {
            "uuid": 9,
            "nome": "Child",
            "ativo": 1,
            "childrens": [
                {
                    "uuid": 70,
                    "nome": "Child of Child",
                    "ativo": 1,
                    "childrens": [
                        {
                            "uuid": 391,
                            "nome": "Child of Child of Child",
                            "ativo": 1,
                            "childrens": []
                        },
                    ]
                },
            ]
        },
    ]
}
</code>```

I would like it to be like this:

```<code>"array": [
{
    "uuid": 7,
    "nome": "Parent",
    "ativo": 1,
    "childrens": [
        {
            "uuid": 9,
            "parent_id": 7,
            "nome": "Child",
            "ativo": 1,
            "childrens": [
                {
                    "uuid": 70,
                    "parent_id": 9,
                    "nome": "Child of Child",
                    "ativo": 1,
                    "childrens": [
                        {
                            "uuid": 391,
                            "parent_id": 70,
                            "nome": "Child of Child of Child",
                            "ativo": 1,
                            "childrens": []
                        },
                    ]
                },
            ]
        },
    ]
}]
</code>```

I've tried several ways without success. Thanks in advance for anyone who can help.

答:
```<code>$json = '{"array": [
{
    "uuid": 7,
    "nome": "Parent",
    "ativo": 1,
    "childrens": [
        {
            "uuid": 9,
            "nome": "Child",
            "ativo": 1,
            "childrens": [
                {
                    "uuid": 70,
                    "nome": "Child of Child",
                    "ativo": 1,
                    "childrens": [
                        {
                            "uuid": 391,
                            "nome": "Child of Child of Child",
                            "ativo": 1,
                            "childrens": []
                        }
                    ]
                }
            ]
        }
    ]
}]}';
$object = json_decode($json);

foreach($object->array as $elem)
    add_parent($elem->childrens,$elem->uuid);

function add_parent($chs,$id){
    foreach($chs as $ch)
    {
        $ch->parent_id = $id;
        if(count($ch->childrens))
            add_parent($ch->childrens,$ch->uuid);
    }
}

var_dump(json_encode($object));

</code>```

Output:

```<code>{
  "array": [
    {
      "uuid": 7,
      "nome": "Parent",
      "ativo": 1,
      "childrens": [
        {
          "uuid": 9,
          "nome": "Child",
          "ativo": 1,
          "childrens": [
            {
              "uuid": 70,
              "nome": "Child of Child",
              "ativo": 1,
              "childrens": [
                {
                  "uuid": 391,
                  "nome": "Child of Child of Child",
                  "ativo": 1,
                  "childrens": [],
                  "parent_id": 70
                }
              ],
              "parent_id": 9
            }
          ],
          "parent_id": 7
        }
      ]
    }
  ]
}
</code>```

Body:
I need to display the parent id in the child's array. I have the id of the parent (uuid), now I need to add a new key in the array of the child (parent_id) with the uuid of the parent.
I have the following array (PHP):

"array": [
{
    "uuid": 7,
    "nome": "Parent",
    "ativo": 1,
    "childrens": [
        {
            "uuid": 9,
            "nome": "Child",
            "ativo": 1,
            "childrens": [
                {
                    "uuid": 70,
                    "nome": "Child of Child",
                    "ativo": 1,
                    "childrens": [
                        {
                            "uuid": 391,
                            "nome": "Child of Child of Child",
                            "ativo": 1,
                            "childrens": []
                        },
                    ]
                },
            ]
        },
    ]
}

I would like it to be like this:

"array": [
{
    "uuid": 7,
    "nome": "Parent",
    "ativo": 1,
    "childrens": [
        {
            "uuid": 9,
            "parent_id": 7,
            "nome": "Child",
            "ativo": 1,
            "childrens": [
                {
                    "uuid": 70,
                    "parent_id": 9,
                    "nome": "Child of Child",
                    "ativo": 1,
                    "childrens": [
                        {
                            "uuid": 391,
                            "parent_id": 70,
                            "nome": "Child of Child of Child",
                            "ativo": 1,
                            "childrens": []
                        },
                    ]
                },
            ]
        },
    ]
}]

I've tried several ways without success. Thanks in advance for anyone who can help.

Body:
$json = '{"array": [
{
    "uuid": 7,
    "nome": "Parent",
    "ativo": 1,
    "childrens": [
        {
            "uuid": 9,
            "nome": "Child",
            "ativo": 1,
            "childrens": [
                {
                    "uuid": 70,
                    "nome": "Child of Child",
                    "ativo": 1,
                    "childrens": [
                        {
                            "uuid": 391,
                            "nome": "Child of Child of Child",
                            "ativo": 1,
                            "childrens": []
                        }
                    ]
                }
            ]
        }
    ]
}]}';
$object = json_decode($json);

foreach($object->array as $elem)
    add_parent($elem->childrens,$elem->uuid);

function add_parent($chs,$id){
    foreach($chs as $ch)
    {
        $ch->parent_id = $id;
        if(count($ch->childrens))
            add_parent($ch->childrens,$ch->uuid);
    }
}

var_dump(json_encode($object));

Output:

{
  "array": [
    {
      "uuid": 7,
      "nome": "Parent",
      "ativo": 1,
      "childrens": [
        {
          "uuid": 9,
          "nome": "Child",
          "ativo": 1,
          "childrens": [
            {
              "uuid": 70,
              "nome": "Child of Child",
              "ativo": 1,
              "childrens": [
                {
                  "uuid": 391,
                  "nome": "Child of Child of Child",
                  "ativo": 1,
                  "childrens": [],
                  "parent_id": 70
                }
              ],
              "parent_id": 9
            }
          ],
          "parent_id": 7
        }
      ]
    }
  ]
}


问:
SSRS: ASP.NET ReportViewer parameters reset to default when clicking View Report
I have a SQL Reporting Services report (SQL 2008 built using Report Builder v2.0) which has a multi select integer parameter (in this case a list of stores).

The default value is 0 ("All Stores"). The parameter is passed to a stored procedure as a varchar(1024).

This all works fine in Report Builder or from the Reporting Services website.

However from an ASP.NET website using the ReportViewer component the parameters are reset to the default each time you choose "View Report".

I've tried setting the view to non-asynchronous loading (changes the rendering container?) plus any other setting I could find, without success. Does anyone know a trick to fix this?

答:
For those of you who experience this error for reasons not listed by the original poster...

Here is a similar scenario.

You have a report which uses a multi-select report parameter.
This parameter is populated by a datasource, which bases its values off some table query.

When you use the 'Select All' option for this report parameter and press the 'View Report' button, the parameter is reset to blank and your report is not generated.

I believe this problem occurs because something invalidates your dataset while the query is being performed, but I cannot be 100% certain.

What I do know, is that by using a table variable as the dataset's query source, you make this problem go away.

For example, your CityDataSource could be populated by the query:

```<code>SELECT DISTINCT city, city as SortOrder from accounts
UNION
SELECT 'All' as city, '0' as SortOrder
ORDER BY SortOrder
</code>```

If you've been making SQL Reporting Services reports, you may have stumbled upon this solution once or twice.

Now, we change the CityDataSource query to look like the following:

```<code>DECLARE @citytable TABLE (city varchar(255), sortorder varchar(255))
INSERT INTO @citytable (city, sortorder) VALUES
(
SELECT DISTINCT city, city as SortOrder from accounts
)
SELECT city, sortorder FROM @citytable ORDER BY sortorder
</code>```

And by doing that your report's parameters won't reset anymore.

A stored procedure would also work, I suspect.

OwnerDisplayName: Andrew

Body:
For those of you who experience this error for reasons not listed by the original poster...

Here is a similar scenario.

You have a report which uses a multi-select report parameter.
This parameter is populated by a datasource, which bases its values off some table query.

When you use the 'Select All' option for this report parameter and press the 'View Report' button, the parameter is reset to blank and your report is not generated.

I believe this problem occurs because something invalidates your dataset while the query is being performed, but I cannot be 100% certain.

What I do know, is that by using a table variable as the dataset's query source, you make this problem go away.

For example, your CityDataSource could be populated by the query:

SELECT DISTINCT city, city as SortOrder from accounts
UNION
SELECT 'All' as city, '0' as SortOrder
ORDER BY SortOrder

If you've been making SQL Reporting Services reports, you may have stumbled upon this solution once or twice.

Now, we change the CityDataSource query to look like the following:

DECLARE @citytable TABLE (city varchar(255), sortorder varchar(255))
INSERT INTO @citytable (city, sortorder) VALUES
(
SELECT DISTINCT city, city as SortOrder from accounts
)
SELECT city, sortorder FROM @citytable ORDER BY sortorder

And by doing that your report's parameters won't reset anymore.

A stored procedure would also work, I suspect.

OwnerDisplayName: kreadus