问:
Filter in column based on word?
I need to filter out values from a column based on true/false information

example below.

Column A
Column B

Cell 1
Cell 2

Cell 3
Cell 4

Where
cell 2 = {"rnd": false, "sales": true, "customer": false, "management": false, "production": true, "shared_services": false, "national_directorate": false}

cell 4 = {"rnd": true, "sales": false, "customer": true, "management": false, "production": false, "shared_services": false, "national_directorate": false}

I need to have result as this

cell 1 = sales, production
cell 3 = rnd, customer

I was thinking about usage of regexp for this case, but as a newbie I don't even know where to start.

I tried this, but it seems to be to much complicated.

```<code>SELECT
*,
  trim (venture,',') as venture,
FROM (
  SELECT
    *,
    CONCAT(a,', ',b,' ',c,' ',d,' ',e,' ',f,' ',g) AS venture,
  FROM (
    SELECT
      *,
      CASE
        WHEN REGEXP_CONTAINS(rnd, r"((?i).*true).*") THEN "R&D"
      ELSE
      ""
    END
      AS a,
      CASE
        WHEN REGEXP_CONTAINS(sal, r"((?i).*true).*") THEN "Sales"
      ELSE
      ""
    END
      AS b,
      CASE
        WHEN REGEXP_CONTAINS(cus, r"((?i).*true).*") THEN "Customer"
      ELSE
      ""
    END
      AS c,
      CASE
        WHEN REGEXP_CONTAINS(man, r"((?i).*true).*") THEN "Management"
      ELSE
      ""
    END
      AS d,
      CASE
        WHEN REGEXP_CONTAINS(pro, r"((?i).*true).*") THEN "Production"
      ELSE
      ""
    END
      AS e,
      CASE
        WHEN REGEXP_CONTAINS(sha, r"((?i).*true).*") THEN "Shared Service"
      ELSE
      ""
    END
      AS f,
      CASE
        WHEN REGEXP_CONTAINS(nat, r"((?i).*true).*") THEN "National Directorate"
      ELSE
      ""
    END
      AS g,
    FROM (
      SELECT
        *,
        split (actsim,
          ',')[
      OFFSET
        (0)] AS rnd,
        split (actsim,
          ',')[
      OFFSET
        (1)] AS sal,
        split (actsim,
          ',')[
      OFFSET
        (2)] AS cus,
        split (actsim,
          ',')[
      OFFSET
        (3)] AS man,
        split (actsim,
          ',')[
      OFFSET
        (4)] AS pro,
        split (actsim,
          ',')[
      OFFSET
        (5)] AS sha,
        split (actsim,
          ',')[
      OFFSET
        (6)] AS nat,
      FROM (
        SELECT
          *,

          REPLACE (REPLACE(activity, "{",""),"}","") AS actsim,
        FROM (source)
</code>```

Title: Filter in column based on word?

Body:
I need to filter out values from a column based on true/false information

example below.

Column A
Column B

Cell 1
Cell 2

Cell 3
Cell 4

Where
cell 2 = {"rnd": false, "sales": true, "customer": false, "management": false, "production": true, "shared_services": false, "national_directorate": false}

cell 4 = {"rnd": true, "sales": false, "customer": true, "management": false, "production": false, "shared_services": false, "national_directorate": false}

I need to have result as this

cell 1 = sales, production
cell 3 = rnd, customer

I was thinking about usage of regexp for this case, but as a newbie I don't even know where to start.

I tried this, but it seems to be to much complicated.

SELECT
*,
  trim (venture,',') as venture,
FROM (
  SELECT
    *,
    CONCAT(a,', ',b,' ',c,' ',d,' ',e,' ',f,' ',g) AS venture,
  FROM (
    SELECT
      *,
      CASE
        WHEN REGEXP_CONTAINS(rnd, r"((?i).*true).*") THEN "R&D"
      ELSE
      ""
    END
      AS a,
      CASE
        WHEN REGEXP_CONTAINS(sal, r"((?i).*true).*") THEN "Sales"
      ELSE
      ""
    END
      AS b,
      CASE
        WHEN REGEXP_CONTAINS(cus, r"((?i).*true).*") THEN "Customer"
      ELSE
      ""
    END
      AS c,
      CASE
        WHEN REGEXP_CONTAINS(man, r"((?i).*true).*") THEN "Management"
      ELSE
      ""
    END
      AS d,
      CASE
        WHEN REGEXP_CONTAINS(pro, r"((?i).*true).*") THEN "Production"
      ELSE
      ""
    END
      AS e,
      CASE
        WHEN REGEXP_CONTAINS(sha, r"((?i).*true).*") THEN "Shared Service"
      ELSE
      ""
    END
      AS f,
      CASE
        WHEN REGEXP_CONTAINS(nat, r"((?i).*true).*") THEN "National Directorate"
      ELSE
      ""
    END
      AS g,
    FROM (
      SELECT
        *,
        split (actsim,
          ',')[
      OFFSET
        (0)] AS rnd,
        split (actsim,
          ',')[
      OFFSET
        (1)] AS sal,
        split (actsim,
          ',')[
      OFFSET
        (2)] AS cus,
        split (actsim,
          ',')[
      OFFSET
        (3)] AS man,
        split (actsim,
          ',')[
      OFFSET
        (4)] AS pro,
        split (actsim,
          ',')[
      OFFSET
        (5)] AS sha,
        split (actsim,
          ',')[
      OFFSET
        (6)] AS nat,
      FROM (
        SELECT
          *,

          REPLACE (REPLACE(activity, "{",""),"}","") AS actsim,
        FROM (source)


来源: stackexchange

问:
Unable to find an entry point named 'OrtGetApiBase' in DLL 'onnxruntime'
First of all I made a ML python model and then convert it to .onnx extention file by following step. and then i downloaded this .onnx extension file and put this my Controllers folder.I am using .NET Core Version 6 API and then i install some package:-  [I am actually followed this article]

```<code>"Microsoft.ML" Version="2.0.0"
"Microsoft.ML.OnnxRuntime" Version="1.13.1"
"Microsoft.ML.OnnxRuntime.Gpu" Version="1.13.1"
"Microsoft.ML.OnnxTransformer" Version="2.0.0"
</code>```

Controller code

```<code>  [HttpGet]
        public ActionResult Score()
        {

        var session1 = new InferenceSession(@"stroke.onnx"); //here is i found exception

     ...
</code>```

i debugged my code.I notice when i go to this line var session1 = new InferenceSession(@"stroke.onnx"); I found an unexpected exception:-

```<code>Exception has occurred: CLR/System.TypeInitializationException
An exception of type 'System.TypeInitializationException' occurred in Microsoft.ML.OnnxRuntime.dll but was not handled in user code: 'The type initializer for 'Microsoft.ML.OnnxRuntime.NativeMethods' threw an exception.'
 Inner exceptions found, see $exception in variables window for more details.
 Innermost exception     System.EntryPointNotFoundException : Unable to find an entry point named 'OrtGetApiBase' in DLL 'onnxruntime'.
   at Microsoft.ML.OnnxRuntime.NativeMethods.OrtGetApiBase()
   at Microsoft.ML.OnnxRuntime.NativeMethods..cctor()
</code>```

I don't understand why i found such an unexpected error. I am an absolute beginner. how i resolve this problem, please help.

ContentLicense: CC BY-SA 4.0

Body:
First of all I made a ML python model and then convert it to .onnx extention file by following step. and then i downloaded this .onnx extension file and put this my Controllers folder.I am using .NET Core Version 6 API and then i install some package:-  [I am actually followed this article]

"Microsoft.ML" Version="2.0.0"
"Microsoft.ML.OnnxRuntime" Version="1.13.1"
"Microsoft.ML.OnnxRuntime.Gpu" Version="1.13.1"
"Microsoft.ML.OnnxTransformer" Version="2.0.0"

Controller code

  [HttpGet]
        public ActionResult Score()
        {

        var session1 = new InferenceSession(@"stroke.onnx"); //here is i found exception

     ...

i debugged my code.I notice when i go to this line var session1 = new InferenceSession(@"stroke.onnx"); I found an unexpected exception:-

Exception has occurred: CLR/System.TypeInitializationException
An exception of type 'System.TypeInitializationException' occurred in Microsoft.ML.OnnxRuntime.dll but was not handled in user code: 'The type initializer for 'Microsoft.ML.OnnxRuntime.NativeMethods' threw an exception.'
 Inner exceptions found, see $exception in variables window for more details.
 Innermost exception     System.EntryPointNotFoundException : Unable to find an entry point named 'OrtGetApiBase' in DLL 'onnxruntime'.
   at Microsoft.ML.OnnxRuntime.NativeMethods.OrtGetApiBase()
   at Microsoft.ML.OnnxRuntime.NativeMethods..cctor()

I don't understand why i found such an unexpected error. I am an absolute beginner. how i resolve this problem, please help.


问:
In Odoo 13, is it possible to have a dropdown on a form that is selectable when in view mode?
I'm using Odoo 13.

Is it possible to add a dropdown on a form that I can select from even when in view mode?

I have looked through a lot of the code, trying various classes and so on but so far have not been able to do it. Is it even possible?


问:
How can i add a dataframe to a powerpoint slides in python using pptx
Hi is it possible to load a data frame to a power point slide without any borders so I want a transparent table using python and pptx</p>


问:
Shopify automatic discount by customer tag
I would like to program an app that gives an automatic discount as soon as a customer has stored a certain attribute.

The following app implements this ready, I just don't understand how the whole thing works...:
https://apps.shopify.com/b2b-solution-custom-pricing?locale=de

I am happy about a technical approach


问:
Python Selenium_handle of pop-ups & timeout exception
I am writing a code that will hopefully be able to click on a defined button on a pop-up window. The pop-up window appears only after having clicked somewhere else (this part is working).

here's the code:

```<code>from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.common.exceptions import TimeoutException

from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 2)
wait.until(EC.element_to_be_clickable((By.XPATH, '//button\[text()="OK"\]')))
wait.until(ExpectedConditions.visibilityOfElementLocated(By.XPATH, '//button\[text()="OK"\]'))
wait.until(ExpectedConditions.elementToBeClickable(By.XPATH, '//button\[text()="OK"\]'))
driver.findElement(By.XPATH, '//button\[text()="OK"\]').click()
</code>```

I am getting an error "TimeoutException". Anyone able to fix that?

thanks a lot

Body:
I am writing a code that will hopefully be able to click on a defined button on a pop-up window. The pop-up window appears only after having clicked somewhere else (this part is working).

here's the code:

from selenium.webdriver.support.ui import WebDriverWait

from selenium.webdriver.support import expected_conditions as EC

from selenium.common.exceptions import TimeoutException

from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 2)
wait.until(EC.element_to_be_clickable((By.XPATH, '//button\[text()="OK"\]')))
wait.until(ExpectedConditions.visibilityOfElementLocated(By.XPATH, '//button\[text()="OK"\]'))
wait.until(ExpectedConditions.elementToBeClickable(By.XPATH, '//button\[text()="OK"\]'))
driver.findElement(By.XPATH, '//button\[text()="OK"\]').click()

I am getting an error "TimeoutException". Anyone able to fix that?

thanks a lot


问:
Nginx load balancer & freeradius docker - Reply packet is from docker container
So doing a POC, with Nginx load balancer and freeradius docker. When the request packet is sent to the freeradius container from the proxy, the reply is received by the proxy and all is well.

So the containers are working as expected 100%.

However when the proxy sends the request to the freeradius container through the Nginx load balancer, the freeradius gets the access request packet, but then the access accept packet replies back with the containers IP.

So the proxy sends another request and the freeradius container replies back with the containers IP.

Proxy sends the request to radius:

Sent Accounting-Request Id 90 from xxx.xxx.xxx.xxx:55039 to xxx.xxx.xxx.xxx:1813 length 467

Radius replies

Sent Accounting-Response Id 1 from 172.18.0.5:1813 to xxx.xxx.xxx.xxx:37741 length 25

Proxy never gets the response:

(29) No proxy response, giving up on request and marking it done

(29) ERROR: Failing proxied request for user "vlan1106/lab-1-1070-1106", due to lack of any response from home server 154.119.32.156 port 1813

The Nginx load balancers are configured with transparent, as I need to know the source IP from where the request is made. When not in transparent then it works as the reply packet has the correct IP in the header.

Is there anything that I'm missing here? Been head butting this problem since Saturday.


问:
System.InvalidOperationException while setting up Facebook login in asp.net
Trying to follow this guide: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins?view=aspnetcore-7.0

And trying to add the Facebook Login/Register to my .net app, but when following instructions I ran into that exception on the code:

```<code>services.AddAuthentication().AddFacebook(facebookOptions =>
    {
        facebookOptions.AppId = configuration["Authentication:Facebook:AppId"];
        facebookOptions.AppSecret = configuration["Authentication:Facebook:AppSecret"];
    });
</code>```

The exception is: System.InvalidOperationException has been throw
"The services collection cannot be modified because its read-only."

Any ideas?

Body:
Trying to follow this guide: https://learn.microsoft.com/en-us/aspnet/core/security/authentication/social/facebook-logins?view=aspnetcore-7.0

And trying to add the Facebook Login/Register to my .net app, but when following instructions I ran into that exception on the code:

services.AddAuthentication().AddFacebook(facebookOptions =>
    {
        facebookOptions.AppId = configuration["Authentication:Facebook:AppId"];
        facebookOptions.AppSecret = configuration["Authentication:Facebook:AppSecret"];
    });

The exception is: System.InvalidOperationException has been throw
"The services collection cannot be modified because its read-only."

Any ideas?


问:
Get PEG revision that was used for SVN checkout
When you checkout a directory or file with SVN, you pass the URL and a PEG revision which is implicitely HEAD if not specified, for example:

```<code>svn checkout http://server/svn/directory
</code>```

is actually meaning:

```<code>svn checkout http://server/svn/directory@HEAD
</code>```

this PEG revision can be important in case the file or directory was moved in the past (or will be moved in the future).

I would like to know the PEG revision that was used to do a SVN checkout on my disk.

I am not speaking of the current revision (operative revision) that is present in the checkout and which can evolve other time. The PEG revision that was used to do the SVN checkout is (as far as I know) constant.

I tried svn info but no such information is given.

Body:
When you checkout a directory or file with SVN, you pass the URL and a PEG revision which is implicitely HEAD if not specified, for example:

svn checkout http://server/svn/directory

is actually meaning:

svn checkout http://server/svn/directory@HEAD

this PEG revision can be important in case the file or directory was moved in the past (or will be moved in the future).

I would like to know the PEG revision that was used to do a SVN checkout on my disk.

I am not speaking of the current revision (operative revision) that is present in the checkout and which can evolve other time. The PEG revision that was used to do the SVN checkout is (as far as I know) constant.

I tried svn info but no such information is given.


问:
Why when searching on google with python sometimes the program gets stuck?
So I wrote a script to read through a list of companies, search them on google and deduce which of them are franchises, by searching for words containing the root "Franch". Searching for the words works, but for some companies the script gets stuck after the same website and doesn't move forward and there is no manual way to skip it and move on. In the mean process the file with output companies is therefore not saved. Does anyone have any ideas?

```<code>import pandas as pd
import re
import word as w
import googlesearch as s
global i
i=0
#searching for "x" on google
def search(x,t):
    for j in s.search(x,lang='en',num=10,start=0,stop=10,pause=1.0):
        t+=1
        print(w.word(j,"franch"),j)
        if w.word(j,"franch")!=0:
            output=open("output.txt","a")
            output.write(a+" " + j+" " + str(w.word(j,"franch"))+ "\n")
            output.close()
        #limiting requests to only 500
        if t==500:
            break
file = pd.read_spss('company.sav')
#looping through the companies in the company.sav file (can't share it unfortunately)
for index,row in file.iterrows():
    a = str(file._get_value(index,0,takeable=True))
    a=a.replace(", Inc.",'')
    a=a.replace(" Inc",'')
    search(a,i)

</code>```

In this code word is another custom module which I will attach below.

```<code>from typing import Counter
import requests
from bs4 import BeautifulSoup
def word(x,y):

    # prepare a word counter
    word_count = Counter()
    franch = 0
    str1=y
    # lets get our web page (adjust to the url you want to review)

    base_url = x
    r = requests.get(base_url)

    # parse the webpage into an element hierarchy and store in soup
    soup = BeautifulSoup(r.text, 'html.parser')

    # Get only the main text of the page as list of words
    all_words = soup.get_text(" ", strip=True).lower().split()

    #count words
    for word in all_words:
        cln_word = word.strip('.,?')
        # ignore words less 4 char long
        if len(cln_word) > 3:
            # ignore words in our custom stop list
            word_count[cln_word] += 1
        if str1 in cln_word:
            franch+=1
    # print 50 most common words

    return franch

</code>```

the above program gets stuck at https://robbinsllp.com/asset-acceptance-capital-corp/

Body:
So I wrote a script to read through a list of companies, search them on google and deduce which of them are franchises, by searching for words containing the root "Franch". Searching for the words works, but for some companies the script gets stuck after the same website and doesn't move forward and there is no manual way to skip it and move on. In the mean process the file with output companies is therefore not saved. Does anyone have any ideas?

import pandas as pd
import re
import word as w
import googlesearch as s
global i
i=0
#searching for "x" on google
def search(x,t):
    for j in s.search(x,lang='en',num=10,start=0,stop=10,pause=1.0):
        t+=1
        print(w.word(j,"franch"),j)
        if w.word(j,"franch")!=0:
            output=open("output.txt","a")
            output.write(a+" " + j+" " + str(w.word(j,"franch"))+ "\n")
            output.close()
        #limiting requests to only 500
        if t==500:
            break
file = pd.read_spss('company.sav')
#looping through the companies in the company.sav file (can't share it unfortunately)
for index,row in file.iterrows():
    a = str(file._get_value(index,0,takeable=True))
    a=a.replace(", Inc.",'')
    a=a.replace(" Inc",'')
    search(a,i)

In this code word is another custom module which I will attach below.

from typing import Counter
import requests
from bs4 import BeautifulSoup
def word(x,y):

    # prepare a word counter
    word_count = Counter()
    franch = 0
    str1=y
    # lets get our web page (adjust to the url you want to review)

    base_url = x
    r = requests.get(base_url)

    # parse the webpage into an element hierarchy and store in soup
    soup = BeautifulSoup(r.text, 'html.parser')

    # Get only the main text of the page as list of words
    all_words = soup.get_text(" ", strip=True).lower().split()

    #count words
    for word in all_words:
        cln_word = word.strip('.,?')
        # ignore words less 4 char long
        if len(cln_word) > 3:
            # ignore words in our custom stop list
            word_count[cln_word] += 1
        if str1 in cln_word:
            franch+=1
    # print 50 most common words

    return franch

the above program gets stuck at https://robbinsllp.com/asset-acceptance-capital-corp/


问:
Compose navigation - passing arguments to startDestination of nested graph
What is the correct way of passing arguments to startDestination of a nested navigation graph? See this example:

```<code>private const val featureGraphRoute = "feature_graph"

private const val firstRouteArg = "intArgument"
private const val firstRoute = "first_route/{$firstRouteArg}"
private const val secondRoute = "second_route"

fun NavController.navigateToFeatureGraph(argument:Int, navOptions: NavOptions? = null) {
    //TODO: pass the argument
    this.navigate(featureGraphRoute, navOptions)
}

fun NavGraphBuilder.featureGraph() {
    navigation(
        route = featureGraphRoute,
        startDestination = firstRoute
    ) {
        composable(
            route = firstRoute,
            arguments = listOf(
                navArgument(firstRouteArg){
                    type = NavType.IntType
                }
            )
        ) { backStackEntry ->
            FirstRoute(
                argument = backStackEntry.arguments?.getInt(firstRouteArg)
            )
        }
        composable(route = firstRoute) {
            SecondRoute()
        }
    }
}
</code>```

Adding the same argument to the featureGraphRoute does seem to work but only if using NavType.StringType. Otherwise app crashes with exception:

java.lang.IllegalArgumentException: Wrong argument type for 'intArgument' in argument bundle. integer expected.

EDIT:

I somehow missed the fact that NavGraphBuilder.navigation has an overload that takes arguments. Moving the navArgument declaration up one level does prevent the crash.

Body:
What is the correct way of passing arguments to startDestination of a nested navigation graph? See this example:

private const val featureGraphRoute = "feature_graph"

private const val firstRouteArg = "intArgument"
private const val firstRoute = "first_route/{$firstRouteArg}"
private const val secondRoute = "second_route"

fun NavController.navigateToFeatureGraph(argument:Int, navOptions: NavOptions? = null) {
    //TODO: pass the argument
    this.navigate(featureGraphRoute, navOptions)
}

fun NavGraphBuilder.featureGraph() {
    navigation(
        route = featureGraphRoute,
        startDestination = firstRoute
    ) {
        composable(
            route = firstRoute,
            arguments = listOf(
                navArgument(firstRouteArg){
                    type = NavType.IntType
                }
            )
        ) { backStackEntry ->
            FirstRoute(
                argument = backStackEntry.arguments?.getInt(firstRouteArg)
            )
        }
        composable(route = firstRoute) {
            SecondRoute()
        }
    }
}

Adding the same argument to the featureGraphRoute does seem to work but only if using NavType.StringType. Otherwise app crashes with exception:

java.lang.IllegalArgumentException: Wrong argument type for 'intArgument' in argument bundle. integer expected.

EDIT:

I somehow missed the fact that NavGraphBuilder.navigation has an overload that takes arguments. Moving the navArgument declaration up one level does prevent the crash.


问:
Hiding Duplicate Legend in Plotly
I'm new in using plotly and I'm trying to make a 2 different graph and show them individually through button; however, when I make it, the legends duplicated, resulting to a bad visualization of the data. Here's the code that I'm running right now:

```<code>import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly as ply
import plotly.express as px
import plotly.graph_objects as go

url = "https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv"
alloy = pd.read_csv('https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv')
del alloy['temper']
alloy = alloy.rename(columns={'aluminum_alloy':'Alloy Number',
                              'modulus_elastic': 'Elastic Modulus',
                              'modulus_shear': 'Shear Modulus',
                              'strength_yield': 'Yield Strength',
                              'strength_tensile': 'Tensile Strength'
                             })

bar1 = px.bar(alloy,
            x = "Alloy Number",
            y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
            barmode = 'group',
            width = 1100,
            height =500,
            orientation = 'v',
            color_discrete_sequence = px.colors.qualitative.Pastel,
            labels={"value": "Data Values"},
            template = 'seaborn').update_traces(legendgroup="group").update_layout(showlegend=False)

line1 = px.line(alloy,
            x = "Alloy Number",
            y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
            width = 1100,
            height =500,
            orientation = 'v',
            color_discrete_sequence = px.colors.qualitative.Pastel,
            labels={"value": "Data Values"},
            template = 'seaborn').update_traces(legendgroup="group", visible = 'legendonly').update_layout(showlegend=False)

# Add buttom
fig.update_layout(
    updatemenus=[
        dict(
            type = "buttons",
            direction = "left",
            buttons=list([
                dict(
                    args=['type', 'bar'],
                    label="Bar Graph",
                    method="restyle",
                ),
                dict(
                    args=["type", "line"],
                    label="Line Graph",
                    method="restyle"
                )
            ]),
            pad={"r": 10, "t": 10},
            showactive=True,
            x=0.11,
            xanchor="left",
            y=1.1,
            yanchor="middle"
        ),
    ]
)

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

and the result of the image would look like this:
Result of the code above

Attempted Solution

I tried to hide it using traces and in the documentation but it seems it didn't work out for me. I also found a similar stackoverflow post 8 years ago, tried it, and it didn't make any changes in my graph.

Title: Hiding Duplicate Legend in Plotly

Body:
I'm new in using plotly and I'm trying to make a 2 different graph and show them individually through button; however, when I make it, the legends duplicated, resulting to a bad visualization of the data. Here's the code that I'm running right now:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import plotly as ply
import plotly.express as px
import plotly.graph_objects as go

url = "https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv"
alloy = pd.read_csv('https://raw.githubusercontent.com/m23chaffee/DS100-Repository/main/Aluminum%20Alloy%20Data%20Set.csv')
del alloy['temper']
alloy = alloy.rename(columns={'aluminum_alloy':'Alloy Number',
                              'modulus_elastic': 'Elastic Modulus',
                              'modulus_shear': 'Shear Modulus',
                              'strength_yield': 'Yield Strength',
                              'strength_tensile': 'Tensile Strength'
                             })

bar1 = px.bar(alloy,
            x = "Alloy Number",
            y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
            barmode = 'group',
            width = 1100,
            height =500,
            orientation = 'v',
            color_discrete_sequence = px.colors.qualitative.Pastel,
            labels={"value": "Data Values"},
            template = 'seaborn').update_traces(legendgroup="group").update_layout(showlegend=False)

line1 = px.line(alloy,
            x = "Alloy Number",
            y = ["Elastic Modulus", "Shear Modulus","Yield Strength","Tensile Strength"],
            width = 1100,
            height =500,
            orientation = 'v',
            color_discrete_sequence = px.colors.qualitative.Pastel,
            labels={"value": "Data Values"},
            template = 'seaborn').update_traces(legendgroup="group", visible = 'legendonly').update_layout(showlegend=False)

# Add buttom
fig.update_layout(
    updatemenus=[
        dict(
            type = "buttons",
            direction = "left",
            buttons=list([
                dict(
                    args=['type', 'bar'],
                    label="Bar Graph",
                    method="restyle",
                ),
                dict(
                    args=["type", "line"],
                    label="Line Graph",
                    method="restyle"
                )
            ]),
            pad={"r": 10, "t": 10},
            showactive=True,
            x=0.11,
            xanchor="left",
            y=1.1,
            yanchor="middle"
        ),
    ]
)

fig.show()

and the result of the image would look like this:
Result of the code above

Attempted Solution

I tried to hide it using traces and in the documentation but it seems it didn't work out for me. I also found a similar stackoverflow post 8 years ago, tried it, and it didn't make any changes in my graph.


问:
How can I permanently tell Quarkus to use Nexus registry?
How can I tell Quarkus to not download images from quay.io, but from our local registry? We have configured our Nexus to be a cache/proxy for all images, since we also want to control what images are being used.</p>


问:
How to scale winform to see the whole view
I'm following online tutorial to learn developing C# program using Visual Studio, and I am struggling with the display difference between my Visual Studio and the Tutor as following pictures, Although I am sure that I've set all the font format to the same :

Tutors' View:

enter image description here

My View:

enter image description here

My question 1  :

How can I display the whole form in a view? It's hard to arrange some layout when you have to scroll up-and-down to see the rest part of the form.

My question 2  :

Why is my view different to the tutors'? Is there something different in the Visual Studio between ours?  Where can I set the  parameters?

I'm using Microsoft Visual Studio Community 2019 Version 16.9.1 and Windows 10

Thanks!

I've tried:

Ctrl + Scroll mouse wheel to room out, but failed, nothing happened.

enter image description here Try this function, even worse, the word became even bigger.


问:
How to retrieve iOS or Android keyboard colour in code?
I'm making an app in React Native and I wanted to make a keyboard accessory view which would basically extend the keyboard on the device, so it would have to have the exact same colour as the keyboard.

I'm using KeyboardAccessoryView for Android and InputAccessoryView for iOS to do this.

My question is - is there any way to retrieve the colour of the keyboard the device is using in code for both iOS and Android?

I thought maybe the PlatformColor function in React Native would have this, but I find nothing mentioning keyboards there.


问:
Explode The Column Horizontally in the given dataframe for specific column
Existing Dataframe :

```<code>sr.no            col
1          ['ABC','CD','ABC']
2          ['AB']
3          ['CD','EF']
</code>```

Expected Dataframe :

```<code>sr.no         col                col_1            col_2        col_3
1       ['ABC','CD','ABC']       'ABC'              'CD'        'ABC'
2            ['AB']              'AB'
3         ['CD','EF']            'CD'               'EF'
</code>```

Approached it using explode but didn't getting the desired output. list in the col can include multiple strings and explode should work accordingly

Body:
Existing Dataframe :

sr.no            col
1          ['ABC','CD','ABC']
2          ['AB']
3          ['CD','EF']

Expected Dataframe :

sr.no         col                col_1            col_2        col_3
1       ['ABC','CD','ABC']       'ABC'              'CD'        'ABC'
2            ['AB']              'AB'
3         ['CD','EF']            'CD'               'EF'

Approached it using explode but didn't getting the desired output. list in the col can include multiple strings and explode should work accordingly


问:
Lua table.foreach missing
I used https://www.lua.org/cgi-bin/demo quite a lot to quickly hack together some scripts and test if they actually work. But today I stumpled across something that is very strange.

Testing this code

```<code>local t = {}
local threshold = 3
local counter = 0
t["1"] = true
t["2"] = true
t["3"] = false
t["4"] = true

table.foreach(t, print)
table.foreach(
  t,
  function(k,v)
    if v then
      counter = counter + 1
    end
  end
)
print(counter)
</code>```

gave me this error message

input:9: attempt to call a nil value (field 'foreach')

so I tried running

```<code>for k,v in pairs(table) do
  print(k,v)
end
</code>```

resulting in this output

```<code>concat  function: 0x42be90
remove  function: 0x42bca0
sort    function: 0x42ba50
move    function: 0x42baf0
insert  function: 0x42bda0
unpack  function: 0x42b2a0
pack    function: 0x42b3a0
</code>```

Since it's about a year ago I last used this site to test my code I can't really tell when there was a change. Or if there was a change. I am very sure last time I used that site I used the table.foreach function. But now it does not work.
I also checked the changelog in case there was a change I missed but https://www.lua.org/versions.html does not show any change past June 2020 with version 5.4

May someone tell me where I messed up or what I am missing?

Title: Lua table.foreach missing

Body:
I used https://www.lua.org/cgi-bin/demo quite a lot to quickly hack together some scripts and test if they actually work. But today I stumpled across something that is very strange.

Testing this code

local t = {}
local threshold = 3
local counter = 0
t["1"] = true
t["2"] = true
t["3"] = false
t["4"] = true

table.foreach(t, print)
table.foreach(
  t,
  function(k,v)
    if v then
      counter = counter + 1
    end
  end
)
print(counter)

gave me this error message

input:9: attempt to call a nil value (field 'foreach')

so I tried running

for k,v in pairs(table) do
  print(k,v)
end

resulting in this output

concat  function: 0x42be90
remove  function: 0x42bca0
sort    function: 0x42ba50
move    function: 0x42baf0
insert  function: 0x42bda0
unpack  function: 0x42b2a0
pack    function: 0x42b3a0

Since it's about a year ago I last used this site to test my code I can't really tell when there was a change. Or if there was a change. I am very sure last time I used that site I used the table.foreach function. But now it does not work.
I also checked the changelog in case there was a change I missed but https://www.lua.org/versions.html does not show any change past June 2020 with version 5.4

May someone tell me where I messed up or what I am missing?


问:
while i login cookies are stored but while delete cookie in onclick event on logout button it gives cors error i also used cors as middileware
```<code>Frontend code

const callLogout = async () =>{
        try{
            let res = await fetch('http://localhost:8000/logout',{
                method:"GET",
                headers:{
                    Accept:"application/json",
                    "Content-Type":"application/json"
                },
                credentials:"include"
            })
            let data = res.json()
            navigate('/login',{replace:true})

            if (res.status!==200){
                const error = new Error(res.error)
                console.log(error)
            }
        }
        catch(err){
            console.log(err)
        }
    }
<button onClick={callLogout} className='btn btn-primary' style={{position: 'absolute', right: '38px'}}>
                Logout
 </button>

Backend code

router.get('/logout' , (req , res) =>{
  res.clearCookie('jwttoken' , {path:'/'})
  return res.status(200)
})
</code>```

the code is working properly when i login but when i click on logout button it gives cors error

Access to fetch at 'http://localhost:8000/logout' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

About.js:10          GET http://localhost:8000/logout net::ERR_FAILED

Body:
Frontend code

const callLogout = async () =>{
        try{
            let res = await fetch('http://localhost:8000/logout',{
                method:"GET",
                headers:{
                    Accept:"application/json",
                    "Content-Type":"application/json"
                },
                credentials:"include"
            })
            let data = res.json()
            navigate('/login',{replace:true})

            if (res.status!==200){
                const error = new Error(res.error)
                console.log(error)
            }
        }
        catch(err){
            console.log(err)
        }
    }
<button onClick={callLogout} className='btn btn-primary' style={{position: 'absolute', right: '38px'}}>
                Logout
 </button>

Backend code

router.get('/logout' , (req , res) =>{
  res.clearCookie('jwttoken' , {path:'/'})
  return res.status(200)
})

the code is working properly when i login but when i click on logout button it gives cors error

Access to fetch at 'http://localhost:8000/logout' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

About.js:10          GET http://localhost:8000/logout net::ERR_FAILED


问:
How to change file Author Metadata
I want to delete/empty the "Author" feature if you have any documents I have. This document can be in PDF format, it can be in Docx, it can be in any picture or video format. I did a run below but I'm getting an error. How can I fix this error? How can I find a different solution?

```<code>        ShellObject tempFile = ShellObject.FromParsingName(filePath);

        ShellPropertyWriter propertyWriter = tempFile.Properties.GetPropertyWriter();

        propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
        propertyWriter.Close();
</code>```

The error I'm getting is this:

```<code>"System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
</code>```

The framework I am using is net6.0,
Can you please help?

Title: How to change file Author Metadata

Body:
I want to delete/empty the "Author" feature if you have any documents I have. This document can be in PDF format, it can be in Docx, it can be in any picture or video format. I did a run below but I'm getting an error. How can I fix this error? How can I find a different solution?

        ShellObject tempFile = ShellObject.FromParsingName(filePath);

        ShellPropertyWriter propertyWriter = tempFile.Properties.GetPropertyWriter();

        propertyWriter.WriteProperty(SystemProperties.System.Author, new string[] { "Author" });
        propertyWriter.Close();

The error I'm getting is this:

"System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

The framework I am using is net6.0,
Can you please help?


问:
How can I define type in ts?
```<code>type TagProps = {
  id: string;
  name: string;
  color: string;
};

  const tags: TagProps[] = data.properties.tag.multi_select;

//

{
id: "xxxx"
name: "xxx"
},
{
id: "xxxx"
name: "xxx"
},
{
id: "xxxx"
name: "xxx"
}

   <section className="mt-2 flex items-start space-x-2">
          {tags.map(({ id, name }: TagProps) => (
            <h1 className="w-30 rounded-md bg-sky-200 px-2 py-1 dark:bg-sky-700" key={id}>
              {name}
            </h1>
          ))}
   </section>

</code>```

I got an error 'Type 'string[]' is not assignable to type 'TagProps[]'.
Type 'string' is not assignable to type 'TagProps'

Is there something I did wrong?

Title: How can I define type in ts?

Body:
type TagProps = {
  id: string;
  name: string;
  color: string;
};

  const tags: TagProps[] = data.properties.tag.multi_select;

//

{
id: "xxxx"
name: "xxx"
},
{
id: "xxxx"
name: "xxx"
},
{
id: "xxxx"
name: "xxx"
}

          {tags.map(({ id, name }: TagProps) => (

              {name}

          ))}

I got an error 'Type 'string[]' is not assignable to type 'TagProps[]'.
Type 'string' is not assignable to type 'TagProps'

Is there something I did wrong?


问:
Calling the auth function will call the wrong url
I'm using the Nuxt/Auth library in a NuxtJs project. I'm trying to make a login request to my backend. So I don't use any of the existing schemes that the library has prepared by default.

This is what my configuration looks like in nuxt.config.js

```<code>axios: {
    baseUrl: 'https://api.release.my-custom-domain.com',
    credentials: true,
    proxy: true
  },

  proxy: {
    '/api/': {
      target: 'https://api.release.my-custom-domain.com',
      pathRewrite: {'^/api/': ''}
    }
  },

  auth: {
    strategies: {
      local: {
        token: {
          property: 'token',
          global: true,
        },
        user: {
          property: 'user'
        },
        endpoint: {
          login: {url: '/api/v1/auth', method: 'post', propertyName: false}
        }
      }
    }
  },
</code>```

I use a proxy because of a problem with cors.

This is what my code looks like in vue.

```<code>methods: {
    async loginFormSubmit () {
      try {
        let response = await this.$auth.loginWith('local', { data: this.login })
        console.log(response);
      } catch (err) {
        console.log(err);
      }
    }
  }
</code>```

After I call the function, the XRH request runs, but it always adds /login to the url request.

This is what the url should look like - http://localhost:3000/api/auth

But the request looks like this - http://localhost:3000/api/auth/login

Didn't someone already solve this problem?
Thank you for your answers.

Body:
I'm using the Nuxt/Auth library in a NuxtJs project. I'm trying to make a login request to my backend. So I don't use any of the existing schemes that the library has prepared by default.

This is what my configuration looks like in nuxt.config.js

axios: {
    baseUrl: 'https://api.release.my-custom-domain.com',
    credentials: true,
    proxy: true
  },

  proxy: {
    '/api/': {
      target: 'https://api.release.my-custom-domain.com',
      pathRewrite: {'^/api/': ''}
    }
  },

  auth: {
    strategies: {
      local: {
        token: {
          property: 'token',
          global: true,
        },
        user: {
          property: 'user'
        },
        endpoint: {
          login: {url: '/api/v1/auth', method: 'post', propertyName: false}
        }
      }
    }
  },

I use a proxy because of a problem with cors.

This is what my code looks like in vue.

methods: {
    async loginFormSubmit () {
      try {
        let response = await this.$auth.loginWith('local', { data: this.login })
        console.log(response);
      } catch (err) {
        console.log(err);
      }
    }
  }

After I call the function, the XRH request runs, but it always adds /login to the url request.

This is what the url should look like - http://localhost:3000/api/auth

But the request looks like this - http://localhost:3000/api/auth/login

Didn't someone already solve this problem?
Thank you for your answers.


问:
Pandas: Creating multiple new columns from function with multiple output values
Im trying to scrape a website for multiple values regarding a list of books. The links to the book pages are stored in a dataframe. Now I need a function that iterates those links and adds the book values to new columns in the dataframe. I don't want to request the page again every time I'm scraping a new book value, so I want to do it all in one function.
The problem is the function then returns multiple values (e.g. book_title and book_rating) which I don't know how to best add to the dataframe.

I tried the following, which I know can't work but I'm stuck:

```<code>import requests as rq
from bs4 import BeautifulSoup as bs
import pandas as pd

#function to get the book page
def get_book_page(page):
    # Construct the URL
    books_page_url = page

    # Get the HTML page content using requests
    response = rq.get(books_page_url, headers = headers)

    # Ensure that the response is valid
    if response.status_code != 200:
        print('Status code:', response.status_code)
        raise Exception('Failed to fetch web page ' + books_page_url)

    # Construct a beautiful soup document
    doc = bs(response.content, "html.parser")

    return doc

#function to scrape the book title
def scrape_book_title(book_content):
    try:
        title_tag = book_content.find("h1", class_="bc-heading bc-color-base bc-size-large bc-text-bold").text.strip()
    except:
        title_tag = "fehlt"
    return title_tag

#function to scrape the book rating
def scrape_book_rating(book_content):
    star_tag = book_content.find("li", class_="bc-list-item ratingsLabel")
    try:
        rating_tag = star_tag.find("span", class_="bc-text bc-pub-offscreen").text.strip()
    except:
        rating_tag = "fehlt"
    return rating_tag

#function I'm trying to fix
def get_book_title(links):
    bs_page = get_book_page(links)
    bs_content = bs_page.find("ul", class_="bc-list bc-spacing-s2 bc-color-secondary bc-list-nostyle")
    book_title = scrape_book_title(bs_content)
    book_rating = scrape_book_rating(bs_content)
    return book_title, book_rating

#here I would like to add the columns "A_Titel" and "A_Rating" with the values of "book_title" and "book_rating"
df['A_Titel'], df['A_Rating'] = df.apply(lambda x: get_book_title(x.Link), axis=1)
</code>```

Body:
Im trying to scrape a website for multiple values regarding a list of books. The links to the book pages are stored in a dataframe. Now I need a function that iterates those links and adds the book values to new columns in the dataframe. I don't want to request the page again every time I'm scraping a new book value, so I want to do it all in one function.
The problem is the function then returns multiple values (e.g. book_title and book_rating) which I don't know how to best add to the dataframe.

I tried the following, which I know can't work but I'm stuck:

import requests as rq
from bs4 import BeautifulSoup as bs
import pandas as pd

#function to get the book page
def get_book_page(page):
    # Construct the URL
    books_page_url = page

    # Get the HTML page content using requests
    response = rq.get(books_page_url, headers = headers)

    # Ensure that the response is valid
    if response.status_code != 200:
        print('Status code:', response.status_code)
        raise Exception('Failed to fetch web page ' + books_page_url)

    # Construct a beautiful soup document
    doc = bs(response.content, "html.parser")

    return doc

#function to scrape the book title
def scrape_book_title(book_content):
    try:
        title_tag = book_content.find("h1", class_="bc-heading bc-color-base bc-size-large bc-text-bold").text.strip()
    except:
        title_tag = "fehlt"
    return title_tag

#function to scrape the book rating
def scrape_book_rating(book_content):
    star_tag = book_content.find("li", class_="bc-list-item ratingsLabel")
    try:
        rating_tag = star_tag.find("span", class_="bc-text bc-pub-offscreen").text.strip()
    except:
        rating_tag = "fehlt"
    return rating_tag

#function I'm trying to fix
def get_book_title(links):
    bs_page = get_book_page(links)
    bs_content = bs_page.find("ul", class_="bc-list bc-spacing-s2 bc-color-secondary bc-list-nostyle")
    book_title = scrape_book_title(bs_content)
    book_rating = scrape_book_rating(bs_content)
    return book_title, book_rating

#here I would like to add the columns "A_Titel" and "A_Rating" with the values of "book_title" and "book_rating"
df['A_Titel'], df['A_Rating'] = df.apply(lambda x: get_book_title(x.Link), axis=1)


问:
Insert an ad image on pdf rendered using pdf.js
I am using pdf js https://github.com/latuminggi/pdf.js_readonly/ to render pdf in my website .Here the viewer.html helps to render the pdf url:https://github.com/latuminggi/pdf.js_readonly/blob/master/generic/web/viewer.html

in our project url will be : localhost/project/generic/web/viewer.html?file=pdfname.pdf

And the code in the viewer.html to render pdf is

```<code>  <div id="viewerContainer" tabindex="0">
          <div id="viewer" class="pdfViewer"></div>
        </div>
</code>```

here in #viewer there pdfjs will read the document and make child divs like
view live example in  : https://latuminggi.github.io/pdf.js_readonly/generic/web/viewer.html

```<code>  <div id="viewerContainer" tabindex="0">
          <div id="viewer" class="pdfViewer">
            <div class="page"> <div>
            <div class="page"> <div>
             .... ....
            <div class="page"> <div>
            <div class="page"> <div>
           </div>
  </div>
</code>```

i wanted to do is to add an ads image after each 5 pages like .

```<code>  <div id="viewerContainer" tabindex="0">
          <div id="viewer" class="pdfViewer">
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="ads"> <img src="path"> <div>
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="page"> <div>
            <div class="ads"> <img src="path"> <div>
            <div class="page"> <div>
            <div class="page"> <div>

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

I dont know much about pdf.js so i asked here

Body:
I am using pdf js https://github.com/latuminggi/pdf.js_readonly/ to render pdf in my website .Here the viewer.html helps to render the pdf url:https://github.com/latuminggi/pdf.js_readonly/blob/master/generic/web/viewer.html

in our project url will be : localhost/project/generic/web/viewer.html?file=pdfname.pdf

And the code in the viewer.html to render pdf is

here in #viewer there pdfjs will read the document and make child divs like
view live example in  : https://latuminggi.github.io/pdf.js_readonly/generic/web/viewer.html

             .... ....

i wanted to do is to add an ads image after each 5 pages like .

I dont know much about pdf.js so i asked here


问:
Couldn't install tableauhyperapi python module
I'm trying to install tableauhyperapi python module on macOS M1 with simple pip install tableauhyperapi, but facing the following error:

```<code>ERROR: Could not find a version that satisfies the requirement tableauhyperapi (from versions: none)
ERROR: No matching distribution found for tableauhyperapi
</code>```

Tried the same install for Ubuntu 18.04 and was facing the same result.

Body:
I'm trying to install tableauhyperapi python module on macOS M1 with simple pip install tableauhyperapi, but facing the following error:

ERROR: Could not find a version that satisfies the requirement tableauhyperapi (from versions: none)
ERROR: No matching distribution found for tableauhyperapi

Tried the same install for Ubuntu 18.04 and was facing the same result.


问:
Is scene(_:openURLContexts:) called when app is launched by an airdropped file?
In the old versions of my app, the scene(_:openURLContexts:) method is always called in these two cases:

The app isn't running. Then It's launched by an airdropped file.

The app is already running. Then a file is airdropped.

I created a separate app to work on the new version and made a lot of code changes. None of the changes should affect the above behavior, but I find the case 1 doesn't work. If the app isn't running, the airdropped file launches it successfully, but scene(_:openURLContexts:) isn't called.

More information:

To verify scene(_:openURLContexts:) is really not called, I added logs in the method and used Console app to monitor the logs.

I tested the old app on the same phone, which runs iOS 16.0.2. It works fine in both cases. So this isn't an OS issue.

Both of the apps are SwiftUI apps.

I searched on the net and found this workaround. It works for me.

I've discovered that the code below is need in willConnectTo session:

self.scene(scene, openURLContexts: connectionOptions.urlContexts)

The Apple's doc is very concise on these APIs. It's not clear to me what's the expected behavior and why my two apps have different behavior. Does anyone know if scene(_:openURLContexts:) is expected to be called when when app is launched by an airdropped file?

UPDATE: from this answer, scene(_:openURLContexts:) is not expected to be called when when app is launched by an airdropped file. If so, I don't understand why my old app works (from my search on the net, I'm not the only one who observed the different behaviors).


问:
Xcode crashed and closed suddenly in Playground wenn using MKLookAroundSnapshotter
can someone tell me what the problem of this code is? In this code I tried to read the addresses from an Excel file and using CLGeocoder to store the coordinates of these addresses in CoordinateWithAddress. In the next step, I wanted to enter these coordinates into the snapshotImage function and save a photo for each saved coordinate.

when I run the program, no errors occur and it runs but suddenly Xcode crashes  and closes after saving a photo or 2.

for one coordinate everything works but if i throw everything in for loop and let it run for 1000 coordinates then Xcode suddenly closes.

```<code>import Foundation
import CoreLocation
import TabularData
import MapKit
import UIKit

guard let path = Bundle.main.url(forResource: "tst1", withExtension: "csv")
else{
    throw NSError()
    }

//let fileContent = try String(contentsOf: path, encoding: .utf8)
//let rows = fileContent.components(separatedBy: "\n")

let cleanString = try! String(contentsOf: path).trimmingCharacters(in: .whitespacesAndNewlines)

let rows = cleanString.components(separatedBy: "\n")

var coordinates:[CLLocationCoordinate2D] = []

let group = DispatchGroup()

var coordinatesWithAddress : [(latitude: Double, longitude: Double,address: String)] = []

for row in rows {
    group.enter()
    sleep(2)
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(row) { (placemarks, error) in
        guard let placemark = placemarks?.first, let location = placemark.location else {
            print("Error geocoding address: \(row)")

            group.leave()
            return
        }
        coordinatesWithAddress.append((latitude: location.coordinate.latitude,
                                      longitude: location.coordinate.longitude,address: row))
        group.leave()
   }
}

group.notify(queue: .main){

    var csvText = "latitude,longitude,address\n"
    for coordinate in coordinatesWithAddress {
        let newLine = String(format: "%f,%f,%@\n", coordinate.latitude, coordinate.longitude,coordinate.address )

        csvText.append(newLine)
    }

    do {
        if let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let fileName = "coordinates.csv"
            let fileURL = directory.appendingPathComponent(fileName)
            try csvText.write(to:fileURL, atomically: true, encoding: .utf8)
            print("file saved successfully")

        }

    } catch {
        print("error saving file : \(error)")
    }

}

enum LookaroundError: Error {
    case unableToCreateScene
}

func snapshotImage(for coordinate: CLLocationCoordinate2D) async throws -> UIImage {
    guard let scene = try await MKLookAroundSceneRequest(coordinate: coordinate).scene else {
        throw LookaroundError.unableToCreateScene
    }
    let options = MKLookAroundSnapshotter.Options()
    options.size = CGSize(width: 512, height: 512)
    return try await MKLookAroundSnapshotter(scene: scene, options: options).snapshot.image
}

enum getLocationError : Error {
    case unableToGetLocation
}

sleep(5)

for coordinate in coordinatesWithAddress {

    sleep(2)

    var image = try await snapshotImage(for: CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude))

    var url = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appending(component: "\(coordinate.address).png")
    try image.pngData()?.write(to: url)

}
</code>```

Body:
can someone tell me what the problem of this code is? In this code I tried to read the addresses from an Excel file and using CLGeocoder to store the coordinates of these addresses in CoordinateWithAddress. In the next step, I wanted to enter these coordinates into the snapshotImage function and save a photo for each saved coordinate.

when I run the program, no errors occur and it runs but suddenly Xcode crashes  and closes after saving a photo or 2.

for one coordinate everything works but if i throw everything in for loop and let it run for 1000 coordinates then Xcode suddenly closes.

import Foundation
import CoreLocation
import TabularData
import MapKit
import UIKit

guard let path = Bundle.main.url(forResource: "tst1", withExtension: "csv")
else{
    throw NSError()
    }

//let fileContent = try String(contentsOf: path, encoding: .utf8)
//let rows = fileContent.components(separatedBy: "\n")

let cleanString = try! String(contentsOf: path).trimmingCharacters(in: .whitespacesAndNewlines)

let rows = cleanString.components(separatedBy: "\n")

var coordinates:[CLLocationCoordinate2D] = []

let group = DispatchGroup()

var coordinatesWithAddress : [(latitude: Double, longitude: Double,address: String)] = []

for row in rows {
    group.enter()
    sleep(2)
    let geocoder = CLGeocoder()
    geocoder.geocodeAddressString(row) { (placemarks, error) in
        guard let placemark = placemarks?.first, let location = placemark.location else {
            print("Error geocoding address: \(row)")

            group.leave()
            return
        }
        coordinatesWithAddress.append((latitude: location.coordinate.latitude,
                                      longitude: location.coordinate.longitude,address: row))
        group.leave()
   }
}

group.notify(queue: .main){

    var csvText = "latitude,longitude,address\n"
    for coordinate in coordinatesWithAddress {
        let newLine = String(format: "%f,%f,%@\n", coordinate.latitude, coordinate.longitude,coordinate.address )

        csvText.append(newLine)
    }

    do {
        if let directory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
            let fileName = "coordinates.csv"
            let fileURL = directory.appendingPathComponent(fileName)
            try csvText.write(to:fileURL, atomically: true, encoding: .utf8)
            print("file saved successfully")

        }

    } catch {
        print("error saving file : \(error)")
    }

}

enum LookaroundError: Error {
    case unableToCreateScene
}

func snapshotImage(for coordinate: CLLocationCoordinate2D) async throws -> UIImage {
    guard let scene = try await MKLookAroundSceneRequest(coordinate: coordinate).scene else {
        throw LookaroundError.unableToCreateScene
    }
    let options = MKLookAroundSnapshotter.Options()
    options.size = CGSize(width: 512, height: 512)
    return try await MKLookAroundSnapshotter(scene: scene, options: options).snapshot.image
}

enum getLocationError : Error {
    case unableToGetLocation
}

sleep(5)

for coordinate in coordinatesWithAddress {

    sleep(2)

    var image = try await snapshotImage(for: CLLocationCoordinate2D(latitude: coordinate.latitude, longitude: coordinate.longitude))

    var url = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appending(component: "\(coordinate.address).png")
    try image.pngData()?.write(to: url)

}


问:
Change wordpress theme file
I tried to change Worpdress theme files. (page.php, style.css)

But changes seem not to affect actual website pages.

I have these plugins installed:

- WooCommerce

- Additional Variation Images Gallery for WooCommerce

- WooCommerce AJAX Products Filter

- XforWooCommerce

Can it be related to some kind of cache?

I tried to clear the cache using the plugin but it didn't help

Title: Change wordpress theme file


问:
Tomcat8 redirect http://8080 to https://8443 not working - instead https://8080
We want to redirect http://8080 to https://8443 with Tomcat 8.
Unfortunately we come accross the situation that http://server:8080is redirected to  https://server:8080 instead of https://server:8443.
I have updated server.xml as well as web.xml - showing below - However the port within the URL is not updated.

When the cache is cleaned (in any browser) then the first URL redirect works as expected while the second one fails again. However, when entering http://server:8080/ as URL again it gets redirected to the wrong URL https://server:8080/ again while the port does not change.

conf/server.xml

```<code><Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           maxPostSize="8388608" />

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true"
           scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           maxPostSize="8388608"
           ... Certificate settings...
           URIEncoding="UTF-8"
           compression="force"
           compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>
</code>```

conf/web.xml

```<code><security-constraint>
    <web-resource-collection>
        <web-resource-name>server</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>
</code>```

Body:
We want to redirect http://8080 to https://8443 with Tomcat 8.
Unfortunately we come accross the situation that http://server:8080is redirected to  https://server:8080 instead of https://server:8443.
I have updated server.xml as well as web.xml - showing below - However the port within the URL is not updated.

When the cache is cleaned (in any browser) then the first URL redirect works as expected while the second one fails again. However, when entering http://server:8080/ as URL again it gets redirected to the wrong URL https://server:8080/ again while the port does not change.

conf/server.xml

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           maxPostSize="8388608" />

<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
           maxThreads="150" SSLEnabled="true"
           scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS"
           maxPostSize="8388608"
           ... Certificate settings...
           URIEncoding="UTF-8"
           compression="force"
           compressableMimeType="text/html,text/xml,text/plain,text/javascript,text/css"/>

conf/web.xml

<security-constraint>
    <web-resource-collection>
        <web-resource-name>server</web-resource-name>
        <url-pattern>/*</url-pattern>
    </web-resource-collection>
    <user-data-constraint>
        <transport-guarantee>CONFIDENTIAL</transport-guarantee>
    </user-data-constraint>
</security-constraint>


问:
The vscode first page main window does not appear
While setting zoom, too large a number was entered by mistake, causing the screen to become excessively large and the vscode execution window to disappear.No matter how hard you try, you can't return to the default setting.Help - Removing and reinstalling the vscode leaves the enlarged window and does not disappear.

I want the first page of vscode (main page) to appear.
I tried to find the settings page, but there was no way. The Run window does not appear.


问:
Webhook stop working after rename Bitbucket repo
I've setup Bitbucket webhook to triger Jenkins job by using bitbucket-push-and-pull-request plugin and work as I need.

I had to rename the repository in BitBucket settings, then change the url in the jenkins job and run the build manualy in order to check the new settings.

Webhook stop working and does not trigger the jenkins job anymore.
I've try to create new webhook in bitbucket and new jenkins job but still don't work.

If I rename the repo to the old name webhook work again.

Any idea how to solve this issue? (We're using Bitbucket server)


问:
limit flex height based on parent grid area - when flex-direction
I am trying to do a flex-wrap with flex-direction column (see #design-content) placed in a grid area (see design-form).
#design-content needs to have the height of the grid area it is placed in.
This works as long as #design-form does NOT have flex-direction: column; but as soon as I add that line the element + the parent grid-template-row height changes (as shown in computed tab in chrome)

Is there a way to force #design content to respect height from the parent elements?

CSS

main {
    height: 80vh;
    display: grid;
    grid-template-areas:
      "ref"
      "design";
    grid-template-rows: fit-content(100%) 1fr;
}

#design-form {
  grid-area: design;
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr min-content;
  grid-template-areas:
    "form    "
    "controls";
  gap: var(--standard-gap);
}

#design-content {
  height: 100%;
  display: flex;
  min-height: 0;
  flex-direction: column;
  flex-wrap: wrap;
  border-style: dotted dashed solid double;
  gap: var(--standard-gap);
}
```
<p>Relevant html</p>
<pre class="lang-html prettyprint-override"><code><main>
<form id="design-form" class="active">
   <div id="design-content">
            <div class="card">
                <h4>setup</h4>
                <div class="check-field-element">
                <input
                   type="checkbox"
                   name="checkbox"
                   id="trophicMethod"}="">
                <label>trophic method</label>
            </div>
            ... more cards
   </div>
</form>
</main>
</code>```

Body:
I am trying to do a flex-wrap with flex-direction column (see #design-content) placed in a grid area (see design-form).
#design-content needs to have the height of the grid area it is placed in.
This works as long as #design-form does NOT have flex-direction: column; but as soon as I add that line the element + the parent grid-template-row height changes (as shown in computed tab in chrome)

Is there a way to force #design content to respect height from the parent elements?

CSS

main {
    height: 80vh;
    display: grid;
    grid-template-areas:
      "ref"
      "design";
    grid-template-rows: fit-content(100%) 1fr;
}

#design-form {
  grid-area: design;
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr min-content;
  grid-template-areas:
    "form    "
    "controls";
  gap: var(--standard-gap);
}

#design-content {
  height: 100%;
  display: flex;
  min-height: 0;
  flex-direction: column;
  flex-wrap: wrap;
  border-style: dotted dashed solid double;
  gap: var(--standard-gap);
}

Relevant html

<form id="design-form" class="active">

setup

                <input
                   type="checkbox"
                   name="checkbox"
                   id="trophicMethod"}="">
                trophic method

            ... more cards

</form>


问:
Page returning same results even though the results are different each time. (Node, puppeteer, cheerio)
Im scraping a dynamic website, which doesn't instantly load a list full of items.
I'm waiting until that content loads then i'm getting the pagination list and extracting the last items value for the page count.

once this is done i'm using a for loop to go through this website x amount of times based on the page count for that list of items.

once the first loop is complete and the data is gathered... i click the next button to move on to the next page, i await the data to change, then go back through the for loop to gather the new data in that list.

For some reason, the results returned is the same for each page, even though they're not the same, and i can see with using headless: false that the data is in-fact changing so why isn't it returning that new data?

`

```<code>try {

    const browser = await puppeteer.launch(
        {
            headless: false
        }
    );

    const page = await browser.newPage();
    await page.goto(url, {
        waitUntil: "networkidle0",
    }).catch((err) => console.log("error loading url", err));

    await page.waitForSelector(selector);

    const pageData = await page.evaluate(() => {
        return {
            html: document.documentElement.innerHTML,
        }

    });

    const $ = cheerio.load(pageData.html);

    for (let i = 0; i < pageCount; i++) {

        await page.waitForSelector(selector);

        $('.itemDivWrapper > div').each(async (i, g) => {
            let itemName = $(g).find('a > div > h3').text();
            console.log(itemName);
        });

        await Promise.all([
            page.$eval('div.itemList > nav > ul > li.nextButton > a', element =>
                element.click()
            ),
            await page.waitForTimeout(5000);
        ]);
    }

    await browser.close();

} catch (error) {
    console.log(error);
}
</code>```

`

Maybe i'm just doing something silly wrong :'D and fresh eyes are needed :D.

Expect each loop to provide the new page data, which 100% showed before it tried to get that data. but returns the same values each time.

Body:
Im scraping a dynamic website, which doesn't instantly load a list full of items.
I'm waiting until that content loads then i'm getting the pagination list and extracting the last items value for the page count.

once this is done i'm using a for loop to go through this website x amount of times based on the page count for that list of items.

once the first loop is complete and the data is gathered... i click the next button to move on to the next page, i await the data to change, then go back through the for loop to gather the new data in that list.

For some reason, the results returned is the same for each page, even though they're not the same, and i can see with using headless: false that the data is in-fact changing so why isn't it returning that new data?

`

try {

    const browser = await puppeteer.launch(
        {
            headless: false
        }
    );

    const page = await browser.newPage();
    await page.goto(url, {
        waitUntil: "networkidle0",
    }).catch((err) => console.log("error loading url", err));

    await page.waitForSelector(selector);

    const pageData = await page.evaluate(() => {
        return {
            html: document.documentElement.innerHTML,
        }

    });

    const $ = cheerio.load(pageData.html);

    for (let i = 0; i < pageCount; i++) {

        await page.waitForSelector(selector);

        $('.itemDivWrapper > div').each(async (i, g) => {
            let itemName = $(g).find('a > div > h3').text();
            console.log(itemName);
        });

        await Promise.all([
            page.$eval('div.itemList > nav > ul > li.nextButton > a', element =>
                element.click()
            ),
            await page.waitForTimeout(5000);
        ]);
    }

    await browser.close();

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

`

Maybe i'm just doing something silly wrong :'D and fresh eyes are needed :D.

Expect each loop to provide the new page data, which 100% showed before it tried to get that data. but returns the same values each time.


问:
Update antd form.Items if initialValue has changed after calling server using class components in react
Hello this is my code:

```<code><Form
   layout='horizontal'
   size='small'
   onFinish={this.handleSubmit.bind(this)}
>
   <Form.Item
      label={`Organization:`}
      name={`Organization`}
   >
     <Input
          onChange={
                    (e) => this.handleOrgInput(e)
                   }
     />
   </Form.Item>
   <Button
       icon={
            this.state.showMenu ?
                 <CaretDownOutlined />
            :
                 <CaretRightFilled />
            }
            shape="circle"
            onClick={() => {
                {
                  this.handleFetchSystemData()
                }
            disabled={this.state.showMenu}
            style={{marginLeft: 5}}
   />
   {this.state.showMenu && this.state.myName!==undefined ?
   <div>
   {console.log('Name :', this.state.myName}
   <Form.Item
      name={"Name"}
      label={`Name:`}
      initialValue={this.state.myName}
   >
      <Input
         // defaultValue={this.state.myName}
      />
   </Form.Item>
   <Form.Item
      name={"lastName"}
      label={`LastName:`}
      initialValue={this.state.myLastName}
   >
      <Input
         // defaultValue={this.state.myLastName}
      />
   </Form.Item>
   <Form.Item>
      <Button
         type="primary"
         htmlType="submit"
         size="middle"
      >
         Submit
      </Button>
    </Form.Item>
    </div>
    :
       undefined
</Form>
</code>```

When i am pressing the button i call my server to fetch the data. But when i change the input and then clicking again the button the values on the Form.Item are remain the same, but my state has change. I can see that my state changes because i console.log it.

When i comment the initialValue attribute on Form.Item and using defaultValue attribute on Input component my values are changing smoothly, but when i press sumbit the values are not senting from the Form. This is a problem for me

I have seen a lot about this situation, but most of it regards functional components and not class components. Also i have seen that with class components some people using refs but Form component has not attribute ref. I have seen this regarding class components but did not help me. In the end the antd documentation regards i think functional components and not class, so i am a comfused.

Body:
Hello this is my code:

<Form
   layout='horizontal'
   size='small'
   onFinish={this.handleSubmit.bind(this)}
>
   <Form.Item
      label={`Organization:`}
      name={`Organization`}
   >
     <Input
          onChange={
                    (e) => this.handleOrgInput(e)
                   }
     />
   </Form.Item>
   <Button
       icon={
            this.state.showMenu ?
                 <CaretDownOutlined />
            :
                 <CaretRightFilled />
            }
            shape="circle"
            onClick={() => {
                {
                  this.handleFetchSystemData()
                }
            disabled={this.state.showMenu}
            style={{marginLeft: 5}}
   />
   {this.state.showMenu && this.state.myName!==undefined ?

   {console.log('Name :', this.state.myName}
   <Form.Item
      name={"Name"}
      label={`Name:`}
      initialValue={this.state.myName}
   >
      <Input
         // defaultValue={this.state.myName}
      />
   </Form.Item>
   <Form.Item
      name={"lastName"}
      label={`LastName:`}
      initialValue={this.state.myLastName}
   >
      <Input
         // defaultValue={this.state.myLastName}
      />
   </Form.Item>
   <Form.Item>
      <Button
         type="primary"
         htmlType="submit"
         size="middle"
      >
         Submit
      </Button>
    </Form.Item>

    :
       undefined
</Form>

When i am pressing the button i call my server to fetch the data. But when i change the input and then clicking again the button the values on the Form.Item are remain the same, but my state has change. I can see that my state changes because i console.log it.

When i comment the initialValue attribute on Form.Item and using defaultValue attribute on Input component my values are changing smoothly, but when i press sumbit the values are not senting from the Form. This is a problem for me

I have seen a lot about this situation, but most of it regards functional components and not class components. Also i have seen that with class components some people using refs but Form component has not attribute ref. I have seen this regarding class components but did not help me. In the end the antd documentation regards i think functional components and not class, so i am a comfused.


问:
Why does my login endpoint in django knox throw "Bad request..." error?
I used files from "https://github.com/Omkar0231/Django-Login-API" with as is. The login request from Postman is resulting in error, "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)", while the terminal shows "Bad request...".

The developer of the source code in above git has also explained it in a video, "https://www.youtube.com/watch?v=6d0fiPj0dsA", however, in video everything seems to be working as expected.

Whatever I understood from Googling, I thought that a bearer token is to be included in the login request as header. But I don't know where to find the bearer token in my Django app. However, in the video, the original author/developer did not include any such header token for the login request from Postman.

Please help me figure out the issue.


问:
react-native run siri shortcut without opening the app
I am using "react-native-siri-shortcut' library to make shortcuts.

suggestedInvocationPhrase for my shortcut is "It's Tea Time" so when the user says "Hey Siri, It's Tea Time" then Siri opens the app and gives the whole shortcut object via addShortcutListener, but this listener only works when the app is in foreground or background.

This listener is not working when the app is completely closed.

So now what I want is to make an one shortcut that work's without opening the app. I just want to call a single API whenever the user say "Hey Siri, It's Tea Time" and once the API called Siri have to say back "Your order was placed successfully..." (I want all this process without opening the app).

here are some reference:

https://medium.com/simform-engineering/how-to-integrate-siri-shortcuts-and-design-custom-intents-tutorial-e53285b550cf

https://github.com/Gustash/react-native-siri-shortcut/issues/87


问:
Resuming Interrupted Snapshot in Flink CDC for Incremental Data Migration from MySQL to StarRocks
If the previous snapshot is interrupted, How to resume the snapshot in Flink CDC without using checkpoint?

About 2 billion data are being migrated through Flink CDC from MySQL to StarRocks. The query is performed without the splitEnd value leaving about 100 million, resulting in a timeout.

So I want to proceed with only incremental snapshots for the remaining 100 million.

How should Flink CDC specify options?

I have tried using debezium.snapshot.select.statement.overrides option. But it is not yet supported.


问:
Cannot access item of object for the tooltip of an infographic I am creating
I am trying to edit the description box or 'tooltip' of an infographic I am creating to show specific data. I am able to access the first item in the array named 'data' using the following code:

```<code>tooltip: {
      customContent: (title, data) => {
        const data1 = data[0]
        console.log(data1)
        return `<div>${data1}</div>`
      },
    }
</code>```

See how this displays in the infographic and console:

However when trying to access an item in this object, in my case, 'name' using the following code:

```<code>tooltip: {
      customContent: (title, data) => {
        const data1 = data[0].name
        console.log(data1)
        return `<div>${data1}</div>`
      },
    }
</code>```

I get the following error shown in the image below:

Does anyone have any ideas of how to overcome this? I am using the antdesign graphing library.

Thanks!

Body:
I am trying to edit the description box or 'tooltip' of an infographic I am creating to show specific data. I am able to access the first item in the array named 'data' using the following code:

tooltip: {
      customContent: (title, data) => {
        const data1 = data[0]
        console.log(data1)
        return `<div>${data1}</div>`
      },
    }

See how this displays in the infographic and console:

However when trying to access an item in this object, in my case, 'name' using the following code:

tooltip: {
      customContent: (title, data) => {
        const data1 = data[0].name
        console.log(data1)
        return `<div>${data1}</div>`
      },
    }

I get the following error shown in the image below:

Does anyone have any ideas of how to overcome this? I am using the antdesign graphing library.

Thanks!


问:
Is there any way to perform some action when list item fully swiped to the end. (action except removing item) (library :- flutter_slidable )
I want this type of behavior in list view item swipe.

When user swipe half the list item I want to show some options.

When user click on that option I am performing some task.

When a user swipes an item all the way through to end(mean full swipe), I don't want to remove it; instead, I want to perform a task, and when that task or process is finished, I want to dismiss the swipe.

Here is my Code!

```<code>child: SlidableAutoCloseBehavior(

              child: ListView.separated(
                itemBuilder: ((context, index) => Slidable(
                    closeOnScroll: true,
                    key: UniqueKey(),
                    startActionPane: ActionPane(
                      dismissible: DismissiblePane(
                        onDismissed: () {
                          Fluttertoast.showToast(
                              msg: "Full swipe ${index + 1}");

                        },
                      ),
                      motion: BehindMotion(),
                      children: [
                        SlidableAction(
                            onPressed: (BuildContext context) {
                              Fluttertoast.showToast(
                                  msg: "Unlock ${index + 1}");
                            },
                            backgroundColor: Colors.red,
                            label: "Unlock",
                            icon: Icons.lock_open),
                        SlidableAction(
                            onPressed: (BuildContext context) {
                              Fluttertoast.showToast(msg: "Lock ${index + 1}");
                            },
                            backgroundColor: Colors.green,
                            label: "Lock",
                            icon: Icons.lock_outline),
                      ],
                    ),
                    child: listViewItem(index))),
                separatorBuilder: (BuildContext context, int index) =>
                    const Divider(),
                itemCount: list.length,
              ),
            )
</code>```

I had accomplished the first and second points successfully, but I have no idea how to archive the third point.

Body:
I want this type of behavior in list view item swipe.

When user swipe half the list item I want to show some options.

When user click on that option I am performing some task.

When a user swipes an item all the way through to end(mean full swipe), I don't want to remove it; instead, I want to perform a task, and when that task or process is finished, I want to dismiss the swipe.

Here is my Code!

child: SlidableAutoCloseBehavior(

              child: ListView.separated(
                itemBuilder: ((context, index) => Slidable(
                    closeOnScroll: true,
                    key: UniqueKey(),
                    startActionPane: ActionPane(
                      dismissible: DismissiblePane(
                        onDismissed: () {
                          Fluttertoast.showToast(
                              msg: "Full swipe ${index + 1}");

                        },
                      ),
                      motion: BehindMotion(),
                      children: [
                        SlidableAction(
                            onPressed: (BuildContext context) {
                              Fluttertoast.showToast(
                                  msg: "Unlock ${index + 1}");
                            },
                            backgroundColor: Colors.red,
                            label: "Unlock",
                            icon: Icons.lock_open),
                        SlidableAction(
                            onPressed: (BuildContext context) {
                              Fluttertoast.showToast(msg: "Lock ${index + 1}");
                            },
                            backgroundColor: Colors.green,
                            label: "Lock",
                            icon: Icons.lock_outline),
                      ],
                    ),
                    child: listViewItem(index))),
                separatorBuilder: (BuildContext context, int index) =>
                    const Divider(),
                itemCount: list.length,
              ),
            )

I had accomplished the first and second points successfully, but I have no idea how to archive the third point.


问:
WCF Endpoints cannot be added after the ServiceHost has been opened/faulted/aborted/closed
I have a C# WCF service. To create a localhost port. It works fine on Windows 10 and Windows XP. Windows 11 gives the following error.

System.InvalidOperationException: 'Endpoints cannot be added after the ServiceHost has been opened/faulted/aborted/closed.

My envoriments:

Visual Studio 2022

Windows Forms

.NET Framework 4.8

I can't figure out exactly where the problem is. My code is as follows:

```<code>//WebServiceHost hostWeb = new WebServiceHost(typeof(Service));
            ServiceEndpoint ep = hostWeb.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
            ServiceDebugBehavior stp = hostWeb.Description.Behaviors.Find<ServiceDebugBehavior>();
            stp.HttpHelpPageEnabled = false;
            hostWeb.Open();
</code>```

My service:

```<code>WebServiceHost hostWeb = new WebServiceHost(typeof(Service));

 //[WebGet()]
        [OperationContract]
        [WebInvoke(UriTemplate = "get/mac",
           ResponseFormat = WebMessageFormat.Json)]
        string PostMacAddress(MachineMac data);

        //This operation uses a GET method.
        [OperationContract]
        [WebGet(UriTemplate = "get/secure/mac",
           ResponseFormat = WebMessageFormat.Json)]
        string LookUpArtist();
</code>```

My app.config:

```<code><?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
  </startup>
  <system.webServer>

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
      </customHeaders>
    </httpProtocol>

    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="true">
        </standardEndpoint>
      </webScriptEndpoint>
    </standardEndpoints>

    <bindings>
      <!--<wsHttpBinding>-->
      <basicHttpBinding>
        <binding name="basicHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">
          <security mode="None">
            <!--<transport clientCredentialType="None" />-->
          </security>
          <!--<reliableSession enabled="true" />-->
        </binding>
      </basicHttpBinding>
      <!--</wsHttpBinding>-->

      <webHttpBinding>
        <binding name="webHttp" crossDomainScriptAccessEnabled="true" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">
          <security mode="None">
            <!--<transport clientCredentialType="None" />-->
          </security>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="PharmAnalytics.Services.Service">
        <endpoint address="rest" binding="webHttpBinding" bindingConfiguration="webHttp" contract="PharmAnalytics.Services.IService" behaviorConfiguration="web"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:3366"/>
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- rest api-->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>
</code>```

How can i fix this error?
Thanks!

Body:
I have a C# WCF service. To create a localhost port. It works fine on Windows 10 and Windows XP. Windows 11 gives the following error.

System.InvalidOperationException: 'Endpoints cannot be added after the ServiceHost has been opened/faulted/aborted/closed.

My envoriments:

Visual Studio 2022

Windows Forms

.NET Framework 4.8

I can't figure out exactly where the problem is. My code is as follows:

//WebServiceHost hostWeb = new WebServiceHost(typeof(Service));
            ServiceEndpoint ep = hostWeb.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "");
            ServiceDebugBehavior stp = hostWeb.Description.Behaviors.Find<ServiceDebugBehavior>();
            stp.HttpHelpPageEnabled = false;
            hostWeb.Open();

My service:

WebServiceHost hostWeb = new WebServiceHost(typeof(Service));

 //[WebGet()]
        [OperationContract]
        [WebInvoke(UriTemplate = "get/mac",
           ResponseFormat = WebMessageFormat.Json)]
        string PostMacAddress(MachineMac data);

        //This operation uses a GET method.
        [OperationContract]
        [WebGet(UriTemplate = "get/secure/mac",
           ResponseFormat = WebMessageFormat.Json)]
        string LookUpArtist();

My app.config:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/>
  </startup>
  <system.webServer>

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
      </customHeaders>
    </httpProtocol>

    <modules runAllManagedModulesForAllRequests="true"/>
    <directoryBrowse enabled="true"/>
  </system.webServer>

  <system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true"/>

    <standardEndpoints>
      <webScriptEndpoint>
        <standardEndpoint crossDomainScriptAccessEnabled="true">
        </standardEndpoint>
      </webScriptEndpoint>
    </standardEndpoints>

    <bindings>

      <basicHttpBinding>
        <binding name="basicHttp" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">
          <security mode="None">

          </security>

        </binding>
      </basicHttpBinding>

      <webHttpBinding>
        <binding name="webHttp" crossDomainScriptAccessEnabled="true" openTimeout="00:10:00" closeTimeout="00:10:00" sendTimeout="00:10:00" receiveTimeout="01:00:00" maxBufferPoolSize="2147483647">
          <security mode="None">

          </security>
        </binding>
      </webHttpBinding>
    </bindings>

    <services>
      <service name="PharmAnalytics.Services.Service">
        <endpoint address="rest" binding="webHttpBinding" bindingConfiguration="webHttp" contract="PharmAnalytics.Services.IService" behaviorConfiguration="web"></endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:3366"/>
          </baseAddresses>
        </host>
      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="mexBehaviour">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>

          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

How can i fix this error?
Thanks!


问:
Problems with some event scripts not appearing
enter image description here
In the trading view, short and long are displayed in the coin or general chart.
Shorts and longs are not marked on futures charts. Strategy testers don't run on futures
I am not able to solve this problem I need help</p>
```<code>//@version=5
strategy('hermes signal1', overlay=true, initial_capital=100000, default_qty_value=50000, default_qty_type=strategy.cash, slippage=3, commission_type=strategy.commission.percent, commission_value=0.075, pyramiding=0)
decay = ta.atr(10) * 0.035
stage1 = 7
stage2 = 15
stage3 = 35
p1 = input(5)
p2 = p1 + input(2)
p3 = input.float(0.01, step=0.001)

// 1day

Price = close

PriceTop = low
PriceBot = high

topvector01 = 0.0
topvector01finalcounter = 0.0
botvector01 = 0.0
botvector01finalcounter = 0.0

pretopvector01 = nz(topvector01[1], PriceTop)
topvector01 := PriceTop >= pretopvector01 ? PriceTop : pretopvector01 - decay * topvector01finalcounter[1]
topvector01counter = bar_index - ta.valuewhen(PriceTop >= topvector01, bar_index, 0)
topvector01finalcounter := topvector01counter <= p1 ? stage1 : topvector01counter <= p2 ? stage2 : stage3

prebotvector01 = nz(botvector01[1], PriceBot)
botvector01 := PriceBot <= prebotvector01 ? PriceBot : prebotvector01 + decay * botvector01finalcounter[1]
botvector01counter = bar_index - ta.valuewhen(PriceBot <= botvector01, bar_index, 0)
botvector01finalcounter := botvector01counter <= p1 ? stage1 : botvector01counter <= p2 ? stage2 : stage3

half = (topvector01[1] * 2 + botvector01[1]) / 2
col = half >= close
sig = col ? topvector01 : botvector01

berate(a, b) =>
    ab = math.abs(1 - a / b)
    ab

br_min = berate(sig, half)

comm_cond = br_min < p3 or br_min > br_min[1]
long_cond = close > sig and comm_cond
short_cond = close < sig and comm_cond

if long_cond
    strategy.entry('Long', strategy.long)
if short_cond
    strategy.entry('Short', strategy.short)

color.new(strategy.position_size > 0 ? color.lime : color.red, transp=90)
</code>```

Body:
enter image description here
In the trading view, short and long are displayed in the coin or general chart.
Shorts and longs are not marked on futures charts. Strategy testers don't run on futures
I am not able to solve this problem I need help

//@version=5
strategy('hermes signal1', overlay=true, initial_capital=100000, default_qty_value=50000, default_qty_type=strategy.cash, slippage=3, commission_type=strategy.commission.percent, commission_value=0.075, pyramiding=0)
decay = ta.atr(10) * 0.035
stage1 = 7
stage2 = 15
stage3 = 35
p1 = input(5)
p2 = p1 + input(2)
p3 = input.float(0.01, step=0.001)

// 1day

Price = close

PriceTop = low
PriceBot = high

topvector01 = 0.0
topvector01finalcounter = 0.0
botvector01 = 0.0
botvector01finalcounter = 0.0

pretopvector01 = nz(topvector01[1], PriceTop)
topvector01 := PriceTop >= pretopvector01 ? PriceTop : pretopvector01 - decay * topvector01finalcounter[1]
topvector01counter = bar_index - ta.valuewhen(PriceTop >= topvector01, bar_index, 0)
topvector01finalcounter := topvector01counter <= p1 ? stage1 : topvector01counter <= p2 ? stage2 : stage3

prebotvector01 = nz(botvector01[1], PriceBot)
botvector01 := PriceBot <= prebotvector01 ? PriceBot : prebotvector01 + decay * botvector01finalcounter[1]
botvector01counter = bar_index - ta.valuewhen(PriceBot <= botvector01, bar_index, 0)
botvector01finalcounter := botvector01counter <= p1 ? stage1 : botvector01counter <= p2 ? stage2 : stage3

half = (topvector01[1] * 2 + botvector01[1]) / 2
col = half >= close
sig = col ? topvector01 : botvector01

berate(a, b) =>
    ab = math.abs(1 - a / b)
    ab

br_min = berate(sig, half)

comm_cond = br_min < p3 or br_min > br_min[1]
long_cond = close > sig and comm_cond
short_cond = close < sig and comm_cond

if long_cond
    strategy.entry('Long', strategy.long)
if short_cond
    strategy.entry('Short', strategy.short)

color.new(strategy.position_size > 0 ? color.lime : color.red, transp=90)