问:
Query for the longest duration of consecutive TRUE
I have a machine logging the running status (True/False) to SQL Server every 1 minute unless there is a change of status. The table Machine_Status looks like this:

Row
Timestamp
Running

1
1/10/2023 08:20:10
0

2
1/10/2023 08:21:10
0

3
1/10/2023 08:21:30
1

4
1/10/2023 08:22:30
1

5
1/10/2023 08:23:30
1

6
1/10/2023 08:23:40
0

7
1/10/2023 08:24:40
0

8
1/10/2023 08:25:30
1

9
1/10/2023 08:26:30
1

10
1/10/2023 08:27:30
1

11
1/10/2023 08:28:30
1

12
1/10/2023 08:28:55
0

13
1/10/2023 08:29:55
0

```<code>CREATE TABLE Machine_Status
(
    Row INT,
    Timestamp   DateTime,
    Running Bit
);

INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('1', '1/10/2023 08:20:10', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('2', '1/10/2023 08:21:10', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('3', '1/10/2023 08:21:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('4', '1/10/2023 08:22:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('5', '1/10/2023 08:23:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('6', '1/10/2023 08:23:40', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('7', '1/10/2023 08:24:40', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('8', '1/10/2023 08:25:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('9', '1/10/2023 08:26:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('10', '1/10/2023 08:27:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('11', '1/10/2023 08:28:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('12', '1/10/2023 08:28:55', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('13', '1/10/2023 08:29:55', '0');
</code>```

My desired output is the longest duration the machine was running within a time range. With data from row 8 to 12, the result is 3 minutes + 25 seconds.

Desired Result:

Longest Duration

205 seconds

```<code>select max(datediff(second, t1.[Timestamp], t2.[Timestamp]))
from [Machine_Status] t1 inner join [Machine_Status] t2
on t1.[Row] <> t2.[Row];
</code>```

The result from this is 585 which is not 205.

Sorry, this is similar to my previous question but is not identical. This machine logs every minute unless there is status change. So it goes 0 0 1 1 1 0 1 1 1 1 0, instead of flip flopping like the previous machine 0 1 0 1 0 1 0 1.

Body:
I have a machine logging the running status (True/False) to SQL Server every 1 minute unless there is a change of status. The table Machine_Status looks like this:

Row
Timestamp
Running

1
1/10/2023 08:20:10
0

2
1/10/2023 08:21:10
0

3
1/10/2023 08:21:30
1

4
1/10/2023 08:22:30
1

5
1/10/2023 08:23:30
1

6
1/10/2023 08:23:40
0

7
1/10/2023 08:24:40
0

8
1/10/2023 08:25:30
1

9
1/10/2023 08:26:30
1

10
1/10/2023 08:27:30
1

11
1/10/2023 08:28:30
1

12
1/10/2023 08:28:55
0

13
1/10/2023 08:29:55
0

CREATE TABLE Machine_Status
(
    Row INT,
    Timestamp   DateTime,
    Running Bit
);

INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('1', '1/10/2023 08:20:10', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('2', '1/10/2023 08:21:10', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('3', '1/10/2023 08:21:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('4', '1/10/2023 08:22:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('5', '1/10/2023 08:23:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('6', '1/10/2023 08:23:40', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('7', '1/10/2023 08:24:40', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('8', '1/10/2023 08:25:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('9', '1/10/2023 08:26:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('10', '1/10/2023 08:27:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('11', '1/10/2023 08:28:30', '1');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('12', '1/10/2023 08:28:55', '0');
INSERT INTO Machine_Status (Row, Timestamp, Running) VALUES ('13', '1/10/2023 08:29:55', '0');

My desired output is the longest duration the machine was running within a time range. With data from row 8 to 12, the result is 3 minutes + 25 seconds.

Desired Result:

Longest Duration

205 seconds

select max(datediff(second, t1.[Timestamp], t2.[Timestamp]))
from [Machine_Status] t1 inner join [Machine_Status] t2
on t1.[Row] <> t2.[Row];

The result from this is 585 which is not 205.

Sorry, this is similar to my previous question but is not identical. This machine logs every minute unless there is status change. So it goes 0 0 1 1 1 0 1 1 1 1 0, instead of flip flopping like the previous machine 0 1 0 1 0 1 0 1.


来源: stackexchange

问:
how to install dependencies from yarn.lock?
I have only yarn.lock file.I don't have package.json or package-lock.json or node_modules folder.Just only yarn.lock with over ten thousand lines.

I still haven't found any question related to this? Guide me If you know.THANK

ContentLicense: CC BY-SA 4.0


问:
Pass Team's Culture in Azure Bot Sign in link
The oauth at my backed expects a culture to render the login page in user's language. I have an oauth connection settings on my bot which works as expected. But now I want it also to include the culture from team.Like below:

https://oauthprovider/auth?&culture=en-US&response_type=code&client_id=xxx&redirect_uri=http%3a%2f%2fwww.myapp.com

How in Generic oauth V2 or in code, I can provide Team's language . I tried below code, but it does not work:

```<code>string signInLink = await GetSignInLinkAsync(turnContext, cancellationToken).ConfigureAwait(false);

signInLink = $"{signInLink}&culture={turnContext.Activity.GetLocale()}";

</code>```

Any suggestions, will help me a lot!

Body:
The oauth at my backed expects a culture to render the login page in user's language. I have an oauth connection settings on my bot which works as expected. But now I want it also to include the culture from team.Like below:

https://oauthprovider/auth?&culture=en-US&response_type=code&client_id=xxx&redirect_uri=http%3a%2f%2fwww.myapp.com

How in Generic oauth V2 or in code, I can provide Team's language . I tried below code, but it does not work:

string signInLink = await GetSignInLinkAsync(turnContext, cancellationToken).ConfigureAwait(false);

signInLink = $"{signInLink}&culture={turnContext.Activity.GetLocale()}";

Any suggestions, will help me a lot!


问:
Math.net get eigenvector for specific eigenvalue
I have a matrix object and want to find the eigenvector that corresponds to an eigenvalue of 1. How would I do that? I'm currently solving it with a good ole' for loop, but am wondering whether there are more elegant ways to do it</p>
```<code>using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Factorization;

public static Vector<double> FindRelevantEigenvector(Matrix<double> matrix)
{
    Evd<double> eigen = matrix.Evd();
    var eigenValues = eigen.EigenValues;
    var relevantIndex = FindEigenValueOfOneIndex(eigenValues);
    if (relevantIndex == eigenValue.Count) return null;
    var eigenVectors = eigen.EigenVectors;
    return eigenVectors.Row(relevantIndex);
}

private static int FindEigenValueOfOneIndex(Vector<Complex> eigenValues)
{
    for (int index = 0; index < eigenValues.Count; index++)
    {
        if (eigenValues[index] == 1) return index;
    }
    return eigenValues.Count;
}
</code>```

Body:
I have a matrix object and want to find the eigenvector that corresponds to an eigenvalue of 1. How would I do that? I'm currently solving it with a good ole' for loop, but am wondering whether there are more elegant ways to do it

using MathNet.Numerics.LinearAlgebra;
using MathNet.Numerics.LinearAlgebra.Factorization;

public static Vector<double> FindRelevantEigenvector(Matrix<double> matrix)
{
    Evd<double> eigen = matrix.Evd();
    var eigenValues = eigen.EigenValues;
    var relevantIndex = FindEigenValueOfOneIndex(eigenValues);
    if (relevantIndex == eigenValue.Count) return null;
    var eigenVectors = eigen.EigenVectors;
    return eigenVectors.Row(relevantIndex);
}

private static int FindEigenValueOfOneIndex(Vector<Complex> eigenValues)
{
    for (int index = 0; index < eigenValues.Count; index++)
    {
        if (eigenValues[index] == 1) return index;
    }
    return eigenValues.Count;
}


问:
How can I add a progressive number in different field in excel?
I have an excel file with a sushi restaurant menu,
in the first column I have a progressive number 1,2,3,4,... and in the second column I have the products onigiri, fried, ecc...
Can I edit the second column simultaneously replacing the name of the product with "001 onigiri, 002 fried, 003 sashimi, 004 ecc..." without changing them manually?

I searched for some formulas but I dont find anything


问:
Typescript - dynamic multidimensional objects array
I have an API that returns dynamic data, in form of an array of objects with changing structure. The objects can have any data type (string, number, null).
So it can be like this:

```<code>{
    "data": [
        {
            "Address": "0x964fd5383dfdbfbd54224de9f773e5ac7bdb0086",
            "Number of Doses": 58,
            "Rank": 1
        },
        {
            "Address": "0x062f95282a797c49f0994699c2c96ae566293e0c",
            "Number of Doses": 53,
            "Rank": 2
        },
....
    ]
}
</code>```

or like this:

```<code>{
    "data": [
        {
            "Type": 1,
            "Change": "true",
            "Name": "abc",
            "Version": 1
        },
        {
            "Type": 2,
            "Change": "false",
            "Name": "xyz",
            "Version": 2
        },
....
    ]
}
</code>```

I'm getting this in Typescript and I need to convert it into an array of all values plus the headers (it gets dumped into a sheet).

So the first example should translate to:

while the second one to:

How can I achieve this in Typescript?

Update:
I managed to do it in JavaScript, with the below code, which doesn't work in TS (should I mention that I have zero experience with TS?).

```<code>let response = [];
let data = result.value["data"]; //data from API
//get the first element in array and extract its items -> the number of columns and the headers
const firstDataElement = data[0];
const keys = Object.keys(firstDataElement);
response = makeArray(data.length + 1, keys.length, undefined); //+1 because we add the columns headers

//add columns headers
for (var k = 0; k < keys.length; k++) {
    response[0][k] = keys[k];
}

//loop through all elements in data array
for (var i = 0; i < data.length; i++) {
    //skip first element of response, we already have columns headers in there
    const item = data[i];
    let values = Object.values(item);
    for (var j = 0; j < values.length; j++) {
      let value = values[j];
      response[i + 1][j] = value;
    }
}
return response;

function makeArray(w, h, val) {
  var arr = [];
  for (let i = 0; i < w; i++) {
    arr[i] = [];
    for (let j = 0; j < h; j++) {
      arr[i][j] = val;
    }
  }
  return arr;
}
</code>```

Body:
I have an API that returns dynamic data, in form of an array of objects with changing structure. The objects can have any data type (string, number, null).
So it can be like this:

{
    "data": [
        {
            "Address": "0x964fd5383dfdbfbd54224de9f773e5ac7bdb0086",
            "Number of Doses": 58,
            "Rank": 1
        },
        {
            "Address": "0x062f95282a797c49f0994699c2c96ae566293e0c",
            "Number of Doses": 53,
            "Rank": 2
        },
....
    ]
}

or like this:

{
    "data": [
        {
            "Type": 1,
            "Change": "true",
            "Name": "abc",
            "Version": 1
        },
        {
            "Type": 2,
            "Change": "false",
            "Name": "xyz",
            "Version": 2
        },
....
    ]
}

I'm getting this in Typescript and I need to convert it into an array of all values plus the headers (it gets dumped into a sheet).

So the first example should translate to:

while the second one to:

How can I achieve this in Typescript?

Update:
I managed to do it in JavaScript, with the below code, which doesn't work in TS (should I mention that I have zero experience with TS?).

let response = [];
let data = result.value["data"]; //data from API
//get the first element in array and extract its items -> the number of columns and the headers
const firstDataElement = data[0];
const keys = Object.keys(firstDataElement);
response = makeArray(data.length + 1, keys.length, undefined); //+1 because we add the columns headers

//add columns headers
for (var k = 0; k < keys.length; k++) {
    response[0][k] = keys[k];
}

//loop through all elements in data array
for (var i = 0; i < data.length; i++) {
    //skip first element of response, we already have columns headers in there
    const item = data[i];
    let values = Object.values(item);
    for (var j = 0; j < values.length; j++) {
      let value = values[j];
      response[i + 1][j] = value;
    }
}
return response;

function makeArray(w, h, val) {
  var arr = [];
  for (let i = 0; i < w; i++) {
    arr[i] = [];
    for (let j = 0; j < h; j++) {
      arr[i][j] = val;
    }
  }
  return arr;
}


问:
React-testing-library testing redux-form, react-select component. test is not failing
I am testing react-select component used with redux-form field, created mocked ReduxForm , my SubsidiaryPicker is render in side TestReduxForm, after updating subsidiary in subsidiary picker,

selected TextReduxForm and added expect toHavedValues({ subsidiary: "mocked-option-1" }), these test is passing but it should fail when i break component intentionally to test test-itself.

here is my test

```<code>it('should select one element when using as single picker', async () => {
        const handleSubmit = (value)=>{
            console.log(value);
            // { subsidiary: { value: 'mocked-option-1', label: 'Mocked option 1' } }
        };
        const { getByTestId, findByTestId, getByRole, findByLabelText, findByText, debug, store } = renderWithProviders(
            <TestReduxForm
                testComponent={
                    <Field name='subsidiary' component={SubsidiaryPicker} label="Subsidiary Picker"  />
                }
                onSubmit={handleSubmit}
            />
        )

        // step: 1 Opens the dropdown options list
        const selectWrapper = await findByTestId('test-id')
        const form = getByTestId("testingForm")
        const submitButtonElement = getByRole('button');
        const input = selectWrapper.firstChild;

        // helper let me picker one option
        await selectOption((input), 'Mocked option 1');

        // now click out of picker so fire on blur
        fireEvent.click(submitButtonElement);

        expect(form).toHaveFormValues({ subsidiary: "mocked-option-1" });
    })
</code>```

TestReduxFrom.jsx

```<code>let TestReduxForm = ({ testComponent, handleSubmit }) => {
  return (
    <Form data-testid="testingForm" id="testingForm" onSubmit={(value) => handleSubmit(value)}>
      {testComponent}
      <Button type="submit">Submit</Button>
    </Form>
  );
};

TestReduxForm = reduxForm({
  form: TEST_FORM_NAME, // a unique identifier for this form
  enableReinitialize: true,
  keepDirtyOnReinitialize: true,
  touchOnChange: false,
  touchOnBlur: false,
})(TestReduxForm);
</code>```

export default TestReduxForm;

but my form value is logged is different { subsidiary: { value: 'mocked-option-1', label: 'Mocked option 1' } } (handleSubmit) than my expect { subsidiary: { value: 'mocked-option-1', label: 'Mocked option 1' } }, i just want to know why my test is not failing and also if there is any other way of testing form value ?

Body:
I am testing react-select component used with redux-form field, created mocked ReduxForm , my SubsidiaryPicker is render in side TestReduxForm, after updating subsidiary in subsidiary picker,

selected TextReduxForm and added expect toHavedValues({ subsidiary: "mocked-option-1" }), these test is passing but it should fail when i break component intentionally to test test-itself.

here is my test

it('should select one element when using as single picker', async () => {
        const handleSubmit = (value)=>{
            console.log(value);
            // { subsidiary: { value: 'mocked-option-1', label: 'Mocked option 1' } }
        };
        const { getByTestId, findByTestId, getByRole, findByLabelText, findByText, debug, store } = renderWithProviders(
            <TestReduxForm
                testComponent={
                    <Field name='subsidiary' component={SubsidiaryPicker} label="Subsidiary Picker"  />
                }
                onSubmit={handleSubmit}
            />
        )

        // step: 1 Opens the dropdown options list
        const selectWrapper = await findByTestId('test-id')
        const form = getByTestId("testingForm")
        const submitButtonElement = getByRole('button');
        const input = selectWrapper.firstChild;

        // helper let me picker one option
        await selectOption((input), 'Mocked option 1');

        // now click out of picker so fire on blur
        fireEvent.click(submitButtonElement);

        expect(form).toHaveFormValues({ subsidiary: "mocked-option-1" });
    })

TestReduxFrom.jsx

let TestReduxForm = ({ testComponent, handleSubmit }) => {
  return (
    <Form data-testid="testingForm" id="testingForm" onSubmit={(value) => handleSubmit(value)}>
      {testComponent}
      <Button type="submit">Submit</Button>
    </Form>
  );
};

TestReduxForm = reduxForm({
  form: TEST_FORM_NAME, // a unique identifier for this form
  enableReinitialize: true,
  keepDirtyOnReinitialize: true,
  touchOnChange: false,
  touchOnBlur: false,
})(TestReduxForm);

export default TestReduxForm;

but my form value is logged is different { subsidiary: { value: 'mocked-option-1', label: 'Mocked option 1' } } (handleSubmit) than my expect { subsidiary: { value: 'mocked-option-1', label: 'Mocked option 1' } }, i just want to know why my test is not failing and also if there is any other way of testing form value ?


问:
Google Form answers to Google Spreadsheet
Is there a way to link answers submitted on a Google form to specific cells on a Google spreadsheet?  Ex: my spreadsheet has 100 cells, if someone completes the form and says they want their name in cell 50, 83 and 99 can that auto-populate so that we can see the spreadsheet update in real time, rather than having to go back and populate the cell with someone's name?

I have created the form and the spreadsheet but I don't know how to take the answers collected and put them in the appropriate cell.


问:
Accessing Azure SQL Database through Unity 3d
Hello I have a Unity3d game and an Azure SQL database which I want to use to store user accounts and scores. I am trying to use Unity Web Request to retrieve information from the database.

I do not understand how to do this however.

I have php code written which should access the database and query the contents of the user table:

```<code><?php

// Create connection
// SQL Server Extension Sample Code:
$connectionInfo = array("UID" => "angeldevadmin", "pwd" => "*******", "Database" => "angelgamesSQL", "LoginTimeout" => 30, "Encrypt" => 1, "TrustServerCertificate" => 0);
$serverName = "tcp:angelgames.database.windows.net,1433";
$conn = sqlsrv_connect($serverName, $connectionInfo);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully...";

$sql = "SELECT * from users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {

    echo "id: " . $row["ID"] . " - user: " . $row["Username"] . " - score: " . $row["Score"] . "<br>";
  }
} else {
  echo "0 results";
}
$conn->close();
?>
</code>```

I am not sure where I am supposed to put this code, whether it be a link on my website that my game can access to run the php code, or if Unity can run the php file itself. Or should the php file be saved somewhere with Azure? All examples of Unity web request access php files from some link https://exampleserver.com/getusers.php

UnityWebRequest.Get takes a url string as it parameter.

I am not a data engineer so maybe this question seems dumb but I have no idea how I am supposed to accomplish my goal. Any help is greatly appreciated :)

I have tried to save the php file in my project, but it seems like that will not work as UnityWebRequest takes a url as its parameter.

Body:
Hello I have a Unity3d game and an Azure SQL database which I want to use to store user accounts and scores. I am trying to use Unity Web Request to retrieve information from the database.

I do not understand how to do this however.

I have php code written which should access the database and query the contents of the user table:

<?php

// Create connection
// SQL Server Extension Sample Code:
$connectionInfo = array("UID" => "angeldevadmin", "pwd" => "*******", "Database" => "angelgamesSQL", "LoginTimeout" => 30, "Encrypt" => 1, "TrustServerCertificate" => 0);
$serverName = "tcp:angelgames.database.windows.net,1433";
$conn = sqlsrv_connect($serverName, $connectionInfo);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully...";

$sql = "SELECT * from users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {

    echo "id: " . $row["ID"] . " - user: " . $row["Username"] . " - score: " . $row["Score"] . "
";
  }
} else {
  echo "0 results";
}
$conn->close();
?>

I am not sure where I am supposed to put this code, whether it be a link on my website that my game can access to run the php code, or if Unity can run the php file itself. Or should the php file be saved somewhere with Azure? All examples of Unity web request access php files from some link https://exampleserver.com/getusers.php

UnityWebRequest.Get takes a url string as it parameter.

I am not a data engineer so maybe this question seems dumb but I have no idea how I am supposed to accomplish my goal. Any help is greatly appreciated :)

I have tried to save the php file in my project, but it seems like that will not work as UnityWebRequest takes a url as its parameter.


问:
how to fetch data from firebase to react app
i want to ask you about fetching data from firebase i'm making a blogpost app which have a choice to write a post on it and this will go to firebase after clicking submit button, the functionality till here is ready but i want to fetch this data from firebase to react how can i do it
i have in blog component a const for blogs:

const blogs = [
{
title: 'title',
text: 'text',
author: 'author',
date: 'date',
state: 'normal',
},
....
];
and in return i have

          subTitle subTitle subTitle subTitle subTitle subTitle

          Lorem ipsum dolor sitadad Lorem ipsum dolor sitadad Lorem ipsum dolor
          sitadad Lorem ipsum ipsum dolor sitadad Lorem ipsum dolor sitadad

so instead of this info in the return i want to  fetch it from firebase :)

to fix it but still don’t  do the functionality right


问:
Xcode Apple Script (on open location)
I'm attempting to build an app in Xcode using the AppleScript template. The intent is to have a custom URL scheme which will launch the app when called and the app will parse the url info an act accordingly.

To test the set up, I just have a couple of simple dialogs set up. One for when the app is opened on its own, and a second for when it's launched with the URL scheme:

```<code>script AppDelegate
    property parent : class "NSObject"

    -- IBOutlets
    property theWindow : missing value

    on applicationWillFinishLaunching_(aNotification)
        display dialog "test"
    end applicationWillFinishLaunching_

    on open location this_url
        display dialog "test open location"
    end open location

    on applicationShouldTerminate_(sender)
        -- Insert code here to do any housekeeping before your application quits
        return current application's NSTerminateNow
    end applicationShouldTerminate_

end script
</code>```

The first dialog works when the app is open ("test"). And the URL scheme is working as the app will open when launched through a browser that's using the custom protocol. But when the app opens this second way, it's not executing the display dialog ("test open location") within the "on open location" statement.

I've set up a similar app using script editor and the "on open location" statement works as expected.

Any thoughts would be greatly appreciated.

Title: Xcode Apple Script (on open location)

Body:
I'm attempting to build an app in Xcode using the AppleScript template. The intent is to have a custom URL scheme which will launch the app when called and the app will parse the url info an act accordingly.

To test the set up, I just have a couple of simple dialogs set up. One for when the app is opened on its own, and a second for when it's launched with the URL scheme:

script AppDelegate
    property parent : class "NSObject"

    -- IBOutlets
    property theWindow : missing value

    on applicationWillFinishLaunching_(aNotification)
        display dialog "test"
    end applicationWillFinishLaunching_

    on open location this_url
        display dialog "test open location"
    end open location

    on applicationShouldTerminate_(sender)
        -- Insert code here to do any housekeeping before your application quits
        return current application's NSTerminateNow
    end applicationShouldTerminate_

end script

The first dialog works when the app is open ("test"). And the URL scheme is working as the app will open when launched through a browser that's using the custom protocol. But when the app opens this second way, it's not executing the display dialog ("test open location") within the "on open location" statement.

I've set up a similar app using script editor and the "on open location" statement works as expected.

Any thoughts would be greatly appreciated.


问:
React testing library userEvent.type not updating TextField value
I have a custom React component which underneath returns a textField component from the Mui library.

```<code>  if (type === DynamicFieldType.STRING) {
    return (
      <TextField
        id="outlined-basic"
        label={label}
        placeholder={placeholder}
        variant="outlined"
        value={defaultValue || ""}
        onChange={(event) => handleOnChange(event.target.value)}
        onKeyDown={handleOnKeyDown}
        sx={{ width: 200 }}
      />
    );
  } else if ...
</code>```

I am trying to create a test for user interactions, and I found the userEvent package from react testing library. (https://github.com/testing-library/user-event)

After following the examples I haven't been able to trigger an update in my test. it seems to find the component, but the action user.type doesn't seem to be having any efect at all.

this is the test

```<code>    it('should respond to user input', async () => {
        const user = userEvent.setup();

        const label = 'label';
        const defaultValue = 'defaultValue';
        const placeholder = 'placeholder';

        const component = render(
            <DynamicField
                label={label}
                type={DynamicFieldType.STRING}
                key="1"
                onChange={(value) => {
                    console.log('value', value);
                 }}
                onKeyDown={() => {

                }}
                placeholder={placeholder}
            />
        );
        const input = component.getByLabelText(label);
        const userinput = await user.type(input, ' adding value', { initialSelectionStart: 0 });
        expect(input.getAttribute('type')).toBe('text');
        expect(component.getByDisplayValue(' adding value')).toBeTruthy();
    });
</code>```

The result shows as if the input doesn't receive a command.

```<code><input
              aria-invalid="false"
              class="MuiInputBase-input MuiOutlinedInput-input css-1t8l2tu-MuiInputBase-input-MuiOutlinedInput-input"
              id="outlined-basic"
              placeholder="placeholder"
              type="text"
              value=""
            />
</code>```

and the error

```<code>TestingLibraryElementError: Unable to find an element with the display value:  adding value.
</code>```

Any idea on why might be causing this issue will be highly appreciated.

Body:
I have a custom React component which underneath returns a textField component from the Mui library.

  if (type === DynamicFieldType.STRING) {
    return (
      <TextField
        id="outlined-basic"
        label={label}
        placeholder={placeholder}
        variant="outlined"
        value={defaultValue || ""}
        onChange={(event) => handleOnChange(event.target.value)}
        onKeyDown={handleOnKeyDown}
        sx={{ width: 200 }}
      />
    );
  } else if ...

I am trying to create a test for user interactions, and I found the userEvent package from react testing library. (https://github.com/testing-library/user-event)

After following the examples I haven't been able to trigger an update in my test. it seems to find the component, but the action user.type doesn't seem to be having any efect at all.

this is the test

    it('should respond to user input', async () => {
        const user = userEvent.setup();

        const label = 'label';
        const defaultValue = 'defaultValue';
        const placeholder = 'placeholder';

        const component = render(
            <DynamicField
                label={label}
                type={DynamicFieldType.STRING}
                key="1"
                onChange={(value) => {
                    console.log('value', value);
                 }}
                onKeyDown={() => {

                }}
                placeholder={placeholder}
            />
        );
        const input = component.getByLabelText(label);
        const userinput = await user.type(input, ' adding value', { initialSelectionStart: 0 });
        expect(input.getAttribute('type')).toBe('text');
        expect(component.getByDisplayValue(' adding value')).toBeTruthy();
    });

The result shows as if the input doesn't receive a command.

<input
              aria-invalid="false"
              class="MuiInputBase-input MuiOutlinedInput-input css-1t8l2tu-MuiInputBase-input-MuiOutlinedInput-input"
              id="outlined-basic"
              placeholder="placeholder"
              type="text"
              value=""
            />

and the error

TestingLibraryElementError: Unable to find an element with the display value:  adding value.

Any idea on why might be causing this issue will be highly appreciated.


问:
Unable to convert ForwardedEvents.evtx to csv format
I have encountered strange behavior.
I have created windows event forwarding subscription and ForwardedEvent.evtx file is capturing subscribed events. When trying to convert ForwardedEvent.evtx file to csv file I see System.AccessViolation exception. I used command

```<code>Get-WinEvent -Path C:\Windows\System32\winevt\Logs\ForwardedEvents.evtx |Export-Csv ForwardedEvents.csv
</code>```

in powershell admin mode

I tried copying ForwardedEvents.evtx file to other location and convert still I see same issue.
I tried to convert other files Application.evtx and Hardware.evtx file in C:\Windows\System32\winevt\Logs that works fine and only this ForwardedEvent.evtx unable to convert.

Body:
I have encountered strange behavior.
I have created windows event forwarding subscription and ForwardedEvent.evtx file is capturing subscribed events. When trying to convert ForwardedEvent.evtx file to csv file I see System.AccessViolation exception. I used command

Get-WinEvent -Path C:\Windows\System32\winevt\Logs\ForwardedEvents.evtx |Export-Csv ForwardedEvents.csv

in powershell admin mode

I tried copying ForwardedEvents.evtx file to other location and convert still I see same issue.
I tried to convert other files Application.evtx and Hardware.evtx file in C:\Windows\System32\winevt\Logs that works fine and only this ForwardedEvent.evtx unable to convert.


问:
call javascript window.open inside js in php
Good day
im using google org chart from a php script i have an hyperlink in each element but i wnat to use the js window.open method instead and href link i try many combinations but i cant make it work... what im missing??? heres my code

```<code><script>
var passedArray = <?php echo json_encode($reeco_net); ?>;
  google.charts.load('current', {packages:["orgchart"]});
  google.charts.setOnLoadCallback(drawChart);
  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Name');
    data.addColumn('string', 'Manager');
    data.addColumn('string', 'ToolTip');
    let rows = [];
    for (let row of passedArray)  {
        let [jid, jpa, jav, jcd, jre, jno, jni, es, tr] = [...row];
        rows.push([{'v':jid, 'f':jno+ '<a href="movis.php?thx='+jid+'&thn='+jno+'"><button type="button" class="btn btn-tool" data-toggle="modal" data-target="#selectables'+jid+'"><img class="table-avatar circular-square'+es+'" src="../img/avatar/'+jav+'" width="40px" height="40px"></button></a>'},
        jpa, tr]);
    }
    data.addRows
    (rows);
    // Create the chart.
    var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
    // Draw the chart, setting the allowHtml option to true for the tooltips.
    chart.draw(data, {'allowHtml':true});
  }
</script>
 id="chart_div"></div>
</code>```

i want to use something like this... newWindow = window.open("catalog.php?thx='+jid+'&thn='+jno","","toolbar=yes,scrollbars=yes, resizable=yes,HEIGHT=700,WIDTH=800") instead of the href.... any help??? tnx in advnace

Body:
Good day
im using google org chart from a php script i have an hyperlink in each element but i wnat to use the js window.open method instead and href link i try many combinations but i cant make it work... what im missing??? heres my code

 id="chart_div">

i want to use something like this... newWindow = window.open("catalog.php?thx='+jid+'&thn='+jno","","toolbar=yes,scrollbars=yes, resizable=yes,HEIGHT=700,WIDTH=800") instead of the href.... any help??? tnx in advnace


问:
OneTrust script executing after Google Tag Manager
I'm trying to reorder the execution of scripts in my codebase. What I need is for the OneTrust scripts to fire before my GTM scripts and for whatever reason I can't seem to get that to happen.

I've tried:

Reordering the scripts in the head

Using j.async and j.defer in the GTM script

Using the addEventListener method to attach a load event listener to the OneTrust script, and then include the Google Tag Manager script inside the event listener function.

```<code>document.addEventListener('DOMContentLoaded', function() {
    var gtmScript = document.createElement('script');
    gtmScript.src = 'googletagmanager.js';
    document.body.appendChild(gtmScript);
  });
</code>```

Body:
I'm trying to reorder the execution of scripts in my codebase. What I need is for the OneTrust scripts to fire before my GTM scripts and for whatever reason I can't seem to get that to happen.

I've tried:

Reordering the scripts in the head

Using j.async and j.defer in the GTM script

Using the addEventListener method to attach a load event listener to the OneTrust script, and then include the Google Tag Manager script inside the event listener function.

document.addEventListener('DOMContentLoaded', function() {
    var gtmScript = document.createElement('script');
    gtmScript.src = 'googletagmanager.js';
    document.body.appendChild(gtmScript);
  });


问:
Is there any waiting for sending message mechanism in RabbitMQ?
I have producer with 3 message types (CREATE, EDIT, DELETE). EDIT method is processing slower then DELETE. So I want to have a guarantee that in situation when EDIT and DELETE messages will be sent one by one, consumer will finish handling this tasks in the correct order.

I propose, to create some data structure that will keep objects, that are now processing. This objects will be waiting for starting processing.

I would like to know best practices in such cases


问:
Passing Oracle Table partition name as parameter in IICS
I am trying to pass the partition name as an in-out parameter in IICS.

select * from xyz partition('$$p_partition')

I am getting mostly [informatica][Oracle JDBC Driver][Oracle]ORA-00933: SQL command not properly ended error. My param file is fine. I tested other parameters without any issues.

How can I pass the parameter successfully?


问:
How to refresh grid when close popup using Blazor DevExpress?
I need refresh a data on DevExpress.Blazor.DxDataGridColumn when I close the PopupEditorContent. The data is a bool of column In Progress.

I have a razor page with a PopupEditorContent that use a Context to edit.

```<code><PopupEditorContent Context="editorContext">
        <DxButton Click="OnCloseClick"
                  Text="CLOSE"></DxButton>
</PopupEditorContent>
</code>```

When I close the popup the data on grid don't change, but when I press F5 and refresh the page, the grid updated and the data change your value.

How to change the value of the gris data without having to refresh the main page?

Body:
I need refresh a data on DevExpress.Blazor.DxDataGridColumn when I close the PopupEditorContent. The data is a bool of column In Progress.

I have a razor page with a PopupEditorContent that use a Context to edit.

<PopupEditorContent Context="editorContext">
        <DxButton Click="OnCloseClick"
                  Text="CLOSE"></DxButton>
</PopupEditorContent>

When I close the popup the data on grid don't change, but when I press F5 and refresh the page, the grid updated and the data change your value.

How to change the value of the gris data without having to refresh the main page?


问:
App Store Connect - Different values in Product Page Optimization vs Analytics? More info via API?
I ran a Product Page Optimization test in App Store Connect. What I don't understand is the "Conversion Rate" measurement.

In the Product Page Optimization I get 6% for both treatments which seems fairly low.

In the app-wide Analytics for that region I see 10% on the "Conversion Rate" metric. I also checked for other regions that MAY have users' localization hit that treatment but they are all above 6%.

Now what exactly is the Product Page Optimization tracking here?

Also, do the Analytics have data on the Revenue per Customer on different treatments or is the only value the Product Page Optimization can be filtered for the weird Conversion Rate? Is there an API that I can programmatically access to get more data or is it all available on the website?


问:
How can I add back the OnInit lifecycle hook and constructor when generating a component in Angular 15?
I know it has been removed in the latest version, so you can add it manually, but i don't really want do copy and paste everytime I generate a component.

I've already found something at this link, but i can't seem to find the files. What should i tweak and how?


问:
VerneMQ enable mqtts protocol on kubernetes
I'm using helm chart to deploy VerneMQ on Kubernetes cluster using the instructed steps to enable mqtts.

values.yaml

service:
  mqtts:
    enabled: true
secretMounts:
  - name: vernemq-certificates
    secretName: vernemq-cert
    path: /etc/ssl/vernemq
additionalEnv:
  - name: DOCKER_VERNEMQ_ACCEPT_EULA
    value: "yes"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__CAFILE
    value: "/etc/ssl/vernemq/tls.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__CERTFILE
    value: "/etc/ssl/vernemq/tls.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__KEYFILE
    value: "/etc/ssl/vernemq/tls.key"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__DEFAULT
    value: "127.0.0.1:8883"
  - name: DOCKER_VERNEMQ_LISTENER__TCP__DEFAULT
    value: "127.0.0.1:8883"
```
<p>The verne-cluster is successfuly deployed but it's not listening on port 8883. The client is disconnected with error <code>Client network socket disconnected before secure TLS connection was established</code>.</p>
<p>I tested the connection using a tcp nginx ingress, <code>port-frowarding</code> and using <code>nc</code> tool from a debug pod on the same namespace to test the port, all indicating the port 8883 was not listening. However the service is enabled for it and inside the container, the service indicates is open.</p>
<pre class="lang-bash prettyprint-override"><code>Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:9100            0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 10.255.21.22:8080       0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 0.0.0.0:4369            0.0.0.0:*               LISTEN      186/epmd
tcp        0      0 127.0.0.1:8883          0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 10.255.21.22:44053      0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 127.0.0.1:8888          0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 10.255.21.22:8888       0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 127.0.0.1:1883          0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 :::4369                 :::*                    LISTEN      186/epmd
</code>```

The only lead I have is the in the error.log, but I've try a fiew configuration variables and none have worked out

[error] <0.434.0>@vmq_ranch_config:reconfigure_listeners_for_type:{269,13} can't reconfigure mqtts listener({127,0,0,1}, 8883) with Options [{max_connections,10000},{nr_of_acceptors,10},{mountpoint,[]},{cafile,"/etc/ssl/vernemq/tls.crt"},{depth,1},{certfile,"/etc/ssl/vernemq/tls.crt"},{eccs,[secp521r1,brainpoolP512r1,brainpoolP384r1,secp384r1,brainpoolP256r1,secp256k1,secp256r1,secp224k1,secp224r1,secp192k1,secp192r1,secp160k1,secp160r1,secp160r2]},{keyfile,"/etc/ssl/vernemq/tls.key"},{require_certificate,false},{tls_version,'tlsv1.2'},{use_identity_as_username,false},{allowed_protocol_versions,[3,4,131]},{allow_anonymous_override,false}] due to {already_started,<0.458.0>}

Body:
I'm using helm chart to deploy VerneMQ on Kubernetes cluster using the instructed steps to enable mqtts.

values.yaml

service:
  mqtts:
    enabled: true
secretMounts:
  - name: vernemq-certificates
    secretName: vernemq-cert
    path: /etc/ssl/vernemq
additionalEnv:
  - name: DOCKER_VERNEMQ_ACCEPT_EULA
    value: "yes"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__CAFILE
    value: "/etc/ssl/vernemq/tls.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__CERTFILE
    value: "/etc/ssl/vernemq/tls.crt"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__KEYFILE
    value: "/etc/ssl/vernemq/tls.key"
  - name: DOCKER_VERNEMQ_LISTENER__SSL__DEFAULT
    value: "127.0.0.1:8883"
  - name: DOCKER_VERNEMQ_LISTENER__TCP__DEFAULT
    value: "127.0.0.1:8883"

The verne-cluster is successfuly deployed but it's not listening on port 8883. The client is disconnected with error Client network socket disconnected before secure TLS connection was established.

I tested the connection using a tcp nginx ingress, port-frowarding and using nc tool from a debug pod on the same namespace to test the port, all indicating the port 8883 was not listening. However the service is enabled for it and inside the container, the service indicates is open.

Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:9100            0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 10.255.21.22:8080       0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 0.0.0.0:4369            0.0.0.0:*               LISTEN      186/epmd
tcp        0      0 127.0.0.1:8883          0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 10.255.21.22:44053      0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 127.0.0.1:8888          0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 10.255.21.22:8888       0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 127.0.0.1:1883          0.0.0.0:*               LISTEN      126/beam.smp
tcp        0      0 :::4369                 :::*                    LISTEN      186/epmd

The only lead I have is the in the error.log, but I've try a fiew configuration variables and none have worked out

[error] <0.434.0>@vmq_ranch_config:reconfigure_listeners_for_type:{269,13} can't reconfigure mqtts listener({127,0,0,1}, 8883) with Options [{max_connections,10000},{nr_of_acceptors,10},{mountpoint,[]},{cafile,"/etc/ssl/vernemq/tls.crt"},{depth,1},{certfile,"/etc/ssl/vernemq/tls.crt"},{eccs,[secp521r1,brainpoolP512r1,brainpoolP384r1,secp384r1,brainpoolP256r1,secp256k1,secp256r1,secp224k1,secp224r1,secp192k1,secp192r1,secp160k1,secp160r1,secp160r2]},{keyfile,"/etc/ssl/vernemq/tls.key"},{require_certificate,false},{tls_version,'tlsv1.2'},{use_identity_as_username,false},{allowed_protocol_versions,[3,4,131]},{allow_anonymous_override,false}] due to {already_started,<0.458.0>}


问:
How to set height in percentage when parent height is in min-height?
The something div grows to 150% of App div but App div doesn't grow to fit something div.

JSFiddle

/* Resetting margin */
*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

html,body,#root
{
  height: 100%;
}

.App {
  height:1px;
  min-height: 100%;
  background-color: green;
}

.something {
  height: 150%;
  width: 50%;
  background-color: blue;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>

  <body>
    <div id="root">
      <div class="App">
        <div class="something"></div>
      </div>
    </div>
  </body>

</html></code>```

As you can tell by the classes, this is actually for a React app. But my problem is that I set the html,body and root div to height:100%; . So next, i set my App div's min-height to min-height:100%; and then I set background-color: green; to the App div cause I want it to have a backgound color. But, setting height:150%;on the something div doesn't work. I found out that it requires the parent div to have a height. So, from a google search, i discovered that setting height:1px; on App div fixes it. I got the 150% value from the App div, but the App div itself doesn't grow to fit the something div's 150% height. How can i fix this?

Body:
The something div grows to 150% of App div but App div doesn't grow to fit something div.

JSFiddle

/* Resetting margin */
*,
*::before,
*::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

html,body,#root
{
  height: 100%;
}

.App {
  height:1px;
  min-height: 100%;
  background-color: green;
}

.something {
  height: 150%;
  width: 50%;
  background-color: blue;
}

As you can tell by the classes, this is actually for a React app. But my problem is that I set the html,body and root div to height:100%; . So next, i set my App div's min-height to min-height:100%; and then I set background-color: green; to the App div cause I want it to have a backgound color. But, setting height:150%;on the something div doesn't work. I found out that it requires the parent div to have a height. So, from a google search, i discovered that setting height:1px; on App div fixes it. I got the 150% value from the App div, but the App div itself doesn't grow to fit the something div's 150% height. How can i fix this?


问:
Plot of direction field and trajectory of second-order ODE (MATLAB)
I need to use Matlab to draw the direction field of the second-order differential equation x'' + sgn(x) = o, where sgn(x) is the sign function: sgn(x) = 1 if x >0 and sgn(x) = -1 if x<0 and also its trajectory when x(0) = 1 and x'(0) = 2. Here is my code for plotting these:

```<code>%Plot direction field:
% set the domain and subintervals in each direction
xdom = linspace(-2,2,25);
ydom = linspace(-2,2,25);

% generate mesh of domain
[X,Y] = meshgrid(xdom,ydom);

% dx/dt
U = Y;

% dy/dt
V = (-0*Y - sign(X));

quiver(X,Y,U,V,'r')

%Plot the trajectory:
syms x(t)
Dx = diff(x)
ode = diff(x,t,2) == -sign(x)
cond1 = x(0) == 1
cond2 = Dx(0) == 2
conds = [cond1 cond2]
xSol = dsolve(ode,conds)
ezplot(xSol)
</code>```

However, two figures seem that the direction field and trajectory don't align with each other (which is contradictory). Could anyone help me point out where I made mistake? Thank you so much!

Body:
I need to use Matlab to draw the direction field of the second-order differential equation x'' + sgn(x) = o, where sgn(x) is the sign function: sgn(x) = 1 if x >0 and sgn(x) = -1 if x<0 and also its trajectory when x(0) = 1 and x'(0) = 2. Here is my code for plotting these:

%Plot direction field:
% set the domain and subintervals in each direction
xdom = linspace(-2,2,25);
ydom = linspace(-2,2,25);

% generate mesh of domain
[X,Y] = meshgrid(xdom,ydom);

% dx/dt
U = Y;

% dy/dt
V = (-0*Y - sign(X));

quiver(X,Y,U,V,'r')

%Plot the trajectory:
syms x(t)
Dx = diff(x)
ode = diff(x,t,2) == -sign(x)
cond1 = x(0) == 1
cond2 = Dx(0) == 2
conds = [cond1 cond2]
xSol = dsolve(ode,conds)
ezplot(xSol)

However, two figures seem that the direction field and trajectory don't align with each other (which is contradictory). Could anyone help me point out where I made mistake? Thank you so much!


问:
Default translation value in custom Angular library
I created Angular library and added translation module @ngx-translate/core and added keys for it. It works properly for keys that root application translated. But if root application (application where is included my custom library) doesn't have some translated keys from Angular library then that value is displayed like key.

My question is how will I set default value for some key in Angular library and that value will be displayed in library if we don't have that translated key in root application.

This is my code in custom library for included Translate

```<code>...
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}
...
@NgModule({
  declarations: [...],
  imports: [...,
TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      },
      defaultLanguage: 'en'
    }),
...],
exports: []
})
export class GridPresetModule {
  static config(authenticationKey: () => string,
    SERVER_ADDRESS: () => string,
    SERVER_ADDRESS_NEW: () => string,
    localStorageTokenKey: () => string): ModuleWithProviders<GridPresetModule> {
    return {
      ngModule: GridPresetModule,
      providers: [...]
        };
  }
}

</code>```

Thanks

Body:
I created Angular library and added translation module @ngx-translate/core and added keys for it. It works properly for keys that root application translated. But if root application (application where is included my custom library) doesn't have some translated keys from Angular library then that value is displayed like key.

My question is how will I set default value for some key in Angular library and that value will be displayed in library if we don't have that translated key in root application.

This is my code in custom library for included Translate

...
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http);
}
...
@NgModule({
  declarations: [...],
  imports: [...,
TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      },
      defaultLanguage: 'en'
    }),
...],
exports: []
})
export class GridPresetModule {
  static config(authenticationKey: () => string,
    SERVER_ADDRESS: () => string,
    SERVER_ADDRESS_NEW: () => string,
    localStorageTokenKey: () => string): ModuleWithProviders<GridPresetModule> {
    return {
      ngModule: GridPresetModule,
      providers: [...]
        };
  }
}

Thanks


问:
php excel Number Validation
I am using php PEAR package to generate MS excel file to allow users supply data offline before uploading.

I need to carry out some numeric validation on specific cells. I want something like this:

cell 1: value<=5 (max=5)
cell 2: value<=10 (max=10)
cell 3: value<=15 (max=15)
```
<p>My code:</p>
```
require_once 'Spreadsheet/Excel/Writer.php';
$workbook = new Spreadsheet_Excel_Writer();
$filename = "Validate.xls";
$workbook->send($filename);
$worksheet =& $workbook->addWorksheet('Number validation');

$worksheet->write(0, 0, 'S/N');
$worksheet->write(0, 1, 'VALUE 2');
$worksheet->write(0, 2, 'VALUE 3');
$worksheet->write(0, 3, 'VALUE 4');

$worksheet->write(1, 0, '1');
$worksheet->write(1, 1, '0');
$worksheet->write(1, 2, '0');
$worksheet->write(1, 3, '0');

$workbook->close();
```
<p>In my search I came across https://pear.php.net/manual/en/package.validate.validate.number.php but don't know how to modify the code above with</p>
```require_once 'Validate.php';

if (Validate::number(8.0004, array('decimal' => '.', 'dec_prec' => 4))) {
    echo 'Valid number';
}
```

to make it validate the user input offline

Any help will be much appreciated

Title: php excel Number Validation

Body:
I am using php PEAR package to generate MS excel file to allow users supply data offline before uploading.

I need to carry out some numeric validation on specific cells. I want something like this:

cell 1: value<=5 (max=5)
cell 2: value<=10 (max=10)
cell 3: value<=15 (max=15)

My code:

require_once 'Spreadsheet/Excel/Writer.php';
$workbook = new Spreadsheet_Excel_Writer();
$filename = "Validate.xls";
$workbook->send($filename);
$worksheet =& $workbook->addWorksheet('Number validation');

$worksheet->write(0, 0, 'S/N');
$worksheet->write(0, 1, 'VALUE 2');
$worksheet->write(0, 2, 'VALUE 3');
$worksheet->write(0, 3, 'VALUE 4');

$worksheet->write(1, 0, '1');
$worksheet->write(1, 1, '0');
$worksheet->write(1, 2, '0');
$worksheet->write(1, 3, '0');

$workbook->close();

In my search I came across https://pear.php.net/manual/en/package.validate.validate.number.php but don't know how to modify the code above with

require_once 'Validate.php';

if (Validate::number(8.0004, array('decimal' => '.', 'dec_prec' => 4))) {
    echo 'Valid number';
}

to make it validate the user input offline

Any help will be much appreciated


问:
Copying all data from Row above to same sheet after double clicking column A
Sorry for the basic question as I'm very new to VBA (day 1). I am trying to create a module which does the following:

You start the module by double clicking column A of the row you want to copy (active row).

The whole of the active row is copied.

A new row is added below the active row (same sheet).

All data in the active row is copied to this new row.

I would also like when you click the cell in column A for a Message box to pop up asking "Would like to copy the data to the row below?" (Yes/No).

I found some code online which allowed me to create the message box when clicking in column A. This seems to work really well and I am happy with this code. But this forum answer only allowed me to copy data from certain columns, not all columns in the active row.

I then found another forum post which did copy the full active row into the row below, and I combined the codes to get the following:

```<code>Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Column > 1 Then Exit Sub
Cancel = True
If MsgBox("Do you want to insert a new row below this row?", vbYesNo) = vbYes Then
    With Target
        Target.Offset(1).EntireRow.Insert
        Target.EntireRow.Copy Target.Offset(1).EntireRow
    End If
End Sub
</code>```

However, when try double clicking in column A, it seems like the original code is still running and its still only copying some of the columns data, not all columns. I'm not sure what I'm missing or if I am using the wrong code to copy the row to the row below.

Any help is appreciated.

Body:
Sorry for the basic question as I'm very new to VBA (day 1). I am trying to create a module which does the following:

You start the module by double clicking column A of the row you want to copy (active row).

The whole of the active row is copied.

A new row is added below the active row (same sheet).

All data in the active row is copied to this new row.

I would also like when you click the cell in column A for a Message box to pop up asking "Would like to copy the data to the row below?" (Yes/No).

I found some code online which allowed me to create the message box when clicking in column A. This seems to work really well and I am happy with this code. But this forum answer only allowed me to copy data from certain columns, not all columns in the active row.

I then found another forum post which did copy the full active row into the row below, and I combined the codes to get the following:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Target.Column > 1 Then Exit Sub
Cancel = True
If MsgBox("Do you want to insert a new row below this row?", vbYesNo) = vbYes Then
    With Target
        Target.Offset(1).EntireRow.Insert
        Target.EntireRow.Copy Target.Offset(1).EntireRow
    End If
End Sub

However, when try double clicking in column A, it seems like the original code is still running and its still only copying some of the columns data, not all columns. I'm not sure what I'm missing or if I am using the wrong code to copy the row to the row below.

Any help is appreciated.


问:
How to pause audio play in expo go react native ios
As per the Expo documentation https://docs.expo.dev/versions/latest/sdk/audio/#pauseasync

it says that pauseAsync() is only available on Android API version 24 and later.

How to pause the audio play in ios?


问:
Target Masking in Huggingface models
I was implementing an encoder-decoder architecture, relying on a custom pytorch encoder and HuggingFace BERT as decoder (so I can't use the EncoderDecoder class of HuggingFace).

My task is translation, so I need to make BERT work in an autoregressive decoder. In the input I don't need word masking, only padding masking. However I do need to mask future target tokens not to "cheat" when training it.

I set the config parameters is_decoder and use_cross_attention to True, and by printing a summary looks like it is correctly linked with the encoder.
However, my issue raises because I don't know what I should pass to the forward method in order to correctly make the target mask.

According to the official documentation (https://huggingface.co/docs/transformers/model_doc/bert#transformers.BertModel), this is the declaration of the method:

def forward(input_ids: typing.Optional[torch.Tensor] = None,
    attention_mask: typing.Optional[torch.Tensor] = None,
    token_type_ids: typing.Optional[torch.Tensor] = None,
    position_ids: typing.Optional[torch.Tensor] = None,
    head_mask: typing.Optional[torch.Tensor] = None,
    inputs_embeds: typing.Optional[torch.Tensor] = None,
    encoder_hidden_states: typing.Optional[torch.Tensor] = None,
    encoder_attention_mask: typing.Optional[torch.Tensor] = None,
    past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None,
    use_cache: typing.Optional[bool] = None,
    output_attentions: typing.Optional[bool] = None,
    output_hidden_states: typing.Optional[bool] = None,
    return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions or tuple(torch.FloatTensor)
```

According to the descriptions, both attention_mask and encoder_attention_mask are used to prevent attending over padding, so as source masks. I was wondering whether one of the two are instead used as target mask when BERT is in is_decoder mode, or if the target mask is automatically handled by HuggingFace, or if simply I'm trying something impossible.

By passing random values to one or the other or both it always gives me an output without exceptions, but I have no clue of what is happening internally, so no way to understand if that output is correct. To know it, I should first train the network, but my training will be very heavy, so I can't try al the possibilities but I need to understand what is happening.

I think that also a general example of BERT used as decoder, assuming to have a working custom encoder could be of great help

Thank you!

Title: Target Masking in Huggingface models

Body:
I was implementing an encoder-decoder architecture, relying on a custom pytorch encoder and HuggingFace BERT as decoder (so I can't use the EncoderDecoder class of HuggingFace).

My task is translation, so I need to make BERT work in an autoregressive decoder. In the input I don't need word masking, only padding masking. However I do need to mask future target tokens not to "cheat" when training it.

I set the config parameters is_decoder and use_cross_attention to True, and by printing a summary looks like it is correctly linked with the encoder.
However, my issue raises because I don't know what I should pass to the forward method in order to correctly make the target mask.

According to the official documentation (https://huggingface.co/docs/transformers/model_doc/bert#transformers.BertModel), this is the declaration of the method:

def forward(input_ids: typing.Optional[torch.Tensor] = None,
    attention_mask: typing.Optional[torch.Tensor] = None,
    token_type_ids: typing.Optional[torch.Tensor] = None,
    position_ids: typing.Optional[torch.Tensor] = None,
    head_mask: typing.Optional[torch.Tensor] = None,
    inputs_embeds: typing.Optional[torch.Tensor] = None,
    encoder_hidden_states: typing.Optional[torch.Tensor] = None,
    encoder_attention_mask: typing.Optional[torch.Tensor] = None,
    past_key_values: typing.Optional[typing.List[torch.FloatTensor]] = None,
    use_cache: typing.Optional[bool] = None,
    output_attentions: typing.Optional[bool] = None,
    output_hidden_states: typing.Optional[bool] = None,
    return_dict: typing.Optional[bool] = None ) → transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions or tuple(torch.FloatTensor)

According to the descriptions, both attention_mask and encoder_attention_mask are used to prevent attending over padding, so as source masks. I was wondering whether one of the two are instead used as target mask when BERT is in is_decoder mode, or if the target mask is automatically handled by HuggingFace, or if simply I'm trying something impossible.

By passing random values to one or the other or both it always gives me an output without exceptions, but I have no clue of what is happening internally, so no way to understand if that output is correct. To know it, I should first train the network, but my training will be very heavy, so I can't try al the possibilities but I need to understand what is happening.

I think that also a general example of BERT used as decoder, assuming to have a working custom encoder could be of great help

Thank you!


问:
Swiper Slider : How to make transitions to slides in CSS and JS?
Could you explain me how to make transitions to Swiper.js slides elements ?

I have a slider with slides that each contains an image and a title.

I would like , when a slide is leaving, fadeOut the title/image of my slide, and when the next slide is arriving, make a fadeIn to its title/image.

Make a blackout between slides is also nice.

I have searched something like "onSlideChange" but I don't know how to use it.

This is a website that contain that kind of functionnality in the homepage :

https://www.operadeparis.fr/

Is it difficult to add/remove CSS to slides depending on their state ? (leaving of arriving)

Thank you


问:
Mui temporary drawer transition not working
I've been trying to implement the temporary drawr on my project together with the responsive and elevated app bar, the responsiviness is working right but the transition of the drawer is gone, aswell as the hover effect of the list items the link how the header of my project is right now

I've tried to search but none of the results helped me.
Thanks in advance!


问:
How to scale sparkline chart relative to cell height in Google Sheets
In Google Sheets, the sparkline formula appears to fill a chart fully into a cell, whatever cell width and cell height is.

Is there any option to scale the chart height relative to the cell height, something like

=sparkline(A1:A5,{"chartheight","50% of cell height"})

I have a very tall cell which stretches the chart unrealistically, which makes it harder to understand.  I have over 100 charts, which is also impractical to define ymin and ymax individually in each sparkline formula and all the charts have way different vales.


问:
Javascript button not downloading image but rather opening it in new tab
```<code>downloadBtn.addEventListener('click', function(e) {
   let a = document.createElement("a");
   a.href = imgTag.src;
   a.target = "_blank";  // open the link in a new tab
   a.click();
});
</code>```

the code above opens the image file in a new browser tab, even after playing with it and trying to make it download the image file, it still and always opens it in rather the same browser tab or in a new browser tab.

If this helps I am testing this on a domain name that is non HTTPS,

I want the button to not open promts but directly download the image file, I read somewhere there is browser blocking for security reasons and that i should use BLOB to find a work around about this.

Can any one help me with this

trying to download the image directly, but it opens the file in browser

Body:
downloadBtn.addEventListener('click', function(e) {
   let a = document.createElement("a");
   a.href = imgTag.src;
   a.target = "_blank";  // open the link in a new tab
   a.click();
});

the code above opens the image file in a new browser tab, even after playing with it and trying to make it download the image file, it still and always opens it in rather the same browser tab or in a new browser tab.

If this helps I am testing this on a domain name that is non HTTPS,

I want the button to not open promts but directly download the image file, I read somewhere there is browser blocking for security reasons and that i should use BLOB to find a work around about this.

Can any one help me with this

trying to download the image directly, but it opens the file in browser


问:
How to make sure all volumes are in a snapshot schedule?
I've been tasked with ensuring all volumes are in a snapshot policy. I have multiple organizations. What's the best/easiest way to make sure everything is getting backed up via snapshot policy?

I can list snapshots and snapshot policies, but how do I make sure nothing's failing to get backed up?

gcloud compute resource-policies list

gcloud compute snapshots list


问:
Which are the benefits of Bayeux protocol compared to REST?
I've been using REST but I want more performance when working with large streams of data. Why does Bayeux protocol may be a better idea than REST? Which are the scenarios where Bayeux is the option?

Doing research and working on a POC for now.


问:
How can I create api users in my node.js app? I can create general login and sign up user but not api user
I want to know how to create an api user and how api user is different from a general user. I want to create api user in node and express.js

I am expecting that I can create an api user.


问:
Glove Vector based model prediction
I trained a model to multilabel input text using glove Vectors.
The model is trained and the tokenizer is also ready but i dont kow how to predict a new input

i tried

```<code>X=tokenizer.texts_to_sequences(["test input"])
X=pad_sequence(X,padding="post",maxlen=maxlen)

prediction = model.predict(X)

</code>```

I though of trying it with the text2vec lib but im also not sure how to use the prediction from that.

the output looks alright but it does not matter what i put in the output is always staying the same.
how do i predict it properly?

Title: Glove Vector based model prediction

Body:
I trained a model to multilabel input text using glove Vectors.
The model is trained and the tokenizer is also ready but i dont kow how to predict a new input

i tried

X=tokenizer.texts_to_sequences(["test input"])
X=pad_sequence(X,padding="post",maxlen=maxlen)

prediction = model.predict(X)

I though of trying it with the text2vec lib but im also not sure how to use the prediction from that.

the output looks alright but it does not matter what i put in the output is always staying the same.
how do i predict it properly?


问:
Does running a multi-threaded Emscripten app in the browser require net access when starting a new thread?
I have a JavaScript+WASM app. The WASM is written in C++, and multi-threaded, built with the -pthread option. It works as expected. But one idea with the app is that, after the app has started and is in a steady state, the network connection can drop and the app should just keep working. I have kinda assumed that of course that will work, why would anything need to be re-downloaded from the web server once things are running.

But now when I then actually try to verify that this indeed is so, to my disappointment I see that after disconnecting the machine from the net, whenever a new thread is to be created, the Emscripten code wants to GET the foo.js and/or foo.worker.js files anew from the web server. Is this a correct understanding? Could this be worked around somehow?


问:
Is there a way to make a test in the meson build system that fails if two files are not identical?
I am using a meson build system to test my program.

As part of the testing process, I generate two files: "a.txt" and "b.txt".

I have a file called "checker.py" that looks like this:

```<code>import argparse
import filecmp
import sys
def checker_main():
    # Initialize parser
    parser = argparse.ArgumentParser()
    parser.parse_args()

    parser.add_argument(
            "file1", required=True
        )
    parser.add_argument(
            "file2", required=True
        )

    args = parser.parse_args()
    same_contents = filecmp.cmp(args.file1, args.file2)

    if same_contents is False:
        sys.exit(args.file1 + " and " + args.file2 + " are different")

if __name__ == "__main__":
    checker_main()
</code>```

I want to run a meson test that fails if "a.txt" and "b.txt" are different. Is there an easy way to do so?

I have tried to make executables in meson and custom_targets, but cannot figure out how to make a test that performs the function I need.

Body:
I am using a meson build system to test my program.

As part of the testing process, I generate two files: "a.txt" and "b.txt".

I have a file called "checker.py" that looks like this:

import argparse
import filecmp
import sys
def checker_main():
    # Initialize parser
    parser = argparse.ArgumentParser()
    parser.parse_args()

    parser.add_argument(
            "file1", required=True
        )
    parser.add_argument(
            "file2", required=True
        )

    args = parser.parse_args()
    same_contents = filecmp.cmp(args.file1, args.file2)

    if same_contents is False:
        sys.exit(args.file1 + " and " + args.file2 + " are different")

if __name__ == "__main__":
    checker_main()

I want to run a meson test that fails if "a.txt" and "b.txt" are different. Is there an easy way to do so?

I have tried to make executables in meson and custom_targets, but cannot figure out how to make a test that performs the function I need.


问:
How Web3j is used to get the SC wrappers and operate with them using Java (Eclipse ide)
I am creating a blockchain related project but can't able to run it appropriately on browser. To know about the project I am attaching the link of the project is given below -
https://github.com/toful/BC_GDPR-Compliant_PDManagement_System

I am trying to configure the truffle, ganache and java file but can't able to get success.
Expecting to get similar to this web page..


问:
Tab out of {} from if statement vscode
I installed the tab out extension in vscode. It works fine for most things, expect when I use a if statement and have a block of code.

If (a=0) {
  printed("test");
}
```

After the ; sign tab out won't work when the } sign is not at the same line.

Title: Tab out of {} from if statement vscode

Body:
I installed the tab out extension in vscode. It works fine for most things, expect when I use a if statement and have a block of code.

If (a=0) {
  printed("test");
}

After the ; sign tab out won't work when the } sign is not at the same line.


问:
how can i change info and position of an excel file that i make a list from information that it has
So i am trying to make a list that i get informations from a excel file and with button i am displaying them. I write this code so far but my problem is that i cant change anything on excel file that i get informations. Also i cant change the location of the excel file when i am trying to change location or add new info on excel file.Excel file stop running and gives error. My code is working but i get problem with excel file. I look up on internet but i couldn't really find a working answer for my situation so how can i solve this problem? Can you help me with it?</p>
```<code>import pandas as pd
import openpyxl
import pathlib
import datetime
import xlrd
import numpy
from tkinter import *
from tkinter import messagebox
import subprocess

parent = Tk()
parent.title('List')

data = pd.ExcelFile('excel_name.xlsx')

def submitFunction1() :

    df1 = pd.read_excel(data, 'excel_sheet', header = 1)

    dates1=pd.DataFrame(df1,columns=['FİRMA','SON BAKIM TARİHİ'])

    aa=len(dates1)

    listT1=[]
    listT2=[]

    for i in range(aa) :
        valueT = dates1.loc[i,'SON BAKIM TARİHİ']
        companiesT = dates1.loc[i,'FİRMA']
        deadlineT = valueT + datetime.timedelta(days=0)
        pdateT = datetime.datetime.now()

        if pdateT<deadlineT:
                listT2.append(companiesT)
                listT2.append(deadlineT)

        elif pdateT>deadlineT: #zamanı geçmiş
            listT1.append(companiesT)
            listT1.append(deadlineT)

        elif pdateT==deadlineT:

               print("bugun kalibrasyon gunu")
    messagebox.showinfo('Message', listT1)

Button(parent, text="List1",command=submitFunction1).grid(row=0, column=10, sticky='e' + 'w', padx=50, pady=50)

parent.mainloop()

</code>```

Body:
So i am trying to make a list that i get informations from a excel file and with button i am displaying them. I write this code so far but my problem is that i cant change anything on excel file that i get informations. Also i cant change the location of the excel file when i am trying to change location or add new info on excel file.Excel file stop running and gives error. My code is working but i get problem with excel file. I look up on internet but i couldn't really find a working answer for my situation so how can i solve this problem? Can you help me with it?

import pandas as pd
import openpyxl
import pathlib
import datetime
import xlrd
import numpy
from tkinter import *
from tkinter import messagebox
import subprocess

parent = Tk()
parent.title('List')

data = pd.ExcelFile('excel_name.xlsx')

def submitFunction1() :

    df1 = pd.read_excel(data, 'excel_sheet', header = 1)

    dates1=pd.DataFrame(df1,columns=['FİRMA','SON BAKIM TARİHİ'])

    aa=len(dates1)

    listT1=[]
    listT2=[]

    for i in range(aa) :
        valueT = dates1.loc[i,'SON BAKIM TARİHİ']
        companiesT = dates1.loc[i,'FİRMA']
        deadlineT = valueT + datetime.timedelta(days=0)
        pdateT = datetime.datetime.now()

        if pdateT<deadlineT:
                listT2.append(companiesT)
                listT2.append(deadlineT)

        elif pdateT>deadlineT: #zamanı geçmiş
            listT1.append(companiesT)
            listT1.append(deadlineT)

        elif pdateT==deadlineT:

               print("bugun kalibrasyon gunu")
    messagebox.showinfo('Message', listT1)

Button(parent, text="List1",command=submitFunction1).grid(row=0, column=10, sticky='e' + 'w', padx=50, pady=50)

parent.mainloop()


问:
Pycharm or EEL timing out?
I'm writing a Python program in Pycharm and using Eel for an HTML front end.

The problem I'm encountering is that my program runs fine and does what it's supposed to do BUT one of my functions takes about 2 hours to run and once it's done, the program stops running with "Process finished with exit code 0" and Python stops running.  My Eel/web interface also becomes unresponsive.

If I comment out the part of the function that's time consuming, everything runs as expected.

I don't know what the issue is and I was hoping someone could share some insight.  Maybe it's a Windows setting, maybe it's something specific to Pycharm or eel.  I really don't know.

Thanks

Title: Pycharm or EEL timing out?


问:
nginx proble : failed (2: No such file or directory)
I try to deploy clearwater-docker on k8s
github:https://github.com/Metaswitch/clearwater-docker
i have some problem on homestead-prov pods

my nginx error.log

```<code>2023/01/10 17:26:31 [crit] 25728#0: *11520 connect() to unix:/tmp/.homestead-prov-sock-5 failed (2: No such file or directory) while connecting to upstream, client: ::ffff:127.0.0.1, server: homestead-prov.default.svc.cluster.local, request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/.homestead-prov-sock-5:/ping", host: "127.0.0.1:8889"
2023/01/10 17:26:31 [crit] 25728#0: *11520 connect() to unix:/tmp/.homestead-prov-sock-6 failed (2: No such file or directory) while connecting to upstream, client: ::ffff:127.0.0.1, server: homestead-prov.default.svc.cluster.local, request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/.homestead-prov-sock-6:/ping", host: "127.0.0.1:8889"
2023/01/10 17:26:34 [crit] 25728#0: *11524 connect() to unix:/tmp/.homestead-prov-sock-7 failed (2: No such file or directory) while connecting to upstream, client: ::ffff:127.0.0.1, server: homestead-prov.default.svc.cluster.local, request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/.homestead-prov-sock-7:/ping", host: "127.0.0.1:8889"

</code>```

and this is my nginx setting

```<code>user www-data;
worker_processes 32;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        server_names_hash_bucket_size 64;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}
</code>```

and this is the code in sites-enabled
sites-enabled/homestead-prov
ping
homestead-prov:

```<code>  upstream http_homestead_prov {
        server unix:/tmp/.homestead-prov-sock-0;
        server unix:/tmp/.homestead-prov-sock-1;
        server unix:/tmp/.homestead-prov-sock-2;
        server unix:/tmp/.homestead-prov-sock-3;
        server unix:/tmp/.homestead-prov-sock-4;
        server unix:/tmp/.homestead-prov-sock-5;
        server unix:/tmp/.homestead-prov-sock-6;
        server unix:/tmp/.homestead-prov-sock-7;

        # The minimum number of idle connections to keep alive to the upstream.
        keepalive 16;
}

server {
        listen       [::]:8889 ipv6only=off;
        server_name  homestead-prov.default.svc.cluster.local;

        location / {
                proxy_pass http://http_homestead_prov;
                proxy_http_version 1.1;

                # The client may have instructed the server to close the
                # connection - do not forward this upstream.
                proxy_set_header Connection "";
        }
}

</code>```

ping

```<code>server {
        listen      127.0.0.1:8000;
        server_name ping;

        location /ping {
                 return 200;
        }
}

</code>```

the problem in homestead-prov

Body:
I try to deploy clearwater-docker on k8s
github:https://github.com/Metaswitch/clearwater-docker
i have some problem on homestead-prov pods

my nginx error.log

2023/01/10 17:26:31 [crit] 25728#0: *11520 connect() to unix:/tmp/.homestead-prov-sock-5 failed (2: No such file or directory) while connecting to upstream, client: ::ffff:127.0.0.1, server: homestead-prov.default.svc.cluster.local, request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/.homestead-prov-sock-5:/ping", host: "127.0.0.1:8889"
2023/01/10 17:26:31 [crit] 25728#0: *11520 connect() to unix:/tmp/.homestead-prov-sock-6 failed (2: No such file or directory) while connecting to upstream, client: ::ffff:127.0.0.1, server: homestead-prov.default.svc.cluster.local, request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/.homestead-prov-sock-6:/ping", host: "127.0.0.1:8889"
2023/01/10 17:26:34 [crit] 25728#0: *11524 connect() to unix:/tmp/.homestead-prov-sock-7 failed (2: No such file or directory) while connecting to upstream, client: ::ffff:127.0.0.1, server: homestead-prov.default.svc.cluster.local, request: "GET /ping HTTP/1.1", upstream: "http://unix:/tmp/.homestead-prov-sock-7:/ping", host: "127.0.0.1:8889"

and this is my nginx setting

user www-data;
worker_processes 32;
pid /run/nginx.pid;

events {
        worker_connections 768;
        # multi_accept on;
}

http {
        sendfile on;
        tcp_nopush on;
        tcp_nodelay on;
        keepalive_timeout 65;
        types_hash_max_size 2048;

        server_names_hash_bucket_size 64;

        include /etc/nginx/mime.types;
        default_type application/octet-stream;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        gzip on;
        gzip_disable "msie6";

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;
}

and this is the code in sites-enabled
sites-enabled/homestead-prov
ping
homestead-prov:

  upstream http_homestead_prov {
        server unix:/tmp/.homestead-prov-sock-0;
        server unix:/tmp/.homestead-prov-sock-1;
        server unix:/tmp/.homestead-prov-sock-2;
        server unix:/tmp/.homestead-prov-sock-3;
        server unix:/tmp/.homestead-prov-sock-4;
        server unix:/tmp/.homestead-prov-sock-5;
        server unix:/tmp/.homestead-prov-sock-6;
        server unix:/tmp/.homestead-prov-sock-7;

        # The minimum number of idle connections to keep alive to the upstream.
        keepalive 16;
}

server {
        listen       [::]:8889 ipv6only=off;
        server_name  homestead-prov.default.svc.cluster.local;

        location / {
                proxy_pass http://http_homestead_prov;
                proxy_http_version 1.1;

                # The client may have instructed the server to close the
                # connection - do not forward this upstream.
                proxy_set_header Connection "";
        }
}

ping

server {
        listen      127.0.0.1:8000;
        server_name ping;

        location /ping {
                 return 200;
        }
}

the problem in homestead-prov


问:
How to play a music after the completion of the function script in google app scripts
How to play a music after the completion of the function script in Google Apps Scripts

Is it possible to play a music after the completion of the function script when the popup "the task has been completed" will be popped up, secondly the Popup of "the task has been completed" is not appearing after the completion of the function. Code is given below:

```<code>function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
    .createMenu('Custom Menu')
    .addItem('Show alert', 'showAlert')
    .addToUi();
}

function showAlert() {
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert(
    Please confirm ',
    Are you sure you want to
    continue ?
        if so then please make sure that your drive folder is completely empty ',
    ui.ButtonSet.YES_NO);
// Process the user's response.
if (result == ui.Button.YES) {
    // User clicked "Yes".
    {
        let sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
        let lastRow = sheet.getLastRow();
        for (let i = 0; i < lastRow - 2; i++) {
            const ss = SpreadsheetApp.getActive();
            const folder_id = ss.getRange("Sheet1!J4").getValue(); // get value in
"Settings!C9"
            const destinationFolder = DriveApp.getFolderById(folder_id)

            let folder = DriveApp.getFolderById(folder_id);
            let url = sheet.getRange(3 + i, 1).getValue();
            let image = SpreadsheetApp.newCellImage().setSourceUrl(url);
            let blob = UrlFetchApp.fetch(url).getBlob();
            let name = sheet.getRange(3 + i, 2).getValue();
            folder.createFile(blob).setName(name);
            sheet.getRange(3 + i, 3).setValue("Completed");
        }
        ui.alert("task has been completed")

    };

} else {
    // User clicked "No" or X in the title bar.
    ui.alert('Permission denied.');
}
}
</code>```

Body:
How to play a music after the completion of the function script in Google Apps Scripts

Is it possible to play a music after the completion of the function script when the popup "the task has been completed" will be popped up, secondly the Popup of "the task has been completed" is not appearing after the completion of the function. Code is given below:

function onOpen() {
SpreadsheetApp.getUi() // Or DocumentApp or SlidesApp or FormApp.
    .createMenu('Custom Menu')
    .addItem('Show alert', 'showAlert')
    .addToUi();
}

function showAlert() {
var ui = SpreadsheetApp.getUi(); // Same variations.
var result = ui.alert(
    Please confirm ',
    Are you sure you want to
    continue ?
        if so then please make sure that your drive folder is completely empty ',
    ui.ButtonSet.YES_NO);
// Process the user's response.
if (result == ui.Button.YES) {
    // User clicked "Yes".
    {
        let sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
        let lastRow = sheet.getLastRow();
        for (let i = 0; i < lastRow - 2; i++) {
            const ss = SpreadsheetApp.getActive();
            const folder_id = ss.getRange("Sheet1!J4").getValue(); // get value in
"Settings!C9"
            const destinationFolder = DriveApp.getFolderById(folder_id)

            let folder = DriveApp.getFolderById(folder_id);
            let url = sheet.getRange(3 + i, 1).getValue();
            let image = SpreadsheetApp.newCellImage().setSourceUrl(url);
            let blob = UrlFetchApp.fetch(url).getBlob();
            let name = sheet.getRange(3 + i, 2).getValue();
            folder.createFile(blob).setName(name);
            sheet.getRange(3 + i, 3).setValue("Completed");
        }
        ui.alert("task has been completed")

    };

} else {
    // User clicked "No" or X in the title bar.
    ui.alert('Permission denied.');
}
}


问:
Angular Storybook ngTemplateOutlet problem
I'm currently implementing a storybook to document my design system, but i can't find ou how to create a story for this component. I'm explaining my problem :
Here is my component which is a select component :

import {Component, EventEmitter, Input, Output, TemplateRef} from '@angular/core';

@Component({
  selector: 'wgw-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.scss']
})
export class SelectComponent<T extends {id: string | number}> {

  @Input() itemTemplate!: TemplateRef<any>;
  @Input() items: T[];
  @Input() selectedItem: T;
  @Output() selectedItemChange: EventEmitter<T> = new EventEmitter<T>();

  selectValue(newValue: T) {
    this.selectedItem = newValue;
    this.selectedItemChange.emit(this.selectedItem);
  }

  equals(item1: T, item2: T) {
    return item1?.id === item2?.id
  }
}
```
<pre class="lang-html prettyprint-override"><code><div class="dropdown">
  <button class="fs-4" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
    <ng-container *ngTemplateOutlet="this.itemTemplate; context: {item: selectedItem}"></ng-container>
    <wgw-icon name="chevron-down" class="ms-4"></wgw-icon>
  </button>
  <div class="dropdown-menu mt-5" aria-labelledby="dropdownMenuButton1">
    <div class="dropdown-item fs-4" *ngFor="let item of items" (click)="selectValue(item)" [class.selected]="equals(selectedItem, item)">
      <wgw-icon [name]="'check'" *ngIf="equals(selectedItem, item)" class="me-4"></wgw-icon>
      <ng-container *ngTemplateOutlet="this.itemTemplate; context: {item: item}"></ng-container>
    </div>
  </div>
</div>
</code>```

And here is the story i've created so far

import {SelectComponent} from '@design-system/atom/select/select.component';
import {moduleMetadata, Story} from '@storybook/angular';
import {IconComponent} from '@design-system/atom/icon/icon.component';

export default {
  title: 'Atom/Select',
  component: SelectComponent,
  args: {

  },
  decorators: [
    moduleMetadata({
      declarations: [IconComponent]
    }),
  ],
}

const Template: Story<SelectComponent<any>> = (args) => ({
  props: args,
  template: `

        <ng-template #itemTestTemplate let-item="item">
          {{ item?.name }}
        </ng-template>
        <wgw-select [items]="items" [itemTemplate]="itemTestTemplate"></wgw-select>

  `
})

export const Select = Template.bind({});
Select.args = {
  items: [
    {id: 0, name: 'item1'},
    {id: 1, name: 'item2'},
    {id: 2, name: 'item3'}
  ],
  selectedItem: {id: 0, name: 'item1'}
}
```

The problem i have is this : i'm passing my template to my component with this [itemTemplate]="itemTestTemplate" but it seems this template have no access to the "item" in my storybook.

Do you know where this problem can come from ? And how i can fix this ?

Thanks !

Body:
I'm currently implementing a storybook to document my design system, but i can't find ou how to create a story for this component. I'm explaining my problem :
Here is my component which is a select component :

import {Component, EventEmitter, Input, Output, TemplateRef} from '@angular/core';

@Component({
  selector: 'wgw-select',
  templateUrl: './select.component.html',
  styleUrls: ['./select.component.scss']
})
export class SelectComponent<T extends {id: string | number}> {

  @Input() itemTemplate!: TemplateRef<any>;
  @Input() items: T[];
  @Input() selectedItem: T;
  @Output() selectedItemChange: EventEmitter<T> = new EventEmitter<T>();

  selectValue(newValue: T) {
    this.selectedItem = newValue;
    this.selectedItemChange.emit(this.selectedItem);
  }

  equals(item1: T, item2: T) {
    return item1?.id === item2?.id
  }
}

  <button class="fs-4" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
    <ng-container *ngTemplateOutlet="this.itemTemplate; context: {item: selectedItem}"></ng-container>
    <wgw-icon name="chevron-down" class="ms-4"></wgw-icon>
  </button>

      <wgw-icon [name]="'check'" *ngIf="equals(selectedItem, item)" class="me-4"></wgw-icon>
      <ng-container *ngTemplateOutlet="this.itemTemplate; context: {item: item}"></ng-container>

And here is the story i've created so far

import {SelectComponent} from '@design-system/atom/select/select.component';
import {moduleMetadata, Story} from '@storybook/angular';
import {IconComponent} from '@design-system/atom/icon/icon.component';

export default {
  title: 'Atom/Select',
  component: SelectComponent,
  args: {

  },
  decorators: [
    moduleMetadata({
      declarations: [IconComponent]
    }),
  ],
}

const Template: Story<SelectComponent<any>> = (args) => ({
  props: args,
  template: `

        <ng-template #itemTestTemplate let-item="item">
          {{ item?.name }}
        </ng-template>
        <wgw-select [items]="items" [itemTemplate]="itemTestTemplate"></wgw-select>

  `
})

export const Select = Template.bind({});
Select.args = {
  items: [
    {id: 0, name: 'item1'},
    {id: 1, name: 'item2'},
    {id: 2, name: 'item3'}
  ],
  selectedItem: {id: 0, name: 'item1'}
}

The problem i have is this : i'm passing my template to my component with this [itemTemplate]="itemTestTemplate" but it seems this template have no access to the "item" in my storybook.

Do you know where this problem can come from ? And how i can fix this ?

Thanks !


问:
Custom line UITextView
I have one UITextView.
I can have a UITextView with only one line and with horizontal scrolling only?

Thanks

ContentLicense: CC BY-SA 3.0

Title: Custom line UITextView


问:
can not add numbers to global variables from inside a function
I am doing a project for a computer science NEA and I need to solve this problem, the problem being that global variables just won't work in the function. I'm probably being stupid but I'm not the best python programmer and it is really bugging me, it is a bunch of 'if' loops due to it being a selection algorithm, all help appreciated thanks!
The main issue is that it always adds 1 to 'c' no matter if i write something like 'warlike' where it should add 1 to 'd'
The bit of the code where issues are being had is down below or above, im not sure how this website works much, but the code is somewhere close to this message, looking forward to hearing from you all!</p>
```<code>    c = int(0)
    csh = int(0)
    d = int(0)
    dsh = int(0)
    e = int(0)
    f = int(0)
    fsh = int(0)
    g = int(0)
    gsh = int(0)
    a = int(0)
    ash = int(0)
    b = int(0)

    def add_item(event=1):
      global list1
      global c
      global csh
      global d
      global dsh
      global e
      global f
      global fsh
      global g
      global gsh
      global a
      global ash
      global b
      if entry1.get() != "":
          listbox.insert(tk.END, entry1.get())
          #entry1.set("")
      if entry1 == "happy" or "cheerful" or "sunny" or "daytime":
        c = c + 1
      elif entry1 == "seldom" or "quaint" or "surly" or "discontent":
        csh = csh + 1
      elif entry1 == "triumphant" or "warlike" or "symphony" or "rejoice":
        d = d + 1
      elif entry1 == "love" or "god" or "heart" or "pop":
        dsh = dsh + 1
      elif entry1 == "joy" or "pleasure" or "laughter" or "delight":
        e = e + 1
      elif entry1 == "calm" or "complaisance" or "relaxing" or "soothing":
        f = f + 1
      elif entry1 == "relief" or "conquering" or "completeness" or "battle":
        fsh = fsh + 1
      elif entry1 == "rustic" or "idyllic" or "satisfying" or "tender":
        g = g + 1
      elif entry1 == "death" or "grave" or "dark" or "doom":
        gsh = gsh + 1
      elif entry1 == "innocence" or "affair" or "beloving" or "parting":
        a = a + 1
      elif entry1 == "cool" or "wild" or "bewildering" or "magestic":
        ash = ash + 1
      elif entry1 == "night" or "party" or "starry" or "galactic":
        b = b + 1
      entry1.delete(0, tk.END)
      list1.append(entry1.get())
</code>```

Body:
I am doing a project for a computer science NEA and I need to solve this problem, the problem being that global variables just won't work in the function. I'm probably being stupid but I'm not the best python programmer and it is really bugging me, it is a bunch of 'if' loops due to it being a selection algorithm, all help appreciated thanks!
The main issue is that it always adds 1 to 'c' no matter if i write something like 'warlike' where it should add 1 to 'd'
The bit of the code where issues are being had is down below or above, im not sure how this website works much, but the code is somewhere close to this message, looking forward to hearing from you all!

    c = int(0)
    csh = int(0)
    d = int(0)
    dsh = int(0)
    e = int(0)
    f = int(0)
    fsh = int(0)
    g = int(0)
    gsh = int(0)
    a = int(0)
    ash = int(0)
    b = int(0)

    def add_item(event=1):
      global list1
      global c
      global csh
      global d
      global dsh
      global e
      global f
      global fsh
      global g
      global gsh
      global a
      global ash
      global b
      if entry1.get() != "":
          listbox.insert(tk.END, entry1.get())
          #entry1.set("")
      if entry1 == "happy" or "cheerful" or "sunny" or "daytime":
        c = c + 1
      elif entry1 == "seldom" or "quaint" or "surly" or "discontent":
        csh = csh + 1
      elif entry1 == "triumphant" or "warlike" or "symphony" or "rejoice":
        d = d + 1
      elif entry1 == "love" or "god" or "heart" or "pop":
        dsh = dsh + 1
      elif entry1 == "joy" or "pleasure" or "laughter" or "delight":
        e = e + 1
      elif entry1 == "calm" or "complaisance" or "relaxing" or "soothing":
        f = f + 1
      elif entry1 == "relief" or "conquering" or "completeness" or "battle":
        fsh = fsh + 1
      elif entry1 == "rustic" or "idyllic" or "satisfying" or "tender":
        g = g + 1
      elif entry1 == "death" or "grave" or "dark" or "doom":
        gsh = gsh + 1
      elif entry1 == "innocence" or "affair" or "beloving" or "parting":
        a = a + 1
      elif entry1 == "cool" or "wild" or "bewildering" or "magestic":
        ash = ash + 1
      elif entry1 == "night" or "party" or "starry" or "galactic":
        b = b + 1
      entry1.delete(0, tk.END)
      list1.append(entry1.get())


问:
Can't run CD command inside a batchfile inside vscode
When I tried to run a batchfile (with a cd command) outside vscode, it is working, but if inside vscode its not. What options do I have in order to run a CD command inside a batchfile inside vscode, when I try to open my project in vscode, it has a lengthy path, so I need to automatically cd to the correct path automatically by using a batchfile? Why does vscode behave like this?</p>