问:
Can I align a Plotly (Python) Sunburst label in the midpoint of the wedge?
```<code>import pandas as pd
import plotly.express as px
import plotly.io as io
import textwrap

wrap_width = 25
def customwrap(s,width=wrap_width): #Function responsible for wrapping text for the captions
    return "<br>".join(textwrap.wrap(s,width=width))

io.renderers.default='browser'

scope = ['Scope 1','Scope 1', 'Scope 2', 'Scope 2', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3',
 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3',
 'Scope 3', 'Scope 3', 'Scope 3']

component = ['Diesel (company vehicles)', 'Petrol (company vehicles)', 'Electricity for<br>appliances', 'Other Scope 2', 'Fuel- and energy-related<br>activities (FERA)', 'Upstream transportation<br>in operations',
             'Other Scope 3', 'Other Scope 3','Employee commuting', 'Downstream transportation<br>and distribution', 'Use of sold products<br>(including indirect use)', 'End-of-life treatment of<br>sold products',
 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services',
 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services',
 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services', 'Purchased goods &<br>services']

other1 = [None, None, None, 'Other electricity usage', None, None, 'Waste generated in operations', 'Business travel', None, None, None, None, 'External services', 'Other', 'Component 3', 'Other', 'Other', 'Other', 'Other', 'Other',
 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Packaging 1', 'Other', 'Other', 'Other', 'Other', 'Packaging 6', 'Other', 'Packaging 8']

other2 = [None, None, None, None, None, None, None, None, None, None, None, None, None, 'Component 2', None, 'Component 4', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Component 18',
 'Other', 'Other', None, 'Packaging 2', 'Packaging 3', 'Packaging 4', 'Other', None, 'Packaging 7', None]

other3 = [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,
 'Component 5', 'Component 6', 'Component 8', 'Component 10', 'Component 11', 'Component 15', 'Component 16', 'Component 17',
 None, 'Component 19', 'Component 20', None, None, None, None, 'Packaging 5', None, None, None]

my_val = [764.7025037682, 922.1573873343998, 1957.1932799999997, 140.7, 1207.8232972546991, 2281.8435614470854, 515.076626462584, 29.182320239999992,
 1121.2985380110642, 1719.9014327173065, 3775.035531264989, 1070.6572813460293, 1674.5794717430463, 30.810666030133756, 422.10395987932935, 56.39659050619138,
 6.3586116808006095, 4.512960708715524, 1.9694367644506894, 1.3722071788772845, 2.7747701218460326, 0.2114258879480555, 0.9394050913579317, 0.04218689368287673,
 45.71662577815401, 8.498568925771194, 0.40354149057007305, 1719.5614117487207, 58.05899316001125, 69.89255424737141, 17.751589750845255, 7.775786234929822,
 3190.0304754954027, 134.42401811928045, 792.7971957632528]

df = pd.DataFrame(list(zip(scope,component,other1,other2,other3,my_val)),
                       columns = ['Scope','Component','Other_label','Layer_2','Layer_3','tCO2e'])

g1 = df.Scope.map(customwrap) #Wrapping the text in the sunburst slices
g2 = df.Component.map(customwrap) #Wrapping the text in the sunburst slices

burst_df = pd.DataFrame(
    dict(scope_layer=g1, component_layer=g2, other_layer=df.Other_label, layer_2=df.Layer_2, layer_3=df.Layer_3, my_values=df.tCO2e)) #Creating a new DataFrame that has the wrapped labels

burst_df = burst_df.drop(burst_df[burst_df.my_values == 0].index) #Drop any rows where the value is zero. They do not show up anyway and can cause problems.

fig = px.sunburst(burst_df, path=['scope_layer','component_layer','other_layer','layer_2','layer_3'], values='my_values',
                  maxdepth=2, title='Carbon footprint of 2021')

fig.update_traces(hovertemplate="%{label} <br>%{value:.1f} tCO\u2082e <extra></extra>",insidetextorientation='radial',rotation=90)

fig.show()
</code>```

Hi,

I am creating a sunburst chart in Python using Plotly Express, but the inside text labels are not centred in the 'wedges'.

It seems that the label on the left most wedge is always set to '9 o'clock', and on the right at '3 o'clock'.

Is there a way to adjust it so the label is in the centre of the wedge, but still in a radial orientation so that it is angled radially. As you can see, almost all of the other labels are oriented correctly.

Current format, where the tags (e.g., Packaging 7) are not in the center of the wedge:

This post addresses the same issue but in Javascript, not Python

Note: Apologies for the large amount of data. Dummy data may not have represented my issues adequately. The data is subject to change too, so I am looking for a solution that would apply to any data...

Body:
import pandas as pd
import plotly.express as px
import plotly.io as io
import textwrap

wrap_width = 25
def customwrap(s,width=wrap_width): #Function responsible for wrapping text for the captions
    return "
".join(textwrap.wrap(s,width=width))

io.renderers.default='browser'

scope = ['Scope 1','Scope 1', 'Scope 2', 'Scope 2', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3',
 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3', 'Scope 3',
 'Scope 3', 'Scope 3', 'Scope 3']

component = ['Diesel (company vehicles)', 'Petrol (company vehicles)', 'Electricity for
appliances', 'Other Scope 2', 'Fuel- and energy-related
activities (FERA)', 'Upstream transportation
in operations',
             'Other Scope 3', 'Other Scope 3','Employee commuting', 'Downstream transportation
and distribution', 'Use of sold products
(including indirect use)', 'End-of-life treatment of
sold products',
 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services',
 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services',
 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services', 'Purchased goods &
services']

other1 = [None, None, None, 'Other electricity usage', None, None, 'Waste generated in operations', 'Business travel', None, None, None, None, 'External services', 'Other', 'Component 3', 'Other', 'Other', 'Other', 'Other', 'Other',
 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Packaging 1', 'Other', 'Other', 'Other', 'Other', 'Packaging 6', 'Other', 'Packaging 8']

other2 = [None, None, None, None, None, None, None, None, None, None, None, None, None, 'Component 2', None, 'Component 4', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Other', 'Component 18',
 'Other', 'Other', None, 'Packaging 2', 'Packaging 3', 'Packaging 4', 'Other', None, 'Packaging 7', None]

other3 = [None, None, None, None, None, None, None, None, None, None, None, None, None, None, None, None,
 'Component 5', 'Component 6', 'Component 8', 'Component 10', 'Component 11', 'Component 15', 'Component 16', 'Component 17',
 None, 'Component 19', 'Component 20', None, None, None, None, 'Packaging 5', None, None, None]

my_val = [764.7025037682, 922.1573873343998, 1957.1932799999997, 140.7, 1207.8232972546991, 2281.8435614470854, 515.076626462584, 29.182320239999992,
 1121.2985380110642, 1719.9014327173065, 3775.035531264989, 1070.6572813460293, 1674.5794717430463, 30.810666030133756, 422.10395987932935, 56.39659050619138,
 6.3586116808006095, 4.512960708715524, 1.9694367644506894, 1.3722071788772845, 2.7747701218460326, 0.2114258879480555, 0.9394050913579317, 0.04218689368287673,
 45.71662577815401, 8.498568925771194, 0.40354149057007305, 1719.5614117487207, 58.05899316001125, 69.89255424737141, 17.751589750845255, 7.775786234929822,
 3190.0304754954027, 134.42401811928045, 792.7971957632528]

df = pd.DataFrame(list(zip(scope,component,other1,other2,other3,my_val)),
                       columns = ['Scope','Component','Other_label','Layer_2','Layer_3','tCO2e'])

g1 = df.Scope.map(customwrap) #Wrapping the text in the sunburst slices
g2 = df.Component.map(customwrap) #Wrapping the text in the sunburst slices

burst_df = pd.DataFrame(
    dict(scope_layer=g1, component_layer=g2, other_layer=df.Other_label, layer_2=df.Layer_2, layer_3=df.Layer_3, my_values=df.tCO2e)) #Creating a new DataFrame that has the wrapped labels

burst_df = burst_df.drop(burst_df[burst_df.my_values == 0].index) #Drop any rows where the value is zero. They do not show up anyway and can cause problems.

fig = px.sunburst(burst_df, path=['scope_layer','component_layer','other_layer','layer_2','layer_3'], values='my_values',
                  maxdepth=2, title='Carbon footprint of 2021')

fig.update_traces(hovertemplate="%{label}
%{value:.1f} tCO\u2082e <extra></extra>",insidetextorientation='radial',rotation=90)

fig.show()

Hi,

I am creating a sunburst chart in Python using Plotly Express, but the inside text labels are not centred in the 'wedges'.

It seems that the label on the left most wedge is always set to '9 o'clock', and on the right at '3 o'clock'.

Is there a way to adjust it so the label is in the centre of the wedge, but still in a radial orientation so that it is angled radially. As you can see, almost all of the other labels are oriented correctly.

Current format, where the tags (e.g., Packaging 7) are not in the center of the wedge:

This post addresses the same issue but in Javascript, not Python

Note: Apologies for the large amount of data. Dummy data may not have represented my issues adequately. The data is subject to change too, so I am looking for a solution that would apply to any data...


来源: stackexchange

问:
Retrieve all page URLs with visits with Matomo WordPress REST
I am trying to extract data from a Matomo WordPress installation through the REST API.
My problem is that, when I look in the Matomo dashboard > Behavior > Pages, I can expand the row wordpress to reveal index.php, which I can further expand to reveal all posts visited.

However, when querying through REST, I only get one single row named wordpress, and I can’t understand how to access the nested layers underneath. My goal here is to end up with an array of page URL <-> visits for all URLs in a given time range. Does anybody know how to obtain that?

Here is a full minimum working example:

```<code>add_action( 'admin_menu', 'admin_menus' );
function admin_menus() {
    add_menu_page( 'REST Test', 'Rest Test', 'manage_options', 'rest-test', 'rest_test');
}

function rest_test() {
    $req = new WP_REST_Request( 'GET', '/matomo/v1/api/processed_report');
    $req->set_query_params(array(
        'period' => 'range',
        'date' => '2022-11-01,2022-11-30',
        'filter_limit' => -1,
        'format' => 'json',
        'expanded' => 1, // no difference without
        'apiModule' => 'Actions',
        'apiAction' => 'getPageUrls'));
    $res = rest_do_request($req);
    var_dump($res->get_data());
}
</code>```

an extract of the result is

```<code>"reportData":[{"label":"wordpress","nb_visits":5,"nb_hits":7,"bounce_rate":"0%","avg_time_on_page":"00:01:54","exit_rate":"40%"}],"reportMetadata":[{"idsubdatatable_in_db":1,"segment":"pageUrl=^http%253A%252F%252Flocalhost%252Fwordpress%252Fwordpress","idsubdatatable":2}],
</code>```

For reference, here is the full result of the request:

```<code>string(2634) "{"website":"Profeta","prettyDate":"November 1 \u2013 30, 2022","metadata":{"category":"Actions","subcategory":"Pages","name":"Page URLs","module":"Actions","action":"getPageUrls","dimension":"Page URL","documentation":"This report contains information about the page URLs that have been visited.
The table is organized hierarchically, the URLs are displayed as a folder structure.
Use the plus and minus icons on the left to navigate.","metrics":{"nb_hits":"Pageviews","nb_visits":"Unique Pageviews"},"metricsDocumentation":{"nb_hits":"The number of times this page was visited.","nb_visits":"The number of visits that included this page. If a page was viewed multiple times during one visit, it is only counted once.","avg_time_on_page":"The average amount of time visitors spent on this page (only the page, not the entire website).","bounce_rate":"The percentage of visits that started on this page and left the website straight away.","exit_rate":"The percentage of visits that left the website after viewing this page."},"processedMetrics":{"avg_time_on_page":"Avg. time on page","bounce_rate":"Bounce Rate","exit_rate":"Exit rate","avg_time_generation":"Avg. generation time"},"actionToLoadSubTables":"getPageUrls","relatedReports":[{"name":"Entry pages","module":"Actions","action":"getEntryPageUrls"},{"name":"Exit pages","module":"Actions","action":"getExitPageUrls"}],"imageGraphUrl":"index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Actions&apiAction=getPageUrls&period=range&date=2022-11-01,2022-11-30","imageGraphEvolutionUrl":"index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Actions&apiAction=getPageUrls&period=day&date=2022-11-01,2022-11-30","uniqueId":"Actions_getPageUrls"},"columns":{"label":"Page URL","nb_hits":"Pageviews","nb_visits":"Unique Pageviews","avg_time_on_page":"Avg. time on page","bounce_rate":"Bounce Rate","exit_rate":"Exit rate"},"reportData":[{"label":"wordpress","nb_visits":5,"nb_hits":7,"bounce_rate":"0%","avg_time_on_page":"00:01:54","exit_rate":"40%"}],"reportMetadata":[{"idsubdatatable_in_db":1,"segment":"pageUrl=^http%253A%252F%252Flocalhost%252Fwordpress%252Fwordpress","idsubdatatable":2}],"reportTotal":{"nb_visits":5,"nb_hits":7,"sum_time_spent":795,"sum_time_server":0.5740000000000001,"nb_hits_with_time_server":7,"min_time_server":0.29900000000000004,"max_time_server":0.33,"sum_time_dom_processing":1.038,"nb_hits_with_time_dom_processing":7,"min_time_dom_processing":0.387,"max_time_dom_processing":0.96,"entry_nb_visits":2,"entry_nb_actions":7,"entry_sum_visit_length":797,"entry_bounce_count":0,"exit_nb_visits":2},"timerMillis":"19"}"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I am trying to extract data from a Matomo WordPress installation through the REST API.
My problem is that, when I look in the Matomo dashboard > Behavior > Pages, I can expand the row wordpress to reveal index.php, which I can further expand to reveal all posts visited.

However, when querying through REST, I only get one single row named wordpress, and I can’t understand how to access the nested layers underneath. My goal here is to end up with an array of page URL <-> visits for all URLs in a given time range. Does anybody know how to obtain that?

Here is a full minimum working example:

add_action( 'admin_menu', 'admin_menus' );
function admin_menus() {
    add_menu_page( 'REST Test', 'Rest Test', 'manage_options', 'rest-test', 'rest_test');
}

function rest_test() {
    $req = new WP_REST_Request( 'GET', '/matomo/v1/api/processed_report');
    $req->set_query_params(array(
        'period' => 'range',
        'date' => '2022-11-01,2022-11-30',
        'filter_limit' => -1,
        'format' => 'json',
        'expanded' => 1, // no difference without
        'apiModule' => 'Actions',
        'apiAction' => 'getPageUrls'));
    $res = rest_do_request($req);
    var_dump($res->get_data());
}

an extract of the result is

"reportData":[{"label":"wordpress","nb_visits":5,"nb_hits":7,"bounce_rate":"0%","avg_time_on_page":"00:01:54","exit_rate":"40%"}],"reportMetadata":[{"idsubdatatable_in_db":1,"segment":"pageUrl=^http%253A%252F%252Flocalhost%252Fwordpress%252Fwordpress","idsubdatatable":2}],

For reference, here is the full result of the request:

string(2634) "{"website":"Profeta","prettyDate":"November 1 \u2013 30, 2022","metadata":{"category":"Actions","subcategory":"Pages","name":"Page URLs","module":"Actions","action":"getPageUrls","dimension":"Page URL","documentation":"This report contains information about the page URLs that have been visited.
The table is organized hierarchically, the URLs are displayed as a folder structure.
Use the plus and minus icons on the left to navigate.","metrics":{"nb_hits":"Pageviews","nb_visits":"Unique Pageviews"},"metricsDocumentation":{"nb_hits":"The number of times this page was visited.","nb_visits":"The number of visits that included this page. If a page was viewed multiple times during one visit, it is only counted once.","avg_time_on_page":"The average amount of time visitors spent on this page (only the page, not the entire website).","bounce_rate":"The percentage of visits that started on this page and left the website straight away.","exit_rate":"The percentage of visits that left the website after viewing this page."},"processedMetrics":{"avg_time_on_page":"Avg. time on page","bounce_rate":"Bounce Rate","exit_rate":"Exit rate","avg_time_generation":"Avg. generation time"},"actionToLoadSubTables":"getPageUrls","relatedReports":[{"name":"Entry pages","module":"Actions","action":"getEntryPageUrls"},{"name":"Exit pages","module":"Actions","action":"getExitPageUrls"}],"imageGraphUrl":"index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Actions&apiAction=getPageUrls&period=range&date=2022-11-01,2022-11-30","imageGraphEvolutionUrl":"index.php?module=API&method=ImageGraph.get&idSite=1&apiModule=Actions&apiAction=getPageUrls&period=day&date=2022-11-01,2022-11-30","uniqueId":"Actions_getPageUrls"},"columns":{"label":"Page URL","nb_hits":"Pageviews","nb_visits":"Unique Pageviews","avg_time_on_page":"Avg. time on page","bounce_rate":"Bounce Rate","exit_rate":"Exit rate"},"reportData":[{"label":"wordpress","nb_visits":5,"nb_hits":7,"bounce_rate":"0%","avg_time_on_page":"00:01:54","exit_rate":"40%"}],"reportMetadata":[{"idsubdatatable_in_db":1,"segment":"pageUrl=^http%253A%252F%252Flocalhost%252Fwordpress%252Fwordpress","idsubdatatable":2}],"reportTotal":{"nb_visits":5,"nb_hits":7,"sum_time_spent":795,"sum_time_server":0.5740000000000001,"nb_hits_with_time_server":7,"min_time_server":0.29900000000000004,"max_time_server":0.33,"sum_time_dom_processing":1.038,"nb_hits_with_time_dom_processing":7,"min_time_dom_processing":0.387,"max_time_dom_processing":0.96,"entry_nb_visits":2,"entry_nb_actions":7,"entry_sum_visit_length":797,"entry_bounce_count":0,"exit_nb_visits":2},"timerMillis":"19"}"


问:
Pyspark new column when otherwise results in "should be a column" error
I have a DataFrame in PySpark, and I would like to add a new column based on the value in another column. I know this is fairly common, and I've searched and tried a bunch of different ways, but always end up with the error message TypeError: condition should be a Column.

So what I want to do is basically, if the value in one column is not null, then I will do a regex on that column, otherwise I'll do a regex on another column.

My original query looked like this:

import pyspark.sql.functions as F

df.withColumn("new_column", F.when(F.col("column_a").isNotNull,
    F.regexp_extract('column_a', 'myregex', 1))
    .otherwise(F.regexp_extract('column_b', 'myotherregex', 1)))
```
<p>That resulted in the mentioned error. As I was simplifying to figure out where the error was, I could never manage to get it working. So even this simplified example fails with the same error:</p>
<pre class="lang-py prettyprint-override"><code>df.withColumn("new_column", F.when(F.col("column_a").isNotNull, F.lit("A"))
    .otherwise(F.lit("B")))
</code>```

I've also tried to refer to column_a in the following way, without success: df["column_a"]

When I search and find examples of people doing the same thing it looks to my untrained eye like it should work. What am I missing?

Body:
I have a DataFrame in PySpark, and I would like to add a new column based on the value in another column. I know this is fairly common, and I've searched and tried a bunch of different ways, but always end up with the error message TypeError: condition should be a Column.

So what I want to do is basically, if the value in one column is not null, then I will do a regex on that column, otherwise I'll do a regex on another column.

My original query looked like this:

import pyspark.sql.functions as F

df.withColumn("new_column", F.when(F.col("column_a").isNotNull,
    F.regexp_extract('column_a', 'myregex', 1))
    .otherwise(F.regexp_extract('column_b', 'myotherregex', 1)))

That resulted in the mentioned error. As I was simplifying to figure out where the error was, I could never manage to get it working. So even this simplified example fails with the same error:

df.withColumn("new_column", F.when(F.col("column_a").isNotNull, F.lit("A"))
    .otherwise(F.lit("B")))

I've also tried to refer to column_a in the following way, without success: df["column_a"]

When I search and find examples of people doing the same thing it looks to my untrained eye like it should work. What am I missing?


问:
using python to automate sharepoint actions on organisation site
I'm trying to automate some data processing in my org but I'm struggling to parse the use of the python module to make the requests. When I use

```<code>from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext, UserCredential
from office365.sharepoint.files.file import File

sharepoint_base_url = 'https://organisation.sharepoint.com/sites/suborganisation'
sharepoint_user = 'username@org.org'
sharepoint_password = 'password'

ctx = ClientContext(sharepoint_base_url).with_credentials(UserCredential(sharepoint_user, sharepoint_password))
web = ctx.web
ctx.load(web)
ctx.execute_query()
print(f"Web title: {web.properties['Title']}")
</code>```

It will access the main site, but as soon as I try to work with any of the sub directories I start to run into errors. I think the problem is either that I just don't understand the relative urls, or that there's something about the structure of the site

For example the full url for the folder I want to point (with modification obviously) to is

```<code>folder_in_sharepoint = 'https://organisation.sharepoint.com/sites/suborganisation/current_project/Forms/AllItems.aspx?id=%2Fsites%2suborganisation%2Fcurrent_project%2FApplications%202023&viewid=longasphanumericstring' # copied directly from the browser

def folder_details(ctx, folder_in_sharepoint):
    folder = ctx.web.get_folder_by_server_relative_url(folder_in_sharepoint)
    fold_names = []
    sub_folders = folder.files
    ctx.load(sub_folders)
    ctx.execute_query()
    for s_folder in sub_folders:
        fold_names.append(s_folder.properties["Name"])
    return fold_names

#listing objects in the folder
file_list = folder_details(ctx, folder_in_sharepoint)
</code>```

I get the error

```<code>ClientRequestException: (None, None, "400 Client Error: Bad Request for url: https://organisation.sharepoint.com/sites/suborganisation/_api/Web/getFolderByServerRelativeUrl('https:%2F%2Forganisation.sharepoint.com%2Fsites%2Fsuborganisation%2Fcurrent_project%2FForms%2FAllItems.aspx%3Fid=%252Fsites%252Fsuborganisation%252Fcurrent_project%252FApplications%25202023%26viewid=longalphanumericstring')/Files")
</code>```

It appears to me that ctx.web.get_folder_by_server_relative_url(folder_in_sharepoint) is where the problem is, and it's something to do with what I'm passing as the relative url, but I've tried commenting out every line, and trying multiple permutation of the url I can make and I'm still getting nowhere.

Any guidance appreciated.

Body:
I'm trying to automate some data processing in my org but I'm struggling to parse the use of the python module to make the requests. When I use

from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext, UserCredential
from office365.sharepoint.files.file import File

sharepoint_base_url = 'https://organisation.sharepoint.com/sites/suborganisation'
sharepoint_user = 'username@org.org'
sharepoint_password = 'password'

ctx = ClientContext(sharepoint_base_url).with_credentials(UserCredential(sharepoint_user, sharepoint_password))
web = ctx.web
ctx.load(web)
ctx.execute_query()
print(f"Web title: {web.properties['Title']}")

It will access the main site, but as soon as I try to work with any of the sub directories I start to run into errors. I think the problem is either that I just don't understand the relative urls, or that there's something about the structure of the site

For example the full url for the folder I want to point (with modification obviously) to is

folder_in_sharepoint = 'https://organisation.sharepoint.com/sites/suborganisation/current_project/Forms/AllItems.aspx?id=%2Fsites%2suborganisation%2Fcurrent_project%2FApplications%202023&viewid=longasphanumericstring' # copied directly from the browser

def folder_details(ctx, folder_in_sharepoint):
    folder = ctx.web.get_folder_by_server_relative_url(folder_in_sharepoint)
    fold_names = []
    sub_folders = folder.files
    ctx.load(sub_folders)
    ctx.execute_query()
    for s_folder in sub_folders:
        fold_names.append(s_folder.properties["Name"])
    return fold_names

#listing objects in the folder
file_list = folder_details(ctx, folder_in_sharepoint)

I get the error

ClientRequestException: (None, None, "400 Client Error: Bad Request for url: https://organisation.sharepoint.com/sites/suborganisation/_api/Web/getFolderByServerRelativeUrl('https:%2F%2Forganisation.sharepoint.com%2Fsites%2Fsuborganisation%2Fcurrent_project%2FForms%2FAllItems.aspx%3Fid=%252Fsites%252Fsuborganisation%252Fcurrent_project%252FApplications%25202023%26viewid=longalphanumericstring')/Files")

It appears to me that ctx.web.get_folder_by_server_relative_url(folder_in_sharepoint) is where the problem is, and it's something to do with what I'm passing as the relative url, but I've tried commenting out every line, and trying multiple permutation of the url I can make and I'm still getting nowhere.

Any guidance appreciated.


问:
Flutter - floating circled widgets around one center widget
Is there, in Flutter, any chance to make floating widgets like Harmony OS devices list.

Harmony OS - devices list

It seems like widgets are "static", because of a tree layout. Maybe there is a library that is able to draw floating widgets.


问:
Lambda doesn't recognize python dependency
For my lambda function I need this library: https://github.com/explosion/tokenizations (Listed under pytokenizations on PyPi)

I've installed it with pip install --target ./package , zipped it and brought it to lambda, but when I run my function (the exact same code works fine on my machine) I get the following error: "Unable to import module 'main': No module named 'tokenizations'"

EDIT: The actual error is  "Unable to import module 'main': No module named 'tokenizations.tokenizations'" Wouldn't the normal output be just one time tokenizations?

The other module I'm using through the /package folder is working just fine.

What could be possible causes for this?


问:
PahoClient to connect to MQTT from Spring is throwing the Certificate Expired Exception
I am using MqttPahoClientFactory to connect to an MQTT client, everything was fine until this exception started to appear.

```<code>[30m2022-12-08 20:17:13,029[0;39m [1;31mERROR[0;39m [[34mtask-scheduler-1[0;39m] [33morg.springframework.core.log.LogAccessor[0;39m: Error connecting or subscribing to [#]
org.eclipse.paho.client.mqttv3.MqttException: MqttException
    at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:738)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: javax.net.ssl.SSLHandshakeException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:325)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:268)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:263)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1340)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1215)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1158)
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:396)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:445)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:423)
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:182)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:171)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1475)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1381)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:441)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:412)
    at org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule.start(SSLNetworkModule.java:159)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:724)
    ... 1 common frames omitted
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
    at java.base/sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:369)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:263)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:132)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1324)
    ... 14 common frames omitted
Caused by: java.security.cert.CertPathValidatorException: validity check failed
    at java.base/sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:135)
    at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:237)
    at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:145)
    at java.base/sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:84)
    at java.base/java.security.cert.CertPathValidator.validate(CertPathValidator.java:309)
    at java.base/sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:364)
    ... 19 common frames omitted
Caused by: java.security.cert.CertificateExpiredException: NotAfter: Mon Nov 21 22:53:10 GMT+05:30 2022
    at java.base/sun.security.x509.CertificateValidity.valid(CertificateValidity.java:277)
    at java.base/sun.security.x509.X509CertImpl.checkValidity(X509CertImpl.java:673)
    at java.base/sun.security.provider.certpath.BasicChecker.verifyValidity(BasicChecker.java:190)
    at java.base/sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:144)
    at java.base/sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
    ... 24 common frames omitted
</code>```

From the looks of it , looks like the server cert is expired but , I am able to connect to same server using the MQTTX desktop clients easily. The server cert is not yet expired.

What are the options to get this resolved and get a connection established again.

Body:
I am using MqttPahoClientFactory to connect to an MQTT client, everything was fine until this exception started to appear.

[30m2022-12-08 20:17:13,029[0;39m [1;31mERROR[0;39m [[34mtask-scheduler-1[0;39m] [33morg.springframework.core.log.LogAccessor[0;39m: Error connecting or subscribing to [#]
org.eclipse.paho.client.mqttv3.MqttException: MqttException
    at org.eclipse.paho.client.mqttv3.internal.ExceptionHelper.createMqttException(ExceptionHelper.java:38)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:738)
    at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: javax.net.ssl.SSLHandshakeException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
    at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:325)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:268)
    at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:263)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1340)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1215)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1158)
    at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:396)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:445)
    at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:423)
    at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:182)
    at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:171)
    at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1475)
    at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1381)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:441)
    at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:412)
    at org.eclipse.paho.client.mqttv3.internal.SSLNetworkModule.start(SSLNetworkModule.java:159)
    at org.eclipse.paho.client.mqttv3.internal.ClientComms$ConnectBG.run(ClientComms.java:724)
    ... 1 common frames omitted
Caused by: sun.security.validator.ValidatorException: PKIX path validation failed: java.security.cert.CertPathValidatorException: validity check failed
    at java.base/sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:369)
    at java.base/sun.security.validator.PKIXValidator.engineValidate(PKIXValidator.java:263)
    at java.base/sun.security.validator.Validator.validate(Validator.java:264)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkTrusted(X509TrustManagerImpl.java:231)
    at java.base/sun.security.ssl.X509TrustManagerImpl.checkServerTrusted(X509TrustManagerImpl.java:132)
    at java.base/sun.security.ssl.CertificateMessage$T13CertificateConsumer.checkServerCerts(CertificateMessage.java:1324)
    ... 14 common frames omitted
Caused by: java.security.cert.CertPathValidatorException: validity check failed
    at java.base/sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:135)
    at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:237)
    at java.base/sun.security.provider.certpath.PKIXCertPathValidator.validate(PKIXCertPathValidator.java:145)
    at java.base/sun.security.provider.certpath.PKIXCertPathValidator.engineValidate(PKIXCertPathValidator.java:84)
    at java.base/java.security.cert.CertPathValidator.validate(CertPathValidator.java:309)
    at java.base/sun.security.validator.PKIXValidator.doValidate(PKIXValidator.java:364)
    ... 19 common frames omitted
Caused by: java.security.cert.CertificateExpiredException: NotAfter: Mon Nov 21 22:53:10 GMT+05:30 2022
    at java.base/sun.security.x509.CertificateValidity.valid(CertificateValidity.java:277)
    at java.base/sun.security.x509.X509CertImpl.checkValidity(X509CertImpl.java:673)
    at java.base/sun.security.provider.certpath.BasicChecker.verifyValidity(BasicChecker.java:190)
    at java.base/sun.security.provider.certpath.BasicChecker.check(BasicChecker.java:144)
    at java.base/sun.security.provider.certpath.PKIXMasterCertPathValidator.validate(PKIXMasterCertPathValidator.java:125)
    ... 24 common frames omitted

From the looks of it , looks like the server cert is expired but , I am able to connect to same server using the MQTTX desktop clients easily. The server cert is not yet expired.

What are the options to get this resolved and get a connection established again.


问:
docker ERROR: "/${DIR_NAME}" not found: not found - How to avoid huge images
I'm running into a problem with docker where I'm using some variables in the dockerfile. The variables work everywhere except in the source= argument of a bind mount.

I'm installing a large (40+ GB) software package. I have three different versions to work with so I made a variable to identify the version directory. I'm using a bind mount to avoid sending the installation source to the image.

What is the best way to debug? --progress=plain and --no-cache don't really show much more on the error message.

Is there a better way to do this whole thing? I don't want to create 150 GB images if I can avoid that. If I have all three versions of software in one directory that could be a long build and a big image since I need to select the version at build time. I guess I may need a more involved build process than allowed here--what would that look like?

How do I get around this variable issue?

The command that causes the problem is here:

```<code>ARG SOFTWARE_DIR=MySoftwareDirectory #this lives in the same directory as the *.docker
ARG SOFTWARE_VER=2022.3

FROM centos:latest AS base

RUN yum update -y \
    && yum upgrade -y \
    && yum install -y libXext libXrender libXtst \
    && yum clean all
RUN mkdir /tools

FROM base as final
ARG SOFTWARE_VER
ARG SOFTWARE_DIR
COPY ./install_config_${SOFTWARE_VER}.txt /tools/install_config.txt
RUN --mount=type=bind,target=/mnt/${SOFTWARE_DIR},readonly,source=${SOFTWARE_DIR} \
    /mnt/${SOFTWARE_DIR}/setup --batch
ENTRYPOINT ["/tools/software/${SOFTWARE_VER}/bin/software"]
</code>```

The error is:

```<code>ERROR: "/${SOFTWARE_DIR}" not found: not found
...
failed to computer cache key: "/${SOFTWARE_DIR}" not found: not found
</code>```

This works:

```<code>ARG SOFTWARE_DIR=MySoftwareDirectory #this lives in the same directory as the *.docker
ARG SOFTWARE_VER=2022.3

FROM centos:latest AS base

RUN yum update -y \
    && yum upgrade -y \
    && yum install -y libXext libXrender libXtst \
    && yum clean all
RUN mkdir /tools

FROM base as final
ARG SOFTWARE_VER
ARG SOFTWARE_DIR
COPY ./install_config_${SOFTWARE_VER}.txt /tools/install_config.txt
RUN --mount=type=bind,target=/mnt/${SOFTWARE_DIR},readonly,source=MySoftwareDirectory \
    /mnt/${SOFTWARE_DIR}/setup --batch
ENTRYPOINT ["/tools/software/${SOFTWARE_VER}/bin/software"]
</code>```

I am building with:

```<code>DOCKER_BUILDKIT=1 docker build -t software -f software.docker .
</code>```

My directory structure looks like this:

```<code>software.docker
MySoftwareDirectory
</code>```

I did chmod 777 on MySoftwareDirectory to correct permissions issue. (I know not the best way)

Docker version is 20.10.21. Host is CentOS 7 fully patched.

Body:
I'm running into a problem with docker where I'm using some variables in the dockerfile. The variables work everywhere except in the source= argument of a bind mount.

I'm installing a large (40+ GB) software package. I have three different versions to work with so I made a variable to identify the version directory. I'm using a bind mount to avoid sending the installation source to the image.

What is the best way to debug? --progress=plain and --no-cache don't really show much more on the error message.

Is there a better way to do this whole thing? I don't want to create 150 GB images if I can avoid that. If I have all three versions of software in one directory that could be a long build and a big image since I need to select the version at build time. I guess I may need a more involved build process than allowed here--what would that look like?

How do I get around this variable issue?

The command that causes the problem is here:

ARG SOFTWARE_DIR=MySoftwareDirectory #this lives in the same directory as the *.docker
ARG SOFTWARE_VER=2022.3

FROM centos:latest AS base

RUN yum update -y \
    && yum upgrade -y \
    && yum install -y libXext libXrender libXtst \
    && yum clean all
RUN mkdir /tools

FROM base as final
ARG SOFTWARE_VER
ARG SOFTWARE_DIR
COPY ./install_config_${SOFTWARE_VER}.txt /tools/install_config.txt
RUN --mount=type=bind,target=/mnt/${SOFTWARE_DIR},readonly,source=${SOFTWARE_DIR} \
    /mnt/${SOFTWARE_DIR}/setup --batch
ENTRYPOINT ["/tools/software/${SOFTWARE_VER}/bin/software"]

The error is:

ERROR: "/${SOFTWARE_DIR}" not found: not found
...
failed to computer cache key: "/${SOFTWARE_DIR}" not found: not found

This works:

ARG SOFTWARE_DIR=MySoftwareDirectory #this lives in the same directory as the *.docker
ARG SOFTWARE_VER=2022.3

FROM centos:latest AS base

RUN yum update -y \
    && yum upgrade -y \
    && yum install -y libXext libXrender libXtst \
    && yum clean all
RUN mkdir /tools

FROM base as final
ARG SOFTWARE_VER
ARG SOFTWARE_DIR
COPY ./install_config_${SOFTWARE_VER}.txt /tools/install_config.txt
RUN --mount=type=bind,target=/mnt/${SOFTWARE_DIR},readonly,source=MySoftwareDirectory \
    /mnt/${SOFTWARE_DIR}/setup --batch
ENTRYPOINT ["/tools/software/${SOFTWARE_VER}/bin/software"]

I am building with:

DOCKER_BUILDKIT=1 docker build -t software -f software.docker .

My directory structure looks like this:

software.docker
MySoftwareDirectory

I did chmod 777 on MySoftwareDirectory to correct permissions issue. (I know not the best way)

Docker version is 20.10.21. Host is CentOS 7 fully patched.


问:
Deleting overlapping lines in QGIS
I had to digitize a geologic map. I've made all the polygons for the different units. Now I want to make the contacts/line styles for each polygon. Some contacts are definite, solid line, while other are inferred, dashed line. So it requires 2 different line types. If I make dashed lines for the inferred polygons, then the polygons that have lines on top of one another may look like a solid line. I went ahead and generated another layer with the polygons and used Polygons to Lines in QGIS. Now I want to delete the overlapping lines. So far none of the processes in QGIS are working. Does anyone have a technique for doing this?

I want to have one line that is doesn't have overlapping lines underneath.

Title: Deleting overlapping lines in QGIS


问:
Is there a way to modify java old code to java8 using java
I want to modify my existing code and my new code work same as my old code . My requirement is I want to iterate for each loop only once how may value I pass and map the list of string value then find and store the value using map. In my old code if I pass ten value my loop iterate ten time  but I do not want this type for your reference I post my old code and new code

```<code>private Item getItemManufacturerPriceCodes(Item item) {
          List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
        //Optional<ManufacturerPriceCodes> mpc = manufacturerPriceCodesRepository.findByManufacturerIDAndPriceCodeAndRecordDeleted(item.getManufacturerID(), itemPriceCodes, NOT_DELETED);
          for(ItemPriceCode ipc : itemPriceCodes) {
              Optional<ManufacturerPriceCodes> mpc = manufacturerPriceCodesRepository.findByManufacturerIDAndPriceCodeAndRecordDeleted(item.getManufacturerID(), ipc.getPriceCode(), NOT_DELETED);
              if(mpc.isPresent())
                  ipc.setManufacturerPriceCode(mpc.get().getName());
          }
          item.getItemPriceCodes()
          .removeIf(ipc -> DELETED.equals(ipc.getRecordDeleted()));
          return item;
      }
</code>```

Above is my old code. I want my new code work same as my old code.

```<code>private Item getItemManufacturerPriceCodes(Item item) {
        List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
        List<String> priceCodeList = new ArrayList<String>();
        for (ItemPriceCode ipc : itemPriceCodes) {
            //get the string value from the list
             priceCodeList = ipc.getPriceCode();
      }
        //pass this string value in query
        List<ManufacturerPriceCodes>mpc = manufacturerPriceCodesRepository.
               findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(),priceCodeList,NOT_DELETED);

        //Convert list to map
        Map<String, ManufacturerPriceCodes> ipcToMFPNameMap = mpc.stream().collect(
                  Collectors.toMap(ManufacturerPriceCodes :: getPriceCode,Function.identity()));
        itemPriceCodes.forEach(ipc ->{
            if(ipcToMFPNameMap.get(ipc.getManuf)
        });

    return item;
    }
</code>```

I want to assign list of ItemPriceCode to priceCodeList and pass the priceCodeList in side my query but I am getting issue while assign the itempricOdeList to priceCodeList. Here is my query declaration inside my repository.

```<code> List<ManufacturerPriceCodes> findByManufacturerIDAndPriceCodeInAndRecordDeleted(String manufacturerID, List<String> priceCode, Byte notDeleted);
</code>```

I tried this way but I am not able get same result as my old code.

Body:
I want to modify my existing code and my new code work same as my old code . My requirement is I want to iterate for each loop only once how may value I pass and map the list of string value then find and store the value using map. In my old code if I pass ten value my loop iterate ten time  but I do not want this type for your reference I post my old code and new code

private Item getItemManufacturerPriceCodes(Item item) {
          List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
        //Optional<ManufacturerPriceCodes> mpc = manufacturerPriceCodesRepository.findByManufacturerIDAndPriceCodeAndRecordDeleted(item.getManufacturerID(), itemPriceCodes, NOT_DELETED);
          for(ItemPriceCode ipc : itemPriceCodes) {
              Optional<ManufacturerPriceCodes> mpc = manufacturerPriceCodesRepository.findByManufacturerIDAndPriceCodeAndRecordDeleted(item.getManufacturerID(), ipc.getPriceCode(), NOT_DELETED);
              if(mpc.isPresent())
                  ipc.setManufacturerPriceCode(mpc.get().getName());
          }
          item.getItemPriceCodes()
          .removeIf(ipc -> DELETED.equals(ipc.getRecordDeleted()));
          return item;
      }

Above is my old code. I want my new code work same as my old code.

private Item getItemManufacturerPriceCodes(Item item) {
        List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
        List<String> priceCodeList = new ArrayList<String>();
        for (ItemPriceCode ipc : itemPriceCodes) {
            //get the string value from the list
             priceCodeList = ipc.getPriceCode();
      }
        //pass this string value in query
        List<ManufacturerPriceCodes>mpc = manufacturerPriceCodesRepository.
               findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(),priceCodeList,NOT_DELETED);

        //Convert list to map
        Map<String, ManufacturerPriceCodes> ipcToMFPNameMap = mpc.stream().collect(
                  Collectors.toMap(ManufacturerPriceCodes :: getPriceCode,Function.identity()));
        itemPriceCodes.forEach(ipc ->{
            if(ipcToMFPNameMap.get(ipc.getManuf)
        });

    return item;
    }

I want to assign list of ItemPriceCode to priceCodeList and pass the priceCodeList in side my query but I am getting issue while assign the itempricOdeList to priceCodeList. Here is my query declaration inside my repository.

 List<ManufacturerPriceCodes> findByManufacturerIDAndPriceCodeInAndRecordDeleted(String manufacturerID, List<String> priceCode, Byte notDeleted);

I tried this way but I am not able get same result as my old code.


问:
How to test the 'if' statement in 'useCallback()' function
I have an React tsx component, and I can't test one part of it.

Component.tsx

```<code>const [inputValue, setInputValue] = useState<number>(100);
  const [beforeRightPoint, setBeforeRightPoint] = useState(0);
  const [afterLeftPoint, setAfterLeftPoint] = useState(0);

  const checkLabelVisibility = useCallback(
    (beforePoint, afterPoint) => {
      const beforeHidingPoint = beforePoint + 16;
      const afterHidingPoint = afterPoint - 16;
      if (refBefore.current && refAfter.current) {
        if (inputValue < beforeHidingPoint) {
          setBeforeOpacity((inputValue - beforePoint) / (beforeHidingPoint - beforePoint));
        }
        if (inputValue > afterHidingPoint) {
          setAfterOpacity((inputValue - afterPoint) / (afterHidingPoint - afterPoint));
        }
        if (inputValue > beforeHidingPoint && inputValue < afterHidingPoint) {
          setAfterOpacity(0.7);
          setBeforeOpacity(0.7);
        }
      }
    },
    [inputValue],
  );
</code>```

It's work when I change my Input value (slider)

component.test.tsx

```<code> it('Before and after labels hides when Slider changes its position', () => {
    const handleSliderUsed = jest.fn();
    render(
      <ImagePreviewSlider leftImage={image} rightImage="rightImage" handleSliderUsed={handleSliderUsed} canvasSize={canvasSize} subscribed />,
    );

    const input = screen.getByTestId(testIds.sliderInput);

    fireEvent.input(input, { target: { value: '0' } });
    expect(input).toHaveValue('0');
    expect(handleSliderUsed).toBeCalled();
    expect(screen.queryByTestId(testIds.leftLabel)).toHaveStyle('opacity: 0%;');
    expect(screen.queryByTestId(testIds.rightLabel)).toHaveStyle('opacity: 100%;');

    fireEvent.change(input, { target: { value: '100' } });
    expect(input).toHaveValue('100');
    expect(handleSliderUsed).toBeCalled();
    expect(screen.queryByTestId(testIds.leftLabel)).toHaveStyle('opacity: 100%;');
    expect(screen.queryByTestId(testIds.rightLabel)).toHaveStyle('opacity: 0%;');

    fireEvent.change(input, { target: { value: '50' } });
    expect(input).toHaveValue('50');
    expect(handleSliderUsed).toBeCalled();
    expect(screen.queryByTestId(testIds.leftLabel)).toHaveStyle('opacity: 100%;');
    expect(screen.queryByTestId(testIds.rightLabel)).toHaveStyle('opacity: 100%;');
  });
</code>```

I am expect that how can test this part of code, maybe mock function with other parameters of beforePoint and afterPoint or mock useState after change

Body:
I have an React tsx component, and I can't test one part of it.

Component.tsx

const [inputValue, setInputValue] = useState<number>(100);
  const [beforeRightPoint, setBeforeRightPoint] = useState(0);
  const [afterLeftPoint, setAfterLeftPoint] = useState(0);

  const checkLabelVisibility = useCallback(
    (beforePoint, afterPoint) => {
      const beforeHidingPoint = beforePoint + 16;
      const afterHidingPoint = afterPoint - 16;
      if (refBefore.current && refAfter.current) {
        if (inputValue < beforeHidingPoint) {
          setBeforeOpacity((inputValue - beforePoint) / (beforeHidingPoint - beforePoint));
        }
        if (inputValue > afterHidingPoint) {
          setAfterOpacity((inputValue - afterPoint) / (afterHidingPoint - afterPoint));
        }
        if (inputValue > beforeHidingPoint && inputValue < afterHidingPoint) {
          setAfterOpacity(0.7);
          setBeforeOpacity(0.7);
        }
      }
    },
    [inputValue],
  );

It's work when I change my Input value (slider)

component.test.tsx

 it('Before and after labels hides when Slider changes its position', () => {
    const handleSliderUsed = jest.fn();
    render(
      <ImagePreviewSlider leftImage={image} rightImage="rightImage" handleSliderUsed={handleSliderUsed} canvasSize={canvasSize} subscribed />,
    );

    const input = screen.getByTestId(testIds.sliderInput);

    fireEvent.input(input, { target: { value: '0' } });
    expect(input).toHaveValue('0');
    expect(handleSliderUsed).toBeCalled();
    expect(screen.queryByTestId(testIds.leftLabel)).toHaveStyle('opacity: 0%;');
    expect(screen.queryByTestId(testIds.rightLabel)).toHaveStyle('opacity: 100%;');

    fireEvent.change(input, { target: { value: '100' } });
    expect(input).toHaveValue('100');
    expect(handleSliderUsed).toBeCalled();
    expect(screen.queryByTestId(testIds.leftLabel)).toHaveStyle('opacity: 100%;');
    expect(screen.queryByTestId(testIds.rightLabel)).toHaveStyle('opacity: 0%;');

    fireEvent.change(input, { target: { value: '50' } });
    expect(input).toHaveValue('50');
    expect(handleSliderUsed).toBeCalled();
    expect(screen.queryByTestId(testIds.leftLabel)).toHaveStyle('opacity: 100%;');
    expect(screen.queryByTestId(testIds.rightLabel)).toHaveStyle('opacity: 100%;');
  });

I am expect that how can test this part of code, maybe mock function with other parameters of beforePoint and afterPoint or mock useState after change


问:
How to set dynamic conditional formatting on color of gauge chart?
In my PowerBi report, I have added a guage chart, and applied conditional formatting, based upon 2 values:

Target

Actual Value

If the actual value is more than target, then the gauge chart will be green otherwise red. Now, based upon the data selected in a multi select drop down, the values of both 'Target' and 'Actual value' changes. Therefore, I want to have a dynamic conditional formatting for the guage chart where the conditional formatting for color is applied correctly according to different targets and their respective actual values.

For example:

Target; Actual Value;   Color of Chart

85;         84;    Red;

77;         79;     Green;

65;         71;     Green;

However, as displayed in the attached screenshot, the highlighted box expects a hardcoded numeric value. Please advise how to achieve this. Thanks in advance.


问:
MongoDB 4.4: Compare particular date with an interval of other date
Basically what I want to do is to compare that the difference between 2 date is less than 1 year, i.e. scheduled_end < scheduled_start + 1 year

I'm trying to use the following expression, but it does not seem valid:

```<code>scheduled_end: {
  $lt: {
    $add: [scheduled_start, 365*24*60*60000 ]
  }
}
</code>```

How to fix it?

I'm using MongoDB 4.4, so $dateAdd is not available in this version.

Body:
Basically what I want to do is to compare that the difference between 2 date is less than 1 year, i.e. scheduled_end < scheduled_start + 1 year

I'm trying to use the following expression, but it does not seem valid:

scheduled_end: {
  $lt: {
    $add: [scheduled_start, 365*24*60*60000 ]
  }
}

How to fix it?

I'm using MongoDB 4.4, so $dateAdd is not available in this version.


问:
Unable to deploy asp.net web app using Apache on Ubuntu 22.04
The web app will be running a default Identity layout with user authentication and a leaderboard for a Unity (WebGL) game which will be hosted as static files inside the application wwwroot.

Currently the application works perfectly fine when connecting to localhost:5000, connecting to localhost:80, instead, brings up the default Apache Index of / explorer. It looks like it is not finding the service to redirect.

The web app was published using dotnet publish --configuration Release and the publish/ directory was put inside the /var/www/ folder.
This is the webapp.service:

Following is the /etc/apache2/sites-available/dotnet.config:

Connecting to localhost or to the domain which is going to host it brings up this:

Connecting to localhost:5000, however, works just fine.

From Microsoft docs:

ASP.NET Core project templates use Kestrel by default when not hosted
with IIS.

I think maybe I am doing something wrong inside launchSettings.json?

I can't wrap my head around this, it's like I'm missing a little thing and I can't really figure out what it is.


问:
Why is the navigation page black after populating an object from a Json scan?
Good afternoon,

My first time posting after using this website for years, so I apologize for formatting and probably a dumb question I can't find the answer for... I am scanning a QR Code that contains the JSON format below and am trying to populate a "device details page" with the full object's data from the ZtdId value from the JSON received from the scanned code. The parameter passes along fine to the new page, but the screen will be black.

JSON Format:

```<code>{"Version":"1.0.0","Id":"5ca169f7-9e7b-4861-abf5-859cdb468f6e","ZtdId":"dfb0527f-64d1-4f78-85ff-50cd6fab7e6c","PKID":"","SerialNumber":"","SequenceBlockNumber":1,"TotalBlocks":1}
</code>```

Black navigated page example

I have a separate collectionview page that navigates to the same "device details page" and works fine. I've tried quite a number of combinations from the code referenced below in the hyperlink and across the internet, though, I can't get the page to load at all. I realized later in my fumbling that it wasn't loading the object and placed an "if the serialnumber is blank.." operator to connect it to the data.

I've even tried passing it to a blank or about page and it loads the page fine...What am I doing wrong here? (I can confirm if I write in a bunch of Console.WriteLine entries I can expose all the fields of the device I'm trying to load from the scanned code.) I've tried going through the "Xanimals" and many other sample solutions, from the sample github repositories, but can't seem to identify why the page comes up black.

https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation?view=net-maui-7.0#pass-data

Scan Page relevant code:

```<code>    async void BarcodesDetected(object sender, BarcodeDetectionEventArgs e)
    {
        try
        {
            var first = e.Results?.FirstOrDefault();
            if (first is not null)
            {
                Dispatcher.Dispatch(() =>
                {
                    barcodeGenerator.ClearValue(BarcodeGeneratorView.ValueProperty);
                    barcodeGenerator.Format = first.Format;
                    barcodeGenerator.Value = first.Value;
                });
            }
            string Json = JToken.Parse(e.Results[0].Value).ToString();
            Models.Device device = JsonConvert.DeserializeObject<Models.Device>(Json);
            var navigationParameters = new Dictionary<string, object>
            {
                { "Device", device }
            };
            await Shell.Current.GoToAsync($"devicedetails", navigationParameters);
        }
        catch (Exception)
        {

        }
    }
</code>```

Device Detail Page relevant code:

```<code>        public Models.Device Device { get; private set; }

        public void ApplyQueryAttributes(IDictionary<string, object> query)
        {
            Device = query["Device"] as Models.Device;
            if(String.IsNullOrEmpty(Device.SerialNumber))
            {
                Models.Device device = DeviceData.Devices.FirstOrDefault(a => a.ZtdId == Device.ZtdId);
                Device = device;
            }
            OnPropertyChanged("Device");
        }
</code>```

Device Example:

```<code>        public static IList<Models.Device> Devices { get; private set; }

        static DeviceData()
        {
            Devices = new List<Models.Device>
            {
                new Models.Device
                {
                    SerialNumber = "00-000001",
                    Manufacturer = "Dell, Inc.",
                    Model = "XPS 13 9360",
                    PurchaseOrderNumber = "",
                    GroupTag = "US-EST-001",
                    DeploymentProfile = "Hybrid AAD",
                    AddressableUserName = "Jane Doe",
                    UserPrincipalName = "janedoe@contoso.com",
                    ZtdId = "dfb0527f-64d1-4f78-85ff-50cd6fab7e6c",
                    AzureActiveDirectoryDeviceId = Guid.NewGuid().ToString(),
                    ManagedDeviceId = Guid.NewGuid().ToString()
                }
            };
        }
</code>```

Body:
Good afternoon,

My first time posting after using this website for years, so I apologize for formatting and probably a dumb question I can't find the answer for... I am scanning a QR Code that contains the JSON format below and am trying to populate a "device details page" with the full object's data from the ZtdId value from the JSON received from the scanned code. The parameter passes along fine to the new page, but the screen will be black.

JSON Format:

{"Version":"1.0.0","Id":"5ca169f7-9e7b-4861-abf5-859cdb468f6e","ZtdId":"dfb0527f-64d1-4f78-85ff-50cd6fab7e6c","PKID":"","SerialNumber":"","SequenceBlockNumber":1,"TotalBlocks":1}

Black navigated page example

I have a separate collectionview page that navigates to the same "device details page" and works fine. I've tried quite a number of combinations from the code referenced below in the hyperlink and across the internet, though, I can't get the page to load at all. I realized later in my fumbling that it wasn't loading the object and placed an "if the serialnumber is blank.." operator to connect it to the data.

I've even tried passing it to a blank or about page and it loads the page fine...What am I doing wrong here? (I can confirm if I write in a bunch of Console.WriteLine entries I can expose all the fields of the device I'm trying to load from the scanned code.) I've tried going through the "Xanimals" and many other sample solutions, from the sample github repositories, but can't seem to identify why the page comes up black.

https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/shell/navigation?view=net-maui-7.0#pass-data

Scan Page relevant code:

    async void BarcodesDetected(object sender, BarcodeDetectionEventArgs e)
    {
        try
        {
            var first = e.Results?.FirstOrDefault();
            if (first is not null)
            {
                Dispatcher.Dispatch(() =>
                {
                    barcodeGenerator.ClearValue(BarcodeGeneratorView.ValueProperty);
                    barcodeGenerator.Format = first.Format;
                    barcodeGenerator.Value = first.Value;
                });
            }
            string Json = JToken.Parse(e.Results[0].Value).ToString();
            Models.Device device = JsonConvert.DeserializeObject<Models.Device>(Json);
            var navigationParameters = new Dictionary<string, object>
            {
                { "Device", device }
            };
            await Shell.Current.GoToAsync($"devicedetails", navigationParameters);
        }
        catch (Exception)
        {

        }
    }

Device Detail Page relevant code:

        public Models.Device Device { get; private set; }

        public void ApplyQueryAttributes(IDictionary<string, object> query)
        {
            Device = query["Device"] as Models.Device;
            if(String.IsNullOrEmpty(Device.SerialNumber))
            {
                Models.Device device = DeviceData.Devices.FirstOrDefault(a => a.ZtdId == Device.ZtdId);
                Device = device;
            }
            OnPropertyChanged("Device");
        }

Device Example:

        public static IList<Models.Device> Devices { get; private set; }

        static DeviceData()
        {
            Devices = new List<Models.Device>
            {
                new Models.Device
                {
                    SerialNumber = "00-000001",
                    Manufacturer = "Dell, Inc.",
                    Model = "XPS 13 9360",
                    PurchaseOrderNumber = "",
                    GroupTag = "US-EST-001",
                    DeploymentProfile = "Hybrid AAD",
                    AddressableUserName = "Jane Doe",
                    UserPrincipalName = "janedoe@contoso.com",
                    ZtdId = "dfb0527f-64d1-4f78-85ff-50cd6fab7e6c",
                    AzureActiveDirectoryDeviceId = Guid.NewGuid().ToString(),
                    ManagedDeviceId = Guid.NewGuid().ToString()
                }
            };
        }


问:
Does Heroku preboot halts the rollout if the newly created dynos fail to serve successful requests?
From Heroku preboot docs:

When you make releases with preboot, Heroku switches the routing from the old dyno to the new dyno at one point. It is possible to have a very short time overlap where the requests go to both dynos during the switchover.

Instead of stopping the existing set of web dynos before starting the new ones, preboot ensures that the new web dynos are started (and receive traffic) before the existing ones are terminated.

I couldn't find anywhere stating if the new dynos need to be healthy (serving successful requests) before the rollout successfully completes or what happens otherwise.

Documentation: https://devcenter.heroku.com/articles/preboot


问:
Is there a tool to lock cookiecutter template files
I've been using cruft and cookiecutter to allow users to get default configuration files. From time to time those files are changing and I want the users to run cruft upgrade. But in order to do so I want to disable them from editing those files so the upgrade process would be clean and the files would include only what I want.

Is there an existing tool that does that? maybe locks the files for future editing?

Thanks !


问:
Rename file in Jira script editor problem error: File doesn't exist on the server filesystem

I am using the Jira script editor and I just want to change the name of my file from CreateMultipleSubtasks/scriptFragment_Condition_CreateMultipleSubtasks.groovy to a new name: CreateMultipleSubtasks/scriptFragment_condition_CreateMultipleSubtasks.groovy

The only change is to make the C of the condition word smaller and I receive the error message shown above. I have no idea why. I have right clicked on my file in ths script editor and I have chosen the option rename and I get this error. Anyone knows how to change the upper case C to a lower case c in the script editor of Jira?


问:
Keycloak 401 (Unauthorized) Angular
I'm trying to set up a keylock with angular.
Everything works if in the keycloak admin panel I don't select settings "Access settings
" --> "Root URL" and "Home URL" in my client's settings.
If they are selected, then I get an error "error", I attach a screenshot of the settings and the code too

enter image description here

Initialize funktion

```<code>import { KeycloakService } from 'keycloak-angular'

export function initializeKeycloak(keycloak: KeycloakService) {
  return () =>
    keycloak.init({
      config: {
        url: 'http://localhost:8080',
        realm: 'cld_poc',
        clientId: 'keycloak-express',
      },
      loadUserProfileAtStartUp: true,
      initOptions: {
        onLoad: 'login-required',
        pkceMethod: 'S256',
        checkLoginIframe: false,
      },
    })
}

</code>```

Auth guard

```<code>import { Injectable } from '@angular/core'
import {
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  Router,
} from '@angular/router'
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular'

@Injectable({
  providedIn: 'root',
})
export class AuthGuard extends KeycloakAuthGuard {
  constructor(
    protected override readonly router: Router,
    protected readonly keycloak: KeycloakService
  ) {
    super(router, keycloak)
  }

  async isAccessAllowed(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean | UrlTree> {
    if (!this.authenticated) {
      await this.keycloak.login({
        redirectUri: window.location.origin + state.url,
      })
    }

    const requiredRoles = route.data['roles']

    if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
      return true
    }

    // return this.authenticated
    return requiredRoles.every((role) => this.roles.includes(role))
  }
}

</code>```

router

```<code>const routes: Routes = [
  {
    path: '',
    component: MediaLibraryComponent,
    canActivate: [AuthGuard],
  },
...
]
</code>```

app module

```<code>@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    KeycloakAngularModule,
  ],
  providers: [
    ...
    {
      provide: APP_INITIALIZER,
      useFactory: initializeKeycloak,
      multi: true,
      deps: [KeycloakService],
    },
  ],
  bootstrap: [AppComponent],
})
</code>```

enter image description here

everything I tried I described above.
I rummaged all over Google and stackoverflow in search of a problem, so I decided to write personally.

Title: Keycloak 401 (Unauthorized) Angular

Body:
I'm trying to set up a keylock with angular.
Everything works if in the keycloak admin panel I don't select settings "Access settings
" --> "Root URL" and "Home URL" in my client's settings.
If they are selected, then I get an error "error", I attach a screenshot of the settings and the code too

enter image description here

Initialize funktion

import { KeycloakService } from 'keycloak-angular'

export function initializeKeycloak(keycloak: KeycloakService) {
  return () =>
    keycloak.init({
      config: {
        url: 'http://localhost:8080',
        realm: 'cld_poc',
        clientId: 'keycloak-express',
      },
      loadUserProfileAtStartUp: true,
      initOptions: {
        onLoad: 'login-required',
        pkceMethod: 'S256',
        checkLoginIframe: false,
      },
    })
}

Auth guard

import { Injectable } from '@angular/core'
import {
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  Router,
} from '@angular/router'
import { KeycloakAuthGuard, KeycloakService } from 'keycloak-angular'

@Injectable({
  providedIn: 'root',
})
export class AuthGuard extends KeycloakAuthGuard {
  constructor(
    protected override readonly router: Router,
    protected readonly keycloak: KeycloakService
  ) {
    super(router, keycloak)
  }

  async isAccessAllowed(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Promise<boolean | UrlTree> {
    if (!this.authenticated) {
      await this.keycloak.login({
        redirectUri: window.location.origin + state.url,
      })
    }

    const requiredRoles = route.data['roles']

    if (!(requiredRoles instanceof Array) || requiredRoles.length === 0) {
      return true
    }

    // return this.authenticated
    return requiredRoles.every((role) => this.roles.includes(role))
  }
}

router

const routes: Routes = [
  {
    path: '',
    component: MediaLibraryComponent,
    canActivate: [AuthGuard],
  },
...
]

app module

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    ...
    KeycloakAngularModule,
  ],
  providers: [
    ...
    {
      provide: APP_INITIALIZER,
      useFactory: initializeKeycloak,
      multi: true,
      deps: [KeycloakService],
    },
  ],
  bootstrap: [AppComponent],
})

enter image description here

everything I tried I described above.
I rummaged all over Google and stackoverflow in search of a problem, so I decided to write personally.


问:
Next.JS - You may need an additional loader to handle the result of these loaders
Seemingly out of nowhere, nothing was updated, this started happening -

```<code>ModuleParseError: Module parse failed: Identifier '_util' has already been declared (35:6)
File was processed with these loaders:
 * ./node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
You may need an additional loader to handle the result of these loaders.
| const _store = require("../shared/store");
| const _api = require("../shared/util/api");
> const _util = require("../shared/util");
| const Home = ({ homeData  })=>{
|     const router = (0, _router.useRouter)();

This error happened while generating the page. Any console logs will be displayed in the terminal window.
</code>```

I have two imports from two util folders in different locations, that's what it seems to complain about. But, worse yet, when I comment one of the imports, it started complaining about seemingly other random things.

I tried clearing node_modules and deleted yarn.lock and also ran yarn cache clean and it changed nothing. Updated all dependencies to their latest versions, reverted to exact versions from last known successful build - nothing. A bit of googling suggested I might've needed to change my tsconfig.json to export a more "browser friendly" ES version. Tried a few, no change. Tried a few other configuration changes, nothing. I even upgraded Node from 16 to 18, thinking... I don't know what I was thinking. I have no idea what's happening or why.

Distraught, I tried yarn build, everything seems fine. Pushed it to Vercel, it works great! But locally, with yarn dev this is still what I see. What could've happened on my local environment that would cause something like this? HELP!

Thank you!

Body:
Seemingly out of nowhere, nothing was updated, this started happening -

ModuleParseError: Module parse failed: Identifier '_util' has already been declared (35:6)
File was processed with these loaders:
 * ./node_modules/next/dist/build/webpack/loaders/next-swc-loader.js
You may need an additional loader to handle the result of these loaders.
| const _store = require("../shared/store");
| const _api = require("../shared/util/api");
> const _util = require("../shared/util");
| const Home = ({ homeData  })=>{
|     const router = (0, _router.useRouter)();

This error happened while generating the page. Any console logs will be displayed in the terminal window.

I have two imports from two util folders in different locations, that's what it seems to complain about. But, worse yet, when I comment one of the imports, it started complaining about seemingly other random things.

I tried clearing node_modules and deleted yarn.lock and also ran yarn cache clean and it changed nothing. Updated all dependencies to their latest versions, reverted to exact versions from last known successful build - nothing. A bit of googling suggested I might've needed to change my tsconfig.json to export a more "browser friendly" ES version. Tried a few, no change. Tried a few other configuration changes, nothing. I even upgraded Node from 16 to 18, thinking... I don't know what I was thinking. I have no idea what's happening or why.

Distraught, I tried yarn build, everything seems fine. Pushed it to Vercel, it works great! But locally, with yarn dev this is still what I see. What could've happened on my local environment that would cause something like this? HELP!

Thank you!


问:
objects as value of parameters which are used in other functions,can not found in device by using OpenACC
I use OpenACC to improve the performance of c++ code running.

In the code files I create Array2D class for data updating.

When I compiled the code file,there are some warning information from some parts of code files.

I found some Array2D objects as value of parameters which are used in other functions,can not found in device.

for example:

```<code>WatershedAlg::thresholdMeasure(cv::Mat &, Array2D<int> &):
     16, Generating enter data copyin(startImg[:imgcols*imgrows],threshmat->matImg[:imgrows][:imgcols],threshmat[:1],startImg[:1])
         Accelerator clause: upper bound for dimension 0 of array 'startImg' is unknown
         Generating NVIDIA GPU code
         19, #pragma acc loop gang, vector(128) /* blockIdx.x threadIdx.x */
         20, #pragma acc loop seq
     16, Generating default present(startImg[:],threshmat)
     20, Complex loop carried dependence of startImg->,threshmat-> prevents parallelization
     23, Generating update self(threshmat->matImg[:imgrows][:imgcols])
         Generating exit data delete(startImg[:imgcols*imgrows])
Array2D<int>::operator ()(int, int):
      1, include "WatershedAlg.h"
           3, include "buffer.cpp"
               23, Generating implicit acc routine seq
                   Generating acc routine seq
                   Generating NVIDIA GPU code

Error Information when I executed the bin file a.out
hostptr=0x7ffc65e55790,eltsize=8,name=rows,flags=0x20000200=present+implicit,async=-1,threadid=1
Present table dump for device[1]: NVIDIA Tesla GPU 0, compute capability 8.6, threadid=1
host:0x7ffc65e55638 device:0x7f44636fa200 size:16 presentcount:0+1 line:5 name:threshMat
host:0x7ffc65e556c8 device:0x7f44636fa000 size:16 presentcount:0+1 line:16 name:threshmat
allocated block device:0x7f44636fa000 size:512 thread:1
allocated block device:0x7f44636fa200 size:512 thread:1
deleted block   device:0x7f3906a00000 size:3232256 threadid=1
deleted block   device:0x7f3906000000 size:9695744 threadid=1
FATAL ERROR: data in PRESENT clause was not found on device 1: name=rows host:0x7ffc65e55790
 file:../functionspace/antiInverseImage.cpp _ZN12WatershedAlg16antiInverseImageER7Array2DIiERiS3_ line:5
</code>```

I don't know why the error comes out.

I have a old version which only include the Mat object from openCV ,the old version works.

Please review the source code ,here is the link of the whole project files:
reference link

And about the compiling command ,please take a look at the file 'pgpp24.sh' in execution file link

If someone could provide hints or any suggestions,I will appreciate that.

Thanks in advance!

Body:
I use OpenACC to improve the performance of c++ code running.

In the code files I create Array2D class for data updating.

When I compiled the code file,there are some warning information from some parts of code files.

I found some Array2D objects as value of parameters which are used in other functions,can not found in device.

for example:

WatershedAlg::thresholdMeasure(cv::Mat &, Array2D<int> &):
     16, Generating enter data copyin(startImg[:imgcols*imgrows],threshmat->matImg[:imgrows][:imgcols],threshmat[:1],startImg[:1])
         Accelerator clause: upper bound for dimension 0 of array 'startImg' is unknown
         Generating NVIDIA GPU code
         19, #pragma acc loop gang, vector(128) /* blockIdx.x threadIdx.x */
         20, #pragma acc loop seq
     16, Generating default present(startImg[:],threshmat)
     20, Complex loop carried dependence of startImg->,threshmat-> prevents parallelization
     23, Generating update self(threshmat->matImg[:imgrows][:imgcols])
         Generating exit data delete(startImg[:imgcols*imgrows])
Array2D<int>::operator ()(int, int):
      1, include "WatershedAlg.h"
           3, include "buffer.cpp"
               23, Generating implicit acc routine seq
                   Generating acc routine seq
                   Generating NVIDIA GPU code

Error Information when I executed the bin file a.out
hostptr=0x7ffc65e55790,eltsize=8,name=rows,flags=0x20000200=present+implicit,async=-1,threadid=1
Present table dump for device[1]: NVIDIA Tesla GPU 0, compute capability 8.6, threadid=1
host:0x7ffc65e55638 device:0x7f44636fa200 size:16 presentcount:0+1 line:5 name:threshMat
host:0x7ffc65e556c8 device:0x7f44636fa000 size:16 presentcount:0+1 line:16 name:threshmat
allocated block device:0x7f44636fa000 size:512 thread:1
allocated block device:0x7f44636fa200 size:512 thread:1
deleted block   device:0x7f3906a00000 size:3232256 threadid=1
deleted block   device:0x7f3906000000 size:9695744 threadid=1
FATAL ERROR: data in PRESENT clause was not found on device 1: name=rows host:0x7ffc65e55790
 file:../functionspace/antiInverseImage.cpp _ZN12WatershedAlg16antiInverseImageER7Array2DIiERiS3_ line:5

I don't know why the error comes out.

I have a old version which only include the Mat object from openCV ,the old version works.

Please review the source code ,here is the link of the whole project files:
reference link

And about the compiling command ,please take a look at the file 'pgpp24.sh' in execution file link

If someone could provide hints or any suggestions,I will appreciate that.

Thanks in advance!


问:
Compare a row with another rows with similar and partially similar value in same dataframe and set value to new column
I have a csv dataset like this

Dataset

I need to assign a new value GP to SP, indicating follow-up from the general clinic to the specialist. The way is by comparing each row with another similar row based on ID Number and Visit Date.

The condition for a true gp_to_sp is something like this

Diagnosis(b) equal to or partially equal to Diagnosis (a)

Panel(b) is SP and Panel(a) is GP

CODE 1

```<code>df['Visit Date'] = pd.to_datetime(df['Visit Date'])

def gp_to_sp(g):
    return (
        (g['Diagnosis'] == g['Diagnosis'].shift()) &
        (g['Panel'] == 'Panel SP') &
        (g['Panel'].shift() == 'Panel GP')
    )
newdf = df.assign(gp_to_sp=df.groupby('ID Number').apply(gp_to_sp).droplevel(0))
</code>```

Output

Output

Currently, my code above is working but as you can see, the visit ID (7) for ID Number (1002) is falsely flagged as False because the Diagnosis between Visit ID (2) and Visit ID (7) is not exactly same (only partially same). The correct value should be True as the patient visit SP from GP but only to treat his Back Pain.

CODE 2

I tried to use str.contains() function like example below but got ‘unhashable type: Series ‘error. Probably because g['Diagnosis'].shift() is series obj not string.

```<code>def gp_to_sp(g):
    return (
        (g['Diagnosis'].str.contains(g['Diagnosis'].shift())) &
        (g['Panel'] == 'Panel SP') &
        (g['Panel'].shift() == 'Panel GP')
    )

newdf = df.assign(gp_to_sp=df.groupby('ID Number').apply(gp_to_sp).droplevel(0))

</code>```

Is there any solution for this?

Body:
I have a csv dataset like this

Dataset

I need to assign a new value GP to SP, indicating follow-up from the general clinic to the specialist. The way is by comparing each row with another similar row based on ID Number and Visit Date.

The condition for a true gp_to_sp is something like this

Diagnosis(b) equal to or partially equal to Diagnosis (a)

Panel(b) is SP and Panel(a) is GP

CODE 1

df['Visit Date'] = pd.to_datetime(df['Visit Date'])

def gp_to_sp(g):
    return (
        (g['Diagnosis'] == g['Diagnosis'].shift()) &
        (g['Panel'] == 'Panel SP') &
        (g['Panel'].shift() == 'Panel GP')
    )
newdf = df.assign(gp_to_sp=df.groupby('ID Number').apply(gp_to_sp).droplevel(0))

Output

Output

Currently, my code above is working but as you can see, the visit ID (7) for ID Number (1002) is falsely flagged as False because the Diagnosis between Visit ID (2) and Visit ID (7) is not exactly same (only partially same). The correct value should be True as the patient visit SP from GP but only to treat his Back Pain.

CODE 2

I tried to use str.contains() function like example below but got ‘unhashable type: Series ‘error. Probably because g['Diagnosis'].shift() is series obj not string.

def gp_to_sp(g):
    return (
        (g['Diagnosis'].str.contains(g['Diagnosis'].shift())) &
        (g['Panel'] == 'Panel SP') &
        (g['Panel'].shift() == 'Panel GP')
    )

newdf = df.assign(gp_to_sp=df.groupby('ID Number').apply(gp_to_sp).droplevel(0))

Is there any solution for this?


问:
How to get left or right node in tsearch node
I used the example (exactly that example) given here: https://man7.org/linux/man-pages/man3/tsearch.3.html

But I could not use LEFT macro or struct node_t struct. I just want to move left or right node by myself because I need to check the tree created by tsearch if it is full tree, or balanced or ccomplete etc.

While using LEFT, I am getting implicit declaration error, with struct node_t I am getting dereferencing pointer to incomplete type.

How can I move to left or right child by myself? Is there any way to check the tree created by tsearch is balanced or not (e.g.)

Thanks

I checked search.c source code, found some macros but cannot use them because of compiling errors


问:
is there a library that helps calculating the wavelength from a graph created in csv file?
I did a physics test wavelength and needed to
calculate the wavelength from the .csv file. where I collected data on a spreadsheet.

do you know about any tools/libraries that can help me calculate the wavelength of the wave?

how can I calculate the wavelength with python or a different language?


问:
Using a multi-region S3 accesspoint with sagemaker (terraform)
I have a sagemaker model that will be deployed in different aws regions. This model will download models from an s3 bucket that is in region x. As long as the model is deployed in region x, the endpoint works.
However, when I deploy the sagemaker model from region y, it fails with the message.

Error: error creating SageMaker model: ValidationException: Could not
access model data at s3://mmmm/. Please ensure that the role
"arn:aws:iam::xxxx:role/dev-xxx-iam-role" exists and that its trust
relationship policy allows the action "sts:AssumeRole" for the service
principal "sagemaker.amazonaws.com". Also ensure that the role has
"s3:GetObject" permissions and that the object is located in region x.

My iam role permissions are as follows:

```<code>resource "aws_iam_policy_attachment" "sm_full_access_attach" {
  name       = "sm-full-access-attachment"
  roles      = [aws_iam_role.sagemaker_inferencer_iam_role.name]
  policy_arn = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"
}

resource "aws_iam_policy_attachment" "s3_full_access_attach" {
  name       = "s3-full-access-attachment"
  roles      = [aws_iam_role.sagemaker_inferencer_iam_role.name]
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
}
</code>```

with the assume role policy of:

```<code>data "aws_iam_policy_document" "sm_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["sagemaker.amazonaws.com"]
    }
  }
}
</code>```

The iam role is as follows:

```<code>resource "aws_iam_role" "sagemaker_inferencer_iam_role" {
  name               = "${var.app_environment}-inferencer-sm-${var.aws_region}-iam-role"
  assume_role_policy = data.aws_iam_policy_document.sm_assume_role_policy.json
}
</code>```

And the above works for same region buckets.

I can of course create have buckets in each region with replication rules from the original bucket. However, this is costly as the model files are huge. So I created a multi-region accesspoint for my original bucket with an alias zzz.mrap

However, when I specify the accesspoint alias in the aws_sagemaker_model resource as follows:

```<code>resource "aws_sagemaker_model" "sagemaker_multimodel" {
  name               = "${var.app_environment}-inferencer-sm-${var.aws_region}-model"
  execution_role_arn = aws_iam_role.sagemaker_inferencer_iam_role.arn

  primary_container {
    image          = local.multi_model_inferencer_container_name
    mode           = "MultiModel"
    model_data_url = "s3://zzz.mrap/"
  }
}
</code>```

I get the following error:

Error: error creating SageMaker model: ValidationException: Could not
access model data at s3://zzzz.mrap/. Please ensure that the role
"arn:aws:iam::878435376106:role/dev-xxx-iam-role" exists and that its
trust relationship policy allows the action "sts:AssumeRole" for the
service principal "sagemaker.amazonaws.com". Also ensure that the role
has "s3:GetObject" permissions and that the object is located in
region x.

AWS says that I only have to replace the bucket name by the alias and that they support sagemaker, however this does not seem to be the case.

What am I doing wrong?

Body:
I have a sagemaker model that will be deployed in different aws regions. This model will download models from an s3 bucket that is in region x. As long as the model is deployed in region x, the endpoint works.
However, when I deploy the sagemaker model from region y, it fails with the message.

Error: error creating SageMaker model: ValidationException: Could not
access model data at s3://mmmm/. Please ensure that the role
"arn:aws:iam::xxxx:role/dev-xxx-iam-role" exists and that its trust
relationship policy allows the action "sts:AssumeRole" for the service
principal "sagemaker.amazonaws.com". Also ensure that the role has
"s3:GetObject" permissions and that the object is located in region x.

My iam role permissions are as follows:

resource "aws_iam_policy_attachment" "sm_full_access_attach" {
  name       = "sm-full-access-attachment"
  roles      = [aws_iam_role.sagemaker_inferencer_iam_role.name]
  policy_arn = "arn:aws:iam::aws:policy/AmazonSageMakerFullAccess"
}

resource "aws_iam_policy_attachment" "s3_full_access_attach" {
  name       = "s3-full-access-attachment"
  roles      = [aws_iam_role.sagemaker_inferencer_iam_role.name]
  policy_arn = "arn:aws:iam::aws:policy/AmazonS3FullAccess"
}

with the assume role policy of:

data "aws_iam_policy_document" "sm_assume_role_policy" {
  statement {
    actions = ["sts:AssumeRole"]

    principals {
      type        = "Service"
      identifiers = ["sagemaker.amazonaws.com"]
    }
  }
}

The iam role is as follows:

resource "aws_iam_role" "sagemaker_inferencer_iam_role" {
  name               = "${var.app_environment}-inferencer-sm-${var.aws_region}-iam-role"
  assume_role_policy = data.aws_iam_policy_document.sm_assume_role_policy.json
}

And the above works for same region buckets.

I can of course create have buckets in each region with replication rules from the original bucket. However, this is costly as the model files are huge. So I created a multi-region accesspoint for my original bucket with an alias zzz.mrap

However, when I specify the accesspoint alias in the aws_sagemaker_model resource as follows:

resource "aws_sagemaker_model" "sagemaker_multimodel" {
  name               = "${var.app_environment}-inferencer-sm-${var.aws_region}-model"
  execution_role_arn = aws_iam_role.sagemaker_inferencer_iam_role.arn

  primary_container {
    image          = local.multi_model_inferencer_container_name
    mode           = "MultiModel"
    model_data_url = "s3://zzz.mrap/"
  }
}

I get the following error:

Error: error creating SageMaker model: ValidationException: Could not
access model data at s3://zzzz.mrap/. Please ensure that the role
"arn:aws:iam::878435376106:role/dev-xxx-iam-role" exists and that its
trust relationship policy allows the action "sts:AssumeRole" for the
service principal "sagemaker.amazonaws.com". Also ensure that the role
has "s3:GetObject" permissions and that the object is located in
region x.

AWS says that I only have to replace the bucket name by the alias and that they support sagemaker, however this does not seem to be the case.

What am I doing wrong?


问:
Lists from a data table aren't being traversed and displayed properly- what's going wrong?
Working on a project in AppLab in Code.org, and I'm trying to traverse and display individual elements of a data table one at a time. The user hits the next button, and it should display the next cat name and image, and when they hit the back button, it goes to the previous cat's info. However, it is displaying the entire list of cat names in the text box, and the setImageURL command isn't working.

```<code>//declare variables
var catName = [getColumn("Cats", "Name")];
var catTemper = [getColumn("Cats", "Temperament")];
var catImage = [getColumn("Cats", "Image")];
var index = 0;
</code>```
```<code>    //Traversing/filtering the lists when the back or next button is chosen
    //next button
    onEvent("nextCatButton", "click", function( ) {
       if(index < (catName.length - 1)) {
         index = index + 1;
       }
      updateScreen();
    });
    //back button
    onEvent("backCatButton", "click", function( ) {
        if(index > 0){
          index = index - 1;
        }
      updateScreen();
    });
    ```

    ```
    //function to display cat name and image on screen 2
    function updateScreen() {
      setText("nameOutput1", catName[index]);
      setImageURL("imageOutput", catImage[index]);
     }
</code>```

I originally tried filtering with a for loop and appending to a filtered list, but switched to using indexes as I thought it would be simpler.

Body:
Working on a project in AppLab in Code.org, and I'm trying to traverse and display individual elements of a data table one at a time. The user hits the next button, and it should display the next cat name and image, and when they hit the back button, it goes to the previous cat's info. However, it is displaying the entire list of cat names in the text box, and the setImageURL command isn't working.

//declare variables
var catName = [getColumn("Cats", "Name")];
var catTemper = [getColumn("Cats", "Temperament")];
var catImage = [getColumn("Cats", "Image")];
var index = 0;

    //Traversing/filtering the lists when the back or next button is chosen
    //next button
    onEvent("nextCatButton", "click", function( ) {
       if(index < (catName.length - 1)) {
         index = index + 1;
       }
      updateScreen();
    });
    //back button
    onEvent("backCatButton", "click", function( ) {
        if(index > 0){
          index = index - 1;
        }
      updateScreen();
    });
    ```

    ```
    //function to display cat name and image on screen 2
    function updateScreen() {
      setText("nameOutput1", catName[index]);
      setImageURL("imageOutput", catImage[index]);
     }

I originally tried filtering with a for loop and appending to a filtered list, but switched to using indexes as I thought it would be simpler.


问:
How to create a Loop using get_All_tweets (AcademictwitterR)
`Hello developers!

Please help me (baby programmer) create a chunk of code in R, where I need to scrape tweet using specific cash tags (S&P500) and stack the data vertically in a data frame. I am interested to collect tweets associated with those Cashtags.

lower <- "2022-08-01T00:00:01Z"
upper <- "2022-12-01T00:00:01Z"
Ctags <- SP_500$Cashtags*
t0 <- as.data.frame(matrix(rep(1,23), nrow = 1, ncol= 23))
t1 <- t0
twt <- t0

for (i in Ctags){
t1 <- as.data.frame(get_all_tweets(Ctags[i],start_tweets = lower, end_tweets =  upper ,bearer_token = Bearer_Token, n = 1, file = "TweetSTrail"))
colnames(twt) <- colnames(t1)
twt <- rbind(twt,t1)
}

I am trying to collect tweets for the certain time interval associated with those cash tags. Since there are +500 cashtags, i thought a for loop would be ideal to scrape data and stack them vertically in a data.frame`


问:
frameless tkinter app not showing when using alt + tab on windows
I have a tkinter app that I want to be frameless. This is quite easily done by adding

```<code>app.overridedirect(True)
</code>```

during the setup process. Once I do that, though, the app stops showing app in the task switcher. So, when pressing alt + tab I cannot see the app or switch to it. All the other apps show up fine and when I set overridedirect to False the tkinter app shows up again. Is there a way to fix that behaviour so I can see the app in the task switcher even without a frame?

Body:
I have a tkinter app that I want to be frameless. This is quite easily done by adding

app.overridedirect(True)

during the setup process. Once I do that, though, the app stops showing app in the task switcher. So, when pressing alt + tab I cannot see the app or switch to it. All the other apps show up fine and when I set overridedirect to False the tkinter app shows up again. Is there a way to fix that behaviour so I can see the app in the task switcher even without a frame?


问:
AWS S3 Restore S3 Glacier Flexible Retrieval storage to S3 Standard, S3 Intelligent-Tiering, S3 Standard-IA, S3 One Zone-IA
I am trying to understand aws s3 object transitioning across various storage classes, and I am using https://docs.aws.amazon.com/AmazonS3/latest/userguide/lifecycle-transition-general-considerations.html to go through details, however I find this confusing. Below is what I am trying to understand

as per this document and nice image provided on this page says that -

"Amazon S3 supports a waterfall model for transitioning between storage classes, as shown in the following diagram.".

For example, object from:
S3 Standard can be transitioned to any of --> Standard IA, Intelligent Tiering, One Zone IA, Glacier Instant, Glacier Flexible , Glacier Deep.
Which means reverse explicit transitioning is not possible

However, on same page it then says

"If you want to change the storage class of an object that is stored in S3 Glacier Flexible Retrieval to a storage class other than S3 Glacier Deep Archive, you must use the restore operation to make a temporary copy of the object first. Then use the copy operation to overwrite the object specifying S3 Standard, S3 Intelligent-Tiering, S3 Standard-IA, S3 One Zone-IA, or Reduced Redundancy as the storage class."

Here confusing part is that it shows option of overwrite the storage class (off course after restoring copy), to S3 Intelligent-Tiering, S3 Standard-IA, S3 One Zone-IA

Confusion is that - how does the aws treat this "restored" object as - a new object ? or existing object?
if it treats this as a "new" object - how can it transition directly to S3 Intelligent-Tiering, S3 Standard-IA, S3 One Zone-IA ? this contradicts to waterfall rule that they have mentioned

Thank you.

My expectation from this was that if object should be transitioned to say One Zone IA , the restored object should be first only treated as S3 Standard object - wait for 30 days and then should allow transition to S3 One Zone IA.


问:
Blazor Client Debug Breakpoint shows Message not found error
Im'trying to debug a Blazor WebAssembly app using VisualStudio 2022. Everytime I launch the app with a breakpoint activated, it shows like this:

I have checked that the inspectUri attribute is setted in launchSettings.json. There is no error in the output window of VS.

Any idea what may be happening?

Thank you.