问:
How to redirect to next question after showing the result for 2s Ruby on Rails / Turbo
I am working on a quiz functionality, and I'd like to show the user the results for 2s before redirecting him to the next question.
Here is my code to show the results to the user (it works):

```<code>def validate_answer
    answer_given = params[:answer_given]
    quiz_question_id = params[:quiz_question_id]
    next_question_id = params[:next_question_id]
    is_right_answer = is_right_answer(Question.find(params[:question_id]), answer_given)
    @quiz_question = QuizQuestion.update(quiz_question_id,answer_given:answer_given,is_answer_right:is_right_answer)
    @question = Question.find(params[:question_id])
    @card = @question.card
    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: [
          turbo_stream.update('questionPartialId', partial: "questionPartial"),
        ]
      end
    end
  end
</code>```

Now if I add the sleep & redirect it does not work as the sleeps blocks the whole app (see code below)
How should I do to perform this sleep ?

```<code>def validate_answer
    answer_given = params[:answer_given]
    quiz_question_id = params[:quiz_question_id]
    next_question_id = params[:next_question_id]
    is_right_answer = is_right_answer(Question.find(params[:question_id]), answer_given)
    @quiz_question = QuizQuestion.update(quiz_question_id,answer_given:answer_given,is_answer_right:is_right_answer)
    @question = Question.find(params[:question_id])
    @card = @question.card
    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: [
          turbo_stream.update('questionPartialId', partial: "questionPartial"),
        ]
      end
    end
    sleep(2)
    if next_question_id != ""
      redirect_to(question_path(next_question_id))
    else
      redirect_to(quiz_path(QuizQuestion.find(quiz_question_id).quiz_id))
    end
  end
</code>```

Thanks a lot in advance !

Body:
I am working on a quiz functionality, and I'd like to show the user the results for 2s before redirecting him to the next question.
Here is my code to show the results to the user (it works):

def validate_answer
    answer_given = params[:answer_given]
    quiz_question_id = params[:quiz_question_id]
    next_question_id = params[:next_question_id]
    is_right_answer = is_right_answer(Question.find(params[:question_id]), answer_given)
    @quiz_question = QuizQuestion.update(quiz_question_id,answer_given:answer_given,is_answer_right:is_right_answer)
    @question = Question.find(params[:question_id])
    @card = @question.card
    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: [
          turbo_stream.update('questionPartialId', partial: "questionPartial"),
        ]
      end
    end
  end

Now if I add the sleep & redirect it does not work as the sleeps blocks the whole app (see code below)
How should I do to perform this sleep ?

def validate_answer
    answer_given = params[:answer_given]
    quiz_question_id = params[:quiz_question_id]
    next_question_id = params[:next_question_id]
    is_right_answer = is_right_answer(Question.find(params[:question_id]), answer_given)
    @quiz_question = QuizQuestion.update(quiz_question_id,answer_given:answer_given,is_answer_right:is_right_answer)
    @question = Question.find(params[:question_id])
    @card = @question.card
    respond_to do |format|
      format.turbo_stream do
        render turbo_stream: [
          turbo_stream.update('questionPartialId', partial: "questionPartial"),
        ]
      end
    end
    sleep(2)
    if next_question_id != ""
      redirect_to(question_path(next_question_id))
    else
      redirect_to(quiz_path(QuizQuestion.find(quiz_question_id).quiz_id))
    end
  end

Thanks a lot in advance !


来源: stackexchange

问:
Color stored in CoreData not equal to original color when retrieved
I am storing a color in Core Data, in my object class I have:

```<code>@NSManaged public var colorData: Data?

func getColor() -> Color {
    guard let colorData = colorData else { return .clear }

    do {
        return try Color(NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData) ?? .clear)
    } catch {
        print("Error getting color")
    }

    return .clear
}
</code>```

I set the color as follows:

```<code>do {
    try habit.colorData = NSKeyedArchiver.archivedData(
        withRootObject: UIColor(color), requiringSecureCoding: false)
} catch {
    print("Error setting habit color data")
}
</code>```

Visually this works fine. However if I save a color such as Color.blue, retrieve it and then check color == Color.blue I get false. Am I doing something wrong here?

ContentLicense: CC BY-SA 4.0

Body:
I am storing a color in Core Data, in my object class I have:

@NSManaged public var colorData: Data?

func getColor() -> Color {
    guard let colorData = colorData else { return .clear }

    do {
        return try Color(NSKeyedUnarchiver.unarchivedObject(ofClass: UIColor.self, from: colorData) ?? .clear)
    } catch {
        print("Error getting color")
    }

    return .clear
}

I set the color as follows:

do {
    try habit.colorData = NSKeyedArchiver.archivedData(
        withRootObject: UIColor(color), requiringSecureCoding: false)
} catch {
    print("Error setting habit color data")
}

Visually this works fine. However if I save a color such as Color.blue, retrieve it and then check color == Color.blue I get false. Am I doing something wrong here?


问:
Optimising Minimax for a Game
I'm currently trying to solve a programming problem using minimax with alpha-beta-pruning.
The game is represented as a tree with a defined root. Each node has a given cost. Each node can have an amount of childs bigger than 0 if its not a leaf. The game has to end at a leaf.

Player A wants to maximize the cost he can receive by traversing the tree. He can choose to stay at the current node, or go to one of its childs.
Player B wants to minimize the cost, but he has to choose a child and can't pass unlike Player A.
Both Players play optimally.

I have implemented a solution, which does return the desired results, but is too slow after a certain amount of nodes, leading to a timeout.
My idea would be to somehow save the results of the previous minimax search for the given tree, but that only helps if Player A chooses to advance, otherwise I would have to do the minimax search again.

```<code>vector<int> edges[MAXN];
int minimax(int node, bool p1_turn, int alpha, int beta) {
    if(edges[node].empty()) return cost[node];

    if(p1_turn) {
        int best = minimax(node, false, alpha, beta);
        for(auto u: edges[node]) {
            int val = minimax(u, false, alpha, beta);
            best = max(val, best);
            alpha = max(alpha, best);

            if(beta <= alpha) {
                break;
            }

        }
        return best;
    } else {
        int best = MAX_INF;
        for(auto u: edges[node]){
            int val = minimax(u, true, alpha, beta);
            best = min(best, val);
            beta = min(best, beta);

            if(beta <= alpha){
                break;
            }
        }
        return best;
    }
}

...
minimax(1, true, MIN_INF, MAX_INF)
...

</code>```

Applying the above algorithm returns the desired results, but is too slow after a certain amount of nodes.

EDIT

Changed the inner if-block to be more in line with https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning#Pseudocode

```<code>    if(edges[node].empty()) return cost[node];
    if(p1_turn) {
        int best = minimax(node, false, alpha, beta);
        for(auto u: edges[node]) {
            best = max(best, minimax(u, false, alpha, beta));
            if(best > beta) {
                break;
            }
            alpha = max(alpha, best);
        }
        return best;
    } else {
        int best = MAX_INF;
        for(auto u: edges[node]){
            best = min(best, minimax(u, true, alpha, beta));
            if(best < alpha){
                break;
            }
            beta = min(best, beta);
        }
        return best;
    }
</code>```

Title: Optimising Minimax for a Game

Body:
I'm currently trying to solve a programming problem using minimax with alpha-beta-pruning.
The game is represented as a tree with a defined root. Each node has a given cost. Each node can have an amount of childs bigger than 0 if its not a leaf. The game has to end at a leaf.

Player A wants to maximize the cost he can receive by traversing the tree. He can choose to stay at the current node, or go to one of its childs.
Player B wants to minimize the cost, but he has to choose a child and can't pass unlike Player A.
Both Players play optimally.

I have implemented a solution, which does return the desired results, but is too slow after a certain amount of nodes, leading to a timeout.
My idea would be to somehow save the results of the previous minimax search for the given tree, but that only helps if Player A chooses to advance, otherwise I would have to do the minimax search again.

vector<int> edges[MAXN];
int minimax(int node, bool p1_turn, int alpha, int beta) {
    if(edges[node].empty()) return cost[node];

    if(p1_turn) {
        int best = minimax(node, false, alpha, beta);
        for(auto u: edges[node]) {
            int val = minimax(u, false, alpha, beta);
            best = max(val, best);
            alpha = max(alpha, best);

            if(beta <= alpha) {
                break;
            }

        }
        return best;
    } else {
        int best = MAX_INF;
        for(auto u: edges[node]){
            int val = minimax(u, true, alpha, beta);
            best = min(best, val);
            beta = min(best, beta);

            if(beta <= alpha){
                break;
            }
        }
        return best;
    }
}

...
minimax(1, true, MIN_INF, MAX_INF)
...

Applying the above algorithm returns the desired results, but is too slow after a certain amount of nodes.

EDIT

Changed the inner if-block to be more in line with https://en.wikipedia.org/wiki/Alpha%E2%80%93beta_pruning#Pseudocode

    if(edges[node].empty()) return cost[node];
    if(p1_turn) {
        int best = minimax(node, false, alpha, beta);
        for(auto u: edges[node]) {
            best = max(best, minimax(u, false, alpha, beta));
            if(best > beta) {
                break;
            }
            alpha = max(alpha, best);
        }
        return best;
    } else {
        int best = MAX_INF;
        for(auto u: edges[node]){
            best = min(best, minimax(u, true, alpha, beta));
            if(best < alpha){
                break;
            }
            beta = min(best, beta);
        }
        return best;
    }


问:
Install new gitlab and have variable error
I run a new Gitlab and get an error:

There was an error fetching the variables

when going to Admin Area > CI/CD.

I test different docker image versions (gitlab/gitlab-ce:15.0.0-ce.0 and latest version) but it not fix my problem:


问:
Does verifying the signature of an RS256 JWT really take half a second?
I am trying to verify a JWT signature in Javascript using a public key. I have tried the 'jose' and 'jsrsasign' libraries with similar results: the verification is painfully slow (400-500ms).

After googling, from what I can understand the actual verification of the signature should be sub-millisecond. Am I doing something wrong or have i misunderstood what people are saying?

This is what the current code looks like using 'jsrsasign':

import rs from 'jsrsasign';

// [...]

const timeBeforeTokenVerify = Date.now();
const keyObject = rs.KEYUTIL.getKey(jwks.keys[0]);
const isValid = rs.jws.JWS.verifyJWT(clientToken, keyObject, { alg: ['RS256'] });
if (!isValid) {
  throw new Error('Token is not valid');
}
console.log(Date.now() - timeBeforeTokenVerify) // prints 400 to 500
```


问:
How to print a dataframe to a treeview without showing the index numbers
I am currently working on a project where I have a dataframe output to a treeview so the user can see the results of a stored procedure that was run. I was wondering, is there any way to make it so that the index column would not appear? Here is my current code and the output:

Code:

```<code>def moniker_query(monik, conn, tv1):
    global moniker
    moniker_results = []
    moniker = monik.get()

    #Clear the treeview of previous results from the last run through.
    for item in tv1.get_children():
        tv1.delete(item)
    #set the cursor value and then created the stored procedure call
    cursor = conn.cursor()
    get_moniker_stored_proc = "EXEC [dbo].[getMoniker] @username = ?"

    #fill in data for the first run through
    rows = cursor.execute(get_moniker_stored_proc, moniker).fetchall()
    columns = [column[0] for column in cursor.description]
    moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))

    #add data for every different table call in the stored procedure
    while True:
        rows = cursor.fetchall()
        columns = [column[0] for column in cursor.description]
        moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))
        if cursor.nextset() == False:
            break
    #Join all the data frames to one data frame
    df = pd.concat(moniker_results, ignore_index=True)
    #Get the total number of columns and then write the columns
    cols = list(df.columns)
    tv1["columns"] =cols
    for i in cols:
        tv1.column(i, anchor='w', width=100, stretch=False)
        tv1.heading(i, text=i, anchor="w")

    #Insert values of each row.
    counter = 0
    for index, row in df.iterrows():
        tv1.insert("",'end',text=index,values=list(row))
        counter = counter + 1
def moniker_query(monik, conn, tv1):
    global moniker
    moniker_results = []
    moniker = monik.get()

    #Clear the treeview of previous results from the last run through.
    for item in tv1.get_children():
        tv1.delete(item)
    #set the cursor value and then created the stored procedure call
    cursor = conn.cursor()
    get_moniker_stored_proc = "EXEC [dbo].[getMoniker] @username = ?"

    #fill in data for the first run through
    rows = cursor.execute(get_moniker_stored_proc, moniker).fetchall()
    columns = [column[0] for column in cursor.description]
    moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))

    #add data for every different table call in the stored procedure
    while True:
        rows = cursor.fetchall()
        columns = [column[0] for column in cursor.description]
        moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))
        if cursor.nextset() == False:
            break
    #Join all the data frames to one data frame
    df = pd.concat(moniker_results, ignore_index=True)
    #Get the total number of columns and then write the columns
    cols = list(df.columns)
    tv1["columns"] =cols
    for i in cols:
        tv1.column(i, anchor='w', width=100, stretch=False)
        tv1.heading(i, text=i, anchor="w")

    #Insert values of each row.
    counter = 0
    for index, row in df.iterrows():
        tv1.insert("",'end',text=index,values=list(row))
        counter = counter + 1
</code>```

Here is the output:

I would like the index number to no longer appear.

Body:
I am currently working on a project where I have a dataframe output to a treeview so the user can see the results of a stored procedure that was run. I was wondering, is there any way to make it so that the index column would not appear? Here is my current code and the output:

Code:

def moniker_query(monik, conn, tv1):
    global moniker
    moniker_results = []
    moniker = monik.get()

    #Clear the treeview of previous results from the last run through.
    for item in tv1.get_children():
        tv1.delete(item)
    #set the cursor value and then created the stored procedure call
    cursor = conn.cursor()
    get_moniker_stored_proc = "EXEC [dbo].[getMoniker] @username = ?"

    #fill in data for the first run through
    rows = cursor.execute(get_moniker_stored_proc, moniker).fetchall()
    columns = [column[0] for column in cursor.description]
    moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))

    #add data for every different table call in the stored procedure
    while True:
        rows = cursor.fetchall()
        columns = [column[0] for column in cursor.description]
        moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))
        if cursor.nextset() == False:
            break
    #Join all the data frames to one data frame
    df = pd.concat(moniker_results, ignore_index=True)
    #Get the total number of columns and then write the columns
    cols = list(df.columns)
    tv1["columns"] =cols
    for i in cols:
        tv1.column(i, anchor='w', width=100, stretch=False)
        tv1.heading(i, text=i, anchor="w")

    #Insert values of each row.
    counter = 0
    for index, row in df.iterrows():
        tv1.insert("",'end',text=index,values=list(row))
        counter = counter + 1
def moniker_query(monik, conn, tv1):
    global moniker
    moniker_results = []
    moniker = monik.get()

    #Clear the treeview of previous results from the last run through.
    for item in tv1.get_children():
        tv1.delete(item)
    #set the cursor value and then created the stored procedure call
    cursor = conn.cursor()
    get_moniker_stored_proc = "EXEC [dbo].[getMoniker] @username = ?"

    #fill in data for the first run through
    rows = cursor.execute(get_moniker_stored_proc, moniker).fetchall()
    columns = [column[0] for column in cursor.description]
    moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))

    #add data for every different table call in the stored procedure
    while True:
        rows = cursor.fetchall()
        columns = [column[0] for column in cursor.description]
        moniker_results.append(pd.DataFrame.from_records(rows, columns=columns))
        if cursor.nextset() == False:
            break
    #Join all the data frames to one data frame
    df = pd.concat(moniker_results, ignore_index=True)
    #Get the total number of columns and then write the columns
    cols = list(df.columns)
    tv1["columns"] =cols
    for i in cols:
        tv1.column(i, anchor='w', width=100, stretch=False)
        tv1.heading(i, text=i, anchor="w")

    #Insert values of each row.
    counter = 0
    for index, row in df.iterrows():
        tv1.insert("",'end',text=index,values=list(row))
        counter = counter + 1

Here is the output:

I would like the index number to no longer appear.


问:
Typescript baseUrl and paths not extending in mono-repo
I'm currently building out a mono-repository for a UI design system project using Yarn Workspaces in Typescript.

I intend to have a single tsconfig.json file at the project root which will contain all common settings shared by all packages and then have a tsconfig.json file in each package where package-specific settings can reside.

I've set up a path alias in the root tsconfig.json for a utils package  which I'd like to import into another package - e.g my-theme-1. However the path alias is not resolving in VS Code. However if I add the path alias to the tsconfig.json of my-theme-1 and change the relative paths to relevant values the alias does resolve.

My root level tsconfig.json looks like this:

{
  "compilerOptions": {
    "composite": true,
    "target": "es2016",
    "lib": [
      "ESNext"
    ],
    "jsx": "react-jsx",
    "module": "commonjs",
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "@mycompany/utils/*": ["packages/ui-common/utils"]
    },
    "declaration": true /,
    "declarationMap": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "skipLibCheck": true
  }
}```
</div>
</div>
</p>
<p>And <code>my-theme-1</code> has a <code>tsconfig</code> like this:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "extends": "../../../../tsconfig.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    "composite": true,
  },
  "include": ["src/**/*"],
}</code>```

Body:
I'm currently building out a mono-repository for a UI design system project using Yarn Workspaces in Typescript.

I intend to have a single tsconfig.json file at the project root which will contain all common settings shared by all packages and then have a tsconfig.json file in each package where package-specific settings can reside.

I've set up a path alias in the root tsconfig.json for a utils package  which I'd like to import into another package - e.g my-theme-1. However the path alias is not resolving in VS Code. However if I add the path alias to the tsconfig.json of my-theme-1 and change the relative paths to relevant values the alias does resolve.

My root level tsconfig.json looks like this:

{
  "compilerOptions": {
    "composite": true,
    "target": "es2016",
    "lib": [
      "ESNext"
    ],
    "jsx": "react-jsx",
    "module": "commonjs",
    "moduleResolution": "node",
    "baseUrl": "./",
    "paths": {
      "@mycompany/utils/*": ["packages/ui-common/utils"]
    },
    "declaration": true /,
    "declarationMap": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "skipLibCheck": true
  }
}

And my-theme-1 has a tsconfig like this:

{
  "extends": "../../../../tsconfig.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src",
    "composite": true,
  },
  "include": ["src/**/*"],
}


问:
How to bind different buttons to one self-defined method containing conditional statements
For school I have to code the Othello game in Python, but I'm a beginner coder and am struggling with various parts of my code. So basically, we have to make our own classes and use self-defined methods. I made my user interface in a subclass of Frame, where I constructed the buttons. The size of the board is supposed to be changeable.
I defined a list in this class and made a method that changes the board size and the positioning of the tokens for one button, but can't seem to figure out how to make this method applicable to different buttons.

I tried different things like:

```<code>#method for changing the board input positions
def klik_grootte(self, ea):
if ea.widget == self.four:
    sz = 4
    self.bord[1][1] = '2'
    self.bord[1][2] = '1'
    self.bord[2][1] = '1'
    self.bord[2][2] = '2'
    Reversi.drawboard(self)
elif ea.widget == self.six:
    sz = 6
    self.bord[2][2] = '2'
    self.bord[2][3] = '1'
    self.bord[3][2] = '1'
    self.bord[3][3] = '2'
    Reversi.drawboard(self)

#binding method to button
self.four.configure(command=self.ea.klik_grootte)
self.six.configure(command=self.ea.klik_grootte)`
</code>```

This obviously doesn't work, but just so you get the idea.
I also thought it would be better to write this method in a different class but don't know how you would bind the buttons to self-defined methods in that case

Body:
For school I have to code the Othello game in Python, but I'm a beginner coder and am struggling with various parts of my code. So basically, we have to make our own classes and use self-defined methods. I made my user interface in a subclass of Frame, where I constructed the buttons. The size of the board is supposed to be changeable.
I defined a list in this class and made a method that changes the board size and the positioning of the tokens for one button, but can't seem to figure out how to make this method applicable to different buttons.

I tried different things like:

#method for changing the board input positions
def klik_grootte(self, ea):
if ea.widget == self.four:
    sz = 4
    self.bord[1][1] = '2'
    self.bord[1][2] = '1'
    self.bord[2][1] = '1'
    self.bord[2][2] = '2'
    Reversi.drawboard(self)
elif ea.widget == self.six:
    sz = 6
    self.bord[2][2] = '2'
    self.bord[2][3] = '1'
    self.bord[3][2] = '1'
    self.bord[3][3] = '2'
    Reversi.drawboard(self)

#binding method to button
self.four.configure(command=self.ea.klik_grootte)
self.six.configure(command=self.ea.klik_grootte)`

This obviously doesn't work, but just so you get the idea.
I also thought it would be better to write this method in a different class but don't know how you would bind the buttons to self-defined methods in that case


问:
DLL load failed: The specified module could not be found
I am using Python 3.7 . And have vidstream installed , when I run the code from a terminal on windows no error occurs but when i compile it using Pyinstaller the following occurs

```<code>DLL load failed: The specified module could not be found.
  File "server.py", line 23, in server
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "vidstream\__init__.py", line 1, in <module>
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "vidstream\streaming.py", line 21, in <module>
</code>```

The error appears when the code tries to import Vidstream

```<code>    try:
        from vidstream import StreamingServer # error here after compilation
        global server
        server = StreamingServer(self.host, 8080)
        server.start_server()
    except Exception as e:
        print("Module not found...\n",e)
        traceback.print_tb(e.__traceback__)
        time.sleep(5)
</code>```

Is there a way to fix this ?

Thanks in advance.

Body:
I am using Python 3.7 . And have vidstream installed , when I run the code from a terminal on windows no error occurs but when i compile it using Pyinstaller the following occurs

DLL load failed: The specified module could not be found.
  File "server.py", line 23, in server
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "vidstream\__init__.py", line 1, in <module>
  File "PyInstaller\loader\pyimod02_importers.py", line 499, in exec_module
  File "vidstream\streaming.py", line 21, in <module>

The error appears when the code tries to import Vidstream

    try:
        from vidstream import StreamingServer # error here after compilation
        global server
        server = StreamingServer(self.host, 8080)
        server.start_server()
    except Exception as e:
        print("Module not found...\n",e)
        traceback.print_tb(e.__traceback__)
        time.sleep(5)

Is there a way to fix this ?

Thanks in advance.


问:
Local Symfony site hosted in container is unreachable
I have the following setup for local development:

Symfony website in a Docker container

Using the symfony serve command in the container to serve the website

Port mapping "8083:8000" specified in the docker-compose.yaml

Using containerd container runtime with nerdctl compose up to run the Docker containers. These are on macOS Ventura using Rancher Desktop.

Expected behavior

Going to https://127.0.0.1:8083 or https://localhost:8083 in a browser while the Symfony site is being served in its container should serve the website hosted on the container's port 8000.

Actual behavior

ERR_CONNECTION_REFUSED from the browser -- the website refuses to connect.

Details

docker-compose.yaml (relevant parts):

version: '3'
services:
  php:
    container_name: nudgeforce-api
    build: .
    ports:
      - "8083:8000"
    command: php
    volumes:
      - .:/var/task
```
<h3>Dockerfile</h3>
<pre class="lang-docker prettyprint-override"><code>FROM bref/php-82-fpm
RUN yum install -y git gzip zip unzip python3 tar
COPY --from=composer:2.4 /usr/bin/composer /usr/local/bin/composer
WORKDIR /var/task
# Symfony server
RUN curl -sS https://get.symfony.com/cli/installer | bash
RUN mv /root/.symfony5/bin/symfony /usr/local/bin/symfony \
    && symfony server:ca:install
</code>```

symfony serve output

Body:
I have the following setup for local development:

Symfony website in a Docker container

Using the symfony serve command in the container to serve the website

Port mapping "8083:8000" specified in the docker-compose.yaml

Using containerd container runtime with nerdctl compose up to run the Docker containers. These are on macOS Ventura using Rancher Desktop.

Expected behavior

Going to https://127.0.0.1:8083 or https://localhost:8083 in a browser while the Symfony site is being served in its container should serve the website hosted on the container's port 8000.

Actual behavior

ERR_CONNECTION_REFUSED from the browser -- the website refuses to connect.

Details

docker-compose.yaml (relevant parts):

version: '3'
services:
  php:
    container_name: nudgeforce-api
    build: .
    ports:
      - "8083:8000"
    command: php
    volumes:
      - .:/var/task

Dockerfile

FROM bref/php-82-fpm
RUN yum install -y git gzip zip unzip python3 tar
COPY --from=composer:2.4 /usr/bin/composer /usr/local/bin/composer
WORKDIR /var/task
# Symfony server
RUN curl -sS https://get.symfony.com/cli/installer | bash
RUN mv /root/.symfony5/bin/symfony /usr/local/bin/symfony \
    && symfony server:ca:install

symfony serve output


问:
Get request of google maps api from postman is working properly but in the app it is showing null(NoSuchMethodError)
Why is the GET request to the Google Maps API working properly in Postman but showing a null error (NoSuchMethodError) when implemented in the app?

Environment

I've configured a local REST API:

static const String BASE_URL = "http://localhost:8000";
static const String GEOCODE_URI = "api/v1/config/geocode-api";
```
<h3>Code I'm Using</h3>
<ul>
<li><p>Here are the excerpts of the code I'm attempting this with.
The main implementation is in <em>location_controller.dart</em>:</p>
<pre class="lang-dart prettyprint-override"><code><!-- location_controller.dart -->

import 'package:ecommerceapp/models/address_model.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get_connect/http/src/response/response.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

import 'package:ecommerceapp/data/repositary/location_repo.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class LocationController extends GetxController implements GetxService {
  LocationRepo locationRepo;
  LocationController({
    required this.locationRepo,
  });
  bool _loading = false;
  late Position _position;
  late Position _pickPosition;
  Placemark _placemark = Placemark();
  Placemark _pickPlacemark = Placemark();
  List<AddressModel> _addressList = [];

  late List<AddressModel> _allAddressList = [];
  List<String> _addressTypelist = ["home", "office", "others"];
  int _addressTypeIndex = 0;

  late Map<String, dynamic> _getAddress;

  late GoogleMapController _mapController;

  List<AddressModel> get addressList => _addressList;
  bool get loading => _loading;
  Position get position => _position;
  Position get pickPosition => _pickPosition;
  Map get getAddress => _getAddress;

  bool _updateAddressData = true;
  bool _changeAddress = true;

  void setMapController(GoogleMapController mapController) {
    _mapController = mapController;
  }

  void updatePosition(CameraPosition position, bool fromAddress) async {
    print("Update Position");
    if (_updateAddressData) {
      _loading = true;
      update();
      try {
        if (fromAddress) {
          _position = Position(
            latitude: position.target.latitude,
            longitude: position.target.longitude,
            timestamp: DateTime.now(),
            heading: 1,
            accuracy: 1,
            altitude: 1,
            speedAccuracy: 1,
            speed: 1,
          );
        } else {
          _pickPosition = Position(
            latitude: position.target.latitude,
            longitude: position.target.longitude,
            timestamp: DateTime.now(),
            heading: 1,
            accuracy: 1,
            altitude: 1,
            speedAccuracy: 1,
            speed: 1,
          );
        }

        if (_changeAddress) {
          String _address = await getAddressfromGeocode(LatLng(position.target.latitude, position.target.longitude));
        }
      } catch (e) {
        print(e);
      }
    }
  }

  Future<String> getAddressfromGeocode(LatLng latLng) async {
    String _address = "Unknown Location Found";
    print("Address : $_address");
    Response response = await locationRepo.getAddressfromGeocode(latLng);
    print("Status Code : ${response.statusCode}");
    print(response.body);
    if (response.body["status"] == "OK") {
      _address = response.body["result"][0]['formatted_address'].toString();
      print("Printing Address : $_address");
    } else {
      print("Error getting the google api");
    }

    return _address;
  }
}
</code>```

which calls the location_repo.dart:

import 'package:ecommerceapp/utils/app_constants.dart';
import 'package:get/get_connect/http/src/response/response.dart';
import 'package:google_maps_flutter_platform_interface/src/types/location.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ecommerceapp/data/api/api_client.dart';

class LocationRepo {
  final ApiClient apiClient;
  final SharedPreferences sharedPreferences;
  LocationRepo({
    required this.apiClient,
    required this.sharedPreferences,
  });

  Future<Response> getAddressfromGeocode(LatLng latLng) async {

    return await apiClient.getData('${AppConstants.GEOCODE_URI}'
        '?lat=${latLng.latitude}&lng=${latLng.longitude}');
  }
}
```
</li>
<li><p>In the <code>getAddressfromGeocode</code> method, when I tried to print the latitude and longitude, the print statements were also working fine:</p>
<pre class="lang-dart prettyprint-override"><code>  Future<Response> getData(String uri, {Map<String, String>? headers}) async {
    try {

      Response response = await get(
        uri,
        headers: headers == null ? _mainHeaders : headers,
      );
      return response;
    } catch (e) {
      return Response(statusCode: 1, statusText: e.toString());
    }
  }
</code>```

But, my code fails and response.body is null:

flutter: NoSuchMethodError: The method '\[\]' was called on null.

Receiver: null

Tried calling: \[\]("status")

I have no idea what I'm doing and still haven't asked ChatGTP, so I did not find any working solutions. Please help.

Body:
Why is the GET request to the Google Maps API working properly in Postman but showing a null error (NoSuchMethodError) when implemented in the app?

Environment

I've configured a local REST API:

static const String BASE_URL = "http://localhost:8000";
static const String GEOCODE_URI = "api/v1/config/geocode-api";

Code I'm Using

Here are the excerpts of the code I'm attempting this with.
The main implementation is in location_controller.dart:

import 'package:ecommerceapp/models/address_model.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get_connect/http/src/response/response.dart';
import 'package:get/get_state_manager/get_state_manager.dart';

import 'package:ecommerceapp/data/repositary/location_repo.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class LocationController extends GetxController implements GetxService {
  LocationRepo locationRepo;
  LocationController({
    required this.locationRepo,
  });
  bool _loading = false;
  late Position _position;
  late Position _pickPosition;
  Placemark _placemark = Placemark();
  Placemark _pickPlacemark = Placemark();
  List<AddressModel> _addressList = [];

  late List<AddressModel> _allAddressList = [];
  List<String> _addressTypelist = ["home", "office", "others"];
  int _addressTypeIndex = 0;

  late Map<String, dynamic> _getAddress;

  late GoogleMapController _mapController;

  List<AddressModel> get addressList => _addressList;
  bool get loading => _loading;
  Position get position => _position;
  Position get pickPosition => _pickPosition;
  Map get getAddress => _getAddress;

  bool _updateAddressData = true;
  bool _changeAddress = true;

  void setMapController(GoogleMapController mapController) {
    _mapController = mapController;
  }

  void updatePosition(CameraPosition position, bool fromAddress) async {
    print("Update Position");
    if (_updateAddressData) {
      _loading = true;
      update();
      try {
        if (fromAddress) {
          _position = Position(
            latitude: position.target.latitude,
            longitude: position.target.longitude,
            timestamp: DateTime.now(),
            heading: 1,
            accuracy: 1,
            altitude: 1,
            speedAccuracy: 1,
            speed: 1,
          );
        } else {
          _pickPosition = Position(
            latitude: position.target.latitude,
            longitude: position.target.longitude,
            timestamp: DateTime.now(),
            heading: 1,
            accuracy: 1,
            altitude: 1,
            speedAccuracy: 1,
            speed: 1,
          );
        }

        if (_changeAddress) {
          String _address = await getAddressfromGeocode(LatLng(position.target.latitude, position.target.longitude));
        }
      } catch (e) {
        print(e);
      }
    }
  }

  Future<String> getAddressfromGeocode(LatLng latLng) async {
    String _address = "Unknown Location Found";
    print("Address : $_address");
    Response response = await locationRepo.getAddressfromGeocode(latLng);
    print("Status Code : ${response.statusCode}");
    print(response.body);
    if (response.body["status"] == "OK") {
      _address = response.body["result"][0]['formatted_address'].toString();
      print("Printing Address : $_address");
    } else {
      print("Error getting the google api");
    }

    return _address;
  }
}

which calls the location_repo.dart:

import 'package:ecommerceapp/utils/app_constants.dart';
import 'package:get/get_connect/http/src/response/response.dart';
import 'package:google_maps_flutter_platform_interface/src/types/location.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:ecommerceapp/data/api/api_client.dart';

class LocationRepo {
  final ApiClient apiClient;
  final SharedPreferences sharedPreferences;
  LocationRepo({
    required this.apiClient,
    required this.sharedPreferences,
  });

  Future<Response> getAddressfromGeocode(LatLng latLng) async {

    return await apiClient.getData('${AppConstants.GEOCODE_URI}'
        '?lat=${latLng.latitude}&lng=${latLng.longitude}');
  }
}

In the getAddressfromGeocode method, when I tried to print the latitude and longitude, the print statements were also working fine:

  Future<Response> getData(String uri, {Map<String, String>? headers}) async {
    try {

      Response response = await get(
        uri,
        headers: headers == null ? _mainHeaders : headers,
      );
      return response;
    } catch (e) {
      return Response(statusCode: 1, statusText: e.toString());
    }
  }

But, my code fails and response.body is null:

flutter: NoSuchMethodError: The method '\[\]' was called on null.

Receiver: null

Tried calling: \[\]("status")

I have no idea what I'm doing and still haven't asked ChatGTP, so I did not find any working solutions. Please help.


问:
Skip K6 test iterations without failing the test
I'm authoring a K6 test which is configured to run many iterations.

During init or setup, I determine that I want to skip this test (i.e. based on something about the environment).

I'm familiar with fail() and test.abort(); both of these will fail the test.

Is there a way to complete it immediately (without running through the configured iterations) and successfully (e.g. with 0 out of 0 checks passing)?


问:
SwiftUI & Contentful Client Error: Type of expression is ambiguous without more context
The code below shows the code I am using to fetch data from Contentful API to my SwiftUI app. However, by calling the function client.fetchArray, I got an error message saying that the type of expression is ambiguous. I tried look up the documentation and the example code for client.fetchArray uses the exact parameters and hence I assume the error message should be gone? Can anyone please help me out here! I am super confused! Thank you!

```<code>import SwiftUI
import Contentful
import Combine

let client = Client(spaceId: "qqq2yu4vbtpl", environmentId: "master", accessToken: "LurTiklxcr0ARTpI9z7GVTz-mjMO6OFVsoSZ8V7GJ4c")
//let client = Client(spaceId: "0ge8xzmnbp2c", accessToken: "03010b0d79abcb655ca3fda453f2f493b5472e0aaa53664bc7dea5ef4fce2676")

func getArray(id: String, completion: @escaping([Entry]) -> ()) {
    let query = Query.where(contentTypeId: id)

    client.fetchArray(of: Entry.self, matching: query) { result in
        switch result {
        case .success(let array):
            DispatchQueue.main.async {
                completion(array.items)
            }
        case .error(let error):
            print(error)
        }
        print(result)
    }
}

class CourseStore: ObservableObject {
    @Published var courses: [Course] = courseData

    init() {
        let colors = [#colorLiteral(red: 0.3635728061, green: 0, blue: 0.8927152753, alpha: 0.8470588235), #colorLiteral(red: 0.2461163998, green: 0.3063159585, blue: 1, alpha: 0.8470588235), #colorLiteral(red: 0.3414418995, green: 0.653152287, blue: 0.405282855, alpha: 0.8470588235), #colorLiteral(red: 0.8906980753, green: 0.684363246, blue: 0, alpha: 0.8470588235), #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1), #colorLiteral(red: 0.5058823824, green: 0.3372549117, blue: 0.06666667014, alpha: 1), #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1), #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1), #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)]

        getArray(id: "course") { (items) in
            items.forEach { (item) in
                self.courses.append(Course(
                    title: item.fields["title"] as! String,
                    subtitle: item.fields["subtitle"] as! String,
                    image: item.fields["image"] as! String,
                    logo: item.fields["logo"] as! String,
                    color: colors.randomElement()!,
                    show: false))
            }
        }
    }
}
</code>```

For my Data.swift file, I have written the following code fyi:

```<code>import SwiftUI

struct Post: Codable, Identifiable {
    var id = UUID()
    var title : String
    var body : String

}

class API {
    func getPosts(completion: @escaping ([Post]) -> ()) {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }

        URLSession.shared.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }

            let posts = try! JSONDecoder().decode([Post].self, from: data)

            // Must be async to run API call
            DispatchQueue.main.async {
                completion(posts)
            }
        }
        .resume()
    }
}
</code>```

And here is the code for my DataStore.swift, think it will be helpful for my data fetching script:

```<code>import SwiftUI
import Combine

class DataStore: ObservableObject {
    @Published var posts: [Post] = []

    init() {
        getPosts()
    }

    func getPosts() {
        API().getPosts { (posts) in
            self.posts = posts
        }
    }
}
</code>```

Body:
The code below shows the code I am using to fetch data from Contentful API to my SwiftUI app. However, by calling the function client.fetchArray, I got an error message saying that the type of expression is ambiguous. I tried look up the documentation and the example code for client.fetchArray uses the exact parameters and hence I assume the error message should be gone? Can anyone please help me out here! I am super confused! Thank you!

import SwiftUI
import Contentful
import Combine

let client = Client(spaceId: "qqq2yu4vbtpl", environmentId: "master", accessToken: "LurTiklxcr0ARTpI9z7GVTz-mjMO6OFVsoSZ8V7GJ4c")
//let client = Client(spaceId: "0ge8xzmnbp2c", accessToken: "03010b0d79abcb655ca3fda453f2f493b5472e0aaa53664bc7dea5ef4fce2676")

func getArray(id: String, completion: @escaping([Entry]) -> ()) {
    let query = Query.where(contentTypeId: id)

    client.fetchArray(of: Entry.self, matching: query) { result in
        switch result {
        case .success(let array):
            DispatchQueue.main.async {
                completion(array.items)
            }
        case .error(let error):
            print(error)
        }
        print(result)
    }
}

class CourseStore: ObservableObject {
    @Published var courses: [Course] = courseData

    init() {
        let colors = [#colorLiteral(red: 0.3635728061, green: 0, blue: 0.8927152753, alpha: 0.8470588235), #colorLiteral(red: 0.2461163998, green: 0.3063159585, blue: 1, alpha: 0.8470588235), #colorLiteral(red: 0.3414418995, green: 0.653152287, blue: 0.405282855, alpha: 0.8470588235), #colorLiteral(red: 0.8906980753, green: 0.684363246, blue: 0, alpha: 0.8470588235), #colorLiteral(red: 0.5725490451, green: 0, blue: 0.2313725501, alpha: 1), #colorLiteral(red: 0.5058823824, green: 0.3372549117, blue: 0.06666667014, alpha: 1), #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1), #colorLiteral(red: 0.5568627715, green: 0.3529411852, blue: 0.9686274529, alpha: 1), #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)]

        getArray(id: "course") { (items) in
            items.forEach { (item) in
                self.courses.append(Course(
                    title: item.fields["title"] as! String,
                    subtitle: item.fields["subtitle"] as! String,
                    image: item.fields["image"] as! String,
                    logo: item.fields["logo"] as! String,
                    color: colors.randomElement()!,
                    show: false))
            }
        }
    }
}

For my Data.swift file, I have written the following code fyi:

import SwiftUI

struct Post: Codable, Identifiable {
    var id = UUID()
    var title : String
    var body : String

}

class API {
    func getPosts(completion: @escaping ([Post]) -> ()) {
        guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }

        URLSession.shared.dataTask(with: url) { (data, _, _) in
            guard let data = data else { return }

            let posts = try! JSONDecoder().decode([Post].self, from: data)

            // Must be async to run API call
            DispatchQueue.main.async {
                completion(posts)
            }
        }
        .resume()
    }
}

And here is the code for my DataStore.swift, think it will be helpful for my data fetching script:

import SwiftUI
import Combine

class DataStore: ObservableObject {
    @Published var posts: [Post] = []

    init() {
        getPosts()
    }

    func getPosts() {
        API().getPosts { (posts) in
            self.posts = posts
        }
    }
}


问:
How to transfer the value of an array between components SAC [Angular 15]
I'm looking to transfer the value of an array between two components. My application is a basic crud application that will store accounts with an id, name and date.

I have a service that has 2 basic functions and an array to pull from -

The array is holding the accounts. It is acting as my database for right now.

account-crud.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'

import { Account } from '../models/Account';
import { AddAccountComponent } from '../dashboard/add-account/add-account.component';

@Injectable({
  providedIn: 'root'
})
export class AccountCrudService {

  private accounts:Account[] = [];

  addAccount(account: Account){
      this.accounts.push(account);
  };

  getAccounts(): Account[] {
    console.log(this.getAccounts)
    return this.accounts;
  }

}
</code>```

This service is used by 2 components. The desired behavior is for me to use the AddAccountComponent to add components, which will then push to the array in our service and then display all the accounts in the AllAccountsComponent.
Here is the add account component -

add-account.component.ts

```<code>@Component({
  selector: 'app-add-account',
  standalone: true,
  imports: [FormsModule, ReactiveFormsModule, JsonPipe, RouterModule],
  providers: [AccountCrudService],
  templateUrl: './add-account.component.html',
  styleUrls: ['./add-account.component.scss']
})

export class AddAccountComponent {
  constructor(titleService:Title, private AccountCrudService: AccountCrudService) {
    titleService.setTitle("Add Account")
  }

  public printAccounts() {
    console.log('accounts :');
    console.log(this.AccountCrudService.getAccounts());
  }

  private account:Account = {id: 0, name:'', date:''};

  public get Account():Account{
    return this.account;
  }

  public addAccount(){
      const currentAccount:Account = {
          id: this.account.id,
          name: this.account.name,
          date: this.account.date
      };

    this.AccountCrudService.addAccount(currentAccount);

  }
</code>```

And here is the HTML for the add account component -

add-account.component.html

```<code><form #addAccountForm="ngForm">
    <label for="name">Account Name</label>
    <input name="accountName" type="text" [(ngModel)]="Account.name">
    <br>
    <label for="date">Initial Email Date</label>
    <input name="date" [(ngModel)]="Account.date">

    <br>
    <button type="submit" (click)="addAccount()">Submit</button>
    <button type="button" (click)="printAccounts()">console log accts</button>
    <button type="button" routerLink="/dashboard">back</button>

    <!-- this is for debugging purposes -->
    {{ addAccountForm.value | json }}
</form>
</code>```

And this component is where I plan to display all the accounts from that array. The line that I suspect is not working is the

```<code>this.accounts = this.AccountCrudService.getAccounts();
</code>```

line in the getAllAccounts() function. -

all-accounts.component.ts

```<code>@Component({
  selector: 'app-all-accounts',
  templateUrl: './all-accounts.component.html',
  styleUrls: ['./all-accounts.component.scss'],
  imports: [AccountCardComponent, RouterModule, CommonModule, AddAccountComponent, FormsModule],
  providers: [AccountCrudService],
  standalone: true
})
export class AllAccountsComponent {

  accounts: Account[];

  constructor(titleService:Title, public AccountCrudService: AccountCrudService) {
    titleService.setTitle("Dashboard")
    this.getAllAccounts();
  }

  //this is a debugging function
  public printAccounts(){
    console.log('accounts :');
    console.log(this.AccountCrudService.getAccounts());
  }

    public getAllAccounts() {
      //I want the value of accounts to be equal to the value of getAccounts()
      this.accounts = this.AccountCrudService.getAccounts();
      return this.accounts;
    }
  }

</code>```

all-accounts.component.html

```<code><div class="all-accounts-header">
    <h1>All Accounts</h1>
    <div class="all-accounts-options">
        <button class="all-accounts-addBtn" routerLink="/add-account">Add</button>
    </div>
</div>
<br>
<div class="all-accounts-cards">
    <app-account-card [accounts]='accounts'></app-account-card>
</div>

</code>```

I send this array to the account-card component where it uses an ngFor to display all the accounts. This functionality works when given a full array of accounts manually.

from account-card.component

```<code><div *ngFor="let account of accounts" class="account-card-container">
  <div class="account-card-name">
    <div class="account-card-header">
      <h2>{{ account.name }}</h2>
      <div class="account-card-date">
        <p></p>
      </div>
    </div>
  </div>
</code>```

And here is the .ts file.

account-card.component.ts

```<code>@Component({
  selector: 'app-account-card',
  templateUrl: './account-card.component.html',
  styleUrls: ['./account-card.component.scss'],
  imports: [AllAccountsComponent, CommonModule],
  providers: [AccountCrudService],
  standalone: true
})
export class AccountCardComponent {

  @Input() accounts: any[];

}
</code>```

When I console log the array in the add-account component, it displays my array just fine. But once I do it anywhere else, the whole array is gone.

I have used @Input() to try and input the array directly from the service, but that didn't work.

Any help is appreciated. Thanks!

Body:
I'm looking to transfer the value of an array between two components. My application is a basic crud application that will store accounts with an id, name and date.

I have a service that has 2 basic functions and an array to pull from -

The array is holding the accounts. It is acting as my database for right now.

account-crud.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http'

import { Account } from '../models/Account';
import { AddAccountComponent } from '../dashboard/add-account/add-account.component';

@Injectable({
  providedIn: 'root'
})
export class AccountCrudService {

  private accounts:Account[] = [];

  addAccount(account: Account){
      this.accounts.push(account);
  };

  getAccounts(): Account[] {
    console.log(this.getAccounts)
    return this.accounts;
  }

}

This service is used by 2 components. The desired behavior is for me to use the AddAccountComponent to add components, which will then push to the array in our service and then display all the accounts in the AllAccountsComponent.
Here is the add account component -

add-account.component.ts

@Component({
  selector: 'app-add-account',
  standalone: true,
  imports: [FormsModule, ReactiveFormsModule, JsonPipe, RouterModule],
  providers: [AccountCrudService],
  templateUrl: './add-account.component.html',
  styleUrls: ['./add-account.component.scss']
})

export class AddAccountComponent {
  constructor(titleService:Title, private AccountCrudService: AccountCrudService) {
    titleService.setTitle("Add Account")
  }

  public printAccounts() {
    console.log('accounts :');
    console.log(this.AccountCrudService.getAccounts());
  }

  private account:Account = {id: 0, name:'', date:''};

  public get Account():Account{
    return this.account;
  }

  public addAccount(){
      const currentAccount:Account = {
          id: this.account.id,
          name: this.account.name,
          date: this.account.date
      };

    this.AccountCrudService.addAccount(currentAccount);

  }

And here is the HTML for the add account component -

add-account.component.html

<form #addAccountForm="ngForm">
    Account Name
    <input name="accountName" type="text" [(ngModel)]="Account.name">

    Initial Email Date
    <input name="date" [(ngModel)]="Account.date">

    <button type="submit" (click)="addAccount()">Submit</button>
    <button type="button" (click)="printAccounts()">console log accts</button>
    <button type="button" routerLink="/dashboard">back</button>

    {{ addAccountForm.value | json }}
</form>

And this component is where I plan to display all the accounts from that array. The line that I suspect is not working is the

this.accounts = this.AccountCrudService.getAccounts();

line in the getAllAccounts() function. -

all-accounts.component.ts

@Component({
  selector: 'app-all-accounts',
  templateUrl: './all-accounts.component.html',
  styleUrls: ['./all-accounts.component.scss'],
  imports: [AccountCardComponent, RouterModule, CommonModule, AddAccountComponent, FormsModule],
  providers: [AccountCrudService],
  standalone: true
})
export class AllAccountsComponent {

  accounts: Account[];

  constructor(titleService:Title, public AccountCrudService: AccountCrudService) {
    titleService.setTitle("Dashboard")
    this.getAllAccounts();
  }

  //this is a debugging function
  public printAccounts(){
    console.log('accounts :');
    console.log(this.AccountCrudService.getAccounts());
  }

    public getAllAccounts() {
      //I want the value of accounts to be equal to the value of getAccounts()
      this.accounts = this.AccountCrudService.getAccounts();
      return this.accounts;
    }
  }

all-accounts.component.html

All Accounts

        <button class="all-accounts-addBtn" routerLink="/add-account">Add</button>

    <app-account-card [accounts]='accounts'></app-account-card>

I send this array to the account-card component where it uses an ngFor to display all the accounts. This functionality works when given a full array of accounts manually.

from account-card.component

{{ account.name }}

And here is the .ts file.

account-card.component.ts

@Component({
  selector: 'app-account-card',
  templateUrl: './account-card.component.html',
  styleUrls: ['./account-card.component.scss'],
  imports: [AllAccountsComponent, CommonModule],
  providers: [AccountCrudService],
  standalone: true
})
export class AccountCardComponent {

  @Input() accounts: any[];

}

When I console log the array in the add-account component, it displays my array just fine. But once I do it anywhere else, the whole array is gone.

I have used @Input() to try and input the array directly from the service, but that didn't work.

Any help is appreciated. Thanks!


问:
how to click on label with pupeeter?
```<code><label class="_6G4BGa _0Qm8W1 _7Cm1F9 FxZV-M IvnZ13 Pb4Ja8 ibou8b JT3_zV
ZkIJC- Md_Vex JCuRr_ na6fBM _0xLoFW FCIprz pVrzNP KRmOLG NuVH8Q"
for="size-picker-LA815O008-Q110010000" data-testid="pdp-stockAvailable-
label"><span class="hDNRPv r9BRio qXofat ZkIJC- agLu8- JCuRr_"><div
class="_0xLoFW FCIprz"><span class="_0Qm8W1 _7Cm1F9 dgII7d pVrzNP">44</span>
</div></span><div class="nXkCf3"></div></label>
</code>```

The label I want to click on is on this page: https://www.zalando.fr/lakai-cambridge-unisex-baskets-basses-blackwhite-la815o008-q11.html

i want to select the size 44

i would like to be able to presse on the size 44

all the sizes have the same label but not the same id

ex : for="size-picker-LA815O008-Q110010000"

and i cant put together a code click on this size .

Title: how to click on label with pupeeter?

Body:
44

The label I want to click on is on this page: https://www.zalando.fr/lakai-cambridge-unisex-baskets-basses-blackwhite-la815o008-q11.html

i want to select the size 44

i would like to be able to presse on the size 44

all the sizes have the same label but not the same id

ex : for="size-picker-LA815O008-Q110010000"

and i cant put together a code click on this size .


问:
Corda Jmeter Performance testing takes more time for first sampler inside Thread group (all are Java Request Samplers)
I followed https://docs.r3.com/en/platform/corda/4.9/enterprise/performance-testing/jmeter-samplers.html & used

JAVA request samplers instead of http samplers, so that the Corda flow class can be invoked directly. But the result behaviour is like, for the first run after the node is restarted, all samplers take significantly more Sample time than the second run.

I would like to know the reasons behind it, like whether it is due to first call of rpc connection to corda node?

If so, does it need to effect on all samplers in a thread group (since all samplers call - FlowInvoke inside)

Is there some other time result type which is more efficient than sample time to check on?


问:
Click button to autofill text in Adobe Acrobat
So I need some help writing some code in Adobe Acrobat. The sheet has a row of names on the left side, next to it a signature box, and then a series of boxes where numbers will go. Simply, I need some code that will work so that a series of numbers will be displayed to the right of the person's name when I click a button that is covering their name. Attached is an example of what I need. Any help would be GREATLY appreciated.
enter image description here

I have tried using "action buttons" and adding a custom button that would allow me to enter text when clicked, but unfortunately that didn't work. I was hoping that if I clicked a button (as seen in picture) that it would fill out a series of text boxes for me automatically.


问:
How to configure WiFi / Cellular preference for call admission and call transfer programmatically?
I am developing a carrier app (https://source.android.com/docs/core/connect/uicc) for managing configurations for operators/providers.

The issue is configuring WiFi / Cellular preference (RAT given preference) for call admission and call transfer.

After checking various Android APIs, I couldn't find any that would seem to suite the need. There is this configuration key for CarrierConfigManager https://developer.android.com/reference/android/telephony/CarrierConfigManager#KEY_CARRIER_DEFAULT_WFC_IMS_MODE_INT . But it does not seem to relate specifically to call admission or call transfer.

What would be the best API for this configuration if any exists?


问:
Delete node from a binary search tree in python correctly
I want to correctly delete  a element from a binary search tree.

Tree node:

```<code>class tree_node:

def  __init__(self,val,rightChild,leftChild):
    self.val = val
    self.rightChild = rightChild
    self.leftChild = leftChild
</code>```

Here is my deletion algorithm:

```<code> def deleteNode(self,treeNode):
    current = self.baseNode
    prev = None
    while current:
        prev = current
        if treeNode.val<current.val:
            current = current.rightChild
            if current is treeNode:
                break
        elif treeNode.val>current.val:
            current = current.leftChild
            if current is treeNode:
                break
    if not  current.rightChild and not current.leftChild:
        if current is prev.rightChild:
            prev.rightChild = None
            current = None
        elif current is prev.leftChild:
            prev.leftChild = None
            current = None
     elif (current.rightChild and not current.leftChild) or (current.leftChild and not current.rightChild):
        if not current.leftChild:
            prev.rightChild = current.rightChild
            current = None
        else:
            prev.rightChild = current.leftChild
            current = None
    elif current.rightChild and current.leftChild:
         if current is prev.rightChild:
            prev.rightChild = current.rightChild
            prev.rightChild.rightChild = current.leftChild
            current = None
         elif current is prev.leftChild:
            prev.rightChild = current.rightChild
            prev.rightChild.rightChild = current.leftChild
            current = None

</code>```

I have add these tree nodes in my binary search tree:

```<code>zero = tree_node(0,None,None)
minusone = tree_node(-1,None,None)
one = tree_node(1,None,None)
minustwo = tree_node(-2,None,None)
two= tree_node(2,None,None)
three= tree_node(3,None,None)
minusthree= tree_node(-3,None,None)
four= tree_node(4,None,None)
minusfour= tree_node(-4,None,None)
minusfive= tree_node(-5,None,None)
minusonehalf = tree_node(-1/2,None,None)
onehalf = tree_node(1/2,None,None)
six = tree_node(6,None,None)
bst = binary_tree(zero)
bst.addTreeNode(one)
bst.addTreeNode(two)
bst.addTreeNode(minusonehalf)
bst.addTreeNode(minustwo)
bst.addTreeNode(minusone)
bst.addTreeNode(three)
bst.addTreeNode(minusfive)
bst.addTreeNode(minusthree)
bst.addTreeNode(four)
bst.addTreeNode(minusfour)
bst.addTreeNode(onehalf)
bst.addTreeNode(six)
</code>```

The addition algorithm is OK.
I am calling a print_tree function:

```<code>def print_tree(self):
    def dfs(node):
        if node:
            print("",node.val)
            dfs(node.rightChild)
            dfs(node.leftChild)
    dfs(self.baseNode)
</code>```

then I call  print_tree() and deleteNode() succesively to see if the deleteNode function works correctly.

```<code>bst.print_tree()
Output: 0
-0.5
-2
-5
-3
-4
-1
 1
 0.5
 2
 3
 4
 6
 bst.deleteNode(minustwo)
 Output:
 0
 -0.5
 -5
 -1
 -3
 -4
  1
  0.5
  2
  3
  4
  6
  bst.deleteNode(four)
  bst.print_tree()
  Output:
  0
  -0.5
  -5
  -1
  -3
  -4
   1
   0.5
   2
   3
   6
   4
   6
</code>```

and obviously the delete of tree_node with value 4 doesnt happen correctly.Since the deletion of tree nodes happening in the right side of tree is correct and 4 has only 1 child(6) then I suspect the culprit is somewhere here:

```<code>else:
            prev.rightChild = current.leftChild
            current = None
</code>```

but im not sure why this is the case.

Body:
I want to correctly delete  a element from a binary search tree.

Tree node:

class tree_node:

def  __init__(self,val,rightChild,leftChild):
    self.val = val
    self.rightChild = rightChild
    self.leftChild = leftChild

Here is my deletion algorithm:

 def deleteNode(self,treeNode):
    current = self.baseNode
    prev = None
    while current:
        prev = current
        if treeNode.val<current.val:
            current = current.rightChild
            if current is treeNode:
                break
        elif treeNode.val>current.val:
            current = current.leftChild
            if current is treeNode:
                break
    if not  current.rightChild and not current.leftChild:
        if current is prev.rightChild:
            prev.rightChild = None
            current = None
        elif current is prev.leftChild:
            prev.leftChild = None
            current = None
     elif (current.rightChild and not current.leftChild) or (current.leftChild and not current.rightChild):
        if not current.leftChild:
            prev.rightChild = current.rightChild
            current = None
        else:
            prev.rightChild = current.leftChild
            current = None
    elif current.rightChild and current.leftChild:
         if current is prev.rightChild:
            prev.rightChild = current.rightChild
            prev.rightChild.rightChild = current.leftChild
            current = None
         elif current is prev.leftChild:
            prev.rightChild = current.rightChild
            prev.rightChild.rightChild = current.leftChild
            current = None

I have add these tree nodes in my binary search tree:

zero = tree_node(0,None,None)
minusone = tree_node(-1,None,None)
one = tree_node(1,None,None)
minustwo = tree_node(-2,None,None)
two= tree_node(2,None,None)
three= tree_node(3,None,None)
minusthree= tree_node(-3,None,None)
four= tree_node(4,None,None)
minusfour= tree_node(-4,None,None)
minusfive= tree_node(-5,None,None)
minusonehalf = tree_node(-1/2,None,None)
onehalf = tree_node(1/2,None,None)
six = tree_node(6,None,None)
bst = binary_tree(zero)
bst.addTreeNode(one)
bst.addTreeNode(two)
bst.addTreeNode(minusonehalf)
bst.addTreeNode(minustwo)
bst.addTreeNode(minusone)
bst.addTreeNode(three)
bst.addTreeNode(minusfive)
bst.addTreeNode(minusthree)
bst.addTreeNode(four)
bst.addTreeNode(minusfour)
bst.addTreeNode(onehalf)
bst.addTreeNode(six)

The addition algorithm is OK.
I am calling a print_tree function:

def print_tree(self):
    def dfs(node):
        if node:
            print("",node.val)
            dfs(node.rightChild)
            dfs(node.leftChild)
    dfs(self.baseNode)

then I call  print_tree() and deleteNode() succesively to see if the deleteNode function works correctly.

bst.print_tree()
Output: 0
-0.5
-2
-5
-3
-4
-1
 1
 0.5
 2
 3
 4
 6
 bst.deleteNode(minustwo)
 Output:
 0
 -0.5
 -5
 -1
 -3
 -4
  1
  0.5
  2
  3
  4
  6
  bst.deleteNode(four)
  bst.print_tree()
  Output:
  0
  -0.5
  -5
  -1
  -3
  -4
   1
   0.5
   2
   3
   6
   4
   6

and obviously the delete of tree_node with value 4 doesnt happen correctly.Since the deletion of tree nodes happening in the right side of tree is correct and 4 has only 1 child(6) then I suspect the culprit is somewhere here:

else:
            prev.rightChild = current.leftChild
            current = None

but im not sure why this is the case.


问:
Microsoft Graph Table component not updating after input property value changes
Parent Component

```<code> <user-settings #userSettings [isexpanded]="isexpanded"></user-settings>
</code>```

Child Component

```<code><mgt-login id="loggedInUser" (loginCompleted)="loginCompleted($event)">
    <template data-type="signed-in-button-content" *ngIf="!isexpanded">
        <mgt-person person-query="me"></mgt-person>
    </template>
</code>```

When the value of the isexpanded property changes in the parent component, it gets passed to the child/mgt-login/template successfully.

But then the template component is not updating and showing/hiding itself without having to be clicked on. Once clicked on it updates and changes display like it should.

I am needing to get it to display/hide automatically when the property value changes in the parent.

I have tried to implement NgOnChange within the child component with a console.log to make sure the prop changes make it all the way through and it worked, but did not force it to refresh the component and display correctly.

I have tried ChangeDetectionStrategy.default to .onpush but that did not make any difference either.

I am starting to think that it has something to do with the mgt template and its properties or the mgt-login component.

Body:
Parent Component

 <user-settings #userSettings [isexpanded]="isexpanded"></user-settings>

Child Component

<mgt-login id="loggedInUser" (loginCompleted)="loginCompleted($event)">
    <template data-type="signed-in-button-content" *ngIf="!isexpanded">
        <mgt-person person-query="me"></mgt-person>
    </template>

When the value of the isexpanded property changes in the parent component, it gets passed to the child/mgt-login/template successfully.

But then the template component is not updating and showing/hiding itself without having to be clicked on. Once clicked on it updates and changes display like it should.

I am needing to get it to display/hide automatically when the property value changes in the parent.

I have tried to implement NgOnChange within the child component with a console.log to make sure the prop changes make it all the way through and it worked, but did not force it to refresh the component and display correctly.

I have tried ChangeDetectionStrategy.default to .onpush but that did not make any difference either.

I am starting to think that it has something to do with the mgt template and its properties or the mgt-login component.


问:
ag-grid set filter Not Filtering items excluded from Set List
i am building an account lookup feature using ag-grid and Angular
There is a quick filter that searches for Names
There is a set filter that filters on type/subtype

I have an ag-grid w/ 2 columns
The first column is a concatenation of account type and account subtype
The second column is account name

it all works in the wide open use case (user can select any account from the entire chart of accounts)

There will be cases where I want  to constrain what the user can look up

For this example lets assume I am constraining the Account set to be:

Type = Expense or Income

Subtype = Operating

I have the Set-Filter-Value-list defined and correctly shows the intended options ( Expense/Income and operating)
When I select just 1 of the 2 account types, the list of accounts is perfect.

however, when I select both of them, the ag-grid sees that I have all the filter items selected and it includes all accounts. not just the accounts that match the filter.

I have tried adding an extra item, just so ALL items are not selected, this mechanically solves the problem, but obviously not a production solution.

I tried setting  SuppressSelectAll.  you can observe that the SelectAll item is not available on the filter, but it does not change the behaviour of the grid.

MY QUESTION :  IS THERE A WAY TO MAKE THE GRID HONOR THE FILTER WHEN ALL ITEMS ARE SELECTED AND FILTER OUT DATA ROWS THAT DO NOT MATCH IT?

Here is the component code

```<code>import { Component, OnInit, Input } from '@angular/core';
import { COAModule } from 'src/app/coa/coa.module';
import { ChartOfAccoutsService } from 'src/app/coa/services/chart-of-accouts.service';

import{
  ColDef, ValueParserParams, ValueSetterParams,
  GridApi, GridReadyEvent, ICellRendererParams,
} from 'ag-grid-community';

import { empty, Observable, of   } from 'rxjs';
import { distinctUntilKeyChanged, pluck
  , switchMap ,tap, map} from 'rxjs/operators';

import { getData } from './data';
import { COA_Account } from 'src/app/coa/COA_Account';
import { coaType_List } from 'src/app/coa/coaTypeList';
import { COA_Header } from 'src/app/coa/COA_Header';

export class COAlookupConfig {
  AccountTypes : string[] = ['Equity','Expense','Asset','Income','Liability']
  AccountSubTypes: string[] =['Current', 'Fixed', 'Capital Expense', 'Non-operating', 'Operating', '', 'Current','Long Term' ]

}

@Component({
  selector: 'app-account-look-up',
  templateUrl: './account-look-up.component.html',
  styleUrls: ['./account-look-up.component.css']
})
export class AccountLookUpComponent implements OnInit {

  @Input() config : COAlookupConfig= new COAlookupConfig();

  private gridApi!: GridApi;
  public acctTypeSubtypes : string;

  public columnDefs: ColDef[] =[];
  public defaultColDef: ColDef = {};

  public rowData: any[] | null = getData();

public myCOA_Header$! : Observable<COA_Header>;
public myTST_ctl$ : Observable<coaType_List>;
public myTST_TypeList : string[];

  constructor( private acctService : ChartOfAccoutsService ) { }

  ngOnInit(): void {
          let projId: number = 4200;
          this.myCOA_Header$ = this.acctService.getCOAByProjectId(projId) ;

         //this is where i constrain the available accounts
           this.config.AccountTypes = ['Expense', 'Income']
          this.config.AccountSubTypes = ['Operating']

          this.myTST_ctl$ = this.acctService.get_coaTypeList(this.config.AccountTypes, this.config.AccountSubTypes).pipe(
            tap( ctl => {this.myTST_TypeList = ctl.ItemList();
                  this.defineGrid(); // now that we have the types, we can set up the grid
            })
          ) ;

      }

   defineGrid(){
      //call this once we have the data

      this.defaultColDef = {
        flex: 1,
        editable: false,
        sortable:false,
        filter:true,
         menuTabs: ['filterMenuTab'],
      };

      this.columnDefs = [
        // simple column, easy to understand
        { field: 'TypeSubType'
              ,filter: 'agSetColumnFilter'
              , filterParams:{suppressSelectAll : true, suppressMiniFilter: true,  values: this.myTST_TypeList}
              // ,getQuickFilterText: (params) => {
              //   return params.value;}
            },

        { field: 'Name' ,filter: false
            , suppressMenu : true
          ,   filterParams:{defaultToNothingSelected:true}}

      ];
   }
   onGridReady(params: GridReadyEvent) {
    this.gridApi = params.api;
     params.columnApi.autoSizeAllColumns(true);
  }

  onFilterTextBoxChanged() {
    this.gridApi.setQuickFilter(
      (document.getElementById('filter-text-box') as HTMLInputElement).value
    );
  }
</code>```

Here is the HTML  template for the component

```<code>  <div class="example-wrapper">
      <div class="example-header">
        <input
          type="text"
          id="filter-text-box"
          placeholder="Search Account Names..."
          (input)="onFilterTextBoxChanged()"
        />

      </div>

      <ag-grid-angular
        style="width: 600px; height: 500px;"
        class="ag-theme-balham"
        [suppressMenuHide]="true"
        [columnDefs]="columnDefs"
        [defaultColDef]="defaultColDef"
        [rowData]="myCOA_Header.Accounts"

        [cacheQuickFilter]="true"
        (gridReady)="onGridReady($event)"
      ></ag-grid-angular>

    </div>
</code>```

Body:
i am building an account lookup feature using ag-grid and Angular
There is a quick filter that searches for Names
There is a set filter that filters on type/subtype

I have an ag-grid w/ 2 columns
The first column is a concatenation of account type and account subtype
The second column is account name

it all works in the wide open use case (user can select any account from the entire chart of accounts)

There will be cases where I want  to constrain what the user can look up

For this example lets assume I am constraining the Account set to be:

Type = Expense or Income

Subtype = Operating

I have the Set-Filter-Value-list defined and correctly shows the intended options ( Expense/Income and operating)
When I select just 1 of the 2 account types, the list of accounts is perfect.

however, when I select both of them, the ag-grid sees that I have all the filter items selected and it includes all accounts. not just the accounts that match the filter.

I have tried adding an extra item, just so ALL items are not selected, this mechanically solves the problem, but obviously not a production solution.

I tried setting  SuppressSelectAll.  you can observe that the SelectAll item is not available on the filter, but it does not change the behaviour of the grid.

MY QUESTION :  IS THERE A WAY TO MAKE THE GRID HONOR THE FILTER WHEN ALL ITEMS ARE SELECTED AND FILTER OUT DATA ROWS THAT DO NOT MATCH IT?

Here is the component code

import { Component, OnInit, Input } from '@angular/core';
import { COAModule } from 'src/app/coa/coa.module';
import { ChartOfAccoutsService } from 'src/app/coa/services/chart-of-accouts.service';

import{
  ColDef, ValueParserParams, ValueSetterParams,
  GridApi, GridReadyEvent, ICellRendererParams,
} from 'ag-grid-community';

import { empty, Observable, of   } from 'rxjs';
import { distinctUntilKeyChanged, pluck
  , switchMap ,tap, map} from 'rxjs/operators';

import { getData } from './data';
import { COA_Account } from 'src/app/coa/COA_Account';
import { coaType_List } from 'src/app/coa/coaTypeList';
import { COA_Header } from 'src/app/coa/COA_Header';

export class COAlookupConfig {
  AccountTypes : string[] = ['Equity','Expense','Asset','Income','Liability']
  AccountSubTypes: string[] =['Current', 'Fixed', 'Capital Expense', 'Non-operating', 'Operating', '', 'Current','Long Term' ]

}

@Component({
  selector: 'app-account-look-up',
  templateUrl: './account-look-up.component.html',
  styleUrls: ['./account-look-up.component.css']
})
export class AccountLookUpComponent implements OnInit {

  @Input() config : COAlookupConfig= new COAlookupConfig();

  private gridApi!: GridApi;
  public acctTypeSubtypes : string;

  public columnDefs: ColDef[] =[];
  public defaultColDef: ColDef = {};

  public rowData: any[] | null = getData();

public myCOA_Header$! : Observable<COA_Header>;
public myTST_ctl$ : Observable<coaType_List>;
public myTST_TypeList : string[];

  constructor( private acctService : ChartOfAccoutsService ) { }

  ngOnInit(): void {
          let projId: number = 4200;
          this.myCOA_Header$ = this.acctService.getCOAByProjectId(projId) ;

         //this is where i constrain the available accounts
           this.config.AccountTypes = ['Expense', 'Income']
          this.config.AccountSubTypes = ['Operating']

          this.myTST_ctl$ = this.acctService.get_coaTypeList(this.config.AccountTypes, this.config.AccountSubTypes).pipe(
            tap( ctl => {this.myTST_TypeList = ctl.ItemList();
                  this.defineGrid(); // now that we have the types, we can set up the grid
            })
          ) ;

      }

   defineGrid(){
      //call this once we have the data

      this.defaultColDef = {
        flex: 1,
        editable: false,
        sortable:false,
        filter:true,
         menuTabs: ['filterMenuTab'],
      };

      this.columnDefs = [
        // simple column, easy to understand
        { field: 'TypeSubType'
              ,filter: 'agSetColumnFilter'
              , filterParams:{suppressSelectAll : true, suppressMiniFilter: true,  values: this.myTST_TypeList}
              // ,getQuickFilterText: (params) => {
              //   return params.value;}
            },

        { field: 'Name' ,filter: false
            , suppressMenu : true
          ,   filterParams:{defaultToNothingSelected:true}}

      ];
   }
   onGridReady(params: GridReadyEvent) {
    this.gridApi = params.api;
     params.columnApi.autoSizeAllColumns(true);
  }

  onFilterTextBoxChanged() {
    this.gridApi.setQuickFilter(
      (document.getElementById('filter-text-box') as HTMLInputElement).value
    );
  }

Here is the HTML  template for the component

        <input
          type="text"
          id="filter-text-box"
          placeholder="Search Account Names..."
          (input)="onFilterTextBoxChanged()"
        />

      <ag-grid-angular
        style="width: 600px; height: 500px;"
        class="ag-theme-balham"
        [suppressMenuHide]="true"
        [columnDefs]="columnDefs"
        [defaultColDef]="defaultColDef"
        [rowData]="myCOA_Header.Accounts"

        [cacheQuickFilter]="true"
        (gridReady)="onGridReady($event)"
      ></ag-grid-angular>


问:
I need to display related product carousel in my sidebar
I have added the code remove_action( 'woocommerce_after_single_product_summary', 'woocommerce_output_related_products',20); and add inside the text editor the shortcode [related_products per_page="3" columns="1"], but it is displaying unproperly. Is there is any solution

Displaying Like this:
https://im4.ezgif.com/tmp/ezgif-4-233a5a5d74.webp

Does anybody have the solution??


问:
Filter documents out of the facet count in enterprise search
We use enterprise search indexes to store items that can be tagged by multiple tenants.
e.g

```<code>[
  {
    "id": 1,
    "name": "document 1",
    "tags": [
      { "company_id": 1, "tag_id": 1, "tag_name": "bla" },
      { "company_id": 2, "tag_id": 1, "tag_name": "bla" }
    ]
  }
]
</code>```

I'm looking to find a way to retrieve all documents with only the tags of company 1

This request:

```<code>{
  "query": "",
  "facets": {
    "tags": {
      "type": "value"
    }
  },
  "sort": {
    "created": "desc"
  },
  "page": {
    "size": 20,
    "current": 1
  }
}
</code>```

Is coming back with

```<code>...
    "facets": {
        "tags": [
            {
                "type": "value",
                "data": [
                    {
                        "value": "{\"company_id\":1,\"tag_id\":1,\"tag_name\":\"bla\"}",
                        "count": 1
                    },
                    {
                        "value": "{\"company_id\":2,\"tag_id\":1,\"tag_name\":\"bla\"}",
                        "count": 1
                    }
                ]
            }
        ],
}
...
</code>```

Can I modify the request in a way such that I get no tags by "company_id" = 2 ?

I have a solution that involves modifying the results to strip the extra data after they are retrieved but I'm looking for a better solution.

Body:
We use enterprise search indexes to store items that can be tagged by multiple tenants.
e.g

[
  {
    "id": 1,
    "name": "document 1",
    "tags": [
      { "company_id": 1, "tag_id": 1, "tag_name": "bla" },
      { "company_id": 2, "tag_id": 1, "tag_name": "bla" }
    ]
  }
]

I'm looking to find a way to retrieve all documents with only the tags of company 1

This request:

{
  "query": "",
  "facets": {
    "tags": {
      "type": "value"
    }
  },
  "sort": {
    "created": "desc"
  },
  "page": {
    "size": 20,
    "current": 1
  }
}

Is coming back with

...
    "facets": {
        "tags": [
            {
                "type": "value",
                "data": [
                    {
                        "value": "{\"company_id\":1,\"tag_id\":1,\"tag_name\":\"bla\"}",
                        "count": 1
                    },
                    {
                        "value": "{\"company_id\":2,\"tag_id\":1,\"tag_name\":\"bla\"}",
                        "count": 1
                    }
                ]
            }
        ],
}
...

Can I modify the request in a way such that I get no tags by "company_id" = 2 ?

I have a solution that involves modifying the results to strip the extra data after they are retrieved but I'm looking for a better solution.


问:
Cucumber: Multiple tags giving 0 scenarios and 0 steps
I have multiple cucumber feature files with different tags, and in my package.json I specify all tags with and but it giving me 0 scenarios and 0 steps, any thoughts/idea on what I'm missing ?

```<code> "scripts": {
    "atdd:dev": "./node_modules/.bin/cucumber-js --format json:cucumber.json --tags='@putLockDev and @getLockDev and @dev'"
  }
</code>```

0 scenarios
0 steps
0m00.002s (executing steps: 0m00.000s)

Body:
I have multiple cucumber feature files with different tags, and in my package.json I specify all tags with and but it giving me 0 scenarios and 0 steps, any thoughts/idea on what I'm missing ?

 "scripts": {
    "atdd:dev": "./node_modules/.bin/cucumber-js --format json:cucumber.json --tags='@putLockDev and @getLockDev and @dev'"
  }

0 scenarios
0 steps
0m00.002s (executing steps: 0m00.000s)


问:
FastAI - AttributeError: 'Sequential' object has no attribute 'hps'
When I try to call learn.recorder.plot_sched() just after learn.lr_find()
I get the following error:

```<code>---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [20], in <module>
      1 learn.summary()
      2 learn.lr_find()
----> 3 learn.recorder.plot_sched()

File ~/.local/lib/python3.8/site-packages/fastai/callback/schedule.py:124, in plot_sched(self, keys, figsize)
    122 @patch
    123 def plot_sched(self:Recorder, keys=None, figsize=None):
--> 124     keys = self.hps.keys() if keys is None else L(keys)
    125     rows,cols = (len(keys)+1)//2, min(2, len(keys))
    126     figsize = figsize or (6*cols,4*rows)

File ~/.local/lib/python3.8/site-packages/fastcore/basics.py:496, in GetAttr.__getattr__(self, k)
    494 if self._component_attr_filter(k):
    495     attr = getattr(self,self._default,None)
--> 496     if attr is not None: return getattr(attr,k)
    497 raise AttributeError(k)

File ~/.local/lib/python3.8/site-packages/fastcore/basics.py:496, in GetAttr.__getattr__(self, k)
    494 if self._component_attr_filter(k):
    495     attr = getattr(self,self._default,None)
--> 496     if attr is not None: return getattr(attr,k)
    497 raise AttributeError(k)

File ~/.local/lib/python3.8/site-packages/torch/nn/modules/module.py:1269, in Module.__getattr__(self, name)
   1267     if name in modules:
   1268         return modules[name]
-> 1269 raise AttributeError("'{}' object has no attribute '{}'".format(
   1270     type(self).__name__, name))

AttributeError: 'Sequential' object has no attribute 'hps'

</code>```

Even if I replace learn.recorder.plot_sched() with learn.recorder.plot() I now get the error AttributeError: 'Sequential' object has no attribute 'plot'

This is my code:

```<code>import torchvision
from fastai.vision import *
from fastai.vision.all import *
from fastai.metrics import error_rate
from fastai import *
from fastai.vision.data import ImageDataLoaders
import cv2 as cv
import numpy as np
import pandas as pd
import scipy.io as sio

tfms = aug_transforms(do_flip=True, flip_vert=False, max_lighting=0.1, max_zoom=1.05,
                      max_warp=0.,
                      xtra_tfms=[RandomCrop((128,128)), Zoom(1, 1.5),
                                 Warp(magnitude=(-0.2, 0.2))])

data = ImageDataLoaders.from_folder('content/cars_dataset/data/working/data','train','valid',
                                  ds_tfms=tfms
                                  ,size=128,bs=64, batch_tfms=Normalize.from_stats(*imagenet_stats))

data.show_batch()

import pretrainedmodels
from torch import nn
import torch.nn.functional as F

class FocalLoss(nn.Module):
    def __init__(self, alpha=1., gamma=2.):
        super().__init__()
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, inputs, targets, **kwargs):
        CE_loss = nn.CrossEntropyLoss(reduction='none')(inputs, targets)
        pt = torch.exp(-CE_loss)
        F_loss = self.alpha * ((1-pt)**self.gamma) * CE_loss
        return F_loss.mean()

def se_resnext50_32x4d(pretrained=False):
    pretrained = 'imagenet' if pretrained else None
    model = pretrainedmodels.se_resnext50_32x4d(pretrained=pretrained)
    return nn.Sequential(*list(model.children()))

import ssl

ssl._create_default_https_context = ssl._create_unverified_context
learn = vision_learner(data, se_resnext50_32x4d, pretrained=True, cut=-2,
                    splitter=lambda m: (m[0][3], m[1]),
                    metrics=[accuracy])
learn.loss_fn = FocalLoss()

learn.summary()
learn.lr_find()
learn.recorder.plot_sched()
</code>```

Body:
When I try to call learn.recorder.plot_sched() just after learn.lr_find()
I get the following error:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Input In [20], in <module>
      1 learn.summary()
      2 learn.lr_find()
----> 3 learn.recorder.plot_sched()

File ~/.local/lib/python3.8/site-packages/fastai/callback/schedule.py:124, in plot_sched(self, keys, figsize)
    122 @patch
    123 def plot_sched(self:Recorder, keys=None, figsize=None):
--> 124     keys = self.hps.keys() if keys is None else L(keys)
    125     rows,cols = (len(keys)+1)//2, min(2, len(keys))
    126     figsize = figsize or (6*cols,4*rows)

File ~/.local/lib/python3.8/site-packages/fastcore/basics.py:496, in GetAttr.__getattr__(self, k)
    494 if self._component_attr_filter(k):
    495     attr = getattr(self,self._default,None)
--> 496     if attr is not None: return getattr(attr,k)
    497 raise AttributeError(k)

File ~/.local/lib/python3.8/site-packages/fastcore/basics.py:496, in GetAttr.__getattr__(self, k)
    494 if self._component_attr_filter(k):
    495     attr = getattr(self,self._default,None)
--> 496     if attr is not None: return getattr(attr,k)
    497 raise AttributeError(k)

File ~/.local/lib/python3.8/site-packages/torch/nn/modules/module.py:1269, in Module.__getattr__(self, name)
   1267     if name in modules:
   1268         return modules[name]
-> 1269 raise AttributeError("'{}' object has no attribute '{}'".format(
   1270     type(self).__name__, name))

AttributeError: 'Sequential' object has no attribute 'hps'

Even if I replace learn.recorder.plot_sched() with learn.recorder.plot() I now get the error AttributeError: 'Sequential' object has no attribute 'plot'

This is my code:

import torchvision
from fastai.vision import *
from fastai.vision.all import *
from fastai.metrics import error_rate
from fastai import *
from fastai.vision.data import ImageDataLoaders
import cv2 as cv
import numpy as np
import pandas as pd
import scipy.io as sio

tfms = aug_transforms(do_flip=True, flip_vert=False, max_lighting=0.1, max_zoom=1.05,
                      max_warp=0.,
                      xtra_tfms=[RandomCrop((128,128)), Zoom(1, 1.5),
                                 Warp(magnitude=(-0.2, 0.2))])

data = ImageDataLoaders.from_folder('content/cars_dataset/data/working/data','train','valid',
                                  ds_tfms=tfms
                                  ,size=128,bs=64, batch_tfms=Normalize.from_stats(*imagenet_stats))

data.show_batch()

import pretrainedmodels
from torch import nn
import torch.nn.functional as F

class FocalLoss(nn.Module):
    def __init__(self, alpha=1., gamma=2.):
        super().__init__()
        self.alpha = alpha
        self.gamma = gamma

    def forward(self, inputs, targets, **kwargs):
        CE_loss = nn.CrossEntropyLoss(reduction='none')(inputs, targets)
        pt = torch.exp(-CE_loss)
        F_loss = self.alpha * ((1-pt)**self.gamma) * CE_loss
        return F_loss.mean()

def se_resnext50_32x4d(pretrained=False):
    pretrained = 'imagenet' if pretrained else None
    model = pretrainedmodels.se_resnext50_32x4d(pretrained=pretrained)
    return nn.Sequential(*list(model.children()))

import ssl

ssl._create_default_https_context = ssl._create_unverified_context
learn = vision_learner(data, se_resnext50_32x4d, pretrained=True, cut=-2,
                    splitter=lambda m: (m[0][3], m[1]),
                    metrics=[accuracy])
learn.loss_fn = FocalLoss()

learn.summary()
learn.lr_find()
learn.recorder.plot_sched()


问:
Vue 3 with Vite on Homestead
I am trying to make a vue 3 app with vite on Homestead but I can't get it to work.

It all installs ok and when I run: npm run dev, it says I have it running at Local: http://localhost:5173/

I added the site to the homestead yaml file and the windows hosts file as normal pointing to my vue-projects folder but when I go to my http://vueproject.test/index.html I get a blank screen with the following error in the console:

Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".

I have it installed in a folder called vue-project mapped like so:

map: vueproject.test to: /home/vagrant/laravel_projects/vue-project

I think this is because it's a global installation of vue but not sure how to resolve it as I am totally new to vue and this is to use with a tutorial.

here is my index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>

```
<p>here is my <code>main.js</code></p>
<pre class="lang-js prettyprint-override"><code>import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

import "./assets/main.css";

const app = createApp(App);

app.use(router);

app.mount("#app");
</code>```

Title: Vue 3 with Vite on Homestead

Body:
I am trying to make a vue 3 app with vite on Homestead but I can't get it to work.

It all installs ok and when I run: npm run dev, it says I have it running at Local: http://localhost:5173/

I added the site to the homestead yaml file and the windows hosts file as normal pointing to my vue-projects folder but when I go to my http://vueproject.test/index.html I get a blank screen with the following error in the console:

Failed to resolve module specifier "vue". Relative references must start with either "/", "./", or "../".

I have it installed in a folder called vue-project mapped like so:

map: vueproject.test to: /home/vagrant/laravel_projects/vue-project

I think this is because it's a global installation of vue but not sure how to resolve it as I am totally new to vue and this is to use with a tutorial.

here is my index.html

<!DOCTYPE html>

    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite App</title>

here is my main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";

import "./assets/main.css";

const app = createApp(App);

app.use(router);

app.mount("#app");


问:
My native query returns PGobjects instead of my entities - how can I achieve that?
I'm trying to get a JPA Function in Spring Boot returning my result as convenient as possible. I'm using PostgreSQL as my database.

I have a NativeQuery, which should return a List of objects with

```<code>TableObjectA
TableObjectB
double
</code>```

value as its content.

Instead, I'm getting this:

```<code>PGObject
PGObject
double
</code>```

How can I tell Spring JPA to return my actual entities instead of the "literal" result. Is there a convenient solution to this or do I really have to create several DTOs for this single method?

For clarification, this is my native query. clubAddress and club are defined as entities. Point is calculated.

```<code>SELECT clubAddress ,club, point(?1, ?2) <@> (point(clubAddress.longitude, clubAddress.latitude)\:\:point) as distance FROM club_address clubAddress,club_club club WHERE club.id = clubAddress.club_id
</code>```

Body:
I'm trying to get a JPA Function in Spring Boot returning my result as convenient as possible. I'm using PostgreSQL as my database.

I have a NativeQuery, which should return a List of objects with

TableObjectA
TableObjectB
double

value as its content.

Instead, I'm getting this:

PGObject
PGObject
double

How can I tell Spring JPA to return my actual entities instead of the "literal" result. Is there a convenient solution to this or do I really have to create several DTOs for this single method?

For clarification, this is my native query. clubAddress and club are defined as entities. Point is calculated.

SELECT clubAddress ,club, point(?1, ?2) <@> (point(clubAddress.longitude, clubAddress.latitude)\:\:point) as distance FROM club_address clubAddress,club_club club WHERE club.id = clubAddress.club_id