问:
.NET Core HttpClient upload byte array gives unsupported media type error
I'm trying to upload a simple byte array for my Web Api controller (ASP.NET Core 3)

```<code>using var client = new HttpClient() { BaseAddress = new Uri("http://someUrl.com/") };
var body = new ByteArrayContent(new byte[] {1, 2, 3});

var result = await client.PostAsync("api/somecontroller/content?someField=someData", body);
</code>```

Controller

```<code>[HttpPost("content")]
public IActionResult Upload([FromBody]byte[] documentData, [FromQuery] string someField)
{
    ...

    return Ok();
}
</code>```

but this gives me the error 415 Unsupported media type. Why ? I need to put some additional data in the url, but I don't think that's the issue here.

答:
Based on the excellent answer from @Rena you can also use the following class to read the request body as a Stream parameter:

public class StreamInputFormatter: InputFormatter
{
  public StreamInputFormatter()
    => SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/octet-stream"));

  protected override bool CanReadType(Type ArgType) => ArgType == typeof(Stream);

  public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext ArgContext)
    => InputFormatterResult.SuccessAsync(ArgContext.HttpContext.Request.Body);
}
```
<p>Your API controller action can then look something like this:</p>
<pre class="lang-cs prettyprint-override"><code>  [HttpPost]
  [Consumes("application/octet-stream")]
  public async Task<ActionResult> UploadData([FromBody] Stream ArgData) {}
</code>```

When you do the above and use Swagger UI via the Swashbuckle.AspNetCore package, it will correctly show a file-input control which allows you to upload the binary data:

Body:
I'm trying to upload a simple byte array for my Web Api controller (ASP.NET Core 3)

using var client = new HttpClient() { BaseAddress = new Uri("http://someUrl.com/") };
var body = new ByteArrayContent(new byte[] {1, 2, 3});

var result = await client.PostAsync("api/somecontroller/content?someField=someData", body);

Controller

[HttpPost("content")]
public IActionResult Upload([FromBody]byte[] documentData, [FromQuery] string someField)
{
    ...

    return Ok();
}

but this gives me the error 415 Unsupported media type. Why ? I need to put some additional data in the url, but I don't think that's the issue here.

Body:
Based on the excellent answer from @Rena you can also use the following class to read the request body as a Stream parameter:

public class StreamInputFormatter: InputFormatter
{
  public StreamInputFormatter()
    => SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("application/octet-stream"));

  protected override bool CanReadType(Type ArgType) => ArgType == typeof(Stream);

  public override Task<InputFormatterResult> ReadRequestBodyAsync(InputFormatterContext ArgContext)
    => InputFormatterResult.SuccessAsync(ArgContext.HttpContext.Request.Body);
}

Your API controller action can then look something like this:

  [HttpPost]
  [Consumes("application/octet-stream")]
  public async Task<ActionResult> UploadData([FromBody] Stream ArgData) {}

When you do the above and use Swagger UI via the Swashbuckle.AspNetCore package, it will correctly show a file-input control which allows you to upload the binary data:


来源: stackexchange

问:
How to make a horizontal ListView in flutter take as much height as its children max height, placed in a column?
I have a horizontal ListView placed in a column, and I want it to have as much height as it only needs. One way to do this is to wrap the ListView in a SizedBox and give it a specific hardcoded height. Also, wrapping it in an Expanded widget will cause the ListView take the additional available space in the column. But, I want it to take as much height as it only needs, automatically.
How can this be achieved?  Thank you.

The sample code is as follows:

```<code>@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            children: [
              Text("Hi there!"),
              SizedBox(
                height: 50,
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  children: List.generate(
                    4,
                    (index) => Text("Item $index "),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: () {},
                child: Text("This is a button"),
              ),
            ],
          ),
        ),
      ),
    );
  }
</code>```

The output is:

But what I want (no more or less space around the ListView):

答:
Unfortunately this is not possible. A ListView could potentially have a lot of items (or even unlimited), so figuring out "the biggest one" requires going through each item, which is against the whole point of using a ListView.

If you only have a few items, you can use Row widget instead. If you need scrolling, wrap Row with a SingleChildScrollView.

For example:

```<code>Column(
  children: [
    Container(
      color: Colors.green.shade100,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            FlutterLogo(),
            FlutterLogo(size: 100),
            for (int i = 0; i < 50; i++) FlutterLogo(),
          ],
        ),
      ),
    ),
    const Text('The row has ended.'),
  ],
)
</code>```

Demo:

ContentLicense: CC BY-SA 4.0

Body:
I have a horizontal ListView placed in a column, and I want it to have as much height as it only needs. One way to do this is to wrap the ListView in a SizedBox and give it a specific hardcoded height. Also, wrapping it in an Expanded widget will cause the ListView take the additional available space in the column. But, I want it to take as much height as it only needs, automatically.
How can this be achieved?  Thank you.

The sample code is as follows:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Padding(
          padding: const EdgeInsets.all(20),
          child: Column(
            children: [
              Text("Hi there!"),
              SizedBox(
                height: 50,
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  shrinkWrap: true,
                  children: List.generate(
                    4,
                    (index) => Text("Item $index "),
                  ),
                ),
              ),
              ElevatedButton(
                onPressed: () {},
                child: Text("This is a button"),
              ),
            ],
          ),
        ),
      ),
    );
  }

The output is:

But what I want (no more or less space around the ListView):

Body:
Unfortunately this is not possible. A ListView could potentially have a lot of items (or even unlimited), so figuring out "the biggest one" requires going through each item, which is against the whole point of using a ListView.

If you only have a few items, you can use Row widget instead. If you need scrolling, wrap Row with a SingleChildScrollView.

For example:

Column(
  children: [
    Container(
      color: Colors.green.shade100,
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: [
            FlutterLogo(),
            FlutterLogo(size: 100),
            for (int i = 0; i < 50; i++) FlutterLogo(),
          ],
        ),
      ),
    ),
    const Text('The row has ended.'),
  ],
)

Demo:


问:
Display TextView after ImageView
I want to display TextView after ImageView but right now Text is coming over Image on my Android screen.

layout:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.sitemakers.sitemakers.AboutFragment">

<ImageView
    android:id="@+id/about_image"
    android:src="@drawable/sitemakers_laptops"
    android:layout_width="match_parent"
    android:scaleType="fitXY"
    android:layout_height="420dp" />

<TextView
    android:layout_below="@+id/about_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Site Makers is the web development company engage in the.."
    />

</FrameLayout>
</code>```

Please see above screenshot and help me update my XML in such a way so that TextView will come after ImageView.

答: You can use linearlayout with orientation="vertical" and Its really easy to implement.</p>

ContentLicense: CC BY-SA 3.0

Title: Display TextView after ImageView

Body:
I want to display TextView after ImageView but right now Text is coming over Image on my Android screen.

layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="in.sitemakers.sitemakers.AboutFragment">

<ImageView
    android:id="@+id/about_image"
    android:src="@drawable/sitemakers_laptops"
    android:layout_width="match_parent"
    android:scaleType="fitXY"
    android:layout_height="420dp" />

<TextView
    android:layout_below="@+id/about_image"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Site Makers is the web development company engage in the.."
    />

</FrameLayout>

Please see above screenshot and help me update my XML in such a way so that TextView will come after ImageView.


问:
How do I check whether this user is anonymous or actually a user on my system?
```<code>def index(request):
    the_user = request.user
</code>```

In Django, how do I know if it's a real user or not?  I tried:

if the_user:  but "AnonymousUser" is there even if no one logs in.  So, it always returns true and this doesn't work.

答:
In Django rest framework it's good idea to use permission classes to check if user is authenticated. This will apply to whole viewSet. In the simpliest form it could look like this:</p>
```<code>from rest_framework.permissions import IsAuthenticated
...
class SomeViewSet(viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]
</code>```

ContentLicense: CC BY-SA 2.5

Body:
def index(request):
    the_user = request.user

In Django, how do I know if it's a real user or not?  I tried:

if the_user:  but "AnonymousUser" is there even if no one logs in.  So, it always returns true and this doesn't work.

Body:
In Django rest framework it's good idea to use permission classes to check if user is authenticated. This will apply to whole viewSet. In the simpliest form it could look like this:

from rest_framework.permissions import IsAuthenticated
...
class SomeViewSet(viewsets.GenericViewSet):
    permission_classes = [IsAuthenticated]


问:
ksqldb iso8601 datetime format return null
Hello i have varchar column with datetime.

its utc

```<code>|2022-02-09T13:27:17.165116Z
|2022-02-09T13:27:27.3850848Z
|2022-02-09T13:28:18.5537284Z
</code>```

on select query parse as by standart but return 'null' for all rows:

```<code>PARSE_TIMESTAMP(entrydate, 'yyyy-MM-ddTHH:mm:ss.SSSZZZZ')
</code>```

code:

```<code>JsonSerializer.Serialize(DateTime.UtcNow);
</code>```

答:
This is because ksqldb only supports up to millisecond precision see https://www.confluent.io/blog/ksqldb-2-0-introduces-date-and-time-data-types/

There is a github issue tracking support for finer time resolution like microseconds here https://github.com/confluentinc/ksql/issues/8243

Body:
Hello i have varchar column with datetime.

its utc

|2022-02-09T13:27:17.165116Z
|2022-02-09T13:27:27.3850848Z
|2022-02-09T13:28:18.5537284Z

on select query parse as by standart but return 'null' for all rows:

PARSE_TIMESTAMP(entrydate, 'yyyy-MM-ddTHH:mm:ss.SSSZZZZ')

code:

JsonSerializer.Serialize(DateTime.UtcNow);


问:
Find Percentage of each class for every ID
I am working with a data frame that has 20 ids and for each Id, there are about 10-15 stores, and each store is assigned a status (Zero, Negative and Positive).

Data:

```<code>data =
ID      STORE  STATUS
100001  1      zero
100001  2      positive
100001  3      zero
100001  4      negative
100001  5      zero
100001  6      zero
100001  7      positive
100001  8      negative
....
</code>```

Problem:

I would like to find out what percentage of stores are zeros/ positive/negative for each id.

My attempt:

```<code>zero = 0

for item in data['ID'].unique():
    items = data[data['ID']==item]
    lenght = len(items)
    print(lenght)
    for index, i in items.iterrows():
        if i['STATUS'] == 'Zero':
            zero += 1
            pct = zero/lenght
    items['PCT'] = zero/lenght
    print(items)

</code>```

My result from code above:

```<code>ID      STORE  STATUS.    PCT
100001  1      zero       0.5
100001  2      positive   0.5
100001  3      zero       0.5
100001  4      negative   0.5
100001  5      zero       0.5
100001  6      zero       0.5
100001  7      positive   0.5
100001  8      negative   0.5

</code>```

Expected result :

```<code>ID      STORE  STATUS.    PCT
100001  1      zero       0.5
100001  2      positive   0.25
100001  3      zero       0.5
100001  4      negative   0.25
100001  5      zero       0.5
100001  6      zero       0.5
100001  7      positive   0.25
100001  8      negative   0.25
</code>```

答:
IIUC, you want to transform the share of each status across stores. Then you can groupby "ID" and "Status" and count how many stores are in each group and transform it for the column and divide it by the length:

```<code>df['PCT'] = df.groupby(['ID','STATUS'])['STORE'].transform('count') / df.groupby('ID')['ID'].transform('count')
</code>```

Output:

```<code>       ID  STORE    STATUS   PCT
0  100001      1      zero  0.50
1  100001      2  positive  0.25
2  100001      3      zero  0.50
3  100001      4  negative  0.25
4  100001      5      zero  0.50
5  100001      6      zero  0.50
6  100001      7  positive  0.25
7  100001      8  negative  0.25
</code>```

Body:
I am working with a data frame that has 20 ids and for each Id, there are about 10-15 stores, and each store is assigned a status (Zero, Negative and Positive).

Data:

data =
ID      STORE  STATUS
100001  1      zero
100001  2      positive
100001  3      zero
100001  4      negative
100001  5      zero
100001  6      zero
100001  7      positive
100001  8      negative
....

Problem:

I would like to find out what percentage of stores are zeros/ positive/negative for each id.

My attempt:

zero = 0

for item in data['ID'].unique():
    items = data[data['ID']==item]
    lenght = len(items)
    print(lenght)
    for index, i in items.iterrows():
        if i['STATUS'] == 'Zero':
            zero += 1
            pct = zero/lenght
    items['PCT'] = zero/lenght
    print(items)

My result from code above:

ID      STORE  STATUS.    PCT
100001  1      zero       0.5
100001  2      positive   0.5
100001  3      zero       0.5
100001  4      negative   0.5
100001  5      zero       0.5
100001  6      zero       0.5
100001  7      positive   0.5
100001  8      negative   0.5

Expected result :

ID      STORE  STATUS.    PCT
100001  1      zero       0.5
100001  2      positive   0.25
100001  3      zero       0.5
100001  4      negative   0.25
100001  5      zero       0.5
100001  6      zero       0.5
100001  7      positive   0.25
100001  8      negative   0.25

Body:
IIUC, you want to transform the share of each status across stores. Then you can groupby "ID" and "Status" and count how many stores are in each group and transform it for the column and divide it by the length:

df['PCT'] = df.groupby(['ID','STATUS'])['STORE'].transform('count') / df.groupby('ID')['ID'].transform('count')

Output:

       ID  STORE    STATUS   PCT
0  100001      1      zero  0.50
1  100001      2  positive  0.25
2  100001      3      zero  0.50
3  100001      4  negative  0.25
4  100001      5      zero  0.50
5  100001      6      zero  0.50
6  100001      7  positive  0.25
7  100001      8  negative  0.25


问:
A typical bracket balanced problem in ocaml
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

```<code>false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"
</code>```
```<code>let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;
</code>```

But I got the following results:

```<code>is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false
</code>```

答:
I believe the problem is with this line:

```<code>  |x::xs,0-> if x =')'then false else left(xs,0)
</code>```

Here, if x is not ), the character is simply ignored. Hence, if it is instead (, level will not be incremented.

The quick fix is to instead match the character directly:

```<code>  | ')'::xs, 0 -> false
</code>```

But I fully agree with @octachron's advice, and that the problem would have been avoided by not mixing list iteration and level counting.

Also, note that you can use when to attach a condition to a branch. For example, if you match on just the list, you could instead do:

```<code>  | ')'::xs when level = 0 -> false
</code>```

And you could also do

```<code>  | ')'::xs when level < 0 -> false
</code>```

which is unnecessary in this case, but serves to demonstrate a case that cannot be covered by pattern matching on level directly.

Body:
I'm trying to create a function which returns a boolean value to see if the string is balanced. But the result is just not what I expect. Can someone point out what I did wrong?

For example:

false = is_balanced")("
false = is_balanced "(a)b)"
true = is_balanced "fo"
true = is_balanced "a(b(c)d)e"

let rec list_car ch = match ch with
  | "" -> []
  | ch -> (String.get ch 0 ) :: (list_car (String.sub ch 1 ( (String.length ch)-1) ) )  ;;

let is_balanced klm =
  let brk = list_car klm in
  let rec left = function
    | x::xs, 0 ->
      if x = ')' then false
      else left (xs, 0)
    | x::xs, level ->
      if x = '(' then left (xs, succ level)
      else if x = ')' then left (xs, pred level)
      else left (xs, level)
    | [], level -> if level = 0 then true else false
  in
  left (brk, 0) ;;

But I got the following results:

is_balanced "(((";;
- : bool = true
 is_balanced "()";;
- : bool = false

Body:
I believe the problem is with this line:

  |x::xs,0-> if x =')'then false else left(xs,0)

Here, if x is not ), the character is simply ignored. Hence, if it is instead (, level will not be incremented.

The quick fix is to instead match the character directly:

  | ')'::xs, 0 -> false

But I fully agree with @octachron's advice, and that the problem would have been avoided by not mixing list iteration and level counting.

Also, note that you can use when to attach a condition to a branch. For example, if you match on just the list, you could instead do:

  | ')'::xs when level = 0 -> false

And you could also do

  | ')'::xs when level < 0 -> false

which is unnecessary in this case, but serves to demonstrate a case that cannot be covered by pattern matching on level directly.


问:
Selenium webdriver element identification fails on machine-generated webpage
I am facing a problem identifying elements on an webpage generated by a machine. I am using Selenium Webdriver for Java and Google Chrome as browser.

So, there are ids and values that look very unusually. I tried to identify the elements by id and xpath so far. Here's some code to my problem.

The select box i want to identify:

```<code><select id="singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person" class="form-control" aria-expanded="false" aria-labelledby="lbl_192_982637" aria-describedby="singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person_Sth"><option aria-selected="false" disabled="" style="display:none" aria-hidden="true"></option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[0]" value="OK" aria-selected="false">Ja, die Gehaltsnachweise liegen vor</option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[1]" value="NOK" aria-selected="false">Ja, es bestehen aber Formmängel</option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[2]" value="NO" aria-selected="false">Nein, die Gehaltsnachweise liegen nicht vor</option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[3]" value="WAIVER" aria-selected="false">Unterlagsverzicht</option></select>
</code>```

Full XPath is:

```<code>/html/body/div[1]/div[2]/div[2]/div[1]/div[2]/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[1]/div/div/select
</code>```

The relative xPath is:

```<code>//*[@id="singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person"]
</code>```

Idetification by id ("singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person") fails also like by xpath, even that the xpath entered in Google Chrome is valid:

Unfortunately i cannot post the whole html page but maybe someone has a clue here. Its a big page, maybe the scrolling is the problem as not all items are visible art once in window?

Last try from first comment (checked the preconditions 1/1)

Translated into Java:

```<code>WebDriverWait wait = new WebDriverWait(driver, 30);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout']")));
        WebElement select = driver.findElement(By.cssSelector("select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout']"));
</code>```

...fails with:

```<code>Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.cssSelector: select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout'] (tried for 30 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:95)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
    at com.commerzbank.test.tool.service.e2e.ChromeTest.main(ChromeTest.java:74)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout']"}
  (Session info: chrome=97.0.4692.71)
</code>```

答:
Long research, short answer. The issue have been some very deep nested iframes, two in my specitfic case, on my big web page. I solved it with the following code snippet:

```<code> wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[contains(@title, 'Manual')]")));
        WebElement parentFrame = driver.findElement(By.xpath("//iframe[contains(@title, 'Manual')]"));
        driver.switchTo().frame(parentFrame);
        wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//iframe[contains(@title, 'Test')]"))));
        WebElement childFrame = driver.findElement(By.xpath("//iframe[contains(@title, 'Test')]"));
        driver.switchTo().frame(childFrame);
</code>```

After switching to the child iframe i could find my element. Cheers.

Body:
I am facing a problem identifying elements on an webpage generated by a machine. I am using Selenium Webdriver for Java and Google Chrome as browser.

So, there are ids and values that look very unusually. I tried to identify the elements by id and xpath so far. Here's some code to my problem.

The select box i want to identify:

<select id="singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person" class="form-control" aria-expanded="false" aria-labelledby="lbl_192_982637" aria-describedby="singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person_Sth"><option aria-selected="false" disabled="" style="display:none" aria-hidden="true"></option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[0]" value="OK" aria-selected="false">Ja, die Gehaltsnachweise liegen vor</option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[1]" value="NOK" aria-selected="false">Ja, es bestehen aber Formmängel</option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[2]" value="NO" aria-selected="false">Nein, die Gehaltsnachweise liegen nicht vor</option><option id="singleselect-option-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person[3]" value="WAIVER" aria-selected="false">Unterlagsverzicht</option></select>

Full XPath is:

/html/body/div[1]/div[2]/div[2]/div[1]/div[2]/div/div[2]/div/div/div/div[2]/div[1]/div[2]/div/div[2]/div/div[2]/div/div[1]/div/div/select

The relative xPath is:

//*[@id="singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person"]

Idetification by id ("singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:VPP001_Person") fails also like by xpath, even that the xpath entered in Google Chrome is valid:

Unfortunately i cannot post the whole html page but maybe someone has a clue here. Its a big page, maybe the scrolling is the problem as not all items are visible art once in window?

Last try from first comment (checked the preconditions 1/1)

Translated into Java:

WebDriverWait wait = new WebDriverWait(driver, 30);
 wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout']")));
        WebElement select = driver.findElement(By.cssSelector("select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout']"));

...fails with:

Exception in thread "main" org.openqa.selenium.TimeoutException: Expected condition failed: waiting for visibility of element located by By.cssSelector: select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout'] (tried for 30 second(s) with 500 milliseconds interval)
    at org.openqa.selenium.support.ui.WebDriverWait.timeoutException(WebDriverWait.java:95)
    at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:272)
    at com.commerzbank.test.tool.service.e2e.ChromeTest.main(ChromeTest.java:74)
Caused by: org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"css selector","selector":"select[id^='singleselect-Vertical_Layout2:QuestionGroup1[0]:QuestionGroup:Vertical_Layout1:Question1[0]:Question:Horizontal_Layout1:'][aria-describedby^='singleselect-Vertical_Layout']"}
  (Session info: chrome=97.0.4692.71)

Body:
Long research, short answer. The issue have been some very deep nested iframes, two in my specitfic case, on my big web page. I solved it with the following code snippet:

 wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//iframe[contains(@title, 'Manual')]")));
        WebElement parentFrame = driver.findElement(By.xpath("//iframe[contains(@title, 'Manual')]"));
        driver.switchTo().frame(parentFrame);
        wait.until(ExpectedConditions.visibilityOfElementLocated((By.xpath("//iframe[contains(@title, 'Test')]"))));
        WebElement childFrame = driver.findElement(By.xpath("//iframe[contains(@title, 'Test')]"));
        driver.switchTo().frame(childFrame);

After switching to the child iframe i could find my element. Cheers.


问:
ConvertTo-JSON an array with a single item
I'm trying to create a JSON-serialized array. When that array contains only one item I get a string, not an array of strings (in JSON).

Multiple Items (works as expected):

```<code>PS C:\> @("one", "two") | ConvertTo-JSON
[
    "one",
    "two"
]
</code>```

Single Item Array (not as expected):

```<code>PS C:\> @("one") | ConvertTo-JSON
"one"
</code>```

Am I missing something?

答:
Place a , in front of @:</p>
```<code>,@("one") | ConvertTo-Json
[
  "one"
]
</code>```

Body:
I'm trying to create a JSON-serialized array. When that array contains only one item I get a string, not an array of strings (in JSON).

Multiple Items (works as expected):

PS C:\> @("one", "two") | ConvertTo-JSON
[
    "one",
    "two"
]

Single Item Array (not as expected):

PS C:\> @("one") | ConvertTo-JSON
"one"

Am I missing something?

Body:
Place a , in front of @:

,@("one") | ConvertTo-Json
[
  "one"
]


问:
Problem running SSIS package: "Data source name not found and no default driver specified"
I've developed a SSIS package that takes some data as an XML file, processes it and inserts it into our DB. When the package is being debugged (i.e. running in BIDS), it works fine from my local machine. I can also compile the package to a .dtsx file and run it via command line by executing DTExec.exe. I am running SQL Server 2005. When I move it to a test server, also running SQL Server 2005, and Integration services, I cannot execute the package via command line. I keep receiving this error

Error: 2011-08-16 17:50:39.11
 Code: 0xC0202009
 Source: ProcessSubmissionData Connection manager "Master"
 Description: An OLE DB error has occurred. Error code: 0x80004005.
An OLE DB record is available. Source: "Microsoft OLE DB Provider for ODBC Drivers" Hresult: 0x80004005 Description: "[Microsoft][ODBC Driver Manager]
Data source name not found and no default driver specified".
End Error

I've searched the web and tried every solution I can find, to no avail. Is there anyone who can help with this? If it helps, this is the connection string that the connection manager is using

Data Source=xxxx;User ID=xxxx;Password=xxxx;Initial Catalog=database;Provider=SQLOLEDB;

答:
The error is telling you that the Data Source Name (DSN) does not exist rather than the ODBC Driver.

So, if you machine is 32bit then it seems you have simply not created an ODBC Data Source (DSN) via the ODBC Administrator.

(The parameters within the DSN itself determine which ODBC Driver is used...)

Also - this needs to be a "System" DSN (Not a User DSN) since applications running as a system service will not have access to User DSNs. User DSNs are only available on a per user basis when that user is logged in!!!


问:
Yii2 can not find model file
I have the following directories and files in them:

```<code>- backend
   - models
        Book.php

- frontend

- common
   - OOP
      CommonController.php
</code>```

book.php

```<code>class Book extends ActiveRecord
{
...
}
</code>```

commonController.php

```<code>  public function actionIndex()
  {
    $path="backend\\models\\Book";
    $model=$path::find();
  }
</code>```

In Windows OS it works fine. But in Linux line of $model=$path::find(); throws an error:

```<code>'backend\models\Book' not found
</code>```

So, I changed $path to "backend/models/Book". But, still, I have the following error:

```<code>'backend/models/Book' not found
</code>```

答:
The problem is in case sensitivity.

The file with class Book should be named Book.php. Paths in windows are case-insensitive so it works fine. But in Linux, they are case-sensitive so autoloader looks for class in file backend/models/Book.php which doesn't exist.

The format backend\models\Book in your code is right because this is not filepath but fully qualified name which uses backslash as namespace separator.

Title: Yii2 can not find model file

Body:
I have the following directories and files in them:

- backend
   - models
        Book.php

- frontend

- common
   - OOP
      CommonController.php

book.php

class Book extends ActiveRecord
{
...
}

commonController.php

  public function actionIndex()
  {
    $path="backend\\models\\Book";
    $model=$path::find();
  }

In Windows OS it works fine. But in Linux line of $model=$path::find(); throws an error:

'backend\models\Book' not found

So, I changed $path to "backend/models/Book". But, still, I have the following error:

'backend/models/Book' not found


问:
<Link to=> not switching pages
I've been working on this dropdown menu for a while but I can't seem to get the dropdown menu to change the page I'm on and I don't understand what's wrong with it I am really new to ReactJs, I have a module called DropDownMenu it is calling DropDownItem and when DropDownItem is clicked is called a function called handle click but in the HandleClick it is not switching the page to the current Props.Route clicked on and i don't know enough of whats going on to really figure it out

```<code>import React from "react";
import { Link } from "react-router-dom";

function DropdownItem(props) {
  const handleClick = () => {
    <Link to={props.route}></Link>;
    console.log(props.route);
  };

  return (
    <a href="#" className="menu-item" onClick={handleClick}>
      <span className="icon-button">{props.leftIcon}</span>
      <span className="Route">{props.route}</span>

      {props.children}
      <span className="icon-right">{props.rightIcon}</span>
    </a>
  );
}

export default DropdownItem;
</code>```

答:
You can use useHistory hook.you may use to navigate.

when you use react router dom v5

```<code>      import { useHistory } from "react-router-dom";

     let history = useHistory();
     const handleClick = () => {
        history.push(`/${props.route}`);
        console.log(props.route);
      };
</code>```

when you use react router dom v5

import { useHistory } from "react-router-dom";

```<code>      const navigate = useNavigate();
     const handleClick = () => {
       navigate(`../${props.route}`, { replace: true });
        console.log(props.route);
      };
</code>```

Title: <Link to=> not switching pages

Body:
I've been working on this dropdown menu for a while but I can't seem to get the dropdown menu to change the page I'm on and I don't understand what's wrong with it I am really new to ReactJs, I have a module called DropDownMenu it is calling DropDownItem and when DropDownItem is clicked is called a function called handle click but in the HandleClick it is not switching the page to the current Props.Route clicked on and i don't know enough of whats going on to really figure it out

import React from "react";
import { Link } from "react-router-dom";

function DropdownItem(props) {
  const handleClick = () => {
    <Link to={props.route}></Link>;
    console.log(props.route);
  };

  return (

      {props.leftIcon}
      {props.route}

      {props.children}
      {props.rightIcon}

  );
}

export default DropdownItem;

Body:
You can use useHistory hook.you may use to navigate.

when you use react router dom v5

      import { useHistory } from "react-router-dom";

     let history = useHistory();
     const handleClick = () => {
        history.push(`/${props.route}`);
        console.log(props.route);
      };

when you use react router dom v5

import { useHistory } from "react-router-dom";

      const navigate = useNavigate();
     const handleClick = () => {
       navigate(`../${props.route}`, { replace: true });
        console.log(props.route);
      };


问:
Insert leaflet widget in README.md
I would like to include a map in the README page of an R-Packages repository (vegtable), but I don't know, if it is really possible. For instance one example:

```<code>---
output:
  github_document:
    html_preview: false
---

```{r,echo=FALSE}
knitr::opts_chunk$set(
  collapse=TRUE,
  comment="#>",
  fig.path="man/figures/"
)
```

How to do a map:

```{r}
library(vegtable)
library(leaflet)

leaflet(Kenya_veg@header) %>%
    addTiles() %>%
    addCircleMarkers(lng = ~LONGITUDE, lat = ~LATITUDE, color = "red",
            opacity = 0.3, radius = 1)

```
</code>```

There was a hint of including always_allow_html: true in the yaml head but it is not getting the desired behavior.

答:
I think that is not possible. You can do

---
output:
  md_document:
    variant: gfm
    preserve_yaml: true
---

```
<p>And probably it would render with something like:</p>
<pre class="lang-html prettyprint-override"><code>
  <script type="application/json"data-for="7ab57412f7b1df4d5773">
    {"x":{"options":
      ...
      "jsHooks":[]}
  </script>

</code>```

The problem is that Leaflet is a JavaScript library for use in html. For rendering it properly, the md file should be parsed as html (something that GH is not doing, the README is rendered as Markdown) and you would need to inject the leaflet js library on the GH page, that is something that I doubt you can do.

This post may give you some hints about how troublesome could be using leaflet on a markdown format:

https://dieghernan.github.io/201905_Leaflet_R_Jekyll/

Title: Insert leaflet widget in README.md

Body:
I would like to include a map in the README page of an R-Packages repository (vegtable), but I don't know, if it is really possible. For instance one example:

---
output:
  github_document:
    html_preview: false
---

```{r,echo=FALSE}
knitr::opts_chunk$set(
  collapse=TRUE,
  comment="#>",
  fig.path="man/figures/"
)
```

How to do a map:

```{r}
library(vegtable)
library(leaflet)

leaflet(Kenya_veg@header) %>%
    addTiles() %>%
    addCircleMarkers(lng = ~LONGITUDE, lat = ~LATITUDE, color = "red",
            opacity = 0.3, radius = 1)

```

There was a hint of including always_allow_html: true in the yaml head but it is not getting the desired behavior.

Body:
I think that is not possible. You can do

---
output:
  md_document:
    variant: gfm
    preserve_yaml: true
---

And probably it would render with something like:

  <script type="application/json"data-for="7ab57412f7b1df4d5773">
    {"x":{"options":
      ...
      "jsHooks":[]}
  </script>

The problem is that Leaflet is a JavaScript library for use in html. For rendering it properly, the md file should be parsed as html (something that GH is not doing, the README is rendered as Markdown) and you would need to inject the leaflet js library on the GH page, that is something that I doubt you can do.

This post may give you some hints about how troublesome could be using leaflet on a markdown format:

https://dieghernan.github.io/201905_Leaflet_R_Jekyll/


问:
mod_log_sql_mysql : database connection error
I'm trying to use mod_log_sql to log access log in a mysql database. (The OS is Debian 10)
My database config is fine (double checked)... but it doesn't work and the error I get in the appache error.log is :

```<code>mod_log_sql_mysql:
  database connection error:
    mysql error: Unknown MySQL server host 'loguser' (-2)
</code>```

My virtualhost.conf has the following:

LogSQLLoginInfo mysql://loguser:password@localhost:3306/apachelogs

Following the pattern driver://username[:password]@hostname[:port]/database

What is strange is that the error shows a confusion between the user and the host:

```<code> params : Unknown MySQL server host 'loguser'
</code>```

whereas 'loguser' is the username.

Any ideas where the problem comes from?

答:
Can you upload any code? I use:

```<code>$conn = new mysqli($servername, $username, $password, $dbname);
</code>```

To make a connection.

Body:
I'm trying to use mod_log_sql to log access log in a mysql database. (The OS is Debian 10)
My database config is fine (double checked)... but it doesn't work and the error I get in the appache error.log is :

mod_log_sql_mysql:
  database connection error:
    mysql error: Unknown MySQL server host 'loguser' (-2)

My virtualhost.conf has the following:

LogSQLLoginInfo mysql://loguser:password@localhost:3306/apachelogs

Following the pattern driver://username[:password]@hostname[:port]/database

What is strange is that the error shows a confusion between the user and the host:

 params : Unknown MySQL server host 'loguser'

whereas 'loguser' is the username.

Any ideas where the problem comes from?

Body:
Can you upload any code? I use:

$conn = new mysqli($servername, $username, $password, $dbname);

To make a connection.


问:
How to solve this error while making training file in python
So I have been making an A.I. program with 0 experience in coding in python just as a hobby. While making the training file, I faced an error and I am not able to solve it.

This is my Training file-

```<code>import numpy as np
import json
import torch
import torch.nn as nn
from torch.utils.data import Dataset,DataLoader
from NeuralNetwork import bag_of_words , tokenize , stem
from Brain import NeuralNet

with open('intents.json','r') as f:
    intents = json.load(f)

all_words = []
tags = []
xy = []

for intent in intents['intents']:
    tag = intent['tag']
    tags.append(tag)

    for pattern in intent['patterns']:
        w = tokenize(pattern)
        all_words.extend(w)
        xy.append((w,tag))

ignore_words = [',','?','/','.','!']
all_words = [stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))

x_train = []
y_train = []

for (pattern_sentence,tag) in xy:
    bag = bag_of_words(pattern_sentence,all_words)
    x_train.append(bag)

    label = tags.index(tag)
    y_train.append(label)

x_train = np.array(x_train)
y_train = np.array(y_train)

num_epochs = 1000
batch_size = 8
learning_rate = 0.001
input_size = len(x_train[0])
hidden_size = 8
output_size = len(tags)

print("Training the model...")

class ChatDataset(Dataset):

    def __init__(self):
        self.n_samples = len(x_train)
        self.x_data = x_train
        self.y_data = y_train

    def __getitem__(self,index):
        return self.x_data[index],self.y_data[index]

    def __len__(self):
        return self.n_samples

dataset = ChatDataset()

train_loader = DataLoader(dataset=dataset,
                            batch_size=batch_size,
                            shuffle=True,
                            num_workers=0)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = NeuralNet(input_size,hidden_size,output_size).to(device=device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)

for epoch in range(num_epochs):
    for (words,labels) in train_loader:
        words = words.to(device)
        labels = labels.to(dtype=torch.long).to(device)
        outputs = model(words)
        loss = criterion(outputs,labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    if (epoch+1) % 100 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')

print(f'Final Loss : {loss.item():.4f}')

data = {
"model_state":model.state_dict(),
"input_size":input_size,
"hidden_size":hidden_size,
"output_size":output_size,
"all_words":all_words,
"tags":tags
}

FILE = "TrainData.pth"
torch.save(data,FILE)

print(f"Training Completed, File Saved to {FILE}")
</code>```

This is the program which contains all the layers of the neural network which I have named as Brain.py-

```<code>import torch.nn as nn

class NeuralNet(nn.Module):

    def __init__(self,input_size,hidden_size,num_classes):
        super(NeuralNet,self).__init__()
        self.l1 = nn.Linear(input_size,hidden_size)
        self.l2 = nn.Linear(input_size,hidden_size)
        self.l3 = nn.Linear(hidden_size,num_classes)
        self.relu = nn.ReLU()

    def forward(self,x):
        out = self.l1(x)
        out = self.relu(out)
        out = self.l2(out)
        out = self.relu(out)
        out = self.l3(out)
        return out

</code>```

And this is the error which VSCode is sending me-

```<code>File "f:/Aryav files/J.A.R.V.I.S/J.A.R.V.I.S. Mark III/Train.py", line 81, in <module>
    outputs = model(words)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\linear.py", line 103, in forward
    return F.linear(input, self.weight, self.bias)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\functional.py", line 1848, in linear
    return torch._C._nn.linear(input, weight, bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x8 and 15x8)
</code>```

I am a very beginner in programming so please tell me the exact line no. and the line which I need to replace it with. Thank You

答:
In your second layer you are putting input_size as a dimention instead of hidden_size(which is your output size of the previous layer).
Use the following lines in your model:</p>
```<code>self.l1 = nn.Linear(input_size,hidden_size)
self.l2 = nn.Linear(hidden_size,hidden_size)
self.l3 = nn.Linear(hidden_size,num_classes)
</code>```

Body:
So I have been making an A.I. program with 0 experience in coding in python just as a hobby. While making the training file, I faced an error and I am not able to solve it.

This is my Training file-

import numpy as np
import json
import torch
import torch.nn as nn
from torch.utils.data import Dataset,DataLoader
from NeuralNetwork import bag_of_words , tokenize , stem
from Brain import NeuralNet

with open('intents.json','r') as f:
    intents = json.load(f)

all_words = []
tags = []
xy = []

for intent in intents['intents']:
    tag = intent['tag']
    tags.append(tag)

    for pattern in intent['patterns']:
        w = tokenize(pattern)
        all_words.extend(w)
        xy.append((w,tag))

ignore_words = [',','?','/','.','!']
all_words = [stem(w) for w in all_words if w not in ignore_words]
all_words = sorted(set(all_words))
tags = sorted(set(tags))

x_train = []
y_train = []

for (pattern_sentence,tag) in xy:
    bag = bag_of_words(pattern_sentence,all_words)
    x_train.append(bag)

    label = tags.index(tag)
    y_train.append(label)

x_train = np.array(x_train)
y_train = np.array(y_train)

num_epochs = 1000
batch_size = 8
learning_rate = 0.001
input_size = len(x_train[0])
hidden_size = 8
output_size = len(tags)

print("Training the model...")

class ChatDataset(Dataset):

    def __init__(self):
        self.n_samples = len(x_train)
        self.x_data = x_train
        self.y_data = y_train

    def __getitem__(self,index):
        return self.x_data[index],self.y_data[index]

    def __len__(self):
        return self.n_samples

dataset = ChatDataset()

train_loader = DataLoader(dataset=dataset,
                            batch_size=batch_size,
                            shuffle=True,
                            num_workers=0)

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = NeuralNet(input_size,hidden_size,output_size).to(device=device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(),lr=learning_rate)

for epoch in range(num_epochs):
    for (words,labels) in train_loader:
        words = words.to(device)
        labels = labels.to(dtype=torch.long).to(device)
        outputs = model(words)
        loss = criterion(outputs,labels)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    if (epoch+1) % 100 == 0:
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')

print(f'Final Loss : {loss.item():.4f}')

data = {
"model_state":model.state_dict(),
"input_size":input_size,
"hidden_size":hidden_size,
"output_size":output_size,
"all_words":all_words,
"tags":tags
}

FILE = "TrainData.pth"
torch.save(data,FILE)

print(f"Training Completed, File Saved to {FILE}")

This is the program which contains all the layers of the neural network which I have named as Brain.py-

import torch.nn as nn

class NeuralNet(nn.Module):

    def __init__(self,input_size,hidden_size,num_classes):
        super(NeuralNet,self).__init__()
        self.l1 = nn.Linear(input_size,hidden_size)
        self.l2 = nn.Linear(input_size,hidden_size)
        self.l3 = nn.Linear(hidden_size,num_classes)
        self.relu = nn.ReLU()

    def forward(self,x):
        out = self.l1(x)
        out = self.relu(out)
        out = self.l2(out)
        out = self.relu(out)
        out = self.l3(out)
        return out

And this is the error which VSCode is sending me-

File "f:/Aryav files/J.A.R.V.I.S/J.A.R.V.I.S. Mark III/Train.py", line 81, in <module>
    outputs = model(words)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\module.py", line 1102, in _call_impl
    return forward_call(*input, **kwargs)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\modules\linear.py", line 103, in forward
    return F.linear(input, self.weight, self.bias)
  File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\site-packages\torch\nn\functional.py", line 1848, in linear
    return torch._C._nn.linear(input, weight, bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (8x8 and 15x8)

I am a very beginner in programming so please tell me the exact line no. and the line which I need to replace it with. Thank You

Body:
In your second layer you are putting input_size as a dimention instead of hidden_size(which is your output size of the previous layer).
Use the following lines in your model:

self.l1 = nn.Linear(input_size,hidden_size)
self.l2 = nn.Linear(hidden_size,hidden_size)
self.l3 = nn.Linear(hidden_size,num_classes)


问:
How can I set some values using currentTarget with jQuery from different HTML elements?
Can anyone give me a hand with this?

I am trying to obtain different values depending which button is clicked and assign it into a variable.

A friend told me to add the values in an input to later by extracted by e.currentTarget but I was unable to make it work.

HTML:

```<code><div class="curso-contenedor">
        <div class="curso">

            <input id="precio" value='12000' hidden>
            <input id="cursoNombre" value='Web Developer' hidden>

            <form><button class="btn-curso web-developer" id="webDeveloper">Agregar</button></form>

        </div>
        <div class="curso">

            <input id="precio" value='13000' hidden>
            <input id="cursoNombre" value='Marketing Digital' hidden>

            <form><button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button></form>

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

jQuery:

```<code>$('.btn-curso').click(function(e){

  let curso  = {'precio': e.currentTarget('#precio'), 'curso': e.currentTarget('#cursoNombre')};

  localStorage.setItem('datosCurso', JSON.stringify(curso));

  e.preventDefault()
});
</code>```

If anyone knows how to do this it would mean the world if you can help me since I have been trapped with this for days now trying different things.

答:
Try this:
HTML

```<code>    <div class="curso-contenedor">
        <div class="curso">

            <input name="precio" value='12000' hidden>
            <input name="cursoNombre" value='Web Developer' hidden>

            <button class="btn-curso web-developer" id="webDeveloper">Agregar</button>

        </div>
        <div class="curso">

            <input name="precio" value='13000' hidden>
            <input name="cursoNombre" value='Marketing Digital' hidden>

            <button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button>

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

JQuery:

```<code>        $('.curso-contenedor').on('click', '.curso', function(e){

            let curso  = {
                'precio': $(e.currentTarget).find('input[name=precio]').val(),
                'curso': $(e.currentTarget).find('input[name=cursoNombre]').val()
            };

            localStorage.setItem('datosCurso', JSON.stringify(curso));

            e.preventDefault()
        });
</code>```

You should add delegate event listener to parent element

For more information: https://api.jquery.com/on/

Body:
Can anyone give me a hand with this?

I am trying to obtain different values depending which button is clicked and assign it into a variable.

A friend told me to add the values in an input to later by extracted by e.currentTarget but I was unable to make it work.

HTML:

            <input id="precio" value='12000' hidden>
            <input id="cursoNombre" value='Web Developer' hidden>

            <form><button class="btn-curso web-developer" id="webDeveloper">Agregar</button></form>

            <input id="precio" value='13000' hidden>
            <input id="cursoNombre" value='Marketing Digital' hidden>

            <form><button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button></form>

jQuery:

$('.btn-curso').click(function(e){

  let curso  = {'precio': e.currentTarget('#precio'), 'curso': e.currentTarget('#cursoNombre')};

  localStorage.setItem('datosCurso', JSON.stringify(curso));

  e.preventDefault()
});

If anyone knows how to do this it would mean the world if you can help me since I have been trapped with this for days now trying different things.

Body:
Try this:
HTML

    <div class="curso-contenedor">
        <div class="curso">

            <input name="precio" value='12000' hidden>
            <input name="cursoNombre" value='Web Developer' hidden>

            <button class="btn-curso web-developer" id="webDeveloper">Agregar</button>

        </div>
        <div class="curso">

            <input name="precio" value='13000' hidden>
            <input name="cursoNombre" value='Marketing Digital' hidden>

            <button class="btn-curso marketing-Digital" id="marketinDigital">Agregar</button>

        </div>
    </div>

JQuery:

        $('.curso-contenedor').on('click', '.curso', function(e){

            let curso  = {
                'precio': $(e.currentTarget).find('input[name=precio]').val(),
                'curso': $(e.currentTarget).find('input[name=cursoNombre]').val()
            };

            localStorage.setItem('datosCurso', JSON.stringify(curso));

            e.preventDefault()
        });

You should add delegate event listener to parent element

For more information: https://api.jquery.com/on/


问:
DevOps CI/CD pipelines broken after Kubernetes upgrade to v1.22

Present state

In v1.22 Kubernetes dropped support for v1beta1 API. That made our release pipeline crash and we are not sure how to fix it.

We use build pipelines to build .NET Core applications and deploy them to the Azure Container Registry. Then there are release pipelines that use helm to upgrade them in the cluster from that ACR. This is how it looks exactly.

Build pipeline:

.NET download, restore, build, test, publish

Docker task v0: Build task

Docker task v0: Push to the ACR task

Artifact publish to Azure Pipelines

Release pipeline:

Helm tool installer: Install helm v3.2.4 (check for latest version of Helm unchecked) and install newest Kubectl (Check for latest version checked)

Bash task:

```<code>az acr login --name <acrname>
az acr helm repo add --name <acrname>
</code>```

Helm upgrade task:

chart name <acrname>/<chartname>

version empty

release name `

After the upgrade to Kubernetes v1.22 we are getting the following error in Release step 3.:

Error: UPGRADE FAILED: unable to recognize "": no matches for kind "Ingress" in version "extensions/v1beta1".

What I've already tried

Error is pretty obvious and from Helm compatibility table it states clearly that I need to upgrade the release pipelines to use at least Helm v3.7.x. Unfortunately in this version OCI functionality (about this shortly) is still in experimental phase so at least v3.8.x has to be used.

Bumping helm version to v3.8.0

That makes release step 3. report:

Error: looks like "https://<acrname>.azurecr.io/helm/v1/repo" is not a valid chart repository or cannot be reached: error unmarshaling JSON: while decoding JSON: json: unknown field "acrMetadata"

After reading Microsoft tutorial on how to live with helm and ACR I learned that az acr helm commands use helm v2 so are deprecated and OCI artifacts should be used.

Switching to OCI part 1

After reading that I changed release step 2. to a one-liner:

helm registry login <acrname>.azurecr.io  --username <username> --password <password>

That now gives me Login Succeeded in release step 2. but release step 3. fails with

Error: failed to download "<acrname>/<reponame>".

Switching to OCI part 2

I thought that the helm task is incompatible or something with the new approach so I removed release step 3. and decided to make it from the command line in step 2. So now step 2. looks like this:

```<code>helm registry login <acrname>.azurecr.io  --username <username> --password <password>
helm upgrade --install --wait -n <namespace> <deploymentName> oci://<acrname>.azurecr.io/<reponame> --version latest --values ./values.yaml
</code>```

Unfortunately, that still gives me:

Error: failed to download "oci://<acrname>.azurecr.io/<reponame>" at version "latest"

Helm pull, export, upgrade instead of just upgrade

The next try was to split the help upgrade into separately helm pull, helm export and then helm upgrade but

helm pull oci://<acrname>.azurecr.io/<reponame> --version latest

gives me:

Error: manifest does not contain minimum number of descriptors (2), descriptors found: 0

Changing docker build and docker push tasks to v2

I also tried changing the docker tasks in the build pipelines to v2. But that didn't change anything at all.

答:
Have you tried changing the Ingress object's apiVersion to networking.k8s.io/v1beta1 or networking.k8s.io/v1? Support for Ingress in the extensions/v1beta1 API version is dropped in k8s 1.22.

Our ingress.yaml file in our helm chart looks something like this to support multiple k8s versions. You can ignore the AWS-specific annotations since you're using Azure. Our chart has a global value of  ingress.enablePathType because at the time of writing the yaml file, AWS Load Balancer did not support pathType and so we set the value to false.

{{- if .Values.global.ingress.enabled -}}
{{- $useV1Ingress := and (.Capabilities.APIVersions.Has "networking.k8s.io/v1/Ingress") .Values.global.ingress.enablePathType -}}
{{- if $useV1Ingress -}}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
  name: example-ingress
  labels:
    {{- include "my-chart.labels" . | nindent 4 }}
  annotations:
    {{- if .Values.global.ingress.group.enabled }}
    alb.ingress.kubernetes.io/group.name: {{ required "ingress.group.name is required when ingress.group.enabled is true" .Values.global.ingress.group.name }}
    {{- end }}
    {{- with .Values.global.ingress.annotations }}
    {{- toYaml . | nindent 4 }}
    {{- end }}
    # Add these tags to the AWS Application Load Balancer
    alb.ingress.kubernetes.io/tags: k8s.namespace/{{ .Release.Namespace }}={{ .Release.Namespace }}
spec:
  rules:
    - host: {{ include "my-chart.applicationOneServerUrl" . | quote }}
      http:
        paths:
          {{- if $useV1Ingress }}
          - path: /
            pathType: Prefix
            backend:
              service:
                name: {{ $applicationOneServiceName }}
                port:
                  name: http-grails
          {{- else }}
          - path: /*
            backend:
              serviceName: {{ $applicationOneServiceName }}
              servicePort: http-grails
          {{- end }}
    - host: {{ include "my-chart.applicationTwoServerUrl" . | quote }}
      http:
        paths:
          {{- if $useV1Ingress }}
          - path: /
            pathType: Prefix
            backend:
              service:
                name: {{ .Values.global.applicationTwo.serviceName }}
                port:
                  name: http-grails
          {{- else }}
          - path: /*
            backend:
              serviceName: {{ .Values.global.applicationTwo.serviceName }}
              servicePort: http-grails
          {{- end }}
{{- end }}
```

Body:
Present state

In v1.22 Kubernetes dropped support for v1beta1 API. That made our release pipeline crash and we are not sure how to fix it.

We use build pipelines to build .NET Core applications and deploy them to the Azure Container Registry. Then there are release pipelines that use helm to upgrade them in the cluster from that ACR. This is how it looks exactly.

Build pipeline:

.NET download, restore, build, test, publish

Docker task v0: Build task

Docker task v0: Push to the ACR task

Artifact publish to Azure Pipelines

Release pipeline:

Helm tool installer: Install helm v3.2.4 (check for latest version of Helm unchecked) and install newest Kubectl (Check for latest version checked)

Bash task:

az acr login --name <acrname>
az acr helm repo add --name <acrname>

Helm upgrade task:

chart name <acrname>/<chartname>

version empty

release name `

After the upgrade to Kubernetes v1.22 we are getting the following error in Release step 3.:

Error: UPGRADE FAILED: unable to recognize "": no matches for kind "Ingress" in version "extensions/v1beta1".

What I've already tried

Error is pretty obvious and from Helm compatibility table it states clearly that I need to upgrade the release pipelines to use at least Helm v3.7.x. Unfortunately in this version OCI functionality (about this shortly) is still in experimental phase so at least v3.8.x has to be used.

Bumping helm version to v3.8.0

That makes release step 3. report:

Error: looks like "https://<acrname>.azurecr.io/helm/v1/repo" is not a valid chart repository or cannot be reached: error unmarshaling JSON: while decoding JSON: json: unknown field "acrMetadata"

After reading Microsoft tutorial on how to live with helm and ACR I learned that az acr helm commands use helm v2 so are deprecated and OCI artifacts should be used.

Switching to OCI part 1

After reading that I changed release step 2. to a one-liner:

helm registry login <acrname>.azurecr.io  --username <username> --password <password>

That now gives me Login Succeeded in release step 2. but release step 3. fails with

Error: failed to download "<acrname>/<reponame>".

Switching to OCI part 2

I thought that the helm task is incompatible or something with the new approach so I removed release step 3. and decided to make it from the command line in step 2. So now step 2. looks like this:

helm registry login <acrname>.azurecr.io  --username <username> --password <password>
helm upgrade --install --wait -n <namespace> <deploymentName> oci://<acrname>.azurecr.io/<reponame> --version latest --values ./values.yaml

Unfortunately, that still gives me:

Error: failed to download "oci://<acrname>.azurecr.io/<reponame>" at version "latest"

Helm pull, export, upgrade instead of just upgrade

The next try was to split the help upgrade into separately helm pull, helm export and then helm upgrade but

helm pull oci://<acrname>.azurecr.io/<reponame> --version latest

gives me:

Error: manifest does not contain minimum number of descriptors (2), descriptors found: 0

Changing docker build and docker push tasks to v2

I also tried changing the docker tasks in the build pipelines to v2. But that didn't change anything at all.


问:
Python play again
I am trying to add a play again y/n option but the game asks me to pick a number before asking to play again (if it were to work) and the play again option doesn't pop up.

Code:

```<code>import sys
import os
import time
import random
import colorama
from colorama import Fore
import random
from sys import stdout as s
from time import sleep as j
def w(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
  next = input()
def noinput(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
while True:
  num = random.randint(1, 50)
  guess = "none"

  while guess != num:
    guess = input(Fore.CYAN + "Choose a number: ")
    guess = int(guess)

    if guess == num:
      w(Fore.GREEN + "You guessed the correct number!")
      break
    else:
      w(Fore.RED + "Sorry try again")

    if guess > num:
      w("your number is too large")
      os.system('clear')
    else:
      w("your number is too small")
      os.system('clear')

  play_again = input(Fore.BLUE + "Play again? y/n: ")
  os.system('clear')
  if play_again.lower() != ("y"):
   break
</code>```

I would like to know why this is not working:

```<code>play_again = input(Fore.BLUE + "Play again? y/n: ")
os.system('clear')
if play_again.lower() != ("y"):
 break
</code>```

Help appreciated

答:
Your code is not properly indented.
Every control flow statement should be followed by an additional level of indentation.

As is we cannot comment on why your code doesn't work as expected, since it does not work at all :)

Title: Python play again

Body:
I am trying to add a play again y/n option but the game asks me to pick a number before asking to play again (if it were to work) and the play again option doesn't pop up.

Code:

import sys
import os
import time
import random
import colorama
from colorama import Fore
import random
from sys import stdout as s
from time import sleep as j
def w(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
  next = input()
def noinput(print):
  for i in print:
    j(.03)
    s.write(i)
    s.flush()
while True:
  num = random.randint(1, 50)
  guess = "none"

  while guess != num:
    guess = input(Fore.CYAN + "Choose a number: ")
    guess = int(guess)

    if guess == num:
      w(Fore.GREEN + "You guessed the correct number!")
      break
    else:
      w(Fore.RED + "Sorry try again")

    if guess > num:
      w("your number is too large")
      os.system('clear')
    else:
      w("your number is too small")
      os.system('clear')

  play_again = input(Fore.BLUE + "Play again? y/n: ")
  os.system('clear')
  if play_again.lower() != ("y"):
   break

I would like to know why this is not working:

play_again = input(Fore.BLUE + "Play again? y/n: ")
os.system('clear')
if play_again.lower() != ("y"):
 break

Help appreciated


问:
Chrome Extension - Change styles.CSS var not working
Sorry, I messed that up. I did not update the manifest from the last post and I forgot the content.js, that is how the Change button was sending the value and the page was getting the new style attribute value from the one entered in the text field and then to the content.js, existing content.js file added below.

I have a styles.css that changes the web page and is loaded from the popup but want to change a variable in the styles.css from the data entered at the popup.

I've added a content.js file and I can now pass a value from the Popup and it adds a new style attribute to the page but it's not updating the --ptwidth in the styles.css file. I think I need to have it in the styles.css to give the correct location and add the !important option.

I tried to ask this question before an it was closed\linked to one about webpage DOMs and don't have the reputation to post a comment and not sure I should ask my questions there if I could:

How to access the webpage DOM rather than the extension page DOM?

The styles.css injection works using the Wider button and the --ptwidth var is passed the value given (310) in the styles.CSS, at the very least I'd like to be able to enter a new value in the textbox and then use the existing Wider button to load the updated styles.css but it would be nice to have it auto update and maybe even use the slider.

The change button moves the new value entered in the text field to the content.js file and it then adds the new style attribute but it's not working. The insertCSS on the Wider button works but the info it adds is different.

Content.js adds the Style attribute section and the insertCSS adds the :root section that works.

Added by Content.js No Work:

Added by insertCSS Works and adds these two:

Columns before:

Columns after:

Rule before using the working Wider button with insertCSS:

Rules after the insertCSS injections of styles.css:

Popup:

manifest:

```<code>{
  "manifest_version": 3,
  "name": "Hellper",
  "description": "Extension",
  "version": "0.1",

  "icons": { "16": "logo_16_T.png",
             "48": "logo_48_T.png",
            "128": "logo_128_T.png"
           },

  "action": {
    "default_icon": "logo_16_T.png",
    "default_popup":"popup.html"
            },

  "permissions": ["scripting", "tabs", "activeTab", "content.js"],
  "host_permissions": ["<all_urls>"],

  "content_scripts": [{
    "js": ["jquery-2.2.0.min.js", "popup.js"],
    "matches": ["https://www.google.com/*",
                "https://en.wikipedia.org/*",
                "https://stackoverflow.com/*"]
  }]
}
</code>```

popup.html:

```<code><!doctype html>
<html>
  <head>
    <title>Popup</title>
  </head>
  <body>
    <input id="button1" type=button value=clickme>
    <button class="format">Wider</button>
    <button class="reset">Reset</button>
        <script src="jquery-2.2.0.min.js"></script>
        <script src="popup.js"></script>
      <!--
        <h2>Background Color</h2>
      <input type="color" id="color-changer" />
      <h2>Rotate Page</h2>
      <input type="range" min="0" max="360" step="1" value="0" id="rotate" />
      -->
    <h1>New Width</h1>
    <p>
      <input type="text" id="newWidth" value="120"/>
      <input type="submit" id="btnChange" value="Change"/>
    </p>
  <div class="form-group">
    <lable for="slider">Project/Task Width</lable>
    <input type="range" min="0" max="999" step="1" value="160" id="slider" />
  </div>
  </body>
</html>
</code>```

styles.css:

```<code>:root {
    --ptwidth: 310px
}

.quixote .qx-grid .editor_grid tbody tr td input, .quixote .qx-grid .editor_grid tbody tr td .input-group {
    /*max-width: 450px !important;
    min-width: 450px !important;*/
    max-width: var(--ptwidth) !important;
    min-width: var(--ptwidth) !important;
</code>```

popup.js:

```<code>$(document).ready(function() {
    $('.reset').click(function() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
            chrome.scripting.removeCSS({
                target: { tabId: activeTab.id },
                files: ["styles.css"]
    });
   });
    })

    $('.format').click(function() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
            chrome.scripting.insertCSS({
                target: { tabId: activeTab.id, allFrames: true },
                files: ["styles.css"]
            });
    /*chrome.tabs.sendMessage(activeTab.id, {"buttonclicked": "wider"});*/
   });
    })
})

$(function(){
    var width = $('#newWidth').val();
    $('#newWidth').on("change paste keyup", function(){
      width = $(this).val();
    });
    $('#btnChange').click(function(){
      chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        chrome.tabs.sendMessage(tabs[0].id, {todo: "changeWidth", sliderWidth: width})
      });
    });
});
</code>```

content.js

```<code>let root = document.documentElement;

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      if( request.todo == "changeWidth"){
        var updateWidth = request.sliderWidth;
        root.style.setProperty('--ptwidth', updateWidth + "px");
//      start();
      }
    });
</code>```

答:
I got this working by using the chrome.scripting.insertCSS to replace the --ptwidth value after the styles.css has been injected. So far everything works with just the popup.js and no need for the content.js file.

I use this to load the styles.css with it's default value.

```<code>chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
  var activeTab = tabs[0];
    chrome.scripting.insertCSS({
      target: { tabId: activeTab.id, allFrames: true },
    files: ["styles.css"]
    });
});
</code>```

Then this when I get a new value from the textbox or slider.

```<code>  chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    //alert(readsavewidth);
    $("#slider").val(readsavewidth);
    $("#newWidth").val(readsavewidth);
  chrome.scripting.insertCSS({
    target: { tabId: activeTab.id, allFrames: true },
    css: `:root { --ptwidth: ${readsavewidth + "px"} }`
  });
  });
});
</code>```

I also used the chrome.storage.local to set and get the last value used.

```<code>$(function () {
  // text input listener
  $("#newWidth").on("change paste keyup", function () {
    width = $(this).val();
            //Save it to the localStorage variable which will always remember what you store in it
            chrome.storage.local.set({'savewidth': width});
    // update slider
    $("#slider").val(width);
      chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        var activeTab = tabs[0];
      chrome.scripting.insertCSS({
        target: { tabId: activeTab.id, allFrames: true },
        css: `:root { --ptwidth: ${width + "px"} }`
      });
    });
  });
  // listener for slider changes
  $("#slider").on("input", function () {
    width = $("#slider").val();
    // update text box
    $("#newWidth").val(width);
        chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
            var activeTab = tabs[0];
        chrome.scripting.insertCSS({
            target: { tabId: activeTab.id, allFrames: true },
            css: `:root { --ptwidth: ${width + "px"} }`
        });
    });

    //Pull text from user inputbox
    var data = width;
    //Save it to the localStorage variable which will always remember what you store in it
      chrome.storage.local.set({'savewidth': data});
  });
});
</code>```

Then I get the value when the popup opens and it then overights the --ptwidth value using the chrome.scripting.insertCSS funtion.

```<code>chrome.storage.local.get('savewidth', function (result) {
  readsavewidth = result.savewidth;

  chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    //alert(readsavewidth);
    $("#slider").val(readsavewidth);
    $("#newWidth").val(readsavewidth);
  chrome.scripting.insertCSS({
    target: { tabId: activeTab.id, allFrames: true },
    css: `:root { --ptwidth: ${readsavewidth + "px"} }`
  });
  });
});
</code>```

Body:
Sorry, I messed that up. I did not update the manifest from the last post and I forgot the content.js, that is how the Change button was sending the value and the page was getting the new style attribute value from the one entered in the text field and then to the content.js, existing content.js file added below.

I have a styles.css that changes the web page and is loaded from the popup but want to change a variable in the styles.css from the data entered at the popup.

I've added a content.js file and I can now pass a value from the Popup and it adds a new style attribute to the page but it's not updating the --ptwidth in the styles.css file. I think I need to have it in the styles.css to give the correct location and add the !important option.

I tried to ask this question before an it was closed\linked to one about webpage DOMs and don't have the reputation to post a comment and not sure I should ask my questions there if I could:

How to access the webpage DOM rather than the extension page DOM?

The styles.css injection works using the Wider button and the --ptwidth var is passed the value given (310) in the styles.CSS, at the very least I'd like to be able to enter a new value in the textbox and then use the existing Wider button to load the updated styles.css but it would be nice to have it auto update and maybe even use the slider.

The change button moves the new value entered in the text field to the content.js file and it then adds the new style attribute but it's not working. The insertCSS on the Wider button works but the info it adds is different.

Content.js adds the Style attribute section and the insertCSS adds the :root section that works.

Added by Content.js No Work:

Added by insertCSS Works and adds these two:

Columns before:

Columns after:

Rule before using the working Wider button with insertCSS:

Rules after the insertCSS injections of styles.css:

Popup:

manifest:

{
  "manifest_version": 3,
  "name": "Hellper",
  "description": "Extension",
  "version": "0.1",

  "icons": { "16": "logo_16_T.png",
             "48": "logo_48_T.png",
            "128": "logo_128_T.png"
           },

  "action": {
    "default_icon": "logo_16_T.png",
    "default_popup":"popup.html"
            },

  "permissions": ["scripting", "tabs", "activeTab", "content.js"],
  "host_permissions": ["<all_urls>"],

  "content_scripts": [{
    "js": ["jquery-2.2.0.min.js", "popup.js"],
    "matches": ["https://www.google.com/*",
                "https://en.wikipedia.org/*",
                "https://stackoverflow.com/*"]
  }]
}

popup.html:

<!doctype html>

    <title>Popup</title>

    <input id="button1" type=button value=clickme>
    <button class="format">Wider</button>
    <button class="reset">Reset</button>

New Width

      <input type="text" id="newWidth" value="120"/>
      <input type="submit" id="btnChange" value="Change"/>

    <lable for="slider">Project/Task Width</lable>
    <input type="range" min="0" max="999" step="1" value="160" id="slider" />

styles.css:

:root {
    --ptwidth: 310px
}

.quixote .qx-grid .editor_grid tbody tr td input, .quixote .qx-grid .editor_grid tbody tr td .input-group {
    /*max-width: 450px !important;
    min-width: 450px !important;*/
    max-width: var(--ptwidth) !important;
    min-width: var(--ptwidth) !important;

popup.js:

$(document).ready(function() {
    $('.reset').click(function() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
            chrome.scripting.removeCSS({
                target: { tabId: activeTab.id },
                files: ["styles.css"]
    });
   });
    })

    $('.format').click(function() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
            chrome.scripting.insertCSS({
                target: { tabId: activeTab.id, allFrames: true },
                files: ["styles.css"]
            });
    /*chrome.tabs.sendMessage(activeTab.id, {"buttonclicked": "wider"});*/
   });
    })
})

$(function(){
    var width = $('#newWidth').val();
    $('#newWidth').on("change paste keyup", function(){
      width = $(this).val();
    });
    $('#btnChange').click(function(){
      chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        chrome.tabs.sendMessage(tabs[0].id, {todo: "changeWidth", sliderWidth: width})
      });
    });
});

content.js

let root = document.documentElement;

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      if( request.todo == "changeWidth"){
        var updateWidth = request.sliderWidth;
        root.style.setProperty('--ptwidth', updateWidth + "px");
//      start();
      }
    });

Body:
I got this working by using the chrome.scripting.insertCSS to replace the --ptwidth value after the styles.css has been injected. So far everything works with just the popup.js and no need for the content.js file.

I use this to load the styles.css with it's default value.

chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
  var activeTab = tabs[0];
    chrome.scripting.insertCSS({
      target: { tabId: activeTab.id, allFrames: true },
    files: ["styles.css"]
    });
});

Then this when I get a new value from the textbox or slider.

  chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    //alert(readsavewidth);
    $("#slider").val(readsavewidth);
    $("#newWidth").val(readsavewidth);
  chrome.scripting.insertCSS({
    target: { tabId: activeTab.id, allFrames: true },
    css: `:root { --ptwidth: ${readsavewidth + "px"} }`
  });
  });
});

I also used the chrome.storage.local to set and get the last value used.

$(function () {
  // text input listener
  $("#newWidth").on("change paste keyup", function () {
    width = $(this).val();
            //Save it to the localStorage variable which will always remember what you store in it
            chrome.storage.local.set({'savewidth': width});
    // update slider
    $("#slider").val(width);
      chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        var activeTab = tabs[0];
      chrome.scripting.insertCSS({
        target: { tabId: activeTab.id, allFrames: true },
        css: `:root { --ptwidth: ${width + "px"} }`
      });
    });
  });
  // listener for slider changes
  $("#slider").on("input", function () {
    width = $("#slider").val();
    // update text box
    $("#newWidth").val(width);
        chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
            var activeTab = tabs[0];
        chrome.scripting.insertCSS({
            target: { tabId: activeTab.id, allFrames: true },
            css: `:root { --ptwidth: ${width + "px"} }`
        });
    });

    //Pull text from user inputbox
    var data = width;
    //Save it to the localStorage variable which will always remember what you store in it
      chrome.storage.local.set({'savewidth': data});
  });
});

Then I get the value when the popup opens and it then overights the --ptwidth value using the chrome.scripting.insertCSS funtion.

chrome.storage.local.get('savewidth', function (result) {
  readsavewidth = result.savewidth;

  chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    //alert(readsavewidth);
    $("#slider").val(readsavewidth);
    $("#newWidth").val(readsavewidth);
  chrome.scripting.insertCSS({
    target: { tabId: activeTab.id, allFrames: true },
    css: `:root { --ptwidth: ${readsavewidth + "px"} }`
  });
  });
});


问:
Is it possible to design circle using xamarin forms
Is possible to design circle like the attached image.
I want to create login page like attached image.

Is there any way to create login page like attached image using Xamarin forms.

答: export the image in the format you need. No need to do it by Xamarin</p>


问:
Pygame bad sound quality
Im trying to play a backround music in pygame but the qualtiy is kinda bad, altough if i play the the mp3 file outside python, for example in vlc, the sound quality is perfectly fine, so there is no issue with the file itself / my headset.
this is the code that i used to play the song:

```<code>mixer.music.load("song.mp3")
mixer.music.set_volume(0.6)
mixer.music.play(-1)
</code>```

any ideas how to fix it?

答:
I was able the fix this issue, and it turns out there was no issue with my code.

I did some testing with different mp4 and ogg files, and I have found that, for some reason, if an mp4 file has very low kpbs rate, then its going to sound weird—although in music players like Groove and VLC it’s going to sound fine—when played in pygame with:

```<code>mixer.music.load("song.mp3")
mixer.music.set_volume(0.6)
mixer.music.play(-1) # the -1 is just so the song starts to play again, if it finished
</code>```

So what I did is download the song with a higher kbps rate, and the quality instantly got better in pygame / python aswell.

Title: Pygame bad sound quality

Body:
Im trying to play a backround music in pygame but the qualtiy is kinda bad, altough if i play the the mp3 file outside python, for example in vlc, the sound quality is perfectly fine, so there is no issue with the file itself / my headset.
this is the code that i used to play the song:

mixer.music.load("song.mp3")
mixer.music.set_volume(0.6)
mixer.music.play(-1)

any ideas how to fix it?

Body:
I was able the fix this issue, and it turns out there was no issue with my code.

I did some testing with different mp4 and ogg files, and I have found that, for some reason, if an mp4 file has very low kpbs rate, then its going to sound weird—although in music players like Groove and VLC it’s going to sound fine—when played in pygame with:

mixer.music.load("song.mp3")
mixer.music.set_volume(0.6)
mixer.music.play(-1) # the -1 is just so the song starts to play again, if it finished

So what I did is download the song with a higher kbps rate, and the quality instantly got better in pygame / python aswell.


问:
cannot resolve org.springframework.cloud:spring-cloud-starter-config
I am using gradle to build and here is my build.gradle

Is there anything that I am missing in the gradle file

```<code>repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/libs-milestone" }
    maven { url "https://repo.spring.io/libs-snapshot" }
}

apply plugin: 'org.springframework.boot'
apply plugin: 'java'
apply plugin: 'javac2'
apply plugin: 'docker'

dependencies {
   compile project(':services')
   compile 'org.springframework.boot:spring-boot-starter-web'
   compile('org.springframework.cloud:spring-cloud-starter-config')
   compile('org.springframework.boot:spring-boot-starter-actuator')
   compile 'org.jetbrains:annotations:13.0'
   runtime 'org.aspectj:aspectjweaver'

   testCompile 'junit:junit'
   testCompile 'org.springframework.boot:spring-boot-starter-test'
   testRuntime "com.jayway.awaitility:awaitility:$awaitilityVersion"
   testRuntime 'com.jayway.jsonpath:json-path'
}

apply plugin: 'java'

springBoot {
executable = true
}

dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.BUILD-SNAPSHOT"
}
}

docker {
baseImage "java:8"
}

task buildDocker(type: Docker, dependsOn: build) {
applicationName = "ldp-data-fetcher"
exposePort(8080)
addFile("${buildDir}/libs/app-0.1-SNAPSHOT.jar", "/opt/jmg/app-0.1-SNAPSHOT.jar")
}

sourceCompatibility = 1.8
targetCompatibility = 1.8
</code>```

答:
The first answer is correct or you can explicitly define dependency management and versions as follows:</p>
```<code>plugins {
id 'org.springframework.boot' version '2.5.9'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

ext {
    set('springCloudVersion', "2020.0.5")
}

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-config-server'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

tasks.named('test') {
    useJUnitPlatform()
}
</code>```

Body:
I am using gradle to build and here is my build.gradle

Is there anything that I am missing in the gradle file

repositories {
    mavenCentral()
    maven { url "https://repo.spring.io/libs-milestone" }
    maven { url "https://repo.spring.io/libs-snapshot" }
}

apply plugin: 'org.springframework.boot'
apply plugin: 'java'
apply plugin: 'javac2'
apply plugin: 'docker'

dependencies {
   compile project(':services')
   compile 'org.springframework.boot:spring-boot-starter-web'
   compile('org.springframework.cloud:spring-cloud-starter-config')
   compile('org.springframework.boot:spring-boot-starter-actuator')
   compile 'org.jetbrains:annotations:13.0'
   runtime 'org.aspectj:aspectjweaver'

   testCompile 'junit:junit'
   testCompile 'org.springframework.boot:spring-boot-starter-test'
   testRuntime "com.jayway.awaitility:awaitility:$awaitilityVersion"
   testRuntime 'com.jayway.jsonpath:json-path'
}

apply plugin: 'java'

springBoot {
executable = true
}

dependencyManagement {
imports {
mavenBom "org.springframework.cloud:spring-cloud-dependencies:Finchley.BUILD-SNAPSHOT"
}
}

docker {
baseImage "java:8"
}

task buildDocker(type: Docker, dependsOn: build) {
applicationName = "ldp-data-fetcher"
exposePort(8080)
addFile("${buildDir}/libs/app-0.1-SNAPSHOT.jar", "/opt/jmg/app-0.1-SNAPSHOT.jar")
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

Body:
The first answer is correct or you can explicitly define dependency management and versions as follows:

plugins {
id 'org.springframework.boot' version '2.5.9'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
    mavenCentral()
}

ext {
    set('springCloudVersion', "2020.0.5")
}

dependencies {
    implementation 'org.springframework.cloud:spring-cloud-config-server'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

tasks.named('test') {
    useJUnitPlatform()
}


问:
Detecting when an iframe gets or loses focus
What's the correct way of detecting when an iframe gets or loses focus (i.e. will or will not receive keyboard events)? The following is not working in Fx4:</p>

```<code>var iframe = /* my iframe */;
iframe.addEventListener("focus", function() { /* never gets called */ }, false);
</code>```

答:
I have solved this by using contentWindow instead of contentDocument.
The good thing about contentWindow is

it works also in case user clicks another window (another application) or another browser tab. If using activeElement, if user clicks away from the entire window to go to another application, then that logic still think the iframe is in focus, while it is not

and we don't need to poll and do a setInterval at all. This uses the normal addEventListener

```<code>let iframe = document.getElementsByTagName("iframe")[0];
// or whatever way you do to grab that iFrame, say you have an `id`, then it's even more precise
if(iframe){
  iframeWindow = iframe.contentWindow;
  iframeWindow.addEventListener('focus', handleIframeFocused);
  iframeWindow.addEventListener('blur', handleIframeBlurred);
}

function handleIframeFocused(){
  console.log('iframe focused');
  // Additional logic that you need to implement here when focused
}

function handleIframeBlurred(){
  console.log('iframe blurred');
  // Additional logic that you need to implement here when blurred
}

</code>```

Body:
What's the correct way of detecting when an iframe gets or loses focus (i.e. will or will not receive keyboard events)? The following is not working in Fx4:

var iframe = /* my iframe */;
iframe.addEventListener("focus", function() { /* never gets called */ }, false);

Body:
I have solved this by using contentWindow instead of contentDocument.
The good thing about contentWindow is

it works also in case user clicks another window (another application) or another browser tab. If using activeElement, if user clicks away from the entire window to go to another application, then that logic still think the iframe is in focus, while it is not

and we don't need to poll and do a setInterval at all. This uses the normal addEventListener

let iframe = document.getElementsByTagName("iframe")[0];
// or whatever way you do to grab that iFrame, say you have an `id`, then it's even more precise
if(iframe){
  iframeWindow = iframe.contentWindow;
  iframeWindow.addEventListener('focus', handleIframeFocused);
  iframeWindow.addEventListener('blur', handleIframeBlurred);
}

function handleIframeFocused(){
  console.log('iframe focused');
  // Additional logic that you need to implement here when focused
}

function handleIframeBlurred(){
  console.log('iframe blurred');
  // Additional logic that you need to implement here when blurred
}


问:
Comparing two datetime columns returns FALSE when NaT - Python
I'm extracting data from the database using sqlalchemy. I need to compare the col 'fields_resolved_at' with 'resolved_at' and mark False/True if there is a mismatch/match.

Running:

```<code>comparison_column = np.where(merged_df["fields_resolved_at"] == merged_df["resolved_at"], True, False)
merged_df["equal"] = comparison_column
</code>```

Returns:

However, I would expect rows with index 1, 2, 3 to be marked as True because both are NaT. I am thinking that maybe the easiest way will be to replace NaT with '0' and then, run the comparison but I wonder if there is a more elegant way to do it.

答:
You can't actually do this, because NaN != NaN (and therefore NaT != NaT). Instead, you can check if the two columns are both equal, OR if they're both NaN/NaT:</p>
```<code>comparison_column = (merged_df["fields_resolved_at"] == merged_df["resolved_at"]) | (merged_df["fields_resolved_at"].isna() & merged_df["resolved_at"].isna())
merged_df["equal"] = comparison_column
</code>```

Body:
I'm extracting data from the database using sqlalchemy. I need to compare the col 'fields_resolved_at' with 'resolved_at' and mark False/True if there is a mismatch/match.

Running:

comparison_column = np.where(merged_df["fields_resolved_at"] == merged_df["resolved_at"], True, False)
merged_df["equal"] = comparison_column

Returns:

However, I would expect rows with index 1, 2, 3 to be marked as True because both are NaT. I am thinking that maybe the easiest way will be to replace NaT with '0' and then, run the comparison but I wonder if there is a more elegant way to do it.

Body:
You can't actually do this, because NaN != NaN (and therefore NaT != NaT). Instead, you can check if the two columns are both equal, OR if they're both NaN/NaT:

comparison_column = (merged_df["fields_resolved_at"] == merged_df["resolved_at"]) | (merged_df["fields_resolved_at"].isna() & merged_df["resolved_at"].isna())
merged_df["equal"] = comparison_column


问:
Deploying dotnetcore 5 web api to iis gives 404
I have an Web API project with .NET 5 (created directly from the template of visual studio Asp.NET Core Web API), it works just fine when debugging from Visual studio, tried to deploy it to IIS server, which has the Hosting Bundle of .NET 5 installed, the deployment apparently runs fine, but when I enter the url I have a 404. Have a separate MVC .NET 5 project, which I deploy in the same way and it runs perfectly fine.

Would like to know if someone can point me to the right direction, can't find what I'm missing here.

答:
You can solve your problem by following the steps on this site.

https://learn.microsoft.com/en-us/aspnet/core/tutorials/getting-started-with-swashbuckle?view=aspnetcore-3.1&tabs=visual-studio


问:
Remove multiple spaces and new lines inside of String
Suppose we have string like this:

```<code>Hello, my\n       name is Michael.
</code>```

How can I remove that new line and strip those spaces after that into one inside of string to get this?

```<code>Hello, my name is Michael.
</code>```

答:
Use String#gsub:</p>

```<code>s = "Hello, my\n       name is Michael."
s.gsub(/\s+/, " ")
</code>```

Body:
Suppose we have string like this:

Hello, my\n       name is Michael.

How can I remove that new line and strip those spaces after that into one inside of string to get this?

Hello, my name is Michael.

Body:
Use String#gsub:

s = "Hello, my\n       name is Michael."
s.gsub(/\s+/, " ")