问:
Python Rock, Paper, Scissors game bug?
I created my first ever functional program but something's wrong. If I run the following code, considering every possible outcome, I get wrong results sometimes. For example, the user chooses rock, the program scissors, and the result is the program won, when it should not. I'm a beginner, so this might be a newbie mistake.</p>
```<code>starter = True
while starter:
  import random
  user_input = input("Choose Rock, Paper or Scissors: ")
  choice = ["Rock", "Paper", "Scissors"]
  choice_lower = ["rock", "paper", "scissors"]
  program_choice = random.choice(choice)

  while user_input not in choice or user_input in choice_lower:
    if user_input in choice or user_input in choice_lower:
        break
    else:
        user_input = input("Invalid input! Choose Rock, Paper or Scissors: ")
        continue

  if user_input == program_choice or user_input == program_choice.lower():
    print(f"You chose: {user_input}")
    print(f"It's a draw! The computer chose {program_choice} too!")
  elif user_input == "Rock" or user_input == "rock" and program_choice == "Paper":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nThe program won!")
  elif user_input == "Paper" or user_input == "paper" and program_choice == "Rock":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nYou won!")
  elif user_input == "Scissors" or user_input == "scissors" and program_choice == "Paper":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nYou won!")
  elif user_input == "Rock" or user_input == "rock" and program_choice == "Scissors":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nYou won!")
  elif user_input == "Paper" or user_input == "paper" and program_choice == "Scissors":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nThe program won!")
  elif user_input == "Scissors" or user_input == "scissors" and program_choice == "Rock":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nThe program won!")

  keep_going = input("Do you wanna play again? (Yes/No): ")
  answers = ["Yes", "yes", "No", "no"]
  while keep_going not in answers:
    keep_going = input("Invalid input! Do you wanna play again? (Yes/No): ")
    continue
  if keep_going == "Yes" or keep_going == "yes":
    continue
  else:
    starter = False
</code>```

答:
Instead of checking every case in a separate if/elif case, it's easier (and less error prone) to check things systematically. For instance, consider the following version of a (one-round) "rock paper scissors" program as an alternative.

```<code>import random

choice =["rock", "paper", "scissors"]
lose = [(choice[i],choice[(i+1)%3]) for i in range(3)]
# equivalent: lose = [("rock","paper"),("paper","scissors"),("scissors","rock")]

program_choice = random.choice(choice)
# print(program_choice) # useful if you want to cheat

while True:
    user_input = input("Choose Rock, Paper or Scissors: ").lower()
    if user_input in choice:
        break
    else:
        print("Invalid Input!")

print(f"You chose: {user_input}\nThe program chose: {program_choice}")
if user_input==program_choice:
    print("It\'s a draw!")
elif (user_input,program_choice) in lose:
    print("The program won!")
else:
    print("You won!")
</code>```

Title: Python Rock, Paper, Scissors game bug?

Body:
I created my first ever functional program but something's wrong. If I run the following code, considering every possible outcome, I get wrong results sometimes. For example, the user chooses rock, the program scissors, and the result is the program won, when it should not. I'm a beginner, so this might be a newbie mistake.

starter = True
while starter:
  import random
  user_input = input("Choose Rock, Paper or Scissors: ")
  choice = ["Rock", "Paper", "Scissors"]
  choice_lower = ["rock", "paper", "scissors"]
  program_choice = random.choice(choice)

  while user_input not in choice or user_input in choice_lower:
    if user_input in choice or user_input in choice_lower:
        break
    else:
        user_input = input("Invalid input! Choose Rock, Paper or Scissors: ")
        continue

  if user_input == program_choice or user_input == program_choice.lower():
    print(f"You chose: {user_input}")
    print(f"It's a draw! The computer chose {program_choice} too!")
  elif user_input == "Rock" or user_input == "rock" and program_choice == "Paper":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nThe program won!")
  elif user_input == "Paper" or user_input == "paper" and program_choice == "Rock":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nYou won!")
  elif user_input == "Scissors" or user_input == "scissors" and program_choice == "Paper":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nYou won!")
  elif user_input == "Rock" or user_input == "rock" and program_choice == "Scissors":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nYou won!")
  elif user_input == "Paper" or user_input == "paper" and program_choice == "Scissors":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nThe program won!")
  elif user_input == "Scissors" or user_input == "scissors" and program_choice == "Rock":
    print(f"You chose: {user_input}\nThe program chose: {program_choice}\nThe program won!")

  keep_going = input("Do you wanna play again? (Yes/No): ")
  answers = ["Yes", "yes", "No", "no"]
  while keep_going not in answers:
    keep_going = input("Invalid input! Do you wanna play again? (Yes/No): ")
    continue
  if keep_going == "Yes" or keep_going == "yes":
    continue
  else:
    starter = False

Body:
Instead of checking every case in a separate if/elif case, it's easier (and less error prone) to check things systematically. For instance, consider the following version of a (one-round) "rock paper scissors" program as an alternative.

import random

choice =["rock", "paper", "scissors"]
lose = [(choice[i],choice[(i+1)%3]) for i in range(3)]
# equivalent: lose = [("rock","paper"),("paper","scissors"),("scissors","rock")]

program_choice = random.choice(choice)
# print(program_choice) # useful if you want to cheat

while True:
    user_input = input("Choose Rock, Paper or Scissors: ").lower()
    if user_input in choice:
        break
    else:
        print("Invalid Input!")

print(f"You chose: {user_input}\nThe program chose: {program_choice}")
if user_input==program_choice:
    print("It\'s a draw!")
elif (user_input,program_choice) in lose:
    print("The program won!")
else:
    print("You won!")


来源: stackexchange

问:
Google Sheets JScript Row match and delete if - Take rows from Sheet A and delete if identical to rows in Sheet B, Sheet C, Sheet D... etc
My data import (Sheet A) has all information from the last known events. It only changes them when another event occurs. So if the event is from two days ago it is still in my data import (Sheet A) until that event changes. I need to have my data import (Sheet A) checked against Sheet B, Sheet C, and Sheet D for identical rows. Then delete the row if it already exists.

So far I have:

function testFilter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetA = ss.getSheetByName("SheetA");
var sheetB = ss.getSheetByName("SheetB");
var sheetC = ss.getSheetByName("SheetC");
var sheetD = ss.getSheetByName("SheetD");
var sheetE = ss.getSheetByName("SheetE");
var sheetF = ss.getSheetByName("SheetF");

var valuesA = sheetA.getRange('A2:AC400').getValues();
var valuesB = sheetB.getRange('A2:AC400').getValues();
var valuesC = sheetC.getRange('A2:AC400').getValues();
var valuesD = sheetD.getRange('A2:AC400').getValues();
var valuesE = sheetE.getRange('A2:AC400').getValues();
var valuesF = sheetF.getRange('A2:AC400').getValues();

for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowb in valuesB)
  {
    if(valuesA[rowa].join() == valuesB[rowb].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowc in valuesC)
  {
    if(valuesA[rowa].join() == valuesC[rowc].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowd in valuesD)
  {
    if(valuesA[rowa].join() == valuesD[rowd].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowe in valuesE)
  {
    if(valuesA[rowa].join() == valuesE[rowe].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowf in valuesF)
  {
    if(valuesA[rowa].join() == valuesF[rowf].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
}```

This gives an Exception: out of bounds error on the first attempt of filtering. Does the deleterows() function work for picking out specific rows? Or am I going to have to throw it into a  new list, then delete all rows from original sheet, then insert the list?

答:
Here is about the same algo as Cooper's but, I hope, it's a little bit more readable.</p>
```<code>function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var names = ['SheetA', 'SheetB', 'SheetC', 'SheetD', 'SheetE' ]; // etc

  const get_array_from_sheet = sheet_name =>
    ss.getSheetByName(sheet_name).getRange('A2:AC400').getValues()
    .map(x => x.join('')).filter(String);

  var [sheetA, ...sheets_etc] = names.map(n => get_array_from_sheet(n));

  sheets_etc = sheets_etc.flat();

  var rows_to_delete = sheetA.filter(x => sheets_etc.includes(x))
    .map(x => sheetA.indexOf(x) + 2);

  rows_to_delete.reverse().forEach(x => ss.getSheetByName('SheetA').deleteRow(x));
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My data import (Sheet A) has all information from the last known events. It only changes them when another event occurs. So if the event is from two days ago it is still in my data import (Sheet A) until that event changes. I need to have my data import (Sheet A) checked against Sheet B, Sheet C, and Sheet D for identical rows. Then delete the row if it already exists.

So far I have:

function testFilter() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetA = ss.getSheetByName("SheetA");
var sheetB = ss.getSheetByName("SheetB");
var sheetC = ss.getSheetByName("SheetC");
var sheetD = ss.getSheetByName("SheetD");
var sheetE = ss.getSheetByName("SheetE");
var sheetF = ss.getSheetByName("SheetF");

var valuesA = sheetA.getRange('A2:AC400').getValues();
var valuesB = sheetB.getRange('A2:AC400').getValues();
var valuesC = sheetC.getRange('A2:AC400').getValues();
var valuesD = sheetD.getRange('A2:AC400').getValues();
var valuesE = sheetE.getRange('A2:AC400').getValues();
var valuesF = sheetF.getRange('A2:AC400').getValues();

for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowb in valuesB)
  {
    if(valuesA[rowa].join() == valuesB[rowb].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowc in valuesC)
  {
    if(valuesA[rowa].join() == valuesC[rowc].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowd in valuesD)
  {
    if(valuesA[rowa].join() == valuesD[rowd].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowe in valuesE)
  {
    if(valuesA[rowa].join() == valuesE[rowe].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
for (var rowa in valuesA)
{
var deleteRowa = false;
  for (var rowf in valuesF)
  {
    if(valuesA[rowa].join() == valuesF[rowf].join())
      deleteRowa = true;
  }
    if(deleteRowa == true){
      sheetA.deleteRow(rowa)
    }
SpreadsheetApp.flush();
}
}

This gives an Exception: out of bounds error on the first attempt of filtering. Does the deleterows() function work for picking out specific rows? Or am I going to have to throw it into a  new list, then delete all rows from original sheet, then insert the list?

Body:
Here is about the same algo as Cooper's but, I hope, it's a little bit more readable.

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var names = ['SheetA', 'SheetB', 'SheetC', 'SheetD', 'SheetE' ]; // etc

  const get_array_from_sheet = sheet_name =>
    ss.getSheetByName(sheet_name).getRange('A2:AC400').getValues()
    .map(x => x.join('')).filter(String);

  var [sheetA, ...sheets_etc] = names.map(n => get_array_from_sheet(n));

  sheets_etc = sheets_etc.flat();

  var rows_to_delete = sheetA.filter(x => sheets_etc.includes(x))
    .map(x => sheetA.indexOf(x) + 2);

  rows_to_delete.reverse().forEach(x => ss.getSheetByName('SheetA').deleteRow(x));
}


问:
Hoare logic: how does a strictly decreasing loop variant by itself prove termination?
Referring to the while rule for total correctness, WP seems to tell me that just finding a loop variant that strictly decreases is enough to prove termination.  I can't accept that, either because I'm missing something or the rule is wrong.  Consider

```<code>int i = 1000;
while(true) i--;
</code>```

in which the value of variable i is a strictly decreasing loop variant, but the loop certainly doesn't terminate.

Surely the rule needs to have an additional precondition, something like i<0 → ¬B (where B is the loop condition in the axiom schema) so that the loop condition eventually 'catches' the loop variant and exits.

Or have I missed something?

答:
The usual ordering "<" is well-founded on the natural numbers, but not on the integers.  In order for a relation to be well-founded, every non-empty subset of its domain must have a minimal element.  Since it can be shown that there is no infinite descending chain with respect to a well-founded relation, it follows that a loop with a variant must terminate.

Of course the condition of the loop must be false in the case of a minimal element!

A variant need not be restricted to the natural numbers, however.  Transfinite ordinals are also well-ordered.

ContentLicense: CC BY-SA 3.0

Body:
Referring to the while rule for total correctness, WP seems to tell me that just finding a loop variant that strictly decreases is enough to prove termination.  I can't accept that, either because I'm missing something or the rule is wrong.  Consider

int i = 1000;
while(true) i--;

in which the value of variable i is a strictly decreasing loop variant, but the loop certainly doesn't terminate.

Surely the rule needs to have an additional precondition, something like i<0 → ¬B (where B is the loop condition in the axiom schema) so that the loop condition eventually 'catches' the loop variant and exits.

Or have I missed something?


问:
Handling UI State in Remix.run
I am trying out remix and ohh boy.. I am stuck on creating a simple counter (clicking button increase count)

I guess I am not supposed to use the useState hook so I tried my luck with loader and action as I believe that this is where it should be handled in Remix

What I have on my component is:

```<code>export default function Game() {
    const counter = useLoaderData();

    return (
        <>
            <div>{counter}</div>
            <div>
                <Form method="post">
                    <button type="submit">click</button>
                </Form>
            </div>
        </>
    );
}
</code>```

Server:

```<code>import { ActionFunction, LoaderFunction } from 'remix';

let counter: number = 0;

export const loader: LoaderFunction = async () => {
    console.log('game object!', counter);
    return counter;
};

export let action: ActionFunction = async ({ request, params }) => {
    console.log('[action] game object!', ++counter);
    return counter;
};
</code>```

The code above will have counter always resetting to 0 on every click

Looked around some repositories and what I can find are those storing in Cookie/DB/SessionStorage etc, however what if I just want a simple state for my UI?

答:
You are supposed to use useState for your client-side state in Remix.

If you clone the remix repository and do a grep -r useState in the remix/examples/ folder, you will find many occurrences of it.

For example you have a simple one in the Route modal example (in app/routes/invoices/$id/edit.tsx), being used for a form with controlled inputs.

What Remix does is make it easier to communicate between the client and the server by colocating their codes for the same functionnality, and providing simple ways to perform that communication. This is useful if you need to communicate the data to your server. If it's not the case, then it's totally ok to keep that information only on the client.

About server side rendering

Remix also server-side renders the components by default. Which means that it executes your React code on the server to generate the HTML, and sends that with the JavaScript code. That way the browser can display it even before it executes the JavaScript to run the React code on the browser.

This means that in case your code (or a third party library code you use) uses some browser API in you component, you may need to indicate not to server-side render that component.

There is a Client only components example that demonstrates how to do that. It includes an example with a counter storing its value in the local storage of the browser.

Title: Handling UI State in Remix.run

Body:
I am trying out remix and ohh boy.. I am stuck on creating a simple counter (clicking button increase count)

I guess I am not supposed to use the useState hook so I tried my luck with loader and action as I believe that this is where it should be handled in Remix

What I have on my component is:

export default function Game() {
    const counter = useLoaderData();

    return (
        <>

{counter}

                <Form method="post">
                    <button type="submit">click</button>
                </Form>

        </>
    );
}

Server:

import { ActionFunction, LoaderFunction } from 'remix';

let counter: number = 0;

export const loader: LoaderFunction = async () => {
    console.log('game object!', counter);
    return counter;
};

export let action: ActionFunction = async ({ request, params }) => {
    console.log('[action] game object!', ++counter);
    return counter;
};

The code above will have counter always resetting to 0 on every click

Looked around some repositories and what I can find are those storing in Cookie/DB/SessionStorage etc, however what if I just want a simple state for my UI?


问:
Assignment of Code Inputs and Partial Outputs
I need help with this coding assignment I have.

Assignment:

¨User will input two words

The longer word will output in reverse starting with the last letter until the middle letter

The shorter word will output in order starting at the middle until the end; then output at the beginning until (but not including) the middle

```<code>-in the scenario of same length, the shorter word will be designated with the first input
</code>```

Example

"radio" and "computer" should produce

"radio" would be "diora"

"computer" would be "retu"¨

^thats the assignment.

the thing I'm trying to figure is what exactly to put in the if and else statements.

my code:

```<code>System.out.println("Input word #1:  ");
String w1 = scan.nextLine();

System.out.println("Input word #2:  ");
String w2 = scan.nextLine();

int len1 = w1.length();
int len2 = w2.length();

int location1 =  w1.indexOf( w1 );
int half1 = len1/ 2;

int location2 =  w2.indexOf( w2 );
int half2 = len2/ 2;

if(len1 > len2){
    System.out.println(len1);
}
else{
}
</code>```

Please help me.

答:
I suggest taking a step back and thinking about how to solve the problem by describing the steps in plain English (or any other written language if English isn't your native language). For example, if I were trying to solve this problem, you might break it down into these three steps:

Get two words from the user

Print out the longest word in reverse

Print out the shortest word from the middle out

Next, add more details as needed. For example, to do step 2, we first need to determine which word is longest. Similarly, for step 3, we need to find determine which word is shortest. So now our steps are:

Get two words from the user

Determine which word is the longest

Determine which word is the shortest

Print out the longest word in reverse

Print out the shortest word from the middle out

Continue like this by adding more and more detail for each step until it is detailed enough that you can write code from the verbal description directly.

Body:
I need help with this coding assignment I have.

Assignment:

¨User will input two words

The longer word will output in reverse starting with the last letter until the middle letter

The shorter word will output in order starting at the middle until the end; then output at the beginning until (but not including) the middle

-in the scenario of same length, the shorter word will be designated with the first input

Example

"radio" and "computer" should produce

"radio" would be "diora"

"computer" would be "retu"¨

^thats the assignment.

the thing I'm trying to figure is what exactly to put in the if and else statements.

my code:

System.out.println("Input word #1:  ");
String w1 = scan.nextLine();

System.out.println("Input word #2:  ");
String w2 = scan.nextLine();

int len1 = w1.length();
int len2 = w2.length();

int location1 =  w1.indexOf( w1 );
int half1 = len1/ 2;

int location2 =  w2.indexOf( w2 );
int half2 = len2/ 2;

if(len1 > len2){
    System.out.println(len1);
}
else{
}

Please help me.


问:
Where to free multiple mallocs
I have the following piece of code:

void f(size_t n) {
    int *a = malloc(n * sizeof *a);
    if(a == NULL) {
        report_error_and_exit();
    }

    int *b = malloc(n * sizeof *a);

    if(b == NULL) {
        free(a);
        report_error_and_exit();
    }

    int *c = malloc(n * sizeof *a);
    if(c == NULL) {
        free(a);
        free(b);
        report_error_and_exit();
    }

    /*use a, b, c*/
}
```
<p>or something along those lines. Basically, I need multiple <code>malloc</code>s, and all of them mustn't fail.</p>
<p>I was wondering where should I free <em>some</em> of the allocated memory. As the function gets longer and bigger checking for <code>malloc</code> fails gets more messy.</p>
<p>A possible solution I was thinking was doing something like the following:</p>
<pre class="lang-c prettyprint-override"><code>void f(size_t n) {
    int *a = malloc(n * sizeof *a);
    if(a == NULL) {
        goto malloc_fail;
    }

    /*...*/

malloc_fail:
    free(a);
    free(b);
    /*...*/
    report_error_and_exit();
}
</code>```

however the use of goto is discouraged.

I am wondering what is the appropriate solution to this.

答:
Another approach is to use a wrapper function, e.g.:</p>
```<code>void f()
{
    int *a = malloc(n * sizeof *a);
    int *b = malloc(n2 * sizeof *b);
    int *c = malloc(n3 * sizeof *c);
    bool success = a && b && c;

    if ( success )
        do_stuff(a, b, c);

    free(c);
    free(b);
    free(a);

    if ( !success )
        report_error_and_exit();
}

</code>```

Title: Where to free multiple mallocs

Body:
I have the following piece of code:

void f(size_t n) {
    int *a = malloc(n * sizeof *a);
    if(a == NULL) {
        report_error_and_exit();
    }

    int *b = malloc(n * sizeof *a);

    if(b == NULL) {
        free(a);
        report_error_and_exit();
    }

    int *c = malloc(n * sizeof *a);
    if(c == NULL) {
        free(a);
        free(b);
        report_error_and_exit();
    }

    /*use a, b, c*/
}

or something along those lines. Basically, I need multiple mallocs, and all of them mustn't fail.

I was wondering where should I free some of the allocated memory. As the function gets longer and bigger checking for malloc fails gets more messy.

A possible solution I was thinking was doing something like the following:

void f(size_t n) {
    int *a = malloc(n * sizeof *a);
    if(a == NULL) {
        goto malloc_fail;
    }

    /*...*/

malloc_fail:
    free(a);
    free(b);
    /*...*/
    report_error_and_exit();
}

however the use of goto is discouraged.

I am wondering what is the appropriate solution to this.

Body:
Another approach is to use a wrapper function, e.g.:

void f()
{
    int *a = malloc(n * sizeof *a);
    int *b = malloc(n2 * sizeof *b);
    int *c = malloc(n3 * sizeof *c);
    bool success = a && b && c;

    if ( success )
        do_stuff(a, b, c);

    free(c);
    free(b);
    free(a);

    if ( !success )
        report_error_and_exit();
}


问:
Eclipse reporting "the value of the field is not used" warning even though Lombok enable
I have 2 classes in a Eclipse project.

```<code>package com.example;

import lombok.Getter;
import lombok.experimental.Accessors;

@Accessors(fluent = true)
@Getter
public class MyBean {
    private String value = "aaa";
}
</code>```
```<code>package com.example;

public class MyClass {
    public static void main() {
        System.out.println(new MyBean().value());
    }
}
</code>```

After building, Eclips reports "the value of the field value is not used" for MyBean class and "The method value() is undefined for the type MyClass" even though Eclipse's content assist shows MyBean#value() method, there are no warnings before building, and compilation, execution both are finished successfully.
So I guess Lombok works properly and the problem is Eclipse doesn't recognize Lombok.

Here are what I tried and found.

attaching lombok.jar to Eclipse and checking eclipse.ini

cleaning and rebuild the project

removing Lombok dependency from maven local repository then reinstall

the problems only occur in this project. Eclipse handles other projects with lombok properly (and all projects belong in the same workspace).

I cannot reproduce these problems in other projects.

Any ideas?

答: I install lombok on eclipse(java -jar lombokxxxx.jar) and the problem disapear.</p>

Body:
I have 2 classes in a Eclipse project.

package com.example;

import lombok.Getter;
import lombok.experimental.Accessors;

@Accessors(fluent = true)
@Getter
public class MyBean {
    private String value = "aaa";
}

package com.example;

public class MyClass {
    public static void main() {
        System.out.println(new MyBean().value());
    }
}

After building, Eclips reports "the value of the field value is not used" for MyBean class and "The method value() is undefined for the type MyClass" even though Eclipse's content assist shows MyBean#value() method, there are no warnings before building, and compilation, execution both are finished successfully.
So I guess Lombok works properly and the problem is Eclipse doesn't recognize Lombok.

Here are what I tried and found.

attaching lombok.jar to Eclipse and checking eclipse.ini

cleaning and rebuild the project

removing Lombok dependency from maven local repository then reinstall

the problems only occur in this project. Eclipse handles other projects with lombok properly (and all projects belong in the same workspace).

I cannot reproduce these problems in other projects.

Any ideas?


问:
How to pass a list of values into Lambda environment variables with Terraform
I have a Python script that sends an email to multiple recipients. I'd like to set up my recipients with Terraform and pass them into my Lambda function as environment variables. I have set up SES as separate module.

Lambda function:

```<code>def lambda_handler(event, context):
    email_to = os.environ["EMAIL"]
    # script that sends an email is here
</code>```

Lambda module main.tf:

```<code>resource "aws_lambda_function" "test_lambda" {
  filename      = var.filename
  function_name = "test_name"
  role          = "arn:aws:iam::123:role/lambda_role"
  handler       = var.handler

  source_code_hash = var.source_code_hash
  runtime = var.runtime
  timeout = var.timeout
  kms_key_arn = var.kms_key_arn
  memory_size = var.memory

  dynamic "environment" {
    for_each = var.env_variables != null ? var.env_variables[*] : []
    content {
      variables = environment.value
    }
  }

}
</code>```

SES module main.tf:

```<code>resource "aws_ses_email_identity" "email" {
    email = var.email
}
</code>```

SES module outputs.tf:

```<code> output "email" {
    description = "Emails."
    value       = aws_ses_email_identity.email.email
    }
</code>```

main.tf

```<code>module "lambda_zip" {
    source                = "../modules/lambda_zip"
    handler               = "lambda_function.lambda_handler"
    runtime               = "python3.8"
    filename              = "setup.zip"

    env_variables = {
     EMAIL = module.ses[*].email
   }
}

module "ses" {
    source      = "../modules/ses"
    for_each    = toset(["email1@example.com", "email2@example.com"])
    email       = each.value
}

output "email" {
value = module.ses.email
}
</code>```

With the current setup I get this error:

```<code>│ Error: Unsupported attribute
│
│   on main.tf line 24, in module "lambda_zip":
│   24:    EMAIL = jsonencode(module.ses[*].email)
│
│ This object does not have an attribute named "email".
╵
╷
│ Error: Unsupported attribute
│
│   on main.tf line 40, in output "email":
│   40:   value = module.ses.email
│     ├────────────────
│     │ module.ses is object with 2 attributes
│
│ This object does not have an attribute named "email".
</code>```

How can I register new emails with SES and also pass them into the Python function?

答:
If you want to pass all emails at once, it it should be:

```<code>    env_variables = {
     EMAIL = jsonencode(values(module.ses)[*].email)
   }
</code>```

In your function then, you have to process the EMAIL as json data structure.

Body:
I have a Python script that sends an email to multiple recipients. I'd like to set up my recipients with Terraform and pass them into my Lambda function as environment variables. I have set up SES as separate module.

Lambda function:

def lambda_handler(event, context):
    email_to = os.environ["EMAIL"]
    # script that sends an email is here

Lambda module main.tf:

resource "aws_lambda_function" "test_lambda" {
  filename      = var.filename
  function_name = "test_name"
  role          = "arn:aws:iam::123:role/lambda_role"
  handler       = var.handler

  source_code_hash = var.source_code_hash
  runtime = var.runtime
  timeout = var.timeout
  kms_key_arn = var.kms_key_arn
  memory_size = var.memory

  dynamic "environment" {
    for_each = var.env_variables != null ? var.env_variables[*] : []
    content {
      variables = environment.value
    }
  }

}

SES module main.tf:

resource "aws_ses_email_identity" "email" {
    email = var.email
}

SES module outputs.tf:

 output "email" {
    description = "Emails."
    value       = aws_ses_email_identity.email.email
    }

main.tf

module "lambda_zip" {
    source                = "../modules/lambda_zip"
    handler               = "lambda_function.lambda_handler"
    runtime               = "python3.8"
    filename              = "setup.zip"

    env_variables = {
     EMAIL = module.ses[*].email
   }
}

module "ses" {
    source      = "../modules/ses"
    for_each    = toset(["email1@example.com", "email2@example.com"])
    email       = each.value
}

output "email" {
value = module.ses.email
}

With the current setup I get this error:

│ Error: Unsupported attribute
│
│   on main.tf line 24, in module "lambda_zip":
│   24:    EMAIL = jsonencode(module.ses[*].email)
│
│ This object does not have an attribute named "email".
╵
╷
│ Error: Unsupported attribute
│
│   on main.tf line 40, in output "email":
│   40:   value = module.ses.email
│     ├────────────────
│     │ module.ses is object with 2 attributes
│
│ This object does not have an attribute named "email".

How can I register new emails with SES and also pass them into the Python function?

Body:
If you want to pass all emails at once, it it should be:

    env_variables = {
     EMAIL = jsonencode(values(module.ses)[*].email)
   }

In your function then, you have to process the EMAIL as json data structure.


问:
How can I specify different file extensions as targets for multiple output files?
I'd like to create a set of output files from multiple input files where the output format is specified as a target. E.g., for a single format:

svg: svg/file1.svg svg/file2.svg

svg/file1.svg svg/file2.svg: %.svg: %.dot
    @dot -T svg -o $@ $<
```
<p>Now how can I add more formats without duplicating rules and prerequisites? My approach was something like this:</p>
<pre class="lang-makefile prettyprint-override"><code>input := file1 file2
formats := svg png
output := $(foreach format, ${formats}, $(foreach name, ${input}, ${format}/${name}.${format}))
# output := svg/file1.svg svg/file2.svg png/file1.png png/file2.png

all: ${formats}

${formats}: [somehow filter ${output} based on chosen format?]

${output}: [somehow filter out just the file name?]: %.dot
    @dot -T svg -o $@ $<
</code>```

I haven't been able to figure this out with variables and patterns. I did find a way using a variable for the format; e.g., make format=svg, but I'd rather use target names.

Using GNU Make 4.3.

答:
You're going to want to use a macro/eval for this -- but beware, by doing so, you may cross that line where your makefile can be easily understood/maintained by others.,,</p>
```<code>input := file1 file2
formats := svg png
output := $(foreach format, ${formats}, $(foreach name, ${input}, ${name}.${format}))

all: $(foreach file,$(input),$(foreach format,$(foramts),$(file).$(format)))

define dot_rules
# $$1 is the basenames,
# $$2 is the input extension,
# $$3 is the target extension
$(1:=.$3) : %.$3 : %.$2
        @echo dot -T $3 -o $3/$$@ $$<

endef

# just to be suure you got it right:
$(info $(foreach format,$(formats),\
    $(call dot_rules,$(input),dot,$(format))))

# expand the calls into the makefile
$(eval $(foreach format,$(formats),\
    $(call dot_rules,$(input),dot,$(format))))
</code>```

Body:
I'd like to create a set of output files from multiple input files where the output format is specified as a target. E.g., for a single format:

svg: svg/file1.svg svg/file2.svg

svg/file1.svg svg/file2.svg: %.svg: %.dot
    @dot -T svg -o $@ $<

Now how can I add more formats without duplicating rules and prerequisites? My approach was something like this:

input := file1 file2
formats := svg png
output := $(foreach format, ${formats}, $(foreach name, ${input}, ${format}/${name}.${format}))
# output := svg/file1.svg svg/file2.svg png/file1.png png/file2.png

all: ${formats}

${formats}: [somehow filter ${output} based on chosen format?]

${output}: [somehow filter out just the file name?]: %.dot
    @dot -T svg -o $@ $<

I haven't been able to figure this out with variables and patterns. I did find a way using a variable for the format; e.g., make format=svg, but I'd rather use target names.

Using GNU Make 4.3.

Body:
You're going to want to use a macro/eval for this -- but beware, by doing so, you may cross that line where your makefile can be easily understood/maintained by others.,,

input := file1 file2
formats := svg png
output := $(foreach format, ${formats}, $(foreach name, ${input}, ${name}.${format}))

all: $(foreach file,$(input),$(foreach format,$(foramts),$(file).$(format)))

define dot_rules
# $$1 is the basenames,
# $$2 is the input extension,
# $$3 is the target extension
$(1:=.$3) : %.$3 : %.$2
        @echo dot -T $3 -o $3/$$@ $$<

endef

# just to be suure you got it right:
$(info $(foreach format,$(formats),\
    $(call dot_rules,$(input),dot,$(format))))

# expand the calls into the makefile
$(eval $(foreach format,$(formats),\
    $(call dot_rules,$(input),dot,$(format))))


问:
Error E109 - complete binding failed: port not bound
I have been to create a proof of concept for an instance inside an instance, and I am getting a "complete binding error", which I have not been able to get past. I have searched online, and though I found similar cases, they could not explain mine. I have tried to minimize the code as much as possible for readability. The basic block is an adder (called alu_unit), which is instantiated by a block_unit, which right now only contains the alu_unit. The block_unit is instantiated by sc_main, which assigns a value, and runs the simulation. I will place the code below for all units:

alu.h

```<code>#include <systemc.h>

SC_MODULE (alu_unit) {
  sc_in  < sc_int < 64 > >  addA_in{"addA_in"};
  sc_in  < sc_int < 64 > >  addB_in{"addB_in"};
  sc_in  < sc_lv <1> >      carry_in{"carry_in"};
  sc_out < sc_int < 64 > >  sum_busout{"sum_busout"};

  void sumc();

  SC_CTOR(alu_unit) {
    SC_THREAD(sumc);
    sensitive << addA_in << addB_in << carry_in;
  }

  ~alu_unit() { };
};
</code>```

alu.cpp

```<code>#include "alu.h"

void alu_unit::sumc()
{
  sum_busout.write(addA_in.read() + addB_in.read() + carry_in.read().to_int());
};
</code>```

block.h

```<code>#include <systemc.h>
#include "alu.h"

SC_MODULE (block_unit) {
  sc_in_clk                 clock;
  sc_in  < sc_int < 64 > >  addA_in{"addA_in"};
  sc_in  < sc_int < 64 > >  addB_in{"addB_in"};
  sc_in  < sc_lv <1> >      carry_in{"carry_in"};
  sc_out < sc_int <64> >    sum_regout{"sum_busout"};

  /* Instance declarations */
  alu_unit alu1;

  // Function declarations
  void myblock();

    SC_CTOR(block_unit):alu1("alu1") {
    SC_THREAD(myblock);
    sensitive <<  clock.pos();
  }

  ~block_unit() { };

};
</code>```

block.cpp

```<code>#include "block.h"

void block_unit::myblock()
{
  wait();
  while (true) {
    // Input binding
    // Port conections for block alu1
    alu1.addA_in(addA_in);
    alu1.addB_in(addB_in);
    alu1.carry_in(carry_in);
    alu1.sum_busout(sum_regout);
    wait();
  }
}
</code>```

main.cpp

```<code>#include <systemc.h>
#include "block.h"

int sc_main(int argc, char **argv) {
  sc_signal < sc_int < 64 > > addA_s;
  sc_signal < sc_int < 64 > > addB_s;
  sc_signal < sc_lv < 1 > > carry_s;
  sc_signal < sc_int < 64 > > sum_s;

  // 1ns clock with 50% duty cycle
  sc_clock clock("clock", 1, SC_NS, 0.5);
  block_unit block1("block1");

  sc_start(55, SC_NS);
  addA_s = 4;
  addB_s = 3;
  carry_s = 1;
  block1.clock(clock);
  block1.addA_in(addA_s);
  block1.addB_in(addB_s);
  block1.carry_in(carry_s);
  block1.sum_regout.bind(sum_s);

  sc_trace_file *tf = sc_create_vcd_trace_file("vcd_trace.vcd");
  sc_trace(tf, clock, "clock");
  sc_trace(tf, addA_s, "addA");
  sc_trace(tf, addB_s, "addb");
  sc_trace(tf, carry_s, "carry");
  sc_trace(tf, sum_s, "sum");

  sc_stop();
  return 0;
}
</code>```

The compilation works fine using:

```<code>g++ -I. -I/usr/local/systemc/include -O0 -g3 -Wall -c -lsystemc -std=gnu++11 alu.cpp -o alu.o
[...]
g++  -I/usr/local/systemc/include -L. -L/usr/local/systemc/lib-linux64 -o main -lsystemc -std=gnu++11  alu.o  block.o  main.o -lsystemc
</code>```

And simulation fails as follows:
Error: (E109) complete binding failed: port not bound: port 'block1.alu1.sum_busout' (sc_out)

Any help would be greatly appreciated.  I am happy to give SystemC a try, which is why I am doing these proofs of concepts.

答:
There are a few things that look odd.

I don't think you want to use bind in sc_main to make the connection to sum_regout.

I think it would be better to make the connections in sc_main before calling sc_start.

I don't think you want to make connections to alu inside the myblock function.

I don't know the exact reason for the E109 error, but the error goes away with the following code:

```<code>//////////////////////// block.h

#include <systemc.h>
#include "alu.h"

SC_MODULE (block_unit) {
  sc_in_clk                 clock;
  sc_in  < sc_int < 64 > >  addA_in{"addA_in"};
  sc_in  < sc_int < 64 > >  addB_in{"addB_in"};
  sc_in  < sc_lv <1> >      carry_in{"carry_in"};
  sc_out < sc_int <64> >    sum_regout{"sum_regout"};

  alu_unit alu1;

  // Function declarations
  void myblock();

  SC_CTOR(block_unit):alu1("alu1") {
    alu1.addA_in(addA_in);
    alu1.addB_in(addB_in);
    alu1.carry_in(carry_in);
    alu1.sum_busout(sum_regout);

    SC_THREAD(myblock);
    sensitive <<  clock.pos();
  }

  ~block_unit() { };

};

////////////////////////// block.cpp

#include "block.h"

void block_unit::myblock()
{
  wait();
  while (true) {
    wait();
  }
}

//////////////////////// main.cpp

#include <systemc.h>
#include "block.h"

int sc_main(int argc, char **argv) {
  sc_signal < sc_int < 64 > > addA_s;
  sc_signal < sc_int < 64 > > addB_s;
  sc_signal < sc_lv < 1 > > carry_s;
  sc_signal < sc_int < 64 > > sum_s;

  // 1ns clock with 50% duty cycle
  sc_clock clock("clock", 1, SC_NS, 0.5);
  block_unit block1("block1");

  block1.clock(clock);
  block1.addA_in(addA_s);
  block1.addB_in(addB_s);
  block1.carry_in(carry_s);
  block1.sum_regout(sum_s);

  sc_start(55, SC_NS);
  addA_s = 4;
  addB_s = 3;
  carry_s = 1;

  sc_trace_file *tf = sc_create_vcd_trace_file("vcd_trace.vcd");
  sc_trace(tf, clock, "clock");
  sc_trace(tf, addA_s, "addA");
  sc_trace(tf, addB_s, "addb");
  sc_trace(tf, carry_s, "carry");
  sc_trace(tf, sum_s, "sum");

  sc_stop();
  return 0;
}
</code>```

Here is a link on edaplayground

Body:
I have been to create a proof of concept for an instance inside an instance, and I am getting a "complete binding error", which I have not been able to get past. I have searched online, and though I found similar cases, they could not explain mine. I have tried to minimize the code as much as possible for readability. The basic block is an adder (called alu_unit), which is instantiated by a block_unit, which right now only contains the alu_unit. The block_unit is instantiated by sc_main, which assigns a value, and runs the simulation. I will place the code below for all units:

alu.h

#include <systemc.h>

SC_MODULE (alu_unit) {
  sc_in  < sc_int < 64 > >  addA_in{"addA_in"};
  sc_in  < sc_int < 64 > >  addB_in{"addB_in"};
  sc_in  < sc_lv <1> >      carry_in{"carry_in"};
  sc_out < sc_int < 64 > >  sum_busout{"sum_busout"};

  void sumc();

  SC_CTOR(alu_unit) {
    SC_THREAD(sumc);
    sensitive << addA_in << addB_in << carry_in;
  }

  ~alu_unit() { };
};

alu.cpp

#include "alu.h"

void alu_unit::sumc()
{
  sum_busout.write(addA_in.read() + addB_in.read() + carry_in.read().to_int());
};

block.h

#include <systemc.h>
#include "alu.h"

SC_MODULE (block_unit) {
  sc_in_clk                 clock;
  sc_in  < sc_int < 64 > >  addA_in{"addA_in"};
  sc_in  < sc_int < 64 > >  addB_in{"addB_in"};
  sc_in  < sc_lv <1> >      carry_in{"carry_in"};
  sc_out < sc_int <64> >    sum_regout{"sum_busout"};

  /* Instance declarations */
  alu_unit alu1;

  // Function declarations
  void myblock();

    SC_CTOR(block_unit):alu1("alu1") {
    SC_THREAD(myblock);
    sensitive <<  clock.pos();
  }

  ~block_unit() { };

};

block.cpp

#include "block.h"

void block_unit::myblock()
{
  wait();
  while (true) {
    // Input binding
    // Port conections for block alu1
    alu1.addA_in(addA_in);
    alu1.addB_in(addB_in);
    alu1.carry_in(carry_in);
    alu1.sum_busout(sum_regout);
    wait();
  }
}

main.cpp

#include <systemc.h>
#include "block.h"

int sc_main(int argc, char **argv) {
  sc_signal < sc_int < 64 > > addA_s;
  sc_signal < sc_int < 64 > > addB_s;
  sc_signal < sc_lv < 1 > > carry_s;
  sc_signal < sc_int < 64 > > sum_s;

  // 1ns clock with 50% duty cycle
  sc_clock clock("clock", 1, SC_NS, 0.5);
  block_unit block1("block1");

  sc_start(55, SC_NS);
  addA_s = 4;
  addB_s = 3;
  carry_s = 1;
  block1.clock(clock);
  block1.addA_in(addA_s);
  block1.addB_in(addB_s);
  block1.carry_in(carry_s);
  block1.sum_regout.bind(sum_s);

  sc_trace_file *tf = sc_create_vcd_trace_file("vcd_trace.vcd");
  sc_trace(tf, clock, "clock");
  sc_trace(tf, addA_s, "addA");
  sc_trace(tf, addB_s, "addb");
  sc_trace(tf, carry_s, "carry");
  sc_trace(tf, sum_s, "sum");

  sc_stop();
  return 0;
}

The compilation works fine using:

g++ -I. -I/usr/local/systemc/include -O0 -g3 -Wall -c -lsystemc -std=gnu++11 alu.cpp -o alu.o
[...]
g++  -I/usr/local/systemc/include -L. -L/usr/local/systemc/lib-linux64 -o main -lsystemc -std=gnu++11  alu.o  block.o  main.o -lsystemc

And simulation fails as follows:
Error: (E109) complete binding failed: port not bound: port 'block1.alu1.sum_busout' (sc_out)

Any help would be greatly appreciated.  I am happy to give SystemC a try, which is why I am doing these proofs of concepts.

Body:
There are a few things that look odd.

I don't think you want to use bind in sc_main to make the connection to sum_regout.

I think it would be better to make the connections in sc_main before calling sc_start.

I don't think you want to make connections to alu inside the myblock function.

I don't know the exact reason for the E109 error, but the error goes away with the following code:

//////////////////////// block.h

#include <systemc.h>
#include "alu.h"

SC_MODULE (block_unit) {
  sc_in_clk                 clock;
  sc_in  < sc_int < 64 > >  addA_in{"addA_in"};
  sc_in  < sc_int < 64 > >  addB_in{"addB_in"};
  sc_in  < sc_lv <1> >      carry_in{"carry_in"};
  sc_out < sc_int <64> >    sum_regout{"sum_regout"};

  alu_unit alu1;

  // Function declarations
  void myblock();

  SC_CTOR(block_unit):alu1("alu1") {
    alu1.addA_in(addA_in);
    alu1.addB_in(addB_in);
    alu1.carry_in(carry_in);
    alu1.sum_busout(sum_regout);

    SC_THREAD(myblock);
    sensitive <<  clock.pos();
  }

  ~block_unit() { };

};

////////////////////////// block.cpp

#include "block.h"

void block_unit::myblock()
{
  wait();
  while (true) {
    wait();
  }
}

//////////////////////// main.cpp

#include <systemc.h>
#include "block.h"

int sc_main(int argc, char **argv) {
  sc_signal < sc_int < 64 > > addA_s;
  sc_signal < sc_int < 64 > > addB_s;
  sc_signal < sc_lv < 1 > > carry_s;
  sc_signal < sc_int < 64 > > sum_s;

  // 1ns clock with 50% duty cycle
  sc_clock clock("clock", 1, SC_NS, 0.5);
  block_unit block1("block1");

  block1.clock(clock);
  block1.addA_in(addA_s);
  block1.addB_in(addB_s);
  block1.carry_in(carry_s);
  block1.sum_regout(sum_s);

  sc_start(55, SC_NS);
  addA_s = 4;
  addB_s = 3;
  carry_s = 1;

  sc_trace_file *tf = sc_create_vcd_trace_file("vcd_trace.vcd");
  sc_trace(tf, clock, "clock");
  sc_trace(tf, addA_s, "addA");
  sc_trace(tf, addB_s, "addb");
  sc_trace(tf, carry_s, "carry");
  sc_trace(tf, sum_s, "sum");

  sc_stop();
  return 0;
}

Here is a link on edaplayground


问:
R ggplot: Modifying aesthetics of individual lines without recreating entire color palette
In ggplot, is there any simple way of overriding the line attributes of a single group(s) without having to specify the entirety of the color/line pallet via scale_*_manual()?

In the example below, I basically want to make all the boot_* lines gray and skinny, while I want all other lines to retain the default colors/widths otherwise being used.

I know there's a lot of brute ways of doing this by some combo of a) creating some auxiliary variables in the data-frame based on the string-pattern that will server as my color/size group, then b) generating the plot below, extracting all the color-layer info, and then filling out an entire scale_color_manual() and scale_size_manual() map, and c)replacing the 'boot_*' values with "grey."

Are there any versatile shortcuts here?

```<code>library(dplyr)
library(ggplot)

set.seed(231)
df=tibble(time=c(1:5), actual=2*time+3, estimate = actual+rnorm(length(actual)))
for(i in 1:8){
  df[paste('boot_', i, sep='')] = df$estimate + rnorm(nrow(df))
}

> head(df) %>% data.frame
# time actual  estimate    boot_1    boot_2    boot_3    boot_4    boot_5    boot_6    boot_7
# 1    1      5  4.466898  4.684295  4.240585  4.786520  5.904332  4.862498  2.092772  4.595850
# 2    2      7  4.688336  4.751258  6.074914  5.694181  3.445036  4.639329  4.548511  5.453597
# 3    3      9  8.045802  7.167972  6.858666  7.519752  7.721405  7.801243 10.156436  9.521482
# 4    4     11 11.262516 11.826206 10.682760 11.137814 11.252465 11.452442 11.925339 11.754248
# 5    5     13 12.526643 12.492315 13.927974 14.176896 11.924183 12.950479 11.257865 13.430229
# boot_8
# 1  3.987001
# 2  3.813539
# 3  7.549984
# 4 11.482360
# 5 11.645106

# Melt for ggplot compatibility
df_long = df %>%
  pivot_longer(cols=(-time))

head(df_long) %>% data.frame
# time     name    value
# 1    1   actual 5.000000
# 2    1 estimate 4.466898
# 3    1   boot_1 4.684295
# 4    1   boot_2 4.240585
# 5    1   boot_3 4.786520
# 6    1   boot_4 5.904332

## The basic ggplot
df_long %>%
  ggplot(aes(x=time, y=value, color=name)) + geom_line()

</code>```

答:
You could just use the first four characters of name for the colour aesthetic (using substr), and the full name as a group aesthetic. It's a bit hacky but it's short, effective, and all gets done in the plotting code without extra data wrangling, post-hoc changes or a long vector of colour mappings.

df_long %>%
  ggplot(aes(x = time, y = value, color = substr(name, 1, 4), group = name)) +
  geom_line() +
  scale_color_manual(labels = c("actual", "boot", "estimate"),
                     values = c("orange", "gray", "blue3"), name = "name")
```
<p><img src="https://i.stack.imgur.com/mPK0L.png" alt="enter image description here" /></p>
<p>An alternative is using filtering to have two sets of lines: one coloured, and one merely grouped. This has the benefit that you don't need to add any scale calls at all:</p>
<pre class="lang-r prettyprint-override"><code>df_long %>%
  filter(!grepl("boot", name)) %>%
  ggplot(aes(x = time, y = value, color = name)) +
  geom_line(data = filter(df_long, grepl("boot", name)),
            aes(group = name), color = "gray", size = 0.3) +
  geom_line()
</code>```

EDIT

It's pretty difficult to only specify an aesthetic mapping for a single (multiple) group, while leaving the others at default values. However, it is possible using ggnewscale. Here we only have to specify the color of the boot group:

library(ggnewscale)

df_long %>%
  filter(!grepl("boot", name)) %>%
  ggplot(aes(x = time, y = value)) +
  new_scale_color() +
  geom_line(aes(color = name)) +
  scale_color_discrete(name = "Variable") +
  new_scale_color() +
  geom_line(data = filter(df_long, grepl("boot", name)),
            aes(group = name, color = "boot"), size = 0.3) +
  scale_color_manual(values = "gray", name = "") +
  theme(legend.margin = margin(-28, 10, 0, 0))
```

Body:
In ggplot, is there any simple way of overriding the line attributes of a single group(s) without having to specify the entirety of the color/line pallet via scale_*_manual()?

In the example below, I basically want to make all the boot_* lines gray and skinny, while I want all other lines to retain the default colors/widths otherwise being used.

I know there's a lot of brute ways of doing this by some combo of a) creating some auxiliary variables in the data-frame based on the string-pattern that will server as my color/size group, then b) generating the plot below, extracting all the color-layer info, and then filling out an entire scale_color_manual() and scale_size_manual() map, and c)replacing the 'boot_*' values with "grey."

Are there any versatile shortcuts here?

library(dplyr)
library(ggplot)

set.seed(231)
df=tibble(time=c(1:5), actual=2*time+3, estimate = actual+rnorm(length(actual)))
for(i in 1:8){
  df[paste('boot_', i, sep='')] = df$estimate + rnorm(nrow(df))
}

> head(df) %>% data.frame
# time actual  estimate    boot_1    boot_2    boot_3    boot_4    boot_5    boot_6    boot_7
# 1    1      5  4.466898  4.684295  4.240585  4.786520  5.904332  4.862498  2.092772  4.595850
# 2    2      7  4.688336  4.751258  6.074914  5.694181  3.445036  4.639329  4.548511  5.453597
# 3    3      9  8.045802  7.167972  6.858666  7.519752  7.721405  7.801243 10.156436  9.521482
# 4    4     11 11.262516 11.826206 10.682760 11.137814 11.252465 11.452442 11.925339 11.754248
# 5    5     13 12.526643 12.492315 13.927974 14.176896 11.924183 12.950479 11.257865 13.430229
# boot_8
# 1  3.987001
# 2  3.813539
# 3  7.549984
# 4 11.482360
# 5 11.645106

# Melt for ggplot compatibility
df_long = df %>%
  pivot_longer(cols=(-time))

head(df_long) %>% data.frame
# time     name    value
# 1    1   actual 5.000000
# 2    1 estimate 4.466898
# 3    1   boot_1 4.684295
# 4    1   boot_2 4.240585
# 5    1   boot_3 4.786520
# 6    1   boot_4 5.904332

## The basic ggplot
df_long %>%
  ggplot(aes(x=time, y=value, color=name)) + geom_line()

Body:
You could just use the first four characters of name for the colour aesthetic (using substr), and the full name as a group aesthetic. It's a bit hacky but it's short, effective, and all gets done in the plotting code without extra data wrangling, post-hoc changes or a long vector of colour mappings.

df_long %>%
  ggplot(aes(x = time, y = value, color = substr(name, 1, 4), group = name)) +
  geom_line() +
  scale_color_manual(labels = c("actual", "boot", "estimate"),
                     values = c("orange", "gray", "blue3"), name = "name")

An alternative is using filtering to have two sets of lines: one coloured, and one merely grouped. This has the benefit that you don't need to add any scale calls at all:

df_long %>%
  filter(!grepl("boot", name)) %>%
  ggplot(aes(x = time, y = value, color = name)) +
  geom_line(data = filter(df_long, grepl("boot", name)),
            aes(group = name), color = "gray", size = 0.3) +
  geom_line()

EDIT

It's pretty difficult to only specify an aesthetic mapping for a single (multiple) group, while leaving the others at default values. However, it is possible using ggnewscale. Here we only have to specify the color of the boot group:

library(ggnewscale)

df_long %>%
  filter(!grepl("boot", name)) %>%
  ggplot(aes(x = time, y = value)) +
  new_scale_color() +
  geom_line(aes(color = name)) +
  scale_color_discrete(name = "Variable") +
  new_scale_color() +
  geom_line(data = filter(df_long, grepl("boot", name)),
            aes(group = name, color = "boot"), size = 0.3) +
  scale_color_manual(values = "gray", name = "") +
  theme(legend.margin = margin(-28, 10, 0, 0))


问:
SQL - Converting one value into two or more possible values
I have one table I would like to convert into another set of values.

Table A's Letter Column
Converts into

A
AA AND AB

B
BB

C
CC

So, what I am doing is...

SELECT all the values from Table A

Convert Table A's values using a CASE

```<code>CASE TABLE A COLUMN
 WHEN 'A' THEN 'AA'
 WHEN 'A' THEN 'AB'
 WHEN 'B' THEN 'BB'
 WHEN 'C' THEN 'CC'
 ELSE NULL
END
</code>```

Of course, a CASE statement can only have one outcome and thus I can't get it show both 'AA' and 'AB' when it converts 'A' from Table A. What can I do in this situation?

The expected outcome I want is that it would show (AA, AB, BB, and CC) using the input of (A, B, and C).

Let me know if this sounds confusing!
Thank you!

EDIT: For clarification... I modified the orignal above and added details below.

I have three values that I pulled from one table using a SELECT.

I want these three values to be shown in the converted form as 'AA', 'AB', 'BB', and 'CC'.

答:
You would do this with an additional table and join. So you have table to map the Letter column from TableA to the desired outputs:

Letter
MappedValue

A
AA

A
AB

B
BB

C
CC

OR

Letter
MappedValue

A
AA,AB

B
BB

C
CC

Now you can bring this in with a JOIN. Note that you should strongly prefer the first option. Delimited data in a column is rarely, if ever, the right choice. However, I'm more of a Sql Server guy, and I'm not sure what Hive has in place of Sql Server's string_agg(), which you need in order to avoid spreading the results over multiple records.

Additionally, if you are unable to create the table, Sql Server has a feature called Table Value Constructors that can used to include this mapping directly in the single SQL statement. This feature is actually part of the ansi standard, but it's one of those parts of the standard that tend to get lost by some of the more recent SQL-like projects and again: I'm not sure how it will look in Hive.

Body:
I have one table I would like to convert into another set of values.

Table A's Letter Column
Converts into

A
AA AND AB

B
BB

C
CC

So, what I am doing is...

SELECT all the values from Table A

Convert Table A's values using a CASE

CASE TABLE A COLUMN
 WHEN 'A' THEN 'AA'
 WHEN 'A' THEN 'AB'
 WHEN 'B' THEN 'BB'
 WHEN 'C' THEN 'CC'
 ELSE NULL
END

Of course, a CASE statement can only have one outcome and thus I can't get it show both 'AA' and 'AB' when it converts 'A' from Table A. What can I do in this situation?

The expected outcome I want is that it would show (AA, AB, BB, and CC) using the input of (A, B, and C).

Let me know if this sounds confusing!
Thank you!

EDIT: For clarification... I modified the orignal above and added details below.

I have three values that I pulled from one table using a SELECT.

I want these three values to be shown in the converted form as 'AA', 'AB', 'BB', and 'CC'.


问:
`document` doesn't refer to the shadowDom
So I have code that's something like this:

<template id="cool-btn-template">

  <button id="click-me">Log click event</button>
</template>

<cool-btn></cool-btn>

```

If you run the code, you'll notice that document in the template's script tag refers to the overall document, not the shadowDom. How do I make document mean its shadowDom?

答:
I believe all JavaScript for a custom element is meant to go inside its class, which is how you scope it to the element:

<template id="cool-btn-template">

  <button id="click-me">Log click event</button>
</template>

<cool-btn></cool-btn>

```

Body:
So I have code that's something like this:

<template id="cool-btn-template">

  <button id="click-me">Log click event</button>
</template>

<cool-btn></cool-btn>

If you run the code, you'll notice that document in the template's script tag refers to the overall document, not the shadowDom. How do I make document mean its shadowDom?

Body:
I believe all JavaScript for a custom element is meant to go inside its class, which is how you scope it to the element:

<template id="cool-btn-template">
  <style>
    #click-me {
      all: unset;
      background: tomato;
      border: 0;
      border-radius: 4px;
      color: white;
      font-family: Helvetica;
      font-size: 1.5rem;
      padding: .5rem 1rem;
    }
  </style>
  <button id="click-me">Log click event</button>
</template>

<cool-btn></cool-btn>

<script>
  class CoolBtn extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById('cool-btn-template');
      const shadowRoot = this.attachShadow({mode: 'open'});
      shadowRoot.appendChild(template.content.cloneNode(true));
      shadowRoot.getElementById('click-me').addEventListener('click', event => alert(event))
    }
  }

  customElements.define('cool-btn', CoolBtn);
</script>


问:
if statement causes while loop to run forever in Java
I'm working on a project to convert csv files into html. My problem is that my code will run forever and I have to stop it manually. However, when I remove the if statement, all of the print methods are executed how I intended. Here's the code below.

```<code>package com.company;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

public class TableMaker {

    public static void main(String[] args) {
        System.out.println("Enter file path.");
        Scanner scanner = new Scanner(System.in);
        String filepath = scanner.nextLine();
        String line;
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(filepath));
            while ((line = reader.readLine()) != null) {
                String[] row = line.split(",");
                if (scanner.next().charAt(0) == '#') {
                    continue;
                }
                System.out.print("<tr>");
                for (int n = 0; n < row.length; n++) {
                    System.out.print("<td>" + row[n] + "</td>");
                }
                System.out.print("</tr>" + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
</code>```

If this helps at all, whenever I stop it manually it says it has exit code 130.

答:
I think what you wanted to achieve in the if statement is skip lines in the file provided to the System.in that starts with #.

So you need to check if the first character of line is #, and not of scanner.next().charAt(0) which hangs while it waits for another input to stdin.

try:

if (line.charAt(0) == '#') {
    continue;
}
```

Body:
I'm working on a project to convert csv files into html. My problem is that my code will run forever and I have to stop it manually. However, when I remove the if statement, all of the print methods are executed how I intended. Here's the code below.

package com.company;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

public class TableMaker {

    public static void main(String[] args) {
        System.out.println("Enter file path.");
        Scanner scanner = new Scanner(System.in);
        String filepath = scanner.nextLine();
        String line;
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(filepath));
            while ((line = reader.readLine()) != null) {
                String[] row = line.split(",");
                if (scanner.next().charAt(0) == '#') {
                    continue;
                }
                System.out.print("
");
                for (int n = 0; n < row.length; n++) {
                    System.out.print("" + row[n] + "	");
                }
                System.out.print("
" + "\r\n");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

If this helps at all, whenever I stop it manually it says it has exit code 130.


问:
How to include files outside of Docker's build context?
How can I include files from outside of Docker's build context using the "ADD" command in the Docker file?

From the Docker documentation:

The  path must be inside the context of the build; you cannot ADD
  ../something/something, because the first step of a docker build is to
  send the context directory (and subdirectories) to the docker daemon.

I do not want to restructure my whole project just to accommodate Docker in this matter. I want to keep all my Docker files in the same sub-directory.

Also, it appears Docker does not yet (and may not ever) support symlinks: Dockerfile ADD command does not follow symlinks on host #1676.

The only other thing I can think of is to include a pre-build step to copy the files into the Docker build context (and configure my version control to ignore those files). Is there a better workaround for than that?

答:
This behavior is given by the context directory that the docker or podman uses to present the files to the build process.

A nice trick here is by changing the context dir during the building instruction to the full path of the directory, that you want to expose to the daemon.
e.g:

docker build -t imageName:tag -f /path/to/the/Dockerfile /mysrc/path
```
<p>using <code>/mysrc/path</code> instead of <code>.</code><em>(current directory)</em>, you'll be using that directory as a context, so any files under it can be seen by the build process.<br />
This example you'll be exposing the entire <code>/mysrc/path</code> tree to the docker daemon.<br />
When using this with <code>docker</code> the user ID who triggered the build must have <strong>recursively read permissions</strong> to any single directory or file from the context dir.</p>
<p>This can be useful in cases where you have the <code>/home/user/myCoolProject/Dockerfile</code>  but want to bring to this container build context, files that aren't in the same directory.</p>
<p>Here is an example of building using context dir, but this time using <code>podman</code> instead of <code>docker</code>.</p>
<p>Lets take as example, having inside your <code>Dockerfile</code> a <code>COPY</code> or <code>ADD</code>instruction which is copying files from a directory outside of your project, like:</p>
```FROM myImage:tag
...
...
COPY /opt/externalFile ./
ADD /home/user/AnotherProject/anotherExternalFile ./
...
```
<p>In order to build this, with a container file located in the <code>/home/user/myCoolProject/Dockerfile</code>, just do something like:</p>
```cd /home/user/myCoolProject
podman build -t imageName:tag -f Dockefile /
```
<p>Some known use cases to change the context dir, is when using a container as a toolchain for building your souce code.<br />
e.g:</p>
<pre class="lang-sh prettyprint-override"><code>podman build --platform linux/s390x -t myimage:mytag -f ./Dockerfile /tmp/mysrc
</code>```

or it can be a path relative, like:

podman build --platform linux/s390x -t myimage:mytag -f ./Dockerfile ../../
```
<p>Another example using this time a global path:</p>
```FROM myImage:tag
...
...
COPY externalFile ./
ADD  AnotherProject ./
...
```
<p><em>Notice that now the full global path for the <code>COPY</code> and <code>ADD</code> is omitted in the Dockerfile command layers.</em><br />
In this case the <code>contex dir</code> must be relative to where the files are, if both <code>externalFile</code> and <code>AnotherProject</code> are in <code>/opt</code> directory then the <code>context dir</code> for building it must be:</p>
```podman build -t imageName:tag -f ./Dockerfile /opt
```

Note when using COPY or ADD with context dir in docker:

The docker daemon will try to "stream" all the files visible on the context dir tree to the daemon, which can slowdown the build. And requires the user to have recursively permission from the context dir.
This behavior can be more costly specially when using the build through the API. However,with podman the build happens instantaneously, without needing recursively permissions, that's because podman does not enumerate the entire context dir, and doesn't use a client/server architecture as well.

The build for such cases can be way more interesting to use podman instead of docker, when you face such issues using a different context dir.

Some references:

https://docs.docker.com/engine/reference/commandline/build/

https://docs.podman.io/en/latest/markdown/podman-build.1.html

Body:
This behavior is given by the context directory that the docker or podman uses to present the files to the build process.

A nice trick here is by changing the context dir during the building instruction to the full path of the directory, that you want to expose to the daemon.
e.g:

docker build -t imageName:tag -f /path/to/the/Dockerfile /mysrc/path

using /mysrc/path instead of .(current directory), you'll be using that directory as a context, so any files under it can be seen by the build process.

This example you'll be exposing the entire /mysrc/path tree to the docker daemon.

When using this with docker the user ID who triggered the build must have recursively read permissions to any single directory or file from the context dir.

This can be useful in cases where you have the /home/user/myCoolProject/Dockerfile  but want to bring to this container build context, files that aren't in the same directory.

Here is an example of building using context dir, but this time using podman instead of docker.

Lets take as example, having inside your Dockerfile a COPY or ADDinstruction which is copying files from a directory outside of your project, like:

FROM myImage:tag
...
...
COPY /opt/externalFile ./
ADD /home/user/AnotherProject/anotherExternalFile ./
...

In order to build this, with a container file located in the /home/user/myCoolProject/Dockerfile, just do something like:

cd /home/user/myCoolProject
podman build -t imageName:tag -f Dockefile /

Some known use cases to change the context dir, is when using a container as a toolchain for building your souce code.

e.g:

podman build --platform linux/s390x -t myimage:mytag -f ./Dockerfile /tmp/mysrc

or it can be a path relative, like:

podman build --platform linux/s390x -t myimage:mytag -f ./Dockerfile ../../

Another example using this time a global path:

FROM myImage:tag
...
...
COPY externalFile ./
ADD  AnotherProject ./
...

Notice that now the full global path for the COPY and ADD is omitted in the Dockerfile command layers.

In this case the contex dir must be relative to where the files are, if both externalFile and AnotherProject are in /opt directory then the context dir for building it must be:

podman build -t imageName:tag -f ./Dockerfile /opt

Note when using COPY or ADD with context dir in docker:

The docker daemon will try to "stream" all the files visible on the context dir tree to the daemon, which can slowdown the build. And requires the user to have recursively permission from the context dir.
This behavior can be more costly specially when using the build through the API. However,with podman the build happens instantaneously, without needing recursively permissions, that's because podman does not enumerate the entire context dir, and doesn't use a client/server architecture as well.

The build for such cases can be way more interesting to use podman instead of docker, when you face such issues using a different context dir.

Some references:

https://docs.docker.com/engine/reference/commandline/build/

https://docs.podman.io/en/latest/markdown/podman-build.1.html


问:
python encode string to html unicode for deezer api
I'm struggling with the deezer api.
I want to perform a request which contains umlaute.
While the usual python requests library converts the following:

'album:"Ich schwanke noch" artist:"Ikke Hüftgold"'

To this api search request:

https://api.deezer.com/search/album?q=album%3A%22Ich+schwanke+noch%22+artist%3A%22Ikke+H%C3%BCftgold%22

Which is from utf-8 standards, totally fine as long as I understood.

But unfortunately, deezer don't accept them or just delivers an empty result.

This would be the code to reproduce:

```<code>import requests
search_url = 'https://api.deezer.com/search/'
query_type = 'album'

query = 'album:"Ich schwanke noch" artist:"Ikke Hüftgold"'
response = requests.get(
    search_url + query_type, params={'q': query}
)
print(response.url)
</code>```

After a deep dive I found out, deezer accepts only the following character set.
Only the two Unicode (HTML) from this article:
https://de.wikipedia.org/wiki/Hilfe:Sonderzeichenreferenz

So manually the request look like this:

https://api.deezer.com/search/album?q=album:%22Ich%20schwanke%20noch%22%20artist:%22Ikke%20Hüftgold%22

But how on earth could I tell python to encode using this set.
I didn't find anything till now.

I would love to found help on this way.

答:
This has nothing to do with the encoding, it's how you are using the the search API:

```<code>import requests
search_url = 'https://api.deezer.com/search/'

query = 'Ikke Hüftgold Ich schwanke noch'
response = requests.get(
    search_url, params={'q': query}
)

resp = response.json()

for item in resp["data"]:
    print(item['title'], item['artist']['name'], item['album']['title'], item['album']['id'])
</code>```

Out:

```<code>Ich schwanke noch Ikke Hüftgold Ich schwanke noch 226034622
Ich schwanke noch Ikke Hüftgold Ballermann Playa Hits 2021 235679732
Ich schwanke noch Ikke Hüftgold Après Ski Hütten Hits 2022 271034782
Ich schwanke noch Ikke Hüftgold Oktoberfest Megamix 2021 248418852
Ich schwanke noch Ikke Hüftgold Ballermann Charts 2021 - Der Sommer unseres Lebens 239857652
Ich schwanke noch Ikke Hüftgold Ballermann Après Ski Mega Hits 2022 271529842
Ich schwanke noch Ikke Hüftgold Ballermann Après Ski Party Hits 2022 270321652
Ich schwanke noch Ikke Hüftgold Ballermann Après-Ski Party 2022 269952722
Ich schwanke noch Ikke Hüftgold Wiesn Megamix 2021 : Die Oktoberfest Party Hits 247638622
Ich schwanke noch Ikke Hüftgold Karneval Megamix 2022 282534992
Ich schwanke noch Ikke Hüftgold Ballermann Summer Megahits 2021 - Die Party Songs Von Der Playa 241106462
Ich schwanke noch Ikke Hüftgold Oktoberfest Partyhits 2021: Die Kracher aus dem Bierzelt 255573382
Ich schwanke noch Ikke Hüftgold Ballermann Partyalarm 2021 246561782
Ich schwanke noch Ikke Hüftgold Ballermann Oktoberfest Hits 2021 246828062
Ich schwanke noch Ikke Hüftgold Ballermann Ski Hits Top 100 2022: Der ultimative Party Megamix 263551832
Ich schwanke noch Ikke Hüftgold Ballermann Hüttengaudi 2022 270698482
Ich schwanke noch Ikke Hüftgold Hütten Charts Megamix 2022: Die ultimative Après Ski Party 270840962
Ich schwanke noch Ikke Hüftgold Ballermann Party Knüller 2021 237380692
Ich schwanke noch Ikke Hüftgold Ballermann - We Are Back - Die Party Hits Des Sommers 2021 239281792
Ich schwanke noch Ikke Hüftgold Après Ski Megahits 2022 258969192
Ich schwanke noch Ikke Hüftgold Ballermann Party Classics: Die besten Hits von damals bis heute 242757312
Ich schwanke noch Ikke Hüftgold Ballermann Schlager Hitmix 2021.2 249705922
Ich schwanke noch Ikke Hüftgold Oktoberfest CLASSICS XXL : Die besten Wiesn Party Hits von damals bis heute 257765392
Ich schwanke noch Ikke Hüftgold Ballermann Oktoberfest 2021 249970202
Ich schwanke noch Ikke Hüftgold Oktoberfest Party Classics 2021 249529552
</code>```

Edit:

You need to convert non-ASCII characters to HTML Unicode entities:

```<code>#coding: utf-8
import html
import requests

response = requests.get("https://api.deezer.com/search/album?q=album:%22Ich%20schwanke%20noch%22%20artist:%22Ikke%20H&#252ftgold%22")
expectedResponse = response.json()

query = 'album:"Ich schwanke noch" artist="Ikke Hüftgold"'

q = html.escape(query, quote=False).encode('ascii', 'xmlcharrefreplace').decode()
print(q)

response = requests.get(
    "https://api.deezer.com/search/album", params={'q': q}
)

resp = response.json()
print(response.url)
print(expectedResponse == resp)
</code>```

Out:

```<code>album:"Ich schwanke noch" artist="Ikke Hüftgold"
https://api.deezer.com/search/album?q=album%3A%22Ich+schwanke+noch%22+artist%3D%22Ikke+H%26%23252%3Bftgold%22
True
</code>```

Body:
I'm struggling with the deezer api.
I want to perform a request which contains umlaute.
While the usual python requests library converts the following:

'album:"Ich schwanke noch" artist:"Ikke Hüftgold"'

To this api search request:

https://api.deezer.com/search/album?q=album%3A%22Ich+schwanke+noch%22+artist%3A%22Ikke+H%C3%BCftgold%22

Which is from utf-8 standards, totally fine as long as I understood.

But unfortunately, deezer don't accept them or just delivers an empty result.

This would be the code to reproduce:

import requests
search_url = 'https://api.deezer.com/search/'
query_type = 'album'

query = 'album:"Ich schwanke noch" artist:"Ikke Hüftgold"'
response = requests.get(
    search_url + query_type, params={'q': query}
)
print(response.url)

After a deep dive I found out, deezer accepts only the following character set.
Only the two Unicode (HTML) from this article:
https://de.wikipedia.org/wiki/Hilfe:Sonderzeichenreferenz

So manually the request look like this:

https://api.deezer.com/search/album?q=album:%22Ich%20schwanke%20noch%22%20artist:%22Ikke%20Hüftgold%22

But how on earth could I tell python to encode using this set.
I didn't find anything till now.

I would love to found help on this way.

Body:
This has nothing to do with the encoding, it's how you are using the the search API:

import requests
search_url = 'https://api.deezer.com/search/'

query = 'Ikke Hüftgold Ich schwanke noch'
response = requests.get(
    search_url, params={'q': query}
)

resp = response.json()

for item in resp["data"]:
    print(item['title'], item['artist']['name'], item['album']['title'], item['album']['id'])

Out:

Ich schwanke noch Ikke Hüftgold Ich schwanke noch 226034622
Ich schwanke noch Ikke Hüftgold Ballermann Playa Hits 2021 235679732
Ich schwanke noch Ikke Hüftgold Après Ski Hütten Hits 2022 271034782
Ich schwanke noch Ikke Hüftgold Oktoberfest Megamix 2021 248418852
Ich schwanke noch Ikke Hüftgold Ballermann Charts 2021 - Der Sommer unseres Lebens 239857652
Ich schwanke noch Ikke Hüftgold Ballermann Après Ski Mega Hits 2022 271529842
Ich schwanke noch Ikke Hüftgold Ballermann Après Ski Party Hits 2022 270321652
Ich schwanke noch Ikke Hüftgold Ballermann Après-Ski Party 2022 269952722
Ich schwanke noch Ikke Hüftgold Wiesn Megamix 2021 : Die Oktoberfest Party Hits 247638622
Ich schwanke noch Ikke Hüftgold Karneval Megamix 2022 282534992
Ich schwanke noch Ikke Hüftgold Ballermann Summer Megahits 2021 - Die Party Songs Von Der Playa 241106462
Ich schwanke noch Ikke Hüftgold Oktoberfest Partyhits 2021: Die Kracher aus dem Bierzelt 255573382
Ich schwanke noch Ikke Hüftgold Ballermann Partyalarm 2021 246561782
Ich schwanke noch Ikke Hüftgold Ballermann Oktoberfest Hits 2021 246828062
Ich schwanke noch Ikke Hüftgold Ballermann Ski Hits Top 100 2022: Der ultimative Party Megamix 263551832
Ich schwanke noch Ikke Hüftgold Ballermann Hüttengaudi 2022 270698482
Ich schwanke noch Ikke Hüftgold Hütten Charts Megamix 2022: Die ultimative Après Ski Party 270840962
Ich schwanke noch Ikke Hüftgold Ballermann Party Knüller 2021 237380692
Ich schwanke noch Ikke Hüftgold Ballermann - We Are Back - Die Party Hits Des Sommers 2021 239281792
Ich schwanke noch Ikke Hüftgold Après Ski Megahits 2022 258969192
Ich schwanke noch Ikke Hüftgold Ballermann Party Classics: Die besten Hits von damals bis heute 242757312
Ich schwanke noch Ikke Hüftgold Ballermann Schlager Hitmix 2021.2 249705922
Ich schwanke noch Ikke Hüftgold Oktoberfest CLASSICS XXL : Die besten Wiesn Party Hits von damals bis heute 257765392
Ich schwanke noch Ikke Hüftgold Ballermann Oktoberfest 2021 249970202
Ich schwanke noch Ikke Hüftgold Oktoberfest Party Classics 2021 249529552

Edit:

You need to convert non-ASCII characters to HTML Unicode entities:

#coding: utf-8
import html
import requests

response = requests.get("https://api.deezer.com/search/album?q=album:%22Ich%20schwanke%20noch%22%20artist:%22Ikke%20H&#252ftgold%22")
expectedResponse = response.json()

query = 'album:"Ich schwanke noch" artist="Ikke Hüftgold"'

q = html.escape(query, quote=False).encode('ascii', 'xmlcharrefreplace').decode()
print(q)

response = requests.get(
    "https://api.deezer.com/search/album", params={'q': q}
)

resp = response.json()
print(response.url)
print(expectedResponse == resp)

Out:

album:"Ich schwanke noch" artist="Ikke H&#252;ftgold"
https://api.deezer.com/search/album?q=album%3A%22Ich+schwanke+noch%22+artist%3D%22Ikke+H%26%23252%3Bftgold%22
True


问:
Why do my list item bullets overlap floating elements
I have an (XHTML Strict) page where I float an image alongside regular paragraphs of text. All goes well, except when a list is used instead of paragraphs. The bullets of the list overlap the floated image.

Changing the margin of the list or the list items does not help. The margin is calculated from the left of the page, but the float pushes the list items to the right inside the li itself. So the margin only helps if I make it wider than the image.

Floating the list next to the image also works, but I don't know when the list is next to a float. I don't want to float every list in my content just to fix this. Also, floating left messes up the layout when an image is floated to the right instead of left of the list.

Setting li { list-style-position: inside } does move the bullets along with the content, but it also causes lines that wrap to start aligned with the bullet, instead of aligned with the line above.

The problem is obviously caused by the bullet being rendered outside the box, the float pushing the contents of the box to the right (not the box itself). This is how IE and FF handle the situation, and as far as I know, not wrong according to the spec. The question is, how can I prevent it?

答:
I have found a solution to this problem. Applying an ul { overflow: hidden; } to the ul ensures that the box itself is pushed aside by the float, instead of the contents of the box.

Only IE6 needs an ul { zoom: 1; } in our conditional comments to make sure the ul has layout.

OwnerDisplayName: Kamiel Wanrooij

LastEditorDisplayName: Kamiel Wanrooij

ContentLicense: CC BY-SA 2.5


问:
Can I test just the code in a single module?
I've got a Rust project that uses a fairly large framework. Compilation and macro expansion take a really long time. If I make a tiny change to the code, it takes a minute or more before before "cargo test" actually executes.

Is it possible to create a sub-project or sub-module within the same crate and test just the code in the module, assuming there are no dependencies on code outside the module?

答: Yeah, cargo test will take arguments which match specific tests that you want to run (Cargo book). For example, if you have modules foo and bar, you can run cargo test foo to run tests from that module, excluding all others.


问:
"Message: Unable to locate element" when looking for the first image
again!

I'm trying to build a Pinterest webscraper and I want the program to log in Pinterest, search for "South Korea" and get the first image's attribute and print it out.
Here's the code:

```<code>
    py
    from selenium import webdriver
    from selenium.webdriver.firefox.service import Service
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    browser = webdriver.Firefox(service=Service(r'C:\Users\HP\Desktop\Python Projects\Nova pasta\geckodriver.exe'))
    wait = WebDriverWait(browser, 20)

    browser.get("https://pinterest.com/") # Opens Firefox and enters Pinterest

    login = browser.find_element(By.CSS_SELECTOR, "div.erh") # Looks for the login button
    login.click() # Clicks on it

    email = browser.find_element(By.CSS_SELECTOR, "#email") # Looks for the email box
    email.send_keys("") # Types in the email

    password = browser.find_element(By.CSS_SELECTOR, "#password")
    password.send_keys("")

    login2 = browser.find_element(By.CSS_SELECTOR, ".red > div:nth-child(1)")
    login2.click()

    search = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@name='searchBoxInput']")))
    search.click()
    search.send_keys("South Korea")
    search.send_keys(Keys.ENTER)

    wait = WebDriverWait(browser, 60)

    image1 = browser.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[2]/div/div/div[2]/div/div[1]/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div[1]/a/div/div[1]/div/div/div/div/div/img")
    src = browser.get_attribute("srcset")

    print(src)

</code>```

However, I get this error message:

```<code>File "c:\Users\HP\Desktop\Python Projects\Nova pasta\bruh.py", line 33, in <module>
    image1 = browser.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[2]/div/div/div[2]/div/div[1]/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div[1]/a/div/div[1]/div/div/div/div/div/img")
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div[1]/div[1]/div[2]/div/div/div[2]/div/div[1]/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div[1]/a/div/div[1]/div/div/div/div/div/img
Stacktrace:
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:183:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:395:5
element.find/</<@chrome://remote/content/marionette/element.js:300:16
</code>```

What went wrong and how do I fix it?

答:
Could be a race condition where the found element is executing before it is present on the page. Take a look at the wait timeout documentation. Here is an example from the docs</p>
```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()
</code>```

Body:
again!

I'm trying to build a Pinterest webscraper and I want the program to log in Pinterest, search for "South Korea" and get the first image's attribute and print it out.
Here's the code:

    py
    from selenium import webdriver
    from selenium.webdriver.firefox.service import Service
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC

    browser = webdriver.Firefox(service=Service(r'C:\Users\HP\Desktop\Python Projects\Nova pasta\geckodriver.exe'))
    wait = WebDriverWait(browser, 20)

    browser.get("https://pinterest.com/") # Opens Firefox and enters Pinterest

    login = browser.find_element(By.CSS_SELECTOR, "div.erh") # Looks for the login button
    login.click() # Clicks on it

    email = browser.find_element(By.CSS_SELECTOR, "#email") # Looks for the email box
    email.send_keys("") # Types in the email

    password = browser.find_element(By.CSS_SELECTOR, "#password")
    password.send_keys("")

    login2 = browser.find_element(By.CSS_SELECTOR, ".red > div:nth-child(1)")
    login2.click()

    search = wait.until(EC.visibility_of_element_located((By.XPATH, "//input[@name='searchBoxInput']")))
    search.click()
    search.send_keys("South Korea")
    search.send_keys(Keys.ENTER)

    wait = WebDriverWait(browser, 60)

    image1 = browser.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[2]/div/div/div[2]/div/div[1]/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div[1]/a/div/div[1]/div/div/div/div/div/img")
    src = browser.get_attribute("srcset")

    print(src)

However, I get this error message:

File "c:\Users\HP\Desktop\Python Projects\Nova pasta\bruh.py", line 33, in <module>
    image1 = browser.find_element(By.XPATH, "/html/body/div[1]/div[1]/div[2]/div/div/div[2]/div/div[1]/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div[1]/a/div/div[1]/div/div/div/div/div/img")
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 1244, in find_element
    return self.execute(Command.FIND_ELEMENT, {
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\webdriver.py", line 424, in execute
    self.error_handler.check_response(response)
  File "C:\Users\HP\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: /html/body/div[1]/div[1]/div[2]/div/div/div[2]/div/div[1]/div/div/div/div[1]/div[1]/div/div/div/div/div[1]/div[1]/a/div/div[1]/div/div/div/div/div/img
Stacktrace:
WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:183:5
NoSuchElementError@chrome://remote/content/shared/webdriver/Errors.jsm:395:5
element.find/</<@chrome://remote/content/marionette/element.js:300:16

What went wrong and how do I fix it?

Body:
Could be a race condition where the found element is executing before it is present on the page. Take a look at the wait timeout documentation. Here is an example from the docs

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.Firefox()
driver.get("http://somedomain/url_that_delays_loading")
try:
    element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "myDynamicElement"))
    )
finally:
    driver.quit()


问:
How do I Wait With Extends Script (Adobe)
i'm currently working on an extends script which is the technology that we can use to create extension for adobe softwares, its a javascript similar script language
Im working on a script to automate some boring and repetitive tasks

Here is my problem i've to wait the creation of a bin before use a variable which call this bin but i can't, i tried

.then( Promise => { //Some Code }) ; setTimeout(Function(), time); nothing is working

Can someone help me please ?
Here is my code

    root = app.project.rootItem
    newFilesPath = "Path"
    newFilesBin = root.children[0]

    app.project.importFiles(newFilesPath, true, newFilesBin, false)

    app.project.save()

    for(i=0; i<newFilesBin.children.numItems; i++){  //here is the problem it tells me that
        newFile = newFilesBin.children[i]            //newFilesBin is null, i think he has not the
                                                     //time to create the file and then to put it
                                                     //in the variable
        name = newFile.name

        newTiktokBin = root.createBin(name)

        root.children[i].children[0].moveBin(newTiktokBin)
    }

```

答:
You can simply send your program to sleep for any amount of milliseconds by using the $.sleep() method.

$.sleep(1000);  // sends the program to sleep for a second
```

There is no such thing as .then() or promises in ExtendScript, as it is basically an ancient version of JavaScript.

Body:
You can simply send your program to sleep for any amount of milliseconds by using the $.sleep() method.

$.sleep(1000);  // sends the program to sleep for a second

There is no such thing as .then() or promises in ExtendScript, as it is basically an ancient version of JavaScript.


问:
Python find type of value for typing.Dict
If I have

```<code>class A:
    pass

def my_func(my_dict: typing.Dict[str, A]):
    pass
</code>```

How can I find the type of the values in this dict? Basically, how can I figure out that the values that go into my_dict are supposed to be of type A?

To give some context I have two dataclasses

```<code>@dataclass
class B:
    x: str

@dataclass
class C:
    y: Dict[str, B]
</code>```

I'm trying to look at class C and figure out which object I need to instantiate. In this example, I want to create object B.

```<code>class_type = C.__annotations__["y"]  # this returns typing.Dict[str, B]
# now need to create the object
b = class_type[1](x="bar")  # index 1 to retrieve the B class in typing.Dict[str, B]
c = C(y = {"foo": b})
</code>```

I'm trying to create b but obviously index of 1 in a mutable map doesn't work.

答:
Combine answer from here with __annotations__[<key>] and you will get what you need

```<code>print(typing.get_args(my_func.__annotations__['my_dict']))
# will return (<class 'str'>, <class '__main__.A'>)
</code>```

Body:
If I have

class A:
    pass

def my_func(my_dict: typing.Dict[str, A]):
    pass

How can I find the type of the values in this dict? Basically, how can I figure out that the values that go into my_dict are supposed to be of type A?

To give some context I have two dataclasses

@dataclass
class B:
    x: str

@dataclass
class C:
    y: Dict[str, B]

I'm trying to look at class C and figure out which object I need to instantiate. In this example, I want to create object B.

class_type = C.__annotations__["y"]  # this returns typing.Dict[str, B]
# now need to create the object
b = class_type[1](x="bar")  # index 1 to retrieve the B class in typing.Dict[str, B]
c = C(y = {"foo": b})

I'm trying to create b but obviously index of 1 in a mutable map doesn't work.

Body:
Combine answer from here with __annotations__[<key>] and you will get what you need

print(typing.get_args(my_func.__annotations__['my_dict']))
# will return (<class 'str'>, <class '__main__.A'>)