问:
Get lineage id of a measure from thin pbix file
Is there a way in PowerQuery to extract measure lineage id from a thin pbix report connected to dataset through live connection mode? I access the contents of thin pbix by unzipping it and reading the section Report/Layout.

Lineage id can be found in the DMV of dataset in a column LineageTag

```<code>select * from $SYSTEM.TMSCHEMA_MEASURES
</code>```

I want to find its counterpart in the thin report. The only way I can match a measure from dataset with its thin Report/Layout counterpart is by measure name.

Edit. The purpose of my question. Suppose we want to create a table with a display name of a measure (comes from thin report) and a DAX expression of the same measure (comes from dataset).

Body:
Is there a way in PowerQuery to extract measure lineage id from a thin pbix report connected to dataset through live connection mode? I access the contents of thin pbix by unzipping it and reading the section Report/Layout.

Lineage id can be found in the DMV of dataset in a column LineageTag

select * from $SYSTEM.TMSCHEMA_MEASURES

I want to find its counterpart in the thin report. The only way I can match a measure from dataset with its thin Report/Layout counterpart is by measure name.

Edit. The purpose of my question. Suppose we want to create a table with a display name of a measure (comes from thin report) and a DAX expression of the same measure (comes from dataset).


来源: stackexchange

问:
Import topics into Power Virtual Agent
My context is that I am trying to recreate a bot that was originally made using the deprecated Microsoft QnAMaker framework to the new Microsoft Power Virtual Agents (PVA) framework.

I have exported all my questions and answers and I have them in an Excel file (which could be converted to CSV if necessary). The key columns are Question which contains what is called "trigger phrases" in PVA and Answer (which contains what should be the text of a PVA message). One line of data is a question-answer pair. There can be only one unique question for each line of data. However, there are several duplicate answers. When two or more lines have different questions but the same answer, that means that one answer can respond to different questions, or to questions that are phrased slightly differently. This corresponds to how in PVA a single topic (answer) can have multiple trigger phrases (questions).

I would like to convert these questions and answers to the PVA bot format without having to manually copy and paste each one (I have around a hundred of them). In principle, I understand that the final result would look like this:

Each distinct QnAMaker question becomes a distinct PVA topic.

For a unique question/topic, each distinct answer becomes a distinct PVA trigger phrase for that topic.

Is there an automated way that I can do this QnAMaker-to-PVA import without manually copying and pasting each question?

ContentLicense: CC BY-SA 4.0

Title: Import topics into Power Virtual Agent


问:
Time and space complexity for leetcode's 271. Encode and Decode Strings
This is the same problem that  is posted on Lintcode as 659.

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Please implement encode and decode

I am confused about the time and space complexity for encode based on Leetcode's code.

Does the approach above really use O(n) time and space?

I think that because the strings are immutable and aren't like lists so every time we append a string, we have to create a new string after concatenating the old string and the new one, thereby getting O(n^2) space. Also because we have to find new space for the strings, we will keep on iterating through the beginning of the string multiple times giving O(n^2) complexity as well.

How can we solve the problem for encode in O(n) time and space complexity?

Piggybacking on  Leetcode's explanation, I am using join and for s in strs. I would like to confirm that this counts as a generator and as such doesn't incur the additional space that comes with concatenating strings and so would give me O(n) time and space complexity.

```<code>from typing import List
class Codec:
    def encode(self, strs: List[str]) -> str:
        """Encodes a list of strings to a single string.
        """
        # return "".join(str(len(s)) + s for s in strs)
        return "".join(f'{len(s)}#{s}' for s in strs) # does this count as a generator?

    def decode(self, s: str) -> List[str]:
        """Decodes a single string to a list of strings.
        """
        decodedStrings = []

        i = 0
        while i < len(s):
            j = s.find("#", i)

            # # could also be more fundamental & not use find
            # while s[j] != "#":
            #     j += 1

            length = int(s[i:j])
            decodedStrings.append(s[j+1 : j+1+length]) # if it is over the length of the string, it returns an empty string
            i = j+1+length

        return decodedStrings
</code>```

Body:
This is the same problem that  is posted on Lintcode as 659.

Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Please implement encode and decode

I am confused about the time and space complexity for encode based on Leetcode's code.

Does the approach above really use O(n) time and space?

I think that because the strings are immutable and aren't like lists so every time we append a string, we have to create a new string after concatenating the old string and the new one, thereby getting O(n^2) space. Also because we have to find new space for the strings, we will keep on iterating through the beginning of the string multiple times giving O(n^2) complexity as well.

How can we solve the problem for encode in O(n) time and space complexity?

Piggybacking on  Leetcode's explanation, I am using join and for s in strs. I would like to confirm that this counts as a generator and as such doesn't incur the additional space that comes with concatenating strings and so would give me O(n) time and space complexity.

from typing import List
class Codec:
    def encode(self, strs: List[str]) -> str:
        """Encodes a list of strings to a single string.
        """
        # return "".join(str(len(s)) + s for s in strs)
        return "".join(f'{len(s)}#{s}' for s in strs) # does this count as a generator?

    def decode(self, s: str) -> List[str]:
        """Decodes a single string to a list of strings.
        """
        decodedStrings = []

        i = 0
        while i < len(s):
            j = s.find("#", i)

            # # could also be more fundamental & not use find
            # while s[j] != "#":
            #     j += 1

            length = int(s[i:j])
            decodedStrings.append(s[j+1 : j+1+length]) # if it is over the length of the string, it returns an empty string
            i = j+1+length

        return decodedStrings


问:
How to add marker to last data point in matplotlib animation
How to marker only the last data point?

here is my code

```<code>def generateLines(XData, YData):
    X = XData
    Y = YData
    lineData = np.vstack((X, Y))
    return lineData

def updateLines(num, dataLines, lines):
    for u, v in zip(lines, dataLines):
        u.set_data(v[0:2, :num])
    return lines
fig, ax = plt.subplots()
data = [generateLines(XData, YData)]
ax = plt.axes(xlim=(-40, 40), ylim=(-250, 250))
</code>```

full code:

Note: I use the img for full image becauseI cant write full code here

Body:
How to marker only the last data point?

here is my code

def generateLines(XData, YData):
    X = XData
    Y = YData
    lineData = np.vstack((X, Y))
    return lineData

def updateLines(num, dataLines, lines):
    for u, v in zip(lines, dataLines):
        u.set_data(v[0:2, :num])
    return lines
fig, ax = plt.subplots()
data = [generateLines(XData, YData)]
ax = plt.axes(xlim=(-40, 40), ylim=(-250, 250))

full code:

Note: I use the img for full image becauseI cant write full code here


问:
JWT token from Azure AD is not getting decoded for some, for some its getting decoded using (python-jose)
We are facing a strange problem here, token from Azure AD is being decoded for some, while for some people it is not getting decoded because of which APIs are failing, a flask framework based app uses Azure AD authentication. Adding the code snippet to better understand

```<code>import json
from functools import wraps

from flask import request, _request_ctx_stack
from jose import jwt
from six.moves.urllib.request import urlopen
import logging

import os.path

CLIENT_ID = "client_id"
TENANT_ID = "tenant_id"
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
JWKS_URI = f"{AUTHORITY}/discovery/v2.0/keys"
#ISSUER = f"{AUTHORITY}/v2.0"
ISSUER = f"https://sts.windows.net/{TENANT_ID}/"
ALGORITHMS = ["RS256"]
AUDIENCE = f"https://{company_name}.onmicrosoft.com/{CLIENT_ID}"

def get_token_auth_header():
    """Obtains the Access Token from the Authorization Header"""
    access_token = None
    try:
        header = request.headers.get('Authorization').split(' ')
        if len(header) != 2:
            return {"error": {"code": 11, 'error': 'Token not found'}}, 401
        if header[0].lower() != "bearer":
            return {"error": {"code": 11}, 'error': 'Authorization header must be Bearer'}, 401
        access_token = header[1]
    except:
        return {"error": {"code": 11, 'error': 'Auth not found.'}}, 401
    return access_token

def validate_access_token(f):
    """ Validate the token.
        - Errors
            code: 11 - Token not allowed, something is wrong.
            code: 89 - Token has expired.
    """

    @wraps(f)
    def decorated(*args, **kwargs):

        payload = None
        token = get_token_auth_header()
        if not token:
            return {"error": {"code": 10, 'error': 'Token missing'}}, 401
        jsonurl = urlopen(JWKS_URI)
        jwks = json.loads(jsonurl.read())
        try:
            unverified_header = jwt.get_unverified_header(token)
        except:
            return {"error": {"code": 11, 'error': 'Token not allowed'}}, 401
        rsa_key = {}
        for key in jwks["keys"]:
            if key["kid"] == unverified_header["kid"]:
                rsa_key = {
                    "kty": key["kty"],
                    "kid": key["kid"],
                    "use": key["use"],
                    "n": key["n"],
                    "e": key["e"]
                }
        if rsa_key:
            try:
                payload = jwt.decode(
                    token,
                    key=rsa_key,
                    algorithms=ALGORITHMS,
                    audience=AUDIENCE,
                    issuer=ISSUER
                )
            except Exception as e:
                print('Exception', e)
                return {"error": {"code": 11, 'error': "Unable to parse authentication due to {}".format(e)}}, 401
            except jwt.ExpiredSignatureError:
                return {"error": {"code": 89, 'error': "Token is expired"}}, 401
            except jwt.JWTClaimsError:
                return {"error": {"code": 11, 'error': "Incorrect claims"}}, 401
            _request_ctx_stack.top.current_user = payload
            return f(*args, **kwargs)
        return {"error": {"code": 11, 'error': "Unable to find appropriate key"}}, 401

    return decorated
</code>```

could someone help the code used to decode is correct ?

Trying to understand if some atttribute is missing while decoding the token with the existing code as it works for some and does not work for some

Body:
We are facing a strange problem here, token from Azure AD is being decoded for some, while for some people it is not getting decoded because of which APIs are failing, a flask framework based app uses Azure AD authentication. Adding the code snippet to better understand

import json
from functools import wraps

from flask import request, _request_ctx_stack
from jose import jwt
from six.moves.urllib.request import urlopen
import logging

import os.path

CLIENT_ID = "client_id"
TENANT_ID = "tenant_id"
AUTHORITY = f"https://login.microsoftonline.com/{TENANT_ID}"
JWKS_URI = f"{AUTHORITY}/discovery/v2.0/keys"
#ISSUER = f"{AUTHORITY}/v2.0"
ISSUER = f"https://sts.windows.net/{TENANT_ID}/"
ALGORITHMS = ["RS256"]
AUDIENCE = f"https://{company_name}.onmicrosoft.com/{CLIENT_ID}"

def get_token_auth_header():
    """Obtains the Access Token from the Authorization Header"""
    access_token = None
    try:
        header = request.headers.get('Authorization').split(' ')
        if len(header) != 2:
            return {"error": {"code": 11, 'error': 'Token not found'}}, 401
        if header[0].lower() != "bearer":
            return {"error": {"code": 11}, 'error': 'Authorization header must be Bearer'}, 401
        access_token = header[1]
    except:
        return {"error": {"code": 11, 'error': 'Auth not found.'}}, 401
    return access_token

def validate_access_token(f):
    """ Validate the token.
        - Errors
            code: 11 - Token not allowed, something is wrong.
            code: 89 - Token has expired.
    """

    @wraps(f)
    def decorated(*args, **kwargs):

        payload = None
        token = get_token_auth_header()
        if not token:
            return {"error": {"code": 10, 'error': 'Token missing'}}, 401
        jsonurl = urlopen(JWKS_URI)
        jwks = json.loads(jsonurl.read())
        try:
            unverified_header = jwt.get_unverified_header(token)
        except:
            return {"error": {"code": 11, 'error': 'Token not allowed'}}, 401
        rsa_key = {}
        for key in jwks["keys"]:
            if key["kid"] == unverified_header["kid"]:
                rsa_key = {
                    "kty": key["kty"],
                    "kid": key["kid"],
                    "use": key["use"],
                    "n": key["n"],
                    "e": key["e"]
                }
        if rsa_key:
            try:
                payload = jwt.decode(
                    token,
                    key=rsa_key,
                    algorithms=ALGORITHMS,
                    audience=AUDIENCE,
                    issuer=ISSUER
                )
            except Exception as e:
                print('Exception', e)
                return {"error": {"code": 11, 'error': "Unable to parse authentication due to {}".format(e)}}, 401
            except jwt.ExpiredSignatureError:
                return {"error": {"code": 89, 'error': "Token is expired"}}, 401
            except jwt.JWTClaimsError:
                return {"error": {"code": 11, 'error': "Incorrect claims"}}, 401
            _request_ctx_stack.top.current_user = payload
            return f(*args, **kwargs)
        return {"error": {"code": 11, 'error': "Unable to find appropriate key"}}, 401

    return decorated

could someone help the code used to decode is correct ?

Trying to understand if some atttribute is missing while decoding the token with the existing code as it works for some and does not work for some


问:
MySql Data Cleanup with IF Else
```<code>IF (SELECT count(*) FROM clients) > 0 THEN
      ( TRUNCATE client_revisions )
ELSE
 ( DELETE FROM client_revisions WHERE client_id NOT IN ( SELECT id FROM clients))
END IF;
</code>```

How my I write kind of query in raw MySQL?? is it possible?
I need it for data cleanup

Thanks

Title: MySql Data Cleanup with IF Else

Body:
IF (SELECT count(*) FROM clients) > 0 THEN
      ( TRUNCATE client_revisions )
ELSE
 ( DELETE FROM client_revisions WHERE client_id NOT IN ( SELECT id FROM clients))
END IF;

How my I write kind of query in raw MySQL?? is it possible?
I need it for data cleanup

Thanks


问:
How to run only specific program on a system
So i have built a cnc machine and a custom software for it. I want to run only this software in the system as soon as it opens. For example: ATM machines run on windows but when u go in ATM u only see custom screen for it. How to do this for any other software.

I can run Microsoft apps in this fashion using kiosk but unable to run my custom built software like that.


问:
GStreamer : seek request problem in a pipeline with a mixer with pad offset
I want to mix multiple wav file. Files can have different start time.
For that, I set an offset on the pad of the mixer.

I am using gstreamer-java.

This is an example of the timeline with two files. There is a 10 sec offset for file 2.

It works fine. File 2 start as expected.
But if I do a seek request, I won't hear file 2 for the duration of its offset (here : 10 sec).
When I hear file 2 again, the file is in sync with the expected timeline.

Is it possible to do a seek request when the mixer has pad with offset ?


问:
how to edit discord message before sending using console script?
I am trying to edit the message which will be send using a console script
like I typed

```<code>hi, this is a temp message
</code>```

now when I want to change it to

```<code>hello, this is not a temp message
</code>```

so that when I press enter it send the updated message and not the old one

what I tried to far :-

I tried to edit he text using inspect element, but that didn't work, it somehow manage to store the old message

I tried to find the message stores as draft in local storage but it was not there either

I tried to debug and find the variable which stores the message (it is hard, I didn't finish it yet)

explanation or position of the stored message

Body:
I am trying to edit the message which will be send using a console script
like I typed

hi, this is a temp message

now when I want to change it to

hello, this is not a temp message

so that when I press enter it send the updated message and not the old one

what I tried to far :-

I tried to edit he text using inspect element, but that didn't work, it somehow manage to store the old message

I tried to find the message stores as draft in local storage but it was not there either

I tried to debug and find the variable which stores the message (it is hard, I didn't finish it yet)

explanation or position of the stored message


问:
Why SharePoint remote event receiver calls Azure Function six times?
I have a list in SharePoint that has a synchronous event receiver attached to it that responds to the change event of the list item (ItemUpdating). There is also an Azure Function that the event receiver calls. The function validates the fields. The question is that if the field is validated, then the function is run once, but if the validation is not passed, then the event receiver runs the function six times.

```<code>using namespace System.Net;

param($Request, $TriggerMetadata);
Write-Output "Function started.";

$xmlDocument=[xml]$Request.Body;
$ListItemTitle = $xmlDocument.Envelope.Body.ProcessEvent.properties.ItemEventProperties.AfterProperties.KeyValueOfstringanyType[1].Value.InnerText;
$listName = $xmlDocument.Envelope.Body.ProcessEvent.properties.ItemEventProperties.ListTitle;

Write-Output $ListItemTitle;
Write-Output $listName;

$responseBody = @'
<s:Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <ProcessEventResponse
            xmlns="http://schemas.microsoft.com/sharepoint/remoteapp/">
            <ProcessEventResult
                xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <ChangedItemProperties
                    xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
                <ErrorMessage>Validation Error!</ErrorMessage>
                <RedirectUrl i:nil="true"/>
                <Status>CancelWithError</Status>
            </ProcessEventResult>
        </ProcessEventResponse>
    </s:Body>
</s:Envelope>
'@;

if($ListItemTitle -eq "BadTitle"){
    Write-Output "Validation error!";
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        Body = $responseBody;
        ContentType = "text/xml";
        StatusCode = [HttpStatusCode]::OK;
    });
}
else{
    Write-Output "Validation passed.";
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [HttpStatusCode]::OK;
    });
}

</code>```

How can I make the function run once when validation fails?

Body:
I have a list in SharePoint that has a synchronous event receiver attached to it that responds to the change event of the list item (ItemUpdating). There is also an Azure Function that the event receiver calls. The function validates the fields. The question is that if the field is validated, then the function is run once, but if the validation is not passed, then the event receiver runs the function six times.

using namespace System.Net;

param($Request, $TriggerMetadata);
Write-Output "Function started.";

$xmlDocument=[xml]$Request.Body;
$ListItemTitle = $xmlDocument.Envelope.Body.ProcessEvent.properties.ItemEventProperties.AfterProperties.KeyValueOfstringanyType[1].Value.InnerText;
$listName = $xmlDocument.Envelope.Body.ProcessEvent.properties.ItemEventProperties.ListTitle;

Write-Output $ListItemTitle;
Write-Output $listName;

$responseBody = @'
<s:Envelope
    xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <ProcessEventResponse
            xmlns="http://schemas.microsoft.com/sharepoint/remoteapp/">
            <ProcessEventResult
                xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
                <ChangedItemProperties
                    xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"/>
                <ErrorMessage>Validation Error!</ErrorMessage>
                <RedirectUrl i:nil="true"/>
                <Status>CancelWithError</Status>
            </ProcessEventResult>
        </ProcessEventResponse>
    </s:Body>
</s:Envelope>
'@;

if($ListItemTitle -eq "BadTitle"){
    Write-Output "Validation error!";
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        Body = $responseBody;
        ContentType = "text/xml";
        StatusCode = [HttpStatusCode]::OK;
    });
}
else{
    Write-Output "Validation passed.";
    Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
        StatusCode = [HttpStatusCode]::OK;
    });
}

How can I make the function run once when validation fails?


问:
Odoo v15, better way to write this .xml?
Is it a better way to write this code? I think is not very clean to write the same attr 3 times, it could be better if I can have 3 expr in the same xpath tag

```<code><record id="sale_margin_sale_order_inherit" model="ir.ui.view">
    <field name="name">sale.margin.sale.order.inherit</field>
    <field name="model">sale.order</field>
    <field name="inherit_id" ref="sale_margin.sale_margin_sale_order"/>
    <field name="arch" type="xml">
        <xpath expr="//field[@name='margin']" position="attributes">
            <attribute name="invisible">1</attribute>
        </xpath>
        <xpath expr="//span[hasclass('oe_inline')]" position="attributes">
            <attribute name="invisible">1</attribute>
        </xpath>
        <xpath expr="//label[@for='margin']" position="attributes">
            <attribute name="invisible">1</attribute>
        </xpath>
    </field>
</record>
</code>```

Body:
Is it a better way to write this code? I think is not very clean to write the same attr 3 times, it could be better if I can have 3 expr in the same xpath tag

<record id="sale_margin_sale_order_inherit" model="ir.ui.view">
    <field name="name">sale.margin.sale.order.inherit</field>
    <field name="model">sale.order</field>
    <field name="inherit_id" ref="sale_margin.sale_margin_sale_order"/>
    <field name="arch" type="xml">
        <xpath expr="//field[@name='margin']" position="attributes">
            <attribute name="invisible">1</attribute>
        </xpath>
        <xpath expr="//span[hasclass('oe_inline')]" position="attributes">
            <attribute name="invisible">1</attribute>
        </xpath>
        <xpath expr="//label[@for='margin']" position="attributes">
            <attribute name="invisible">1</attribute>
        </xpath>
    </field>
</record>


问:
TimePicker component was moved from `@mui/lab` to `@mui/x-date-pickers`
I use formik-mui-lab to make  DatePicker but this warning appears
MUI: The TimePicker component was moved from @mui/lab to @mui/x-date-pickers.

You should use import { TimePicker } from '@mui/x-date-pickers'
or import { TimePicker } from '@mui/x-date-pickers/TimePicker'

nots i want to use formik-mui-lab note @mui/lab
https://stackworx.github.io/formik-mui/docs/api/mui-lab // link site

You should use import { TimePicker } from '@mui/x-date-pickers'
or import { TimePicker } from '@mui/x-date-pickers/TimePicker'


问:
Electron-builder uses wrong filename in https request when trying to fetch the latest release
I am building an application in electron and currently I'm trying to implement electron-builders autoUpdate. I have one private repository with my source code and one public repository where I want to release the updated artifacts of my app.

The process looks like the folliwing:

Install v1 of app on computer

Build v2 of app

Publish v2 of app on github

Open v1 of app on computer -> starts downloading newer version

My application is able to recognise that there is a new release published on github but when it tries to download it generates the wrong url. I get the following error message

error Cannot download "https://github.com/user/repo/releases/download/v2/application-1-universal-mac.zip", status 404:

To me the problem seems to be that in the request the wrong version number is being used. It uses the artifact name "application-1-universal-mac.zip" instead of "application-2-universal-mac.zip" which is uploaded.

In package.json I have tried to change:

```<code>"build": {
   "artifactName": "appName.${ext}",
   "executableName": "lol",
   "buildVersion": "400",
   "productName": "app",
 }
</code>```

which changes the name of the file but in the request it always uses the default

"node-app-${version}.${ext}"

Does anyone have a clue which variable electron-builder is looking at when generating file name in the request?

Body:
I am building an application in electron and currently I'm trying to implement electron-builders autoUpdate. I have one private repository with my source code and one public repository where I want to release the updated artifacts of my app.

The process looks like the folliwing:

Install v1 of app on computer

Build v2 of app

Publish v2 of app on github

Open v1 of app on computer -> starts downloading newer version

My application is able to recognise that there is a new release published on github but when it tries to download it generates the wrong url. I get the following error message

error Cannot download "https://github.com/user/repo/releases/download/v2/application-1-universal-mac.zip", status 404:

To me the problem seems to be that in the request the wrong version number is being used. It uses the artifact name "application-1-universal-mac.zip" instead of "application-2-universal-mac.zip" which is uploaded.

In package.json I have tried to change:

"build": {
   "artifactName": "appName.${ext}",
   "executableName": "lol",
   "buildVersion": "400",
   "productName": "app",
 }

which changes the name of the file but in the request it always uses the default

"node-app-${version}.${ext}"

Does anyone have a clue which variable electron-builder is looking at when generating file name in the request?


问:
Deployment to AWS ECS using Github Actions is failing
I have written a github actions workflow yaml file by following this guide. The workflow file is added below:-

```<code>name: Deploy to Staging Amazon ECS

on:
  push:
    branches:
      - staging

env:
  ECR_REPOSITORY: api-staging-jruby/api
  ECS_CLUSTER: api_staging
  J_RUBY_ECS_SERVICE: web-staging
  J_RUBY_ECS_TASK_DEFINITION: infrastructure/staging/web-jruby-task-definition.json
  J_RUBY_CONTAINER_NAME: api-staging-jruby
  ANALYTICS_ECS_SERVICE: analytics-staging
  ANALYTICS_ECS_TASK_DEFINITION: infrastructure/staging/analytics-task-definition.json
  ANALYTICS_CONTAINER_NAME: analytics-staging
  WORKER_ECS_SERVICE: worker-staging
  WORKER_ECS_TASK_DEFINITION: infrastructure/staging/worker-task-definition.json
  WORKER_CONTAINER_NAME: sidekiq-staging
  CONSOLE_ECS_SERVICE: console-staging
  CONSOLE_ECS_TASK_DEFINITION: infrastructure/staging/console-task-definition.json
  CONSOLE_CONTAINER_NAME: api-console-staging

jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest
    environment: staging

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@13d241b293754004c80624b5567555c4a39ffbe3
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_DEFAULT_REGION }}

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@aaf69d68aa3fb14c1d5a6be9ac61fe15b48453a2

      - name: Build, tag, and push image to Amazon ECR
        id: build-image
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          IMAGE_TAG: ${{ github.sha }}
        run: |
          # Build a docker container and
          # push it to ECR so that it can
          # be deployed to ECS.
          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
          echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT

      - name: Fill in the new image ID in the Amazon ECS task definition (JRuby)
        id: task-def-jruby
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.J_RUBY_ECS_TASK_DEFINITION }}
          container-name: ${{ env.J_RUBY_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (JRuby)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-jruby.outputs.task-definition }}
          service: ${{ env.J_RUBY_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true

      - name: Fill in the new image ID in the Amazon ECS task definition (Analytics)
        id: task-def-analytics
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.ANALYTICS_ECS_TASK_DEFINITION }}
          container-name: ${{ env.ANALYTICS_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (Analytics)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-analytics.outputs.task-definition }}
          service: ${{ env.ANALYTICS_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true

      - name: Fill in the new image ID in the Amazon ECS task definition (Worker)
        id: task-def-worker
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.WORKER_ECS_TASK_DEFINITION }}
          container-name: ${{ env.WORKER_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (Worker)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-worker.outputs.task-definition }}
          service: ${{ env.WORKER_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true

      - name: Fill in the new image ID in the Amazon ECS task definition (Console)
        id: task-def-console
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.CONSOLE_ECS_TASK_DEFINITION }}
          container-name: ${{ env.CONSOLE_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (Worker)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-console.outputs.task-definition }}
          service: ${{ env.CONSOLE_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true
</code>```

The workflow is failing in the step Deploy Amazon ECS task definition (JRuby) and I am unable to debug the cause of the issue.

I have also confirmed the image is uploaded into ECR. I turned on the debug logs to check them. Here's is the stack track:-

```<code>##[debug]Evaluating condition for step: 'Deploy Amazon ECS task definition (JRuby)'
##[debug]Evaluating: success()
##[debug]Evaluating success:
##[debug]=> true
##[debug]Result: true
##[debug]Starting: Deploy Amazon ECS task definition (JRuby)
##[debug]Loading inputs
##[debug]Evaluating: steps.task-def-jruby.outputs.task-definition
##[debug]Evaluating Index:
##[debug]..Evaluating Index:
##[debug]....Evaluating Index:
##[debug]......Evaluating steps:
##[debug]......=> Object
##[debug]......Evaluating String:
##[debug]......=> 'task-def-jruby'
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'outputs'
##[debug]..=> Object
##[debug]..Evaluating String:
##[debug]..=> 'task-definition'
##[debug]=> '/home/runner/work/_temp/task-definition--16224-xjXb92vYNt3B-.json'
##[debug]Result: '/home/runner/work/_temp/task-definition--16224-xjXb92vYNt3B-.json'
##[debug]Evaluating: env.J_RUBY_ECS_SERVICE
##[debug]Evaluating Index:
##[debug]..Evaluating env:
##[debug]..=> Object
##[debug]..Evaluating String:
##[debug]..=> 'J_RUBY_ECS_SERVICE'
##[debug]=> 'web-staging'
##[debug]Result: 'web-staging'
##[debug]Evaluating: env.ECS_CLUSTER
##[debug]Evaluating Index:
##[debug]..Evaluating env:
##[debug]..=> Object
##[debug]..Evaluating String:
##[debug]..=> 'ECS_CLUSTER'
##[debug]=> 'api_staging'
##[debug]Result: 'api_staging'
##[debug]Loading env
Run aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
##[debug]Registering the task definition

::set-output name=task-definition-arn::arn:aws:ecs:***:***:task-definition/web-staging-jruby:91
Warning: The `set-output` command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more information see: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
##[debug]='arn:aws:ecs:***:***:task-definition/web-staging-jruby:91'
##[debug]Updating the service
Error: The container api-staging does not exist in the task definition.
##[debug]InvalidParameterException: The container api-staging does not exist in the task definition.
##[debug]    at Request.extractError (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:19497:27)
##[debug]    at Request.callListeners (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:22778:20)
##[debug]    at Request.emit (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:22750:10)
##[debug]    at Request.emit (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:21384:14)
##[debug]    at Request.transition (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:20720:10)
##[debug]    at AcceptorStateMachine.runTo (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:27746:12)
##[debug]    at /home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:27758:10
##[debug]    at Request.<anonymous> (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:20736:9)
##[debug]    at Request.<anonymous> (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:21386:12)
##[debug]    at Request.callListeners (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:22788:18)
##[debug]Node Action run completed with exit code 1
##[debug]Finishing: Deploy Amazon ECS task definition (JRuby)
</code>```

As you can see from the above stack trace that api-staging is nowhere mentioned in the workflow yaml file. This is the reason I am unable to debug it. We are already deploying manually using a shell-script. So we are reusing the same cluster and services. There is a chance api-staging is coming from AWS but I am not 100% sure.

Edit:

Content of web-jruby-task-definition.json:

```<code>{
  "cpu": "2048",
  "memory": "5120",
  "networkMode": "awsvpc",
  "executionRoleArn": "arn:aws:iam::<account_id>:role/ecsTaskExecutionRole",
  "requiresCompatibilities": [
       "FARGATE"
    ],
  "containerDefinitions": [
    {
      "name": "api-staging-jruby",
      "image": "<account_id>.dkr.ecr.<region>.amazonaws.com/api-staging/api:latest",
      "dockerLabels": {
                    "com.datadoghq.ad.instances": "[{\"host\": \"%%host%%\", \"port\": 8000}]",
                    "com.datadoghq.ad.check_names": "[\"api-staging\"]",
                    "com.datadoghq.ad.init_configs": "[{}]"
                },
      "portMappings": [
        {
          "containerPort": 8000,
          "hostPort": 8000
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "api-staging",
          "awslogs-region": "<region>",
          "awslogs-stream-prefix": "jruby-staging-api"
        }
      },
      "secrets": [
        {
          "name": "ELASTIC_SEARCH_URL",
          "valueFrom": "arn:aws:secretsmanager:<region>:<account_id>:secret:staging/ELASTIC_SEARCH_URL-<id>"
        },
        ...
      ]
    },
    {
      "name": "datadog-agent",
      "image": "datadog/agent:latest",
      "essential": true,
      "secrets": [
        {
          "name": "DD_API_KEY",
          "valueFrom": "arn:aws:secretsmanager:<region>:<account_id>:secret:staging/environment-name-<id>"
        },
        ...
      ]
    }
  ],
  "family": "web-staging-jruby"
}
</code>```

Body:
I have written a github actions workflow yaml file by following this guide. The workflow file is added below:-

name: Deploy to Staging Amazon ECS

on:
  push:
    branches:
      - staging

env:
  ECR_REPOSITORY: api-staging-jruby/api
  ECS_CLUSTER: api_staging
  J_RUBY_ECS_SERVICE: web-staging
  J_RUBY_ECS_TASK_DEFINITION: infrastructure/staging/web-jruby-task-definition.json
  J_RUBY_CONTAINER_NAME: api-staging-jruby
  ANALYTICS_ECS_SERVICE: analytics-staging
  ANALYTICS_ECS_TASK_DEFINITION: infrastructure/staging/analytics-task-definition.json
  ANALYTICS_CONTAINER_NAME: analytics-staging
  WORKER_ECS_SERVICE: worker-staging
  WORKER_ECS_TASK_DEFINITION: infrastructure/staging/worker-task-definition.json
  WORKER_CONTAINER_NAME: sidekiq-staging
  CONSOLE_ECS_SERVICE: console-staging
  CONSOLE_ECS_TASK_DEFINITION: infrastructure/staging/console-task-definition.json
  CONSOLE_CONTAINER_NAME: api-console-staging

jobs:
  deploy:
    name: Deploy
    runs-on: ubuntu-latest
    environment: staging

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Configure AWS credentials
        uses: aws-actions/configure-aws-credentials@13d241b293754004c80624b5567555c4a39ffbe3
        with:
          aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
          aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
          aws-region: ${{ secrets.AWS_DEFAULT_REGION }}

      - name: Login to Amazon ECR
        id: login-ecr
        uses: aws-actions/amazon-ecr-login@aaf69d68aa3fb14c1d5a6be9ac61fe15b48453a2

      - name: Build, tag, and push image to Amazon ECR
        id: build-image
        env:
          ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
          IMAGE_TAG: ${{ github.sha }}
        run: |
          # Build a docker container and
          # push it to ECR so that it can
          # be deployed to ECS.
          docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
          docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
          echo "image=$ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG" >> $GITHUB_OUTPUT

      - name: Fill in the new image ID in the Amazon ECS task definition (JRuby)
        id: task-def-jruby
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.J_RUBY_ECS_TASK_DEFINITION }}
          container-name: ${{ env.J_RUBY_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (JRuby)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-jruby.outputs.task-definition }}
          service: ${{ env.J_RUBY_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true

      - name: Fill in the new image ID in the Amazon ECS task definition (Analytics)
        id: task-def-analytics
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.ANALYTICS_ECS_TASK_DEFINITION }}
          container-name: ${{ env.ANALYTICS_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (Analytics)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-analytics.outputs.task-definition }}
          service: ${{ env.ANALYTICS_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true

      - name: Fill in the new image ID in the Amazon ECS task definition (Worker)
        id: task-def-worker
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.WORKER_ECS_TASK_DEFINITION }}
          container-name: ${{ env.WORKER_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (Worker)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-worker.outputs.task-definition }}
          service: ${{ env.WORKER_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true

      - name: Fill in the new image ID in the Amazon ECS task definition (Console)
        id: task-def-console
        uses: aws-actions/amazon-ecs-render-task-definition@v1.1.2
        with:
          task-definition: ${{ env.CONSOLE_ECS_TASK_DEFINITION }}
          container-name: ${{ env.CONSOLE_CONTAINER_NAME }}
          image: ${{ steps.build-image.outputs.image }}

      - name: Deploy Amazon ECS task definition (Worker)
        uses: aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
        with:
          task-definition: ${{ steps.task-def-console.outputs.task-definition }}
          service: ${{ env.CONSOLE_ECS_SERVICE }}
          cluster: ${{ env.ECS_CLUSTER }}
          wait-for-service-stability: true

The workflow is failing in the step Deploy Amazon ECS task definition (JRuby) and I am unable to debug the cause of the issue.

I have also confirmed the image is uploaded into ECR. I turned on the debug logs to check them. Here's is the stack track:-

##[debug]Evaluating condition for step: 'Deploy Amazon ECS task definition (JRuby)'
##[debug]Evaluating: success()
##[debug]Evaluating success:
##[debug]=> true
##[debug]Result: true
##[debug]Starting: Deploy Amazon ECS task definition (JRuby)
##[debug]Loading inputs
##[debug]Evaluating: steps.task-def-jruby.outputs.task-definition
##[debug]Evaluating Index:
##[debug]..Evaluating Index:
##[debug]....Evaluating Index:
##[debug]......Evaluating steps:
##[debug]......=> Object
##[debug]......Evaluating String:
##[debug]......=> 'task-def-jruby'
##[debug]....=> Object
##[debug]....Evaluating String:
##[debug]....=> 'outputs'
##[debug]..=> Object
##[debug]..Evaluating String:
##[debug]..=> 'task-definition'
##[debug]=> '/home/runner/work/_temp/task-definition--16224-xjXb92vYNt3B-.json'
##[debug]Result: '/home/runner/work/_temp/task-definition--16224-xjXb92vYNt3B-.json'
##[debug]Evaluating: env.J_RUBY_ECS_SERVICE
##[debug]Evaluating Index:
##[debug]..Evaluating env:
##[debug]..=> Object
##[debug]..Evaluating String:
##[debug]..=> 'J_RUBY_ECS_SERVICE'
##[debug]=> 'web-staging'
##[debug]Result: 'web-staging'
##[debug]Evaluating: env.ECS_CLUSTER
##[debug]Evaluating Index:
##[debug]..Evaluating env:
##[debug]..=> Object
##[debug]..Evaluating String:
##[debug]..=> 'ECS_CLUSTER'
##[debug]=> 'api_staging'
##[debug]Result: 'api_staging'
##[debug]Loading env
Run aws-actions/amazon-ecs-deploy-task-definition@v1.4.10
##[debug]Registering the task definition

::set-output name=task-definition-arn::arn:aws:ecs:***:***:task-definition/web-staging-jruby:91
Warning: The `set-output` command is deprecated and will be disabled soon. Please upgrade to using Environment Files. For more information see: https://github.blog/changelog/2022-10-11-github-actions-deprecating-save-state-and-set-output-commands/
##[debug]='arn:aws:ecs:***:***:task-definition/web-staging-jruby:91'
##[debug]Updating the service
Error: The container api-staging does not exist in the task definition.
##[debug]InvalidParameterException: The container api-staging does not exist in the task definition.
##[debug]    at Request.extractError (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:19497:27)
##[debug]    at Request.callListeners (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:22778:20)
##[debug]    at Request.emit (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:22750:10)
##[debug]    at Request.emit (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:21384:14)
##[debug]    at Request.transition (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:20720:10)
##[debug]    at AcceptorStateMachine.runTo (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:27746:12)
##[debug]    at /home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:27758:10
##[debug]    at Request.<anonymous> (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:20736:9)
##[debug]    at Request.<anonymous> (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:21386:12)
##[debug]    at Request.callListeners (/home/runner/work/_actions/aws-actions/amazon-ecs-deploy-task-definition/v1.4.10/dist/index.js:22788:18)
##[debug]Node Action run completed with exit code 1
##[debug]Finishing: Deploy Amazon ECS task definition (JRuby)

As you can see from the above stack trace that api-staging is nowhere mentioned in the workflow yaml file. This is the reason I am unable to debug it. We are already deploying manually using a shell-script. So we are reusing the same cluster and services. There is a chance api-staging is coming from AWS but I am not 100% sure.

Edit:

Content of web-jruby-task-definition.json:

{
  "cpu": "2048",
  "memory": "5120",
  "networkMode": "awsvpc",
  "executionRoleArn": "arn:aws:iam::<account_id>:role/ecsTaskExecutionRole",
  "requiresCompatibilities": [
       "FARGATE"
    ],
  "containerDefinitions": [
    {
      "name": "api-staging-jruby",
      "image": "<account_id>.dkr.ecr.<region>.amazonaws.com/api-staging/api:latest",
      "dockerLabels": {
                    "com.datadoghq.ad.instances": "[{\"host\": \"%%host%%\", \"port\": 8000}]",
                    "com.datadoghq.ad.check_names": "[\"api-staging\"]",
                    "com.datadoghq.ad.init_configs": "[{}]"
                },
      "portMappings": [
        {
          "containerPort": 8000,
          "hostPort": 8000
        }
      ],
      "logConfiguration": {
        "logDriver": "awslogs",
        "options": {
          "awslogs-group": "api-staging",
          "awslogs-region": "<region>",
          "awslogs-stream-prefix": "jruby-staging-api"
        }
      },
      "secrets": [
        {
          "name": "ELASTIC_SEARCH_URL",
          "valueFrom": "arn:aws:secretsmanager:<region>:<account_id>:secret:staging/ELASTIC_SEARCH_URL-<id>"
        },
        ...
      ]
    },
    {
      "name": "datadog-agent",
      "image": "datadog/agent:latest",
      "essential": true,
      "secrets": [
        {
          "name": "DD_API_KEY",
          "valueFrom": "arn:aws:secretsmanager:<region>:<account_id>:secret:staging/environment-name-<id>"
        },
        ...
      ]
    }
  ],
  "family": "web-staging-jruby"
}


问:
Calling outside function inside an object JS

const calculateBMI = function (weight, height) {
   let BMI = weight / height ** 2;
   return BMI;
};

const marksData = {
   height: 1.69,
   weight: 78,
   msBMI: calculateBMI(this.weight, this.height),
};

const johnsData = {
   height: 1.95,
   weight: 92,
   jsBMI: calculateBMI(this.weight, this.height),
};

console.log(marksData.msBMI);
console.log("something");
console.log(johnsData.jsBMI);```
</div>
</div>
</p>
<p>I don't know why the output of the function "const calculateBMI" inside two objects ("marksData" and "johnsData") is <strong>NaN</strong>, the problem I see here, is that the object:</p>
```const marksData = {
   height: 1.69,
   weight: 78,
   msBMI: calculateBMI(this.weight, this.height),
};
```
<p>is not catching a value of :</p>
```height: 1.69,
weight: 78,
```

like something is wrong whit this syntax (this.weight, this.height)

Body:
const calculateBMI = function (weight, height) {
   let BMI = weight / height ** 2;
   return BMI;
};

const marksData = {
   height: 1.69,
   weight: 78,
   msBMI: calculateBMI(this.weight, this.height),
};

const johnsData = {
   height: 1.95,
   weight: 92,
   jsBMI: calculateBMI(this.weight, this.height),
};

console.log(marksData.msBMI);
console.log("something");
console.log(johnsData.jsBMI);

I don't know why the output of the function "const calculateBMI" inside two objects ("marksData" and "johnsData") is NaN, the problem I see here, is that the object:

const marksData = {
   height: 1.69,
   weight: 78,
   msBMI: calculateBMI(this.weight, this.height),
};

is not catching a value of :

height: 1.69,
weight: 78,

like something is wrong whit this syntax (this.weight, this.height)


问:
How do i rename the "Show Filterbar" / "Hide Filterbar" Button Text of a Filterbar?
Working with the sap.ui.comp.filterbar.FilterBar.
This is what ive tried so far:

```<code>onInit():
var oFilterbar = this.getView().byId("filterBar");
            oFilterbar._oHideShowButton.setProperty("text", "Anzeigen");
            oFilterbar._oHideShowButton.setAggregation("tooltip", "Anzeigen");
</code>```

This does rename the button... until u press it. Then its back to "Hide Filter Bar" and "Show Filter Bar".

also onInit():

```<code>oFilterbar.addEventDelegate({
                onclick: (oEvent) => {
                    if(oEvent.target.id.includes("btnShowHide")) {
                            oFilterbar._oHideShowButton.setProperty("text", "Anzeigen");
                            oFilterbar._oHideShowButton.setAggregation("tooltip", "Anzeigen");
                    }
                  },
              });
</code>```

This one is being called everytime u press the Show/Hide Button but doesnt do anything. Im guessing that is because the original button renaming event happens after.

Thankful for any ideas

Body:
Working with the sap.ui.comp.filterbar.FilterBar.
This is what ive tried so far:

onInit():
var oFilterbar = this.getView().byId("filterBar");
            oFilterbar._oHideShowButton.setProperty("text", "Anzeigen");
            oFilterbar._oHideShowButton.setAggregation("tooltip", "Anzeigen");

This does rename the button... until u press it. Then its back to "Hide Filter Bar" and "Show Filter Bar".

also onInit():

oFilterbar.addEventDelegate({
                onclick: (oEvent) => {
                    if(oEvent.target.id.includes("btnShowHide")) {
                            oFilterbar._oHideShowButton.setProperty("text", "Anzeigen");
                            oFilterbar._oHideShowButton.setAggregation("tooltip", "Anzeigen");
                    }
                  },
              });

This one is being called everytime u press the Show/Hide Button but doesnt do anything. Im guessing that is because the original button renaming event happens after.

Thankful for any ideas


问:
Optimal index in Postgres for append-only transaction log table?
I have a table in Postgres that stores chat room presence events (join/leave) events.  The events are only ever inserted (never updated or deleted).

```<code>presence_event
-- id (bigint)
-- user_id (bigint, FK -> "user"."id")
-- channel_id (bigint, FK -> "channel"."id")
-- created_at (timestamptz)
-- event (char "join" or "leave")
</code>```

Over a long period of time this table contains several billion rows, but the only online query I will be doing is counting join and leave events grouped by (user_id, channel_id) within a recent sliding window (now - 1 hour).

Is there a way that I can have postgres maintain an index only on rows created within a specific time (now - 1 hour)?  Otherwise I fear the index will be become enormous with nearly all the rows being irrelevant.

Body:
I have a table in Postgres that stores chat room presence events (join/leave) events.  The events are only ever inserted (never updated or deleted).

presence_event
-- id (bigint)
-- user_id (bigint, FK -> "user"."id")
-- channel_id (bigint, FK -> "channel"."id")
-- created_at (timestamptz)
-- event (char "join" or "leave")

Over a long period of time this table contains several billion rows, but the only online query I will be doing is counting join and leave events grouped by (user_id, channel_id) within a recent sliding window (now - 1 hour).

Is there a way that I can have postgres maintain an index only on rows created within a specific time (now - 1 hour)?  Otherwise I fear the index will be become enormous with nearly all the rows being irrelevant.


问:
Is there some way to circumvent sluggish Android Studio editor after debugging?
Every time I make debugging in a system written in Kotlin (I think the same thing should happen in Java) inside Android Studio the editor becomes extremely slow, even after stop running the code, forcing myself to write in another editor and after use copy & paste.

The longer it passes, it seems that Android Studio's IDE slowly recovers its agility. It's insane.

Since Android Studio's support is not very responsive, I appeal to someone who also goes through this situation and has found some practical solution different from restarting Android Studio again and again.

In any case, I've posted on the Android Studio Issue Tracker, something that has always been useless.

PS: I always use the most updated stable version from Android Studio.


问:
Python Path For Local Import Git Bash
How should git bash be set up to run an non pip installed python library?

I am trying to run a Python library that I have git cloned (not pip installed) on Windows using git bash. I keep getting an error that the module cannot be found even though I have set the $PYTHONPATH to point to this folder.

This occurs both when using a venv and the base environment.

I've activated the venv using the activate command in the venv folder, and then added the folder to the PYTHONPATH as is shown here (excuse the blanking):

The first line shows the error I get when running the script which calls in other modules. The second shows my PYTHONPATH, the third my PATH

Adding the local folder to the path is how this functionality works on mac.

This the particular file that is meant to run, datagen.py:

```<code>#!/usr/bin/env python
from msq_data_gen.cli import cli

if __name__ == '__main__':
    cli.datagen()
</code>```

The code fails on the first import of msq_data_gen.

The structure of the program is as so:

Curiously, the integrated running of Pycharm works correctly, but as the code is based off a CLI, this isn't the intended usecase. (I could also use the unit testing mode for click, but I think an answer for this could be useful for other people!)

Title: Python Path For Local Import Git Bash

Body:
How should git bash be set up to run an non pip installed python library?

I am trying to run a Python library that I have git cloned (not pip installed) on Windows using git bash. I keep getting an error that the module cannot be found even though I have set the $PYTHONPATH to point to this folder.

This occurs both when using a venv and the base environment.

I've activated the venv using the activate command in the venv folder, and then added the folder to the PYTHONPATH as is shown here (excuse the blanking):

The first line shows the error I get when running the script which calls in other modules. The second shows my PYTHONPATH, the third my PATH

Adding the local folder to the path is how this functionality works on mac.

This the particular file that is meant to run, datagen.py:

#!/usr/bin/env python
from msq_data_gen.cli import cli

if __name__ == '__main__':
    cli.datagen()

The code fails on the first import of msq_data_gen.

The structure of the program is as so:

Curiously, the integrated running of Pycharm works correctly, but as the code is based off a CLI, this isn't the intended usecase. (I could also use the unit testing mode for click, but I think an answer for this could be useful for other people!)


问:
Using orderBy for custom sorting in Spring Boot
I'm unable to figure out the Spring query for my SQL query

```<code>SELECT person_name, role FROM persons
GROUP BY person_name, role
ORDER BY ROLE = 'viewer',
     ROLE = 'participant',
     ROLE = 'collaborator',
     ROLE = 'lead';
</code>```

I tried

```<code>select(field("person_name"), field("role"))
 .from(table("person")
 .groupBy(field("person_name"), field("role"))
 .orderBy((field("role").equals("viewer")).and(field("role").equals("participant")).and(
               field("role").equals("collaborator")).and(field("role").equals("lead")));
</code>```

but no luck.

If I do orderBy(role) then I'm getting ascending order result like
collaborator > lead > participant > viewer

But I'm expecting lead > collaborator > participant > viewer

Body:
I'm unable to figure out the Spring query for my SQL query

SELECT person_name, role FROM persons
GROUP BY person_name, role
ORDER BY ROLE = 'viewer',
     ROLE = 'participant',
     ROLE = 'collaborator',
     ROLE = 'lead';

I tried

select(field("person_name"), field("role"))
 .from(table("person")
 .groupBy(field("person_name"), field("role"))
 .orderBy((field("role").equals("viewer")).and(field("role").equals("participant")).and(
               field("role").equals("collaborator")).and(field("role").equals("lead")));

but no luck.

If I do orderBy(role) then I'm getting ascending order result like
collaborator > lead > participant > viewer

But I'm expecting lead > collaborator > participant > viewer


问:
Python 3 Action Chains click on element behaves as right click when mobile phone touch screen is enabled
I have a driver using selenium.
If you enter the inspect mode you can toggle the mobile pone view in which window size imitates a mobile phone and instead of a mouse there is a touch simulator.

My problem is that sometimes when I use ActionChains to perform some clicks instead of a left click it performs a right click and I don't know neither why is that nor how to solve it.

Using ActionChains is mandatory by the way. Here are some examples of what I tried

```<code>element = driver.find_element(By.XPATH, "xpath to it")

action=ActionChains(browser)
action.move_to_element(element).click().perform()

#Alternative way from the above
action.w3c_actions.pointer_action.click(element)
action.perform()
</code>```

While this work on some elements it is not consistent and sometimes it acts as a right click. What am I doing wrong?

By the way, to reach this mobile emulation I do the following

```<code>browser.execute_cdp_cmd('Emulation.setDeviceMetricsOverride', emulation) #emulation is a dict with heigh and width of screen
browser.execute_cdp_cmd('Page.setDeviceMetricsOverride', emulation)

config, enabled = 'mobile', True
browser.execute_cdp_cmd('Emulation.setEmitTouchEventsForMouse', {'enabled': enabled, 'configuration': config})

maxpoints = 3
browser.execute_cdp_cmd('Emulation.setTouchEmulationEnabled', {'enabled': enabled, 'maxTouchPoints': maxpoints})
</code>```

Body:
I have a driver using selenium.
If you enter the inspect mode you can toggle the mobile pone view in which window size imitates a mobile phone and instead of a mouse there is a touch simulator.

My problem is that sometimes when I use ActionChains to perform some clicks instead of a left click it performs a right click and I don't know neither why is that nor how to solve it.

Using ActionChains is mandatory by the way. Here are some examples of what I tried

element = driver.find_element(By.XPATH, "xpath to it")

action=ActionChains(browser)
action.move_to_element(element).click().perform()

#Alternative way from the above
action.w3c_actions.pointer_action.click(element)
action.perform()

While this work on some elements it is not consistent and sometimes it acts as a right click. What am I doing wrong?

By the way, to reach this mobile emulation I do the following

browser.execute_cdp_cmd('Emulation.setDeviceMetricsOverride', emulation) #emulation is a dict with heigh and width of screen
browser.execute_cdp_cmd('Page.setDeviceMetricsOverride', emulation)

config, enabled = 'mobile', True
browser.execute_cdp_cmd('Emulation.setEmitTouchEventsForMouse', {'enabled': enabled, 'configuration': config})

maxpoints = 3
browser.execute_cdp_cmd('Emulation.setTouchEmulationEnabled', {'enabled': enabled, 'maxTouchPoints': maxpoints})


问:
Rsyslog regex extract trigrams from hostname
I have difficulties to find a way to extract a trigram from the %hostname% var in rsyslog conf to create a path with POSIX regex.

My logic was to take the 3 characters before the first digit of the hostname.

Any ideas to have this result from only one regex ? I tried to find solutions on forum/website but none works for my case. i know that positioning lookbehind and lookforward does not work with POSIX

Hope you can help me with this one.

thx !

exemple: zyabc01da and need to keep the abc trigrams to make something like this /LOGS/abc/hostname/*.logs

i tried regex like this one (.{3}[\d]) or (.{3}[\D]), but i can't get rid of the first digit and the only solution i have is to make a second regex ([\D]+)


问:
How to prevent EF Core Code First from scaffolding SQL Server Views
I know SQL Server views are supported in EF Core.  Using the code first approach, EF Core 7 keeps scaffolding my SQL Server Views.  I do not want it to.  The only way I've been able to accomplish this it to use

```<code>modelBuilder.Ignore<LogBudgetView>();
</code>```

I then have to comment that out after scaffolding because if I don't then EF Core won't recognize my view when I try to use it which is annoying.  Any idea how I can get EF Core to STOP scaffolding my SQL Server Views?

My code...

```<code>public class LogBudgetView
{
    public int Id { get; set; }

    public string Message { get; set; } = null!;
...

public virtual DbSet<LogBudgetView> LogBudgetViews { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // views
    modelBuilder.Entity<LogBudgetView>().ToView("vwBudgetLog").HasKey(x => x.Id);
    //modelBuilder.Ignore<LogBudgetView>();
    ...
</code>```

Body:
I know SQL Server views are supported in EF Core.  Using the code first approach, EF Core 7 keeps scaffolding my SQL Server Views.  I do not want it to.  The only way I've been able to accomplish this it to use

modelBuilder.Ignore<LogBudgetView>();

I then have to comment that out after scaffolding because if I don't then EF Core won't recognize my view when I try to use it which is annoying.  Any idea how I can get EF Core to STOP scaffolding my SQL Server Views?

My code...

public class LogBudgetView
{
    public int Id { get; set; }

    public string Message { get; set; } = null!;
...

public virtual DbSet<LogBudgetView> LogBudgetViews { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    // views
    modelBuilder.Entity<LogBudgetView>().ToView("vwBudgetLog").HasKey(x => x.Id);
    //modelBuilder.Ignore<LogBudgetView>();
    ...


问:
How to assign the colors for the values and make piechart using plotly
I have this dataframe, for that I'm trying to create the piechart similar to the attached image.

Index
Category

SE
3

COL
2

PE
1

DP-PD
1

COL
1

OTH
1

I have tried the following, it's creating a pie chart, but not as expected.

import matplotlib.pyplot as plt
# assign data of lists.
data = {'index': ['SE', 'COL', 'PE', 'OTH', 'DP-PD'], 'Category': [3, 2, 1, 1,1]}

# Create DataFrame
df = pd.DataFrame(data)
plt.pie(df["Category"], labels = df["Category"],startangle=90)
plt.title("Observation statistics", fontsize = 24)
```
<p>I need the same color which is mentioned in the legend for each category. These are the color codes:</p>
```{'DP-PD': '#1E90FF', 'ID': '#FFA500', 'ENC': '#D3D3D3', 'SE': '#FFFF00',
 'COL': '#FF0000', 'GL': '#32CD32', 'COT': '#0000CD', 'PE': '#A52A2A',
 'FI': '#000000', 'OTH': '#00BFFF'}
```

I'd like the following output:

Body:
I have this dataframe, for that I'm trying to create the piechart similar to the attached image.

Index
Category

SE
3

COL
2

PE
1

DP-PD
1

COL
1

OTH
1

I have tried the following, it's creating a pie chart, but not as expected.

import matplotlib.pyplot as plt
# assign data of lists.
data = {'index': ['SE', 'COL', 'PE', 'OTH', 'DP-PD'], 'Category': [3, 2, 1, 1,1]}

# Create DataFrame
df = pd.DataFrame(data)
plt.pie(df["Category"], labels = df["Category"],startangle=90)
plt.title("Observation statistics", fontsize = 24)

I need the same color which is mentioned in the legend for each category. These are the color codes:

{'DP-PD': '#1E90FF', 'ID': '#FFA500', 'ENC': '#D3D3D3', 'SE': '#FFFF00',
 'COL': '#FF0000', 'GL': '#32CD32', 'COT': '#0000CD', 'PE': '#A52A2A',
 'FI': '#000000', 'OTH': '#00BFFF'}

I'd like the following output:


问:
Angular - I added ngbtimepicker in a ngbpopover in the ag grid and the popover is hiding at the back
I'm trying to add a ngbtimepicker in a ngbpopover. The popover is triggered and it is hiding at the back of the element. I tried to add some z-index to the popover to bring that to the front, but still It didn't work. But when we try to add a ngbdatepicker it worked as expected.
Any idea how to resolve it

```<code><div>

    <ng-template #popTemplate>
        <ngb-timepicker [(ngModel)]="mytime"></ngb-timepicker>
    </ng-template>
    <input [(ngModel)]="mytime" [ngbPopover]="popTemplate" placement="bottom" />

</div>
</code>```

Body:
I'm trying to add a ngbtimepicker in a ngbpopover. The popover is triggered and it is hiding at the back of the element. I tried to add some z-index to the popover to bring that to the front, but still It didn't work. But when we try to add a ngbdatepicker it worked as expected.
Any idea how to resolve it

    <ng-template #popTemplate>
        <ngb-timepicker [(ngModel)]="mytime"></ngb-timepicker>
    </ng-template>
    <input [(ngModel)]="mytime" [ngbPopover]="popTemplate" placement="bottom" />


问:
How to preselect Select2.js on page load using API call?
I have the following code:

```<code>var zoneListEl = $("#zones-list"),
    zoneListPopupEl = $("#zones-list-popup");

$.ajax({
    type: 'GET',
    url: 'https://my-domain.com/api/v1/zone/get-zone-by-ip'
}).then(function (data) {
    var zone = data.data.zones,
        option = new Option(zone.name + ", " + zone.abbreviated_state_name, zone.id, true, true);
    zoneListEl.append(option).trigger('change');
    // zoneListPopupEl.append(option).trigger('change');
});
</code>```

The code above works well. I mean, on the page load that ajax call happens and puts the response as an option inside the $("#zones-list") (which is a select element) as a default value.

My problem is, I have two different select elements that I  want to do the same for both. When I uncomment the following line

```<code>zoneListPopupEl.append(option).trigger('change');
</code>```

Then the code doesn't work (without throwing error) and I cannot see any default value (<option>) for neither selects. Why? Why when I do that for one select it works well but for two selects, it doesn't?

Update: I set that line inside setInterval like this:

```<code>setInterval(function(){ zoneListPopupEl.append(option).trigger('change'); },3000);
</code>```

In this case, the default value (option) will be shown for zoneListEl on page load and after 3 sec it does away.

Body:
I have the following code:

var zoneListEl = $("#zones-list"),
    zoneListPopupEl = $("#zones-list-popup");

$.ajax({
    type: 'GET',
    url: 'https://my-domain.com/api/v1/zone/get-zone-by-ip'
}).then(function (data) {
    var zone = data.data.zones,
        option = new Option(zone.name + ", " + zone.abbreviated_state_name, zone.id, true, true);
    zoneListEl.append(option).trigger('change');
    // zoneListPopupEl.append(option).trigger('change');
});

The code above works well. I mean, on the page load that ajax call happens and puts the response as an option inside the $("#zones-list") (which is a select element) as a default value.

My problem is, I have two different select elements that I  want to do the same for both. When I uncomment the following line

zoneListPopupEl.append(option).trigger('change');

Then the code doesn't work (without throwing error) and I cannot see any default value (<option>) for neither selects. Why? Why when I do that for one select it works well but for two selects, it doesn't?

Update: I set that line inside setInterval like this:

setInterval(function(){ zoneListPopupEl.append(option).trigger('change'); },3000);

In this case, the default value (option) will be shown for zoneListEl on page load and after 3 sec it does away.


问:
Convert sign in column names if not at certain position in R
I have a couple of dataframe column names that I would like to modify. Specifically, I would like to remove the underscore if it's not at the position before the number at the end of the column name. For example, I have these column names:

```<code>learn_anx_1, learn_anx_2, learn_anx_3, job_anx_1, job_anx_2, Beh_Int2_1, Beh_Int2_2, anxty1_1, anxty1_2
</code>```

And I would like to convert them to these:

```<code>learnanx_1, learnanx_2, learnanx_3, jobanx_1, jobanx_2, BehInt2_1, BehInt2_2, anxty1_1, anxty1_2
</code>```

(So please note that the last two should stay the same because the underscore does only appear once at the end before the number!)

I hope this is clear. I'm just not very good with regex, but I believe that would be the best approach?

Thank you!

Body:
I have a couple of dataframe column names that I would like to modify. Specifically, I would like to remove the underscore if it's not at the position before the number at the end of the column name. For example, I have these column names:

learn_anx_1, learn_anx_2, learn_anx_3, job_anx_1, job_anx_2, Beh_Int2_1, Beh_Int2_2, anxty1_1, anxty1_2

And I would like to convert them to these:

learnanx_1, learnanx_2, learnanx_3, jobanx_1, jobanx_2, BehInt2_1, BehInt2_2, anxty1_1, anxty1_2

(So please note that the last two should stay the same because the underscore does only appear once at the end before the number!)

I hope this is clear. I'm just not very good with regex, but I believe that would be the best approach?

Thank you!


问:
Deeplink in Microsoft Teams(Redirection is fine but message is not getting populated in chat window)
I have implemented deeplink (Organisation Teams) to redirect to a specific bot and write a message in the chat window. This is working fine in Mobile teams and when it comes to Microsoft desktop or browser, the flow is getting redirected but the message is not written in the chat window.
Following is the format of the Deeplink Used

https://teams.microsoft.com/l/Chat/0/0?users=28:&message=Agent%20handoff

I sent a message along with the redirection id to an app.
Expectation: "Agent Handoff" message to populate in a new app that is deployed in Teams.
Result: New app window is being opened but there is no message in the chat window

And the thing is it's working fine in mobile and browser, but not in Desktop Teams


问:
pm2 keeps restarting when running puppeteer
I am trying to execute a fetch script on pm2 to be run every day using command pm2 start datafetch.js --cron="0 15 * * *"  which is supposed to run the code daily at 15:00 but the code keeps getting restarted like this:

```<code>0|datafetch  | got here!
PM2          | App [datafetch:0] exited with code [0] via signal [SIGINT]
PM2          | App [datafetch:0] starting in -fork mode-
PM2          | App [datafetch:0] online
0|datafetch  | got here!
PM2          | App [datafetch:0] exited with code [0] via signal [SIGINT]
PM2          | App [datafetch:0] starting in -fork mode-
PM2          | App [datafetch:0] online
0|datafetch  | got here!
PM2          | App [datafetch:0] exited with code [0] via signal [SIGINT]
PM2          | App [datafetch:0] starting in -fork mode-
PM2          | App [datafetch:0] online

</code>```

and the code restarts and runs again although I want it to execute the next day?
my datafetch.js file :

```<code>const puppeteer = require("puppeteer");

async function daily() {
    const browser = await puppeteer.launch({
        headless : true,
        args : [
            '--no-sandbox'
        ]
    })
    const page = (await browser.pages())[0];
    await page.goto('https://google.com', { waitUntil : "networkidle0" });
    await page.type("input[title='Search']", "new games", { delay : 50 });
    await page.keyboard.press("Enter");
    await page.waitForXPath("//div[normalize-space()='Video Games / Newest']");
    console.log('got here!');
    await browser.close();
}

daily();
</code>```

is there anything that I'm doing wrong? how do I get my code to run at daily 15:00 only once per day?

edit :
Turns out this was not a bug but pm2 was designed to auto restart upon exit, hence every time the program ended with code 0 which stands for process stopping successfully after execution, pm2 automatically restarted the process.

After searching for a while I found a command --stop-exit-codes 0 which stops the auto restarting process upon exit with code 0, but I couldn't get it working as it turns out to be a not real feature :( .

two options I'm left with is skip the await browser.close() so that process does not stop but it'd consume way too many resources, the other is to use scheduler like node-cron and schedule the program restart and run it in pm2 to run multiple instances.

any additional input would be very helpful, Thank you.

Body:
I am trying to execute a fetch script on pm2 to be run every day using command pm2 start datafetch.js --cron="0 15 * * *"  which is supposed to run the code daily at 15:00 but the code keeps getting restarted like this:

0|datafetch  | got here!
PM2          | App [datafetch:0] exited with code [0] via signal [SIGINT]
PM2          | App [datafetch:0] starting in -fork mode-
PM2          | App [datafetch:0] online
0|datafetch  | got here!
PM2          | App [datafetch:0] exited with code [0] via signal [SIGINT]
PM2          | App [datafetch:0] starting in -fork mode-
PM2          | App [datafetch:0] online
0|datafetch  | got here!
PM2          | App [datafetch:0] exited with code [0] via signal [SIGINT]
PM2          | App [datafetch:0] starting in -fork mode-
PM2          | App [datafetch:0] online

and the code restarts and runs again although I want it to execute the next day?
my datafetch.js file :

const puppeteer = require("puppeteer");

async function daily() {
    const browser = await puppeteer.launch({
        headless : true,
        args : [
            '--no-sandbox'
        ]
    })
    const page = (await browser.pages())[0];
    await page.goto('https://google.com', { waitUntil : "networkidle0" });
    await page.type("input[title='Search']", "new games", { delay : 50 });
    await page.keyboard.press("Enter");
    await page.waitForXPath("//div[normalize-space()='Video Games / Newest']");
    console.log('got here!');
    await browser.close();
}

daily();

is there anything that I'm doing wrong? how do I get my code to run at daily 15:00 only once per day?

edit :
Turns out this was not a bug but pm2 was designed to auto restart upon exit, hence every time the program ended with code 0 which stands for process stopping successfully after execution, pm2 automatically restarted the process.

After searching for a while I found a command --stop-exit-codes 0 which stops the auto restarting process upon exit with code 0, but I couldn't get it working as it turns out to be a not real feature :( .

two options I'm left with is skip the await browser.close() so that process does not stop but it'd consume way too many resources, the other is to use scheduler like node-cron and schedule the program restart and run it in pm2 to run multiple instances.

any additional input would be very helpful, Thank you.


问:
Enable SSL on Sonarqube behind NGINX
I have this dockerfile:

```<code>FROM sonarqube:7.9.3-community
USER root
RUN apt-get update && apt-get install -y nginx

COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80 443 9000

USER sonarqube

CMD ["/bin/bash", "./bin/run.sh"] && ["/usr/sbin/nginx -g "daemon off";]
</code>```

The requirement is that NGINX and Sonarqube are in the same container.

The container and Sonarqube is UP.

2023.01.05 14:31:15 INFO  ce[][o.s.s.e.EsClientProvider] Connected to local Elasticsearch: [127.0.0.1:9001] 2023.01.05 14:31:15 INFO  ce[][o.sonar.db.Database] Create JDBC data source for jdbc:h2:tcp://127.0.0.1:9092/sonar 2023.01.05 14:31:15 WARN  ce[][o.s.db.dialect.H2] H2 database should be used for evaluation purpose only. 2023.01.05 14:31:16 INFO  ce[][o.s.s.p.ServerFileSystemImpl] SonarQube home: /opt/sonarqube 2023.01.05 14:31:16 INFO  ce[][o.s.c.c.CePluginRepository] Load plugins 2023.01.05 14:31:17 INFO  ce[][o.s.c.c.ComputeEngineContainerImpl] Running Community edition 2023.01.05 14:31:17 INFO  ce[][o.s.ce.app.CeServer] Compute Engine is operational 2023.01.05 14:31:18 INFO  app[][o.s.a.SchedulerImpl] Process[ce] is up 2023.01.05 14:31:18 INFO  app[][o.s.a.SchedulerImpl] SonarQube is up

NGINX does not start.

```<code>sonarqube@46ee502f9813:/opt/sonarqube$ service nginx status
[FAIL] nginx is not running ... failed!

sonarqube@46ee502f9813:/opt/sonarqube$ service nginx start
[FAIL] Starting nginx: nginx failed!
</code>```

Title: Enable SSL on Sonarqube behind NGINX

Body:
I have this dockerfile:

FROM sonarqube:7.9.3-community
USER root
RUN apt-get update && apt-get install -y nginx

COPY nginx.conf /etc/nginx/nginx.conf

EXPOSE 80 443 9000

USER sonarqube

CMD ["/bin/bash", "./bin/run.sh"] && ["/usr/sbin/nginx -g "daemon off";]

The requirement is that NGINX and Sonarqube are in the same container.

The container and Sonarqube is UP.

2023.01.05 14:31:15 INFO  ce[][o.s.s.e.EsClientProvider] Connected to local Elasticsearch: [127.0.0.1:9001] 2023.01.05 14:31:15 INFO  ce[][o.sonar.db.Database] Create JDBC data source for jdbc:h2:tcp://127.0.0.1:9092/sonar 2023.01.05 14:31:15 WARN  ce[][o.s.db.dialect.H2] H2 database should be used for evaluation purpose only. 2023.01.05 14:31:16 INFO  ce[][o.s.s.p.ServerFileSystemImpl] SonarQube home: /opt/sonarqube 2023.01.05 14:31:16 INFO  ce[][o.s.c.c.CePluginRepository] Load plugins 2023.01.05 14:31:17 INFO  ce[][o.s.c.c.ComputeEngineContainerImpl] Running Community edition 2023.01.05 14:31:17 INFO  ce[][o.s.ce.app.CeServer] Compute Engine is operational 2023.01.05 14:31:18 INFO  app[][o.s.a.SchedulerImpl] Process[ce] is up 2023.01.05 14:31:18 INFO  app[][o.s.a.SchedulerImpl] SonarQube is up

NGINX does not start.

sonarqube@46ee502f9813:/opt/sonarqube$ service nginx status
[FAIL] nginx is not running ... failed!

sonarqube@46ee502f9813:/opt/sonarqube$ service nginx start
[FAIL] Starting nginx: nginx failed!


问:
input field changes once i enter input
I have a form which uses tabs. Any time input is entered into the text input box the padding changes, I cannot work out what is causing this.

I tried setting margins and padding with !important to see if i could control it, but this was not successful.

Title: input field changes once i enter input


问:
React-hook-form and MUI TextField testing with react-testing-library
I'm using react-hook-form with zod for schema validation and MUI for UI components.
I have this MUI TextField wrapped in Controll HOC from RHF:

```<code>                    <Controller
                        name="docRegistrationNumber"
                        control={control}
                        defaultValue=""
                        render={({
                            field: { ref, onChange, value, ...field },
                        }) => (
                            <TextField
                                label="docRegistrationNumber"
                                variant="outlined"
                                error={Boolean(errors.docRegistrationNumber)}
                                helperText={
                                    errors.docRegistrationNumber?.message
                                }
                                inputRef={ref}
                                onChange={(event) => {
                                    if (errors.docRegistrationNumber) {
                                        trigger('docRegistrationNumber')
                                    }
                                    onChange(event.target.value)
                                }}
                                {...field}
                                value={value}
                            />
                        )}
                    />
</code>```

I'm trying to test the input for error messages.
A use case would be: if the input text is longer than 10 characters, display a error message below the input field "Invalid input".

What I'm trying in my test file is the following:

```<code>test('Should display error message for text longer than 10 characters', async () => {
            const input = screen.getByRole('textbox', {
                name: /docRegistrationNumber/i,
            })
            await user.type(input, 'this text is longer than 10 characters')
            await user.tab()
            const errorMessage = await screen.findByText(/invalid input/i)
            expect(errorMessage).toBeInTheDocument()
        })
</code>```

This does not seems to work. It cannot find element with that error text.
I tried using fireEvent to blur the input, but got same results.
I tried wrapping the expect in a waitFor block with no results.

This is my test setup:

```<code>const Component = () => {
        const {
            control,
            formState: { errors },
        } = useForm()
        return (
            <ContactAttributes
                errors={errors}
                control={control as any}
                trigger={jest.fn()}
                contactDetails={EMPTY_DETAILS_OBJECT}
            />
        )
    }

    beforeEach(() => {
        render(<Component />, { wrapper: BrowserRouter })
    })
</code>```

My guess is that the errors are not generated at test runtime. If I pass the error explicitly in the errors props I can query that error message.

My question is, how should I test this input?
In react-hook-form documentation I saw they test the whole form and check for errors only when submitting the form button.

Thank you!

Using userEvent instead of fireEvent
Wrapping the expectation in waitFor

My expectation was to be able to query the error message.

Body:
I'm using react-hook-form with zod for schema validation and MUI for UI components.
I have this MUI TextField wrapped in Controll HOC from RHF:

                    <Controller
                        name="docRegistrationNumber"
                        control={control}
                        defaultValue=""
                        render={({
                            field: { ref, onChange, value, ...field },
                        }) => (
                            <TextField
                                label="docRegistrationNumber"
                                variant="outlined"
                                error={Boolean(errors.docRegistrationNumber)}
                                helperText={
                                    errors.docRegistrationNumber?.message
                                }
                                inputRef={ref}
                                onChange={(event) => {
                                    if (errors.docRegistrationNumber) {
                                        trigger('docRegistrationNumber')
                                    }
                                    onChange(event.target.value)
                                }}
                                {...field}
                                value={value}
                            />
                        )}
                    />

I'm trying to test the input for error messages.
A use case would be: if the input text is longer than 10 characters, display a error message below the input field "Invalid input".

What I'm trying in my test file is the following:

test('Should display error message for text longer than 10 characters', async () => {
            const input = screen.getByRole('textbox', {
                name: /docRegistrationNumber/i,
            })
            await user.type(input, 'this text is longer than 10 characters')
            await user.tab()
            const errorMessage = await screen.findByText(/invalid input/i)
            expect(errorMessage).toBeInTheDocument()
        })

This does not seems to work. It cannot find element with that error text.
I tried using fireEvent to blur the input, but got same results.
I tried wrapping the expect in a waitFor block with no results.

This is my test setup:

const Component = () => {
        const {
            control,
            formState: { errors },
        } = useForm()
        return (
            <ContactAttributes
                errors={errors}
                control={control as any}
                trigger={jest.fn()}
                contactDetails={EMPTY_DETAILS_OBJECT}
            />
        )
    }

    beforeEach(() => {
        render(<Component />, { wrapper: BrowserRouter })
    })

My guess is that the errors are not generated at test runtime. If I pass the error explicitly in the errors props I can query that error message.

My question is, how should I test this input?
In react-hook-form documentation I saw they test the whole form and check for errors only when submitting the form button.

Thank you!

Using userEvent instead of fireEvent
Wrapping the expectation in waitFor

My expectation was to be able to query the error message.


问:
Translate native sql to JPA code or JPQL and make it pageable and sortable
I have two Entities like Below:

```<code>@Entity
@Table(name="tb_sm_config")
class Config {
   @Id
   private Long id;
   private String code;
   private String name;
   @Enumerated(EnumType.STRING)
   private State state;
   @JsonIgnore
   @OneToMany(mappedBy = "config", fetch = FetchType.LAZY)
   private List<ConfigItem> items;
}

@Entity
@Table(name="tb_sm_config_item")
class ConfigItem {
   @Id
   private Long id;
   private String code;
   private String name;
   @Enumerated(EnumType.STRING)
   private State state;
   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "config_id", referencedColumnName = "id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private Config config;
}
</code>```

the State is an Enum, there are three states : VALID, INVALID, DELETED

Then I define a ConfigVO like below:

```<code>class ConfigVO {
   private Long id;
   private String code;
   private String name;
   private State state;
   private Long validItemCount;
   private Long invalidItemCount;
   pirvate Long deletedItemCount;
}
</code>```

I want to provide fuzzy query based on config.name, config.code and precise query based on config.state and return a list of ConfigVO with pageable and sortable.

I know native sql will like :

```<code>select a.id, a.code, a.name, a.state,
       coalesce(b._valid, 0) validItemCount,
       coalesce(b._invalid, 0) invalidItemCount,
       coalesce(b._deleted, 0) deletedItemCount
from tb_sm_config a left join
    (select config_id, sum(if(state = 'VALID', 1, 0)) _valid, sum(if(state = 'INVALID', 1, 0)) _invalid, sum(if(state = 'DELETED', 1, 0)) _deleted  from tb_sm_config_item group by config_id) b
on a.id = b.config_id
where code like %:code% and name like %:name% and state = :state
</code>```

But here are the problems I don't know how to deal with:

The frontend will not always pass the code, name, state to query, so these three parameters is nullable.

If I use the @Query(nativeQuery=true, value=xxxx) in the ConfigRepository interface method, I don't know how to deal with the null value and the paging and sorting.

Is that any possible to achieve this goal through JpaSpecificationExecutor interface, Example interface, or something else?

I want to query base on the code, name, state, sometimes they will be null and want to count the total number of individual configItem states and pageable and sortable.

Body:
I have two Entities like Below:

@Entity
@Table(name="tb_sm_config")
class Config {
   @Id
   private Long id;
   private String code;
   private String name;
   @Enumerated(EnumType.STRING)
   private State state;
   @JsonIgnore
   @OneToMany(mappedBy = "config", fetch = FetchType.LAZY)
   private List<ConfigItem> items;
}

@Entity
@Table(name="tb_sm_config_item")
class ConfigItem {
   @Id
   private Long id;
   private String code;
   private String name;
   @Enumerated(EnumType.STRING)
   private State state;
   @ManyToOne(fetch = FetchType.LAZY)
   @JoinColumn(name = "config_id", referencedColumnName = "id", foreignKey = @ForeignKey(ConstraintMode.NO_CONSTRAINT))
    private Config config;
}

the State is an Enum, there are three states : VALID, INVALID, DELETED

Then I define a ConfigVO like below:

class ConfigVO {
   private Long id;
   private String code;
   private String name;
   private State state;
   private Long validItemCount;
   private Long invalidItemCount;
   pirvate Long deletedItemCount;
}

I want to provide fuzzy query based on config.name, config.code and precise query based on config.state and return a list of ConfigVO with pageable and sortable.

I know native sql will like :

select a.id, a.code, a.name, a.state,
       coalesce(b._valid, 0) validItemCount,
       coalesce(b._invalid, 0) invalidItemCount,
       coalesce(b._deleted, 0) deletedItemCount
from tb_sm_config a left join
    (select config_id, sum(if(state = 'VALID', 1, 0)) _valid, sum(if(state = 'INVALID', 1, 0)) _invalid, sum(if(state = 'DELETED', 1, 0)) _deleted  from tb_sm_config_item group by config_id) b
on a.id = b.config_id
where code like %:code% and name like %:name% and state = :state

But here are the problems I don't know how to deal with:

The frontend will not always pass the code, name, state to query, so these three parameters is nullable.

If I use the @Query(nativeQuery=true, value=xxxx) in the ConfigRepository interface method, I don't know how to deal with the null value and the paging and sorting.

Is that any possible to achieve this goal through JpaSpecificationExecutor interface, Example interface, or something else?

I want to query base on the code, name, state, sometimes they will be null and want to count the total number of individual configItem states and pageable and sortable.


问:
How can I tell if an emailed SSRS Report has been viewed or opened?
Is there an EASY way to add something to the SSRS Report email being sent to tell if it has been opened or viewed?

I am not really interested in WHO viewed it, I am looking to cleanup the reports so I just want to know if ANYONE opened/viewed the email.

I understand adding things like the URL of single pixel image and recording the calls to get that image gives an approximation of what is viewed (depending on the client, etc..), but I'd rather not write something like that from scratch. And I'm not exactly sure of how to inject that into an SSRS sent email either.


问:
How to Fix “Android studio new logcat nothing to show ” in Android Studio Dolphin | 2021.3.1?
My Logcat shows nothing and it’s completely blank.
I have tried to resolve this problem but my efforts were failed.

I have switched on some times "Enable new Logcat tool window" and restarted Android Studio.

I have checked "Logcat Format"

I have made "Invalidated Caches and Restart" without "Clear file system cache and Local History".

The old Logcat is working in the same Java project.

Below are my screenshots.


问:
how to access local network from avd?
Is it possible to access a device (e.g. a Sonos box) from an emulated android phone via network bridge?

added tap0 and br0 to my Network configuration
from here:

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever

2: enp2s0f0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq master br0 state UP group default qlen 1000
link/ether dc:0e:a1:29:5a:04 brd ff:ff:ff:ff:ff:ff
inet6 fe80::de0e:a1ff:fe29:5a04/64 scope link
valid_lft forever preferred_lft forever

3: tap0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc pfifo_fast master br0 state DOWN group default qlen 1000
link/ether 92:24:b9:90:cc:52 brd ff:ff:ff:ff:ff:ff

4: br0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
link/ether 0a:f8:c3:53:5b:d2 brd ff:ff:ff:ff:ff:ff
inet 192.168.100.14/24 brd 192.168.100.255 scope global dynamic br0
valid_lft 7183sec preferred_lft 7183sec
inet6 fe80::8f8:c3ff:fe53:5bd2/64 scope link
valid_lft forever preferred_lft forever

started avd with:

./emulator

-avd Nexus_5_API_26

-verbose

-qemu

-device virtio-net-pci,netdev=hn0,mac=52:55:00:d1:55:51

-netdev tap,id=hn0,ifname=tap0,script=no,downscript=no

Network configuration from emulated Device :

$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever

3: eth1: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
link/ether 52:55:00:d1:55:51 brd ff:ff:ff:ff:ff:ff

4: wlan0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default qlen 1000
link/ether 02:00:00:44:55:66 brd ff:ff:ff:ff:ff:ff

6: hwsim0: <BROADCAST,MULTICAST> mtu 1500 qdisc noop state DOWN group default
link/ieee802.11/radiotap 12:00:00:00:00:00 brd ff:ff:ff:ff:ff:ff

7: sit0@NONE:  mtu 1480 qdisc noop state DOWN group default
link/sit 0.0.0.0 brd 0.0.0.0

9: radio0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
link/ether 0e:86:a3:d8:13:47 brd ff:ff:ff:ff:ff:ff
inet 192.168.200.2/24 brd 192.168.200.255 scope global
radio0
valid_lft forever preferred_lft forever
inet6 fec0::6d8a:a6a1:3127:532c/64 scope site temporary dynamic
valid_lft 86213sec preferred_lft 14213sec
inet6 fec0::c86:a3ff:fed8:1347/64 scope site mngtmpaddr dynamic
valid_lft 86213sec preferred_lft 14213sec
inet6 fe80::c86:a3ff:fed8:1347/64 scope link
valid_lft forever preferred_lft forever

status of emulated Device:

Device shows IP Address from radio0: 192.168.200.2

eth1 shows the MAC Address (52:55:00:d1:55:51) i gave with the arguments

Is there a change to change the IP-range to 192.168.100.x?

Title: how to access local network from avd?


问:
Change base model when training google automl custom model
Is there a way to change the base model when training a translation custom model in google automl? I was told so, but the drop-down menu in the base model option is blocked and there is a warning that says "All custom translation models are trained based on the Google NMT model".

I want to improve a model that I trained before adding more data and using that previous model as base model.


问:
How to pin down RabbitMQ unroutable messages?
I am trying to understand the source of unroutable messages being dropped in RabbitMQ, as indicated by the metric rabbitmq_channel_messages_unroutable_dropped_total. Is there a way to trace the origin of unroutable messages and determine their contents in RabbitMQ?

I have checked the queues for messages without routing keys that have messages going through to them, but have not been able to find any with those parameters.