问:
Antlr How to avoid reportAttemptingFullContext and reportAmbiguity
In my java program im parsing many lines of code and to avoid ambiguous lines i used:

```<code>ParseTreeWalker walker = new ParseTreeWalker ();
if (!(lexerErrorListener.hasError() || parserErrorListener.hasError ()))
     walker.walk (listener, tree);
else
     line error
</code>```

with the listener:

```<code>        @Override
        public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact,
                BitSet ambigAlts, ATNConfigSet configs) {
            hasError = true;
        }

        @Override
        public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
            BitSet conflictingAlts, ATNConfigSet configs) {
            hasError = true;
        }
</code>```

input like: |U1,0 = comment generate ambiguity and fullcontext error with my grammar.
is a wrong approach or is there a way to handle these errors?

My Lexer:

```<code> lexer grammar LexerGrammar;

SINGLE_COMMENT : '|' -> pushMode(COMMENT);
NUMBER : [0-9];
VIRGOLA : ',';
WS  : [ \t] -> skip ;
EOL : [\r\n]+;

// ------------ Everything INSIDE a COMMENT ------------
mode COMMENT;
    COMMENT_NUMBER  : NUMBER -> type(NUMBER);
    COMMENT_VIRGOLA : VIRGOLA -> type(VIRGOLA);

    TYPE : 'I'| 'U'| 'Q';

    EQUAL : '=';

    COMMENT_TEXT: ('a'..'z' | 'A'..'Z')+;

    WS_1        : [ \t] -> skip ;
    COMMENT_EOL : EOL -> type(EOL),popMode;
</code>```

my parser:

```<code> parser grammar Parser;

options {
      tokenVocab = LexerGrammar;
  }

prog : (line? EOL)+;
line : comment;

comment: SINGLE_COMMENT (defComm | genericComment);
defComm: TYPE arg EQUAL COMMENT_TEXT;
arg : (argument1) (VIRGOLA argument2)?;

argument1    : numbers ;
argument2    : numbers ;
numbers      : NUMBER+ ;
genericComment: .*?;
</code>```

答:
reportAmbiguity and reportAttemptingFullContext are not an indication that there was a syntax error.  You can listen in on these events to know if they happen, but ANTLR has a deterministic approach to resolving this ambiguity (it uses the first alternative).

If you do not treat those as errors, you will get a proper parse tree out of your parse.

Body:
In my java program im parsing many lines of code and to avoid ambiguous lines i used:

ParseTreeWalker walker = new ParseTreeWalker ();
if (!(lexerErrorListener.hasError() || parserErrorListener.hasError ()))
     walker.walk (listener, tree);
else
     line error

with the listener:

        @Override
        public void reportAmbiguity(Parser recognizer, DFA dfa, int startIndex, int stopIndex, boolean exact,
                BitSet ambigAlts, ATNConfigSet configs) {
            hasError = true;
        }

        @Override
        public void reportAttemptingFullContext(Parser recognizer, DFA dfa, int startIndex, int stopIndex,
            BitSet conflictingAlts, ATNConfigSet configs) {
            hasError = true;
        }

input like: |U1,0 = comment generate ambiguity and fullcontext error with my grammar.
is a wrong approach or is there a way to handle these errors?

My Lexer:

 lexer grammar LexerGrammar;

SINGLE_COMMENT : '|' -> pushMode(COMMENT);
NUMBER : [0-9];
VIRGOLA : ',';
WS  : [ \t] -> skip ;
EOL : [\r\n]+;

// ------------ Everything INSIDE a COMMENT ------------
mode COMMENT;
    COMMENT_NUMBER  : NUMBER -> type(NUMBER);
    COMMENT_VIRGOLA : VIRGOLA -> type(VIRGOLA);

    TYPE : 'I'| 'U'| 'Q';

    EQUAL : '=';

    COMMENT_TEXT: ('a'..'z' | 'A'..'Z')+;

    WS_1        : [ \t] -> skip ;
    COMMENT_EOL : EOL -> type(EOL),popMode;

my parser:

 parser grammar Parser;

options {
      tokenVocab = LexerGrammar;
  }

prog : (line? EOL)+;
line : comment;

comment: SINGLE_COMMENT (defComm | genericComment);
defComm: TYPE arg EQUAL COMMENT_TEXT;
arg : (argument1) (VIRGOLA argument2)?;

argument1    : numbers ;
argument2    : numbers ;
numbers      : NUMBER+ ;
genericComment: .*?;


来源: stackexchange

问:
change div to increase progress bar
I'm working to have my progress bar increase when a specific word is said (Bingo)
This is a conversation between a user and a chatbot, where the user is trying to guess a secret that the chatbot olds. Every time the user gets it right, the chatbot replies with "Bingo! " I was hoping to increase the progress bar every time the chatbot replies with "Bingo! " and when the progress bare hits 100% it should restart back to 0%. I get the progress bar shows, but it does not increase. I was thinking of having to loop through the div to look for "Bingo" and change the div in the progress bar. Or simply have a "Bingo" as a variable and match it to the div="bingo1" and then increase the progress bar. What would be the most efficient way?

I'm using chatterbot which contains the conversation between the user and chatbot in a .yml file, so it is possible to do something there

function myBingo(){
  if (document.getElementById('bingo1').innerHTML.indexOf("Bingo")){
    // change progress bar to 10%
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#progress {
 width: 500px;
 border: 1px solid black;
 position: relative;
 padding: 3px;
}
#percent {
 position: absolute;
 left: 50%;
}
#bar {
 height: 20px;
 background-color: green;
 width: 0%;
}</code>```

Bingo! The secret is Garfield

    0%

```

答:
He might have given a different answer as he didn't quite understand what he wanted. In the solution below, the progress bar will be increased by the number of Bingo expressions entered into the item whose id value is bingo1.

If you're asking something different, please edit the question or comment below this answer.

let percent = document.getElementById('percent');
let bar = document.getElementById('bar');
let input = document.getElementById('bingo1');
let counter = 0;

function update() {
  if (input.value.indexOf("Bingo") != -1)
  {
    var count = (input.value.match(/Bingo/g) || []).length;
    counter = count * 10;

    if(counter >= 100)
      counter = 100;

    percent.innerHTML = `${counter}%`;
    bar.style.width = `${counter}%`;
  }
}

input.addEventListener('input', update);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#progress {
 width: 500px;
 border: 1px solid black;
 position: relative;
 padding: 3px;
}

#percent {
 position: absolute;
 left: 50%;
}

#bar {
 height: 20px;
 background-color: green;
 width: 0%;
}</code>```

Input:
<input class="msg-text" id="bingo1">

    0%

```

ContentLicense: CC BY-SA 4.0

Title: change div to increase progress bar

Body:
I'm working to have my progress bar increase when a specific word is said (Bingo)
This is a conversation between a user and a chatbot, where the user is trying to guess a secret that the chatbot olds. Every time the user gets it right, the chatbot replies with "Bingo! " I was hoping to increase the progress bar every time the chatbot replies with "Bingo! " and when the progress bare hits 100% it should restart back to 0%. I get the progress bar shows, but it does not increase. I was thinking of having to loop through the div to look for "Bingo" and change the div in the progress bar. Or simply have a "Bingo" as a variable and match it to the div="bingo1" and then increase the progress bar. What would be the most efficient way?

I'm using chatterbot which contains the conversation between the user and chatbot in a .yml file, so it is possible to do something there

function myBingo(){
  if (document.getElementById('bingo1').innerHTML.indexOf("Bingo")){
    // change progress bar to 10%
  }
}

#progress {
 width: 500px;
 border: 1px solid black;
 position: relative;
 padding: 3px;
}
#percent {
 position: absolute;
 left: 50%;
}
#bar {
 height: 20px;
 background-color: green;
 width: 0%;
}

Bingo! The secret is Garfield

    0%

Body:
He might have given a different answer as he didn't quite understand what he wanted. In the solution below, the progress bar will be increased by the number of Bingo expressions entered into the item whose id value is bingo1.

If you're asking something different, please edit the question or comment below this answer.

let percent = document.getElementById('percent');
let bar = document.getElementById('bar');
let input = document.getElementById('bingo1');
let counter = 0;

function update() {
  if (input.value.indexOf("Bingo") != -1)
  {
    var count = (input.value.match(/Bingo/g) || []).length;
    counter = count * 10;

    if(counter >= 100)
      counter = 100;

    percent.innerHTML = `${counter}%`;
    bar.style.width = `${counter}%`;
  }
}

input.addEventListener('input', update);

#progress {
 width: 500px;
 border: 1px solid black;
 position: relative;
 padding: 3px;
}

#percent {
 position: absolute;
 left: 50%;
}

#bar {
 height: 20px;
 background-color: green;
 width: 0%;
}

<label>Input: </label>
<input class="msg-text" id="bingo1"><br><br>

<div id="progress">
    <span id="percent">0%</span>
    <div id="bar"></div>
</div><br><br>


问:
Setting auth level in CoInitializeSecurity is not raising the authentication level
I am trying to raise the auth level to RPC_C_AUTHN_LEVEL_PKT_INTEGRITY but I still get access denied failure and see the following error in event viewer:

Application XXX is requesting with explicitly set authentication level at 2.

The lowest activation authentication level required by DCOM is 5(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY).

To raise the activation authentication level, please contact the application vendor.

I am not sure why it says "level 2" when I am clearly setting it to 5 (RPC_C_AUTHN_LEVEL_PKT_INTEGRITY) in CoInitializeSecurity().

Is there something else besides setting the authentication level in CoInitializeSecurity() that I need and is missing?

Here is my code:

```<code>hr = CoInitializeSecurity(NULL /*sd*/, -1, NULL, NULL,
                           RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,
                          RPC_C_IMP_LEVEL_IMPERSONATE,  NULL,
                          EOAC_NONE, NULL);
_ASSERTE(SUCCEEDED(hr));
if(FAILED(hr))
   return hr;
</code>```

答: It works! I found out that there were other places too in the code where auth level was being changed after setting it initially with CoInitializeSecurity().</p>

Body:
I am trying to raise the auth level to RPC_C_AUTHN_LEVEL_PKT_INTEGRITY but I still get access denied failure and see the following error in event viewer:

Application XXX is requesting with explicitly set authentication level at 2.

The lowest activation authentication level required by DCOM is 5(RPC_C_AUTHN_LEVEL_PKT_INTEGRITY).

To raise the activation authentication level, please contact the application vendor.

I am not sure why it says "level 2" when I am clearly setting it to 5 (RPC_C_AUTHN_LEVEL_PKT_INTEGRITY) in CoInitializeSecurity().

Is there something else besides setting the authentication level in CoInitializeSecurity() that I need and is missing?

Here is my code:

hr = CoInitializeSecurity(NULL /*sd*/, -1, NULL, NULL,
                           RPC_C_AUTHN_LEVEL_PKT_INTEGRITY,
                          RPC_C_IMP_LEVEL_IMPERSONATE,  NULL,
                          EOAC_NONE, NULL);
_ASSERTE(SUCCEEDED(hr));
if(FAILED(hr))
   return hr;


问:
Merge 2 Arrays and Sum the Values (Numeric Keys)
I have 2 arrays

```<code>Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)

Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)
</code>```

Is it possible that I can combine these separate arrays into one and add the values together so that the outcome will be:

```<code>Array
(
    [010156] => Array
    (
        [supp_number] =>  <<<TOTAL >>>
        [totalamount] =>     <<<TOTAL >>>
        [debtorcred] => <<<TOTAL >>>
        [amount1] =>      <<<TOTAL >>>
        [amount2] =>  <<<TOTAL >>>

        [amount3] =>  <<<TOTAL >>>
        [amount4] =>  <<<TOTAL >>>
        [amount5] =>  <<<TOTAL >>>
        [amount6] =>  <<<TOTAL >>>
    )
)
</code>```

This is the function I have at the moment but I cannot seem to make it work:

```<code>function array_merge_numeric_values()
{
  $arrays = func_get_args();
  $merged = array();
  foreach ($arrays as $array)
  {
    foreach ($array as $key => $value)
    {
      if ( ! isset($merged[$key]))
      {
        $merged[$key] = $value;
      }
      else
      {
        $merged[$key] += $value;
      }
    }
  }
</code>```

答:
Create a new empty array and loop in the first array as following:</p>

```<code>$array1 = array('my_num' => 10, 'my_num2' => 20);
$array2 = array('my_num' => 15, 'my_num2' => 25);
$newArray = array();
foreach($array1 as $key => $value){
    if(isset($array2[$key])){
        $newArray[$key] = $value+$array2[$key];
    } else {
        $newArray[$key] = $value;
    }
}

print_r($newArray);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have 2 arrays

Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)

Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)

Is it possible that I can combine these separate arrays into one and add the values together so that the outcome will be:

Array
(
    [010156] => Array
    (
        [supp_number] =>  <<<TOTAL >>>
        [totalamount] =>     <<<TOTAL >>>
        [debtorcred] => <<<TOTAL >>>
        [amount1] =>      <<<TOTAL >>>
        [amount2] =>  <<<TOTAL >>>

        [amount3] =>  <<<TOTAL >>>
        [amount4] =>  <<<TOTAL >>>
        [amount5] =>  <<<TOTAL >>>
        [amount6] =>  <<<TOTAL >>>
    )
)

This is the function I have at the moment but I cannot seem to make it work:

function array_merge_numeric_values()
{
  $arrays = func_get_args();
  $merged = array();
  foreach ($arrays as $array)
  {
    foreach ($array as $key => $value)
    {
      if ( ! isset($merged[$key]))
      {
        $merged[$key] = $value;
      }
      else
      {
        $merged[$key] += $value;
      }
    }
  }

Body:
Create a new empty array and loop in the first array as following:

$array1 = array('my_num' => 10, 'my_num2' => 20);
$array2 = array('my_num' => 15, 'my_num2' => 25);
$newArray = array();
foreach($array1 as $key => $value){
    if(isset($array2[$key])){
        $newArray[$key] = $value+$array2[$key];
    } else {
        $newArray[$key] = $value;
    }
}

print_r($newArray);


问:
How to validate a Map<String, String> using Spring Validator programmatically
I have a Map that I receive from a browser redirection back from a third party to my Spring Controller as below -

```<code>@RequestMapping(value = "/capture", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void capture(@RequestParam
    final Map<String, String> response)
    {
        // TODO : perform validations first.
        captureResponse(response);
    }
</code>```

Before using this payload, I need to do non-trivial validation, involving first checking for non-null values of a map, and then using those values in a checksum validation. So, I would like to validate my payload programmatically using the Spring Validator interface. However, I could not find any validator example for validating a Map.

For validating a Java Object, I understand how a Validator is invoked by passing the object and a BeanPropertyBindingResult to contain the errors to the Validator as below -

```<code>final Errors errors = new BeanPropertyBindingResult(object, objectName);
myValidator.validate(object, errors);
if (errors.hasErrors())
{
    throw new MyWebserviceValidationException(errors);
}
</code>```

For a Map, I can see that there is a MapBindingResult class that extends AbstractBindingResult. Should I simply use it, and pass my map in the Object object and in the validator cast it back to a Map? Also, how would the Validator method of supports(final Class<?> clazz) be implemented in my validator? Would it simply be like below code snippet where there can only be one validator supporting this generic class of HashMap? Somehow doesn't feel right. (Although this does not matter to me as I will be injecting my validator and use it directly and not through a validator registry, but still curious.)

```<code>@Override
public boolean supports(final Class<?> clazz)
{
    return HashMap.class.equals(clazz);
}
</code>```

Since, there is a MapBindingResult, I'm positive that Spring must be supporting Maps for validation, would like to know how. So would like to know if this is the way to go, or am I heading in the wrong direction and there is a better way of doing this.

Please note I would like to do this programmatically and not via annotations.

答:
Validate the parameters inside the map

For the validation of your Map following a specific mapping you will need a custom validator.

As this may be the usecase for some, validation of @RequestParam can be done using org.springframework.validation annotations, e.g.

```<code>@GetMapping(value = "/search")
public ResponseEntity<T> search(@RequestParam
   Map<@NotBlank String,@NotBlank String> searchParams,
</code>```

While @NotBlank checks if your string is not "",
@NotNull can validate non-null parameters which I guess was something you needed.

Body:
I have a Map that I receive from a browser redirection back from a third party to my Spring Controller as below -

@RequestMapping(value = "/capture", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public void capture(@RequestParam
    final Map<String, String> response)
    {
        // TODO : perform validations first.
        captureResponse(response);
    }

Before using this payload, I need to do non-trivial validation, involving first checking for non-null values of a map, and then using those values in a checksum validation. So, I would like to validate my payload programmatically using the Spring Validator interface. However, I could not find any validator example for validating a Map.

For validating a Java Object, I understand how a Validator is invoked by passing the object and a BeanPropertyBindingResult to contain the errors to the Validator as below -

final Errors errors = new BeanPropertyBindingResult(object, objectName);
myValidator.validate(object, errors);
if (errors.hasErrors())
{
    throw new MyWebserviceValidationException(errors);
}

For a Map, I can see that there is a MapBindingResult class that extends AbstractBindingResult. Should I simply use it, and pass my map in the Object object and in the validator cast it back to a Map? Also, how would the Validator method of supports(final Class<?> clazz) be implemented in my validator? Would it simply be like below code snippet where there can only be one validator supporting this generic class of HashMap? Somehow doesn't feel right. (Although this does not matter to me as I will be injecting my validator and use it directly and not through a validator registry, but still curious.)

@Override
public boolean supports(final Class<?> clazz)
{
    return HashMap.class.equals(clazz);
}

Since, there is a MapBindingResult, I'm positive that Spring must be supporting Maps for validation, would like to know how. So would like to know if this is the way to go, or am I heading in the wrong direction and there is a better way of doing this.

Please note I would like to do this programmatically and not via annotations.

Body:
Validate the parameters inside the map

For the validation of your Map following a specific mapping you will need a custom validator.

As this may be the usecase for some, validation of @RequestParam can be done using org.springframework.validation annotations, e.g.

@GetMapping(value = "/search")
public ResponseEntity<T> search(@RequestParam
   Map<@NotBlank String,@NotBlank String> searchParams,

While @NotBlank checks if your string is not "",
@NotNull can validate non-null parameters which I guess was something you needed.


问:
Remove object from array of objects based on value
I have this array of objects:

```<code>var data = [{
    "code": "8252",
    "name": "Věšák Sentini, antik mosaz",
  },
  {
    "code": "8253",
    "name": "Věšák Sentini, matný chrom",
  },
  {
    "code": "8254",
    "name": "Věšák Sentini, antik měď",
  },
  {
    "code": "8261",
    "name": "Věšák Kasper I, matný nikl",
  }
]
</code>```

How can I remove the object from array that has code == 8254 please?

答:
You can use array.filter to get a new array without specified element:

var data = [{
    "code": "8252",
    "name": "Věšák Sentini, antik mosaz",
  },
  {
    "code": "8253",
    "name": "Věšák Sentini, matný chrom",
  },
  {
    "code": "8254",
    "name": "Věšák Sentini, antik měď",
  },
  {
    "code": "8261",
    "name": "Věšák Kasper I, matný nikl",
  }
]

let output = data.filter(x => x.code !== "8254");

console.log(output);```

Body:
I have this array of objects:

var data = [{
    "code": "8252",
    "name": "Věšák Sentini, antik mosaz",
  },
  {
    "code": "8253",
    "name": "Věšák Sentini, matný chrom",
  },
  {
    "code": "8254",
    "name": "Věšák Sentini, antik měď",
  },
  {
    "code": "8261",
    "name": "Věšák Kasper I, matný nikl",
  }
]

How can I remove the object from array that has code == 8254 please?


问:
Fit a straight line ignoring data points having ceiling effect
I have a data like below and I would like to fit a straight line (like a Black line) ignoring the points following ceiling effect. Then I would like to predict Y values of these points using the slope and find the expected difference due to ceiling effect.

I tried using following code from other stackoverflow question but it does not do a good job at ignoring points with ceiling effect.

```<code>from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit
</code>```

Please feel free to provide any ideas or suggestions. Thank you.

答:
Assuming you have your X and Y as np.array, you can filter out the samples with x > 850 (or y > 2000 from what I see on your plot), like this:

```<code>X_clean = X[X < 850]
Y_clean = Y[X < 850]
# or [Y < 2000]
</code>```

In this way you will have just the points not affected by a ceiling effect.
You can then run your linear regression on that data

Body:
I have a data like below and I would like to fit a straight line (like a Black line) ignoring the points following ceiling effect. Then I would like to predict Y values of these points using the slope and find the expected difference due to ceiling effect.

I tried using following code from other stackoverflow question but it does not do a good job at ignoring points with ceiling effect.

from scipy.optimize import curve_fit

def f(x, A, B): # this is your 'straight line' y=f(x)
    return A*x + B

popt, pcov = curve_fit(f, x, y) # your data x, y to fit

Please feel free to provide any ideas or suggestions. Thank you.

Body:
Assuming you have your X and Y as np.array, you can filter out the samples with x > 850 (or y > 2000 from what I see on your plot), like this:

X_clean = X[X < 850]
Y_clean = Y[X < 850]
# or [Y < 2000]

In this way you will have just the points not affected by a ceiling effect.
You can then run your linear regression on that data


问:
Row number over partition by usage
I would like to filter the below table based on the week column, but only when the year week combination is a max.

In the below example I want my output to only select rows with year 2022 and week 1 as that is the latest year week combination.

I am thinking to use a row number over partition by but did not have any success.

```<code>Car  colour   year   week
aaa  red      2021   52
aaa  black    2021   51
bbb  red      2022   1
bbb  yellow   2022   1
</code>```

答:
From Oracle 12, you can use:

SELECT *
FROM   table_name
ORDER BY year DESC, week DESC
FETCH FIRST ROW WITH TIES;
```
<p>Or, in earlier version, you can use:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT car, colour, year, week
FROM   (
  SELECT t.*,
         RANK() OVER (ORDER BY year DESC, week DESC) AS rnk
  FROM   table_name t
)
WHERE  rnk = 1;
</code>```

Which, for the sample data:

CREATE TABLE table_name (Car, colour, year, week) AS
SELECT 'aaa', 'red',    2021, 52 FROM DUAL UNION ALL
SELECT 'aaa', 'black',  2021, 51 FROM DUAL UNION ALL
SELECT 'bbb', 'red',    2022,  1 FROM DUAL UNION ALL
SELECT 'bbb', 'yellow', 2022,  1 FROM DUAL;
```

Both output:

CAR
COLOUR
YEAR
WEEK

bbb
red
2022
1

bbb
yellow
2022
1

db<>fiddle here

Title: Row number over partition by usage

Body:
I would like to filter the below table based on the week column, but only when the year week combination is a max.

In the below example I want my output to only select rows with year 2022 and week 1 as that is the latest year week combination.

I am thinking to use a row number over partition by but did not have any success.

Car  colour   year   week
aaa  red      2021   52
aaa  black    2021   51
bbb  red      2022   1
bbb  yellow   2022   1

Body:
From Oracle 12, you can use:

SELECT *
FROM   table_name
ORDER BY year DESC, week DESC
FETCH FIRST ROW WITH TIES;

Or, in earlier version, you can use:

SELECT car, colour, year, week
FROM   (
  SELECT t.*,
         RANK() OVER (ORDER BY year DESC, week DESC) AS rnk
  FROM   table_name t
)
WHERE  rnk = 1;

Which, for the sample data:

CREATE TABLE table_name (Car, colour, year, week) AS
SELECT 'aaa', 'red',    2021, 52 FROM DUAL UNION ALL
SELECT 'aaa', 'black',  2021, 51 FROM DUAL UNION ALL
SELECT 'bbb', 'red',    2022,  1 FROM DUAL UNION ALL
SELECT 'bbb', 'yellow', 2022,  1 FROM DUAL;

Both output:

CAR
COLOUR
YEAR
WEEK

bbb
red
2022
1

bbb
yellow
2022
1

db<>fiddle here


问:
Relative imports - ModuleNotFoundError: No module named x
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:

test.py

config.py

config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:

config.py

```<code>debug = True
</code>```

test.py

```<code>import config
print (config.debug)
</code>```

I also have an __init__.py

However, I'm getting the following error:

```<code>ModuleNotFoundError: No module named 'config'
</code>```

I'm aware that the py3 convention is to use absolute imports:

```<code>from . import config
</code>```

However, this leads to the following error:

```<code>ImportError: cannot import name 'config'
</code>```

So I'm at a loss as to what to do here... Any help is greatly appreciated. :)

答:
You may use these statements to set the working directory, which worked for me with python3

```<code>import os
import sys
sys.path.insert(1, os.getcwd())
</code>```

Body:
This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files:

test.py

config.py

config.py has a few functions defined in it as well as a few variables. I've stripped it down to the following:

config.py

debug = True

test.py

import config
print (config.debug)

I also have an __init__.py

However, I'm getting the following error:

ModuleNotFoundError: No module named 'config'

I'm aware that the py3 convention is to use absolute imports:

from . import config

However, this leads to the following error:

ImportError: cannot import name 'config'

So I'm at a loss as to what to do here... Any help is greatly appreciated. :)

Body:
You may use these statements to set the working directory, which worked for me with python3

import os
import sys
sys.path.insert(1, os.getcwd())


问:
Enable Flight mode with out disabling the wifi and bluetooth in android
I want to enable Flight mode but if i enable flight mode i cant able to use bluetooth , wifi. my purpose is to restrict only  the receiving call and sms related things.

I tried the following, but its not working;

```<code>Settings.System.putString(getContentResolver(),
           Settings.System.AIRPLANE_MODE_RADIOS, "cell,bluetooth");
</code>```

can any one help me in this

答:
As far as im aware flight mode will cover selection of setting to disable all wireless communication.

If you wish to only disable parts this will have to be done individually, not via flight mode.

try a method for each part of communication you wish to terminate.

Body:
I want to enable Flight mode but if i enable flight mode i cant able to use bluetooth , wifi. my purpose is to restrict only  the receiving call and sms related things.

I tried the following, but its not working;

Settings.System.putString(getContentResolver(),
           Settings.System.AIRPLANE_MODE_RADIOS, "cell,bluetooth");

can any one help me in this


问:
What does `setupkvm` do in xv6 ? What does it really mean to "set up kernel virtual memory"?
In copyuvm function setupkvm is called to set kernel virtual memory. Why do we need to setup kernel virtual memory when we are copying user process ? Why didn't we need that when we were doing allocuvm ?

Code for copyuvm

// Given a parent process's page table, create a copy
// of it for a child.
pde_t*
copyuvm(pde_t *pgdir, uint sz)
{
  pde_t *d;
  pte_t *pte;
  uint pa, i, flags;
  char *mem;

  if((d = setupkvm()) == 0)
    return 0;
  for(i = 0; i < sz; i += PGSIZE){
    if((pte = walkpgdir(pgdir, (void *) i, 0)) == 0)
      panic("copyuvm: pte should exist");
    if(!(*pte & PTE_P))
      panic("copyuvm: page not present");
    pa = PTE_ADDR(*pte);
    flags = PTE_FLAGS(*pte);
    if((mem = kalloc()) == 0)
      goto bad;
    memmove(mem, (char*)P2V(pa), PGSIZE);
    if(mappages(d, (void*)i, PGSIZE, V2P(mem), flags) < 0) {
      kfree(mem);
      goto bad;
    }
  }
  return d;

bad:
  freevm(d);
  return 0;
}
```
<p>and for <code>allocuvm</code></p>
<pre class="lang-cpp prettyprint-override"><code>int
allocuvm(pde_t *pgdir, uint oldsz, uint newsz)
{
  char *mem;
  uint a;

  if(newsz >= KERNBASE)
    return 0;
  if(newsz < oldsz)
    return oldsz;

  a = PGROUNDUP(oldsz);
  for(; a < newsz; a += PGSIZE){
    mem = kalloc();
    if(mem == 0){
      cprintf("allocuvm out of memory\n");
      deallocuvm(pgdir, newsz, oldsz);
      return 0;
    }
    memset(mem, 0, PGSIZE);
    if(mappages(pgdir, (char*)a, PGSIZE, V2P(mem), PTE_W|PTE_U) < 0){
      cprintf("allocuvm out of memory (2)\n");
      deallocuvm(pgdir, newsz, oldsz);
      kfree(mem);
      return 0;
    }
  }
  return newsz;
}
</code>```

答:
What copyuvm does is that copy whole virtual memory (user + kernel) from a page directory. So during copyuvm we need setupkvm for kernel part.

On the other hand, allocuvm just extends existing virtual memory ( specifically heap portion). Since there already exists kernel portion of mappings in allocuvm, we are not bound to call setupkvm.

Body:
In copyuvm function setupkvm is called to set kernel virtual memory. Why do we need to setup kernel virtual memory when we are copying user process ? Why didn't we need that when we were doing allocuvm ?

Code for copyuvm

// Given a parent process's page table, create a copy
// of it for a child.
pde_t*
copyuvm(pde_t *pgdir, uint sz)
{
  pde_t *d;
  pte_t *pte;
  uint pa, i, flags;
  char *mem;

  if((d = setupkvm()) == 0)
    return 0;
  for(i = 0; i < sz; i += PGSIZE){
    if((pte = walkpgdir(pgdir, (void *) i, 0)) == 0)
      panic("copyuvm: pte should exist");
    if(!(*pte & PTE_P))
      panic("copyuvm: page not present");
    pa = PTE_ADDR(*pte);
    flags = PTE_FLAGS(*pte);
    if((mem = kalloc()) == 0)
      goto bad;
    memmove(mem, (char*)P2V(pa), PGSIZE);
    if(mappages(d, (void*)i, PGSIZE, V2P(mem), flags) < 0) {
      kfree(mem);
      goto bad;
    }
  }
  return d;

bad:
  freevm(d);
  return 0;
}

and for allocuvm

int
allocuvm(pde_t *pgdir, uint oldsz, uint newsz)
{
  char *mem;
  uint a;

  if(newsz >= KERNBASE)
    return 0;
  if(newsz < oldsz)
    return oldsz;

  a = PGROUNDUP(oldsz);
  for(; a < newsz; a += PGSIZE){
    mem = kalloc();
    if(mem == 0){
      cprintf("allocuvm out of memory\n");
      deallocuvm(pgdir, newsz, oldsz);
      return 0;
    }
    memset(mem, 0, PGSIZE);
    if(mappages(pgdir, (char*)a, PGSIZE, V2P(mem), PTE_W|PTE_U) < 0){
      cprintf("allocuvm out of memory (2)\n");
      deallocuvm(pgdir, newsz, oldsz);
      kfree(mem);
      return 0;
    }
  }
  return newsz;
}


问:
Assign a value to a cell from another cell
I would like to assign one value from a specific cell from another value of a specific cell from the same dataframe.

I have tried the following:

```<code>df.loc[i_list[0]][first_empty_column_unique] = df.iloc[i][index_of_duplicate_element]
</code>```

but I am getting the following error:

```<code>SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
</code>```

I have tried also to copy the df as follows:

```<code>elements = df.iloc[i][[index_of_duplicate_element]].copy()
df.loc[i_list[0]][first_empty_column_unique] = elements
</code>```

but I am still getting the error.

Which is the correct way of copying from one cell to another in my case?

答:
I had to deal with a similar problem.

richardec's answer shows how to fix it

But if you are also curious on why it wasn't working as you expected, the warning also redirects to a docs page that explains the problem:

https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-view-versus-copy

Long story short, when you use double braces, the indexing is done in two steps (row-wise and column-wise), and you might end up operating on a copy of the original.

Conversely, when you use the loc function in one go, a multi-index (row and column) is performed so it is ensured that the changes will affect the original dataframe:

```<code>df.loc['row_index']['Column'] = 'SomeValue' #will raise the warning and might not work
df.loc['row_index', 'Column'] = 'SomeValue' #won't raise the warning and works perfectly
````
```

Body:
I would like to assign one value from a specific cell from another value of a specific cell from the same dataframe.

I have tried the following:

df.loc[i_list[0]][first_empty_column_unique] = df.iloc[i][index_of_duplicate_element]

but I am getting the following error:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

I have tried also to copy the df as follows:

elements = df.iloc[i][[index_of_duplicate_element]].copy()
df.loc[i_list[0]][first_empty_column_unique] = elements

but I am still getting the error.

Which is the correct way of copying from one cell to another in my case?

Body:
I had to deal with a similar problem.

richardec's answer shows how to fix it

But if you are also curious on why it wasn't working as you expected, the warning also redirects to a docs page that explains the problem:

https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#indexing-view-versus-copy

Long story short, when you use double braces, the indexing is done in two steps (row-wise and column-wise), and you might end up operating on a copy of the original.

Conversely, when you use the loc function in one go, a multi-index (row and column) is performed so it is ensured that the changes will affect the original dataframe:

df.loc['row_index']['Column'] = 'SomeValue' #will raise the warning and might not work
df.loc['row_index', 'Column'] = 'SomeValue' #won't raise the warning and works perfectly
````


问:
why are my icons showing up like this? this is react-native-vector-icons
enter image description here

When I insert the icon in my code when it appears in the emulator it appears as it appears in the print

答:
This caused by the app JS bundle and font assets are not in sync.

Following step below as per official documentation

This method has the advantage of fonts being copied from this module at build time so that the fonts and JS are always in sync, making upgrades painless.

Edit android/app/build.gradle ( NOT android/build.gradle ) and add the following:

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
To customize the files being copied, add the following instead:

```<code>project.ext.vectoricons = [
    iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
</code>```

Body:
This caused by the app JS bundle and font assets are not in sync.

Following step below as per official documentation

This method has the advantage of fonts being copied from this module at build time so that the fonts and JS are always in sync, making upgrades painless.

Edit android/app/build.gradle ( NOT android/build.gradle ) and add the following:

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
To customize the files being copied, add the following instead:

project.ext.vectoricons = [
    iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"


问:
Typescript generic constraint for type with only properties from another type
I'm trying to create a Overwrite type that can overwrite an existing type's properties with a different type. For instance:

```<code>type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop2: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: string }
</code>```

I found this SO answer which does the job nicely, however it's a bit too permissive for my liking, as it allows you to replace properties that were never in the original type to begin with.

```<code>type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: number; prop3: string }
</code>```

Below is the Overwrite type from that other thread.

```<code>type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
</code>```

How do I need to modify it to prohibit replacement keys that are not present in the initial type?

```<code>type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>; // Throw some sort of error here, prop3 is not a key of TypeA
</code>```

答:
You can add a condition on you generic !

```<code>type Overwrite<T extends { [key in keyof U]: any }, U> = Omit<T, keyof U> & U;

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number }>;  // ok
const foo: OverwrittenType = { prop1: 3, prop2: 3 }

type OverwrittenType2 = Overwrite<TypeA, { prop3: number }>;  // error
const bar: OverwrittenType = { prop1: 3, prop3: 3 }
</code>```

Playground

Body:
I'm trying to create a Overwrite type that can overwrite an existing type's properties with a different type. For instance:

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop2: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: string }

I found this SO answer which does the job nicely, however it's a bit too permissive for my liking, as it allows you to replace properties that were never in the original type to begin with.

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: number; prop3: string }

Below is the Overwrite type from that other thread.

type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;

How do I need to modify it to prohibit replacement keys that are not present in the initial type?

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>; // Throw some sort of error here, prop3 is not a key of TypeA

Body:
You can add a condition on you generic !

type Overwrite<T extends { [key in keyof U]: any }, U> = Omit<T, keyof U> & U;

type TypeA = { prop1: string; prop2: number };

type OverwrittenType = Overwrite<TypeA, { prop1: number }>;  // ok
const foo: OverwrittenType = { prop1: 3, prop2: 3 }

type OverwrittenType2 = Overwrite<TypeA, { prop3: number }>;  // error
const bar: OverwrittenType = { prop1: 3, prop3: 3 }

Playground


问:
How to call a second function within async google cloud function
I'm trying to use the firebase admin SDK to add users with specific roles. I can get it working where newly added users are authenticated, but I also need to create a users/id record in my firestore database.

Here is my code:

```<code>exports.createUser = functions.https.onCall(async (data, context) => {
  const user = await admin.auth().createUser({
    email: data.email,
    emailVerified: true,
    password: data.password,
    displayName: data.displayName,
    disabled: false,
  });
  await admin.firestore().collection('users').doc(user.uid).set({
    displayName: user.displayName,
    id: user.uid,
    email: user.email,
    role: 'clientAccess',
    created: fb.firestore.FieldValue.serverTimestamp()
  })
  return { response: user }
});
</code>```

Where can I put the return admin.firestore().col... part to make this work?

Thanks!

答:
I'm going to suggest that you're not quite asking the right question.  Your task at hand is this:

Create the user account

Add a document to firestore with information about that user

Send the user object back to the calling client.

You don't need at all return for task 2.  You just need a return for step 3.  You can simply use async/await on each of the functions that return a promise to make sure they are all executed and completed in the right order before the function returns the final result to the client.

```<code>    const user = await admin.auth().createUser({ ... });
    await admin.firestore().collection('users').doc(user.uid).set({ ... })
    return { response: user }
</code>```

You probably also don't nee to worry about try/catch unless you have some special error handling.

Body:
I'm trying to use the firebase admin SDK to add users with specific roles. I can get it working where newly added users are authenticated, but I also need to create a users/id record in my firestore database.

Here is my code:

exports.createUser = functions.https.onCall(async (data, context) => {
  const user = await admin.auth().createUser({
    email: data.email,
    emailVerified: true,
    password: data.password,
    displayName: data.displayName,
    disabled: false,
  });
  await admin.firestore().collection('users').doc(user.uid).set({
    displayName: user.displayName,
    id: user.uid,
    email: user.email,
    role: 'clientAccess',
    created: fb.firestore.FieldValue.serverTimestamp()
  })
  return { response: user }
});

Where can I put the return admin.firestore().col... part to make this work?

Thanks!

Body:
I'm going to suggest that you're not quite asking the right question.  Your task at hand is this:

Create the user account

Add a document to firestore with information about that user

Send the user object back to the calling client.

You don't need at all return for task 2.  You just need a return for step 3.  You can simply use async/await on each of the functions that return a promise to make sure they are all executed and completed in the right order before the function returns the final result to the client.

    const user = await admin.auth().createUser({ ... });
    await admin.firestore().collection('users').doc(user.uid).set({ ... })
    return { response: user }

You probably also don't nee to worry about try/catch unless you have some special error handling.


问:
How to solve generic 'Unexpected error in launching an agent. This is probably a bug in Jenkins' error on Jenkins agent startup
I have configured a docker cloud dynamic agent creation with the following settings:

and the agent config as follows:

but they fail to start. Been googling around but since I have little to nothing to go on with the logs, I don't know how to fix this.

```<code>Connecting to docker container 2169d7b0f9de955c89916da421dc6e04f41104423d0fdcd28796162225cf491f, running command java -jar //remoting-4.11.2.jar -noReconnect -noKeepAlive -agentLog //agent.log
HTTP/1.1 101 UPGRADED
Content-Type: application/vnd.docker.raw-stream
Connection: Upgrade
Upgrade: tcp
Api-Version: 1.41
Docker-Experimental: false
Ostype: linux
Server: Docker/20.10.12 (linux)
ERROR: Unexpected error in launching an agent. This is probably a bug in Jenkins
Also:   java.lang.Throwable: launched here
    at hudson.slaves.SlaveComputer._connect(SlaveComputer.java:282)
    at hudson.model.Computer.connect(Computer.java:440)
    at hudson.slaves.SlaveComputer.doLaunchSlaveAgent(SlaveComputer.java:796)
    at java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:627)
    at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:393)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:405)
    at org.kohsuke.stapler.interceptor.RequirePOST$Processor.invoke(RequirePOST.java:77)
    at org.kohsuke.stapler.PreInvokeInterceptedFunction.invoke(PreInvokeInterceptedFunction.java:26)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:208)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:141)
    at org.kohsuke.stapler.MetaClass$11.doDispatch(MetaClass.java:536)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)
</code>```

The last part of the logs stay:

```<code>java.io.EOFException: unexpected stream termination
    at hudson.remoting.ChannelBuilder.negotiate(ChannelBuilder.java:464)
    at hudson.remoting.ChannelBuilder.build(ChannelBuilder.java:409)
    at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:432)
    at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:399)
    at io.jenkins.docker.connector.DockerComputerAttachConnector$DockerAttachLauncher.launch(DockerComputerAttachConnector.java:321)
    at hudson.slaves.DelegatingComputerLauncher.launch(DelegatingComputerLauncher.java:63)
    at io.jenkins.docker.connector.DockerDelegatingComputerLauncher.launch(DockerDelegatingComputerLauncher.java:37)
    at hudson.slaves.SlaveComputer.lambda$_connect$0(SlaveComputer.java:293)
    at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
    at jenkins.security.ImpersonatingExecutorService$2.call(ImpersonatingExecutorService.java:80)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

and in jenkins logs I see:

```<code>96a29780b14e340c1667f2 for node Jenkins JDK11 agent-00000a8utz442 from image: jenkins/agent:alpine
2022-01-27 22:56:32.628+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2): Jan 27, 2022 10:56:32 PM org.jenkinsci.remoting.engine.WorkDirManager setupLogging
INFO: Using /agent.log as an agent error log destination; output log will not be generated
2022-01-27 22:56:32.628+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2): Exception in thread "main"
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2): java.io.FileNotFoundException: /agent.log (Permission denied)
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2):    at java.base/java.io.FileOutputStream.open0(Native Method)
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2):    at java.base/java.io.FileOutputStream.open(Unknown Source)
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2):    at java.base/java.io.FileOutputStream.<init>(Unknown Source)
</code>```

Which is actually not that much info either.

答: In the agent configuration put /home/jenkins in the field Remote File System Root. I had the same problem and this fixed it for me.</p>

Body:
I have configured a docker cloud dynamic agent creation with the following settings:

and the agent config as follows:

but they fail to start. Been googling around but since I have little to nothing to go on with the logs, I don't know how to fix this.

Connecting to docker container 2169d7b0f9de955c89916da421dc6e04f41104423d0fdcd28796162225cf491f, running command java -jar //remoting-4.11.2.jar -noReconnect -noKeepAlive -agentLog //agent.log
HTTP/1.1 101 UPGRADED
Content-Type: application/vnd.docker.raw-stream
Connection: Upgrade
Upgrade: tcp
Api-Version: 1.41
Docker-Experimental: false
Ostype: linux
Server: Docker/20.10.12 (linux)
ERROR: Unexpected error in launching an agent. This is probably a bug in Jenkins
Also:   java.lang.Throwable: launched here
    at hudson.slaves.SlaveComputer._connect(SlaveComputer.java:282)
    at hudson.model.Computer.connect(Computer.java:440)
    at hudson.slaves.SlaveComputer.doLaunchSlaveAgent(SlaveComputer.java:796)
    at java.lang.invoke.MethodHandle.invokeWithArguments(MethodHandle.java:627)
    at org.kohsuke.stapler.Function$MethodFunction.invoke(Function.java:393)
    at org.kohsuke.stapler.Function$InstanceFunction.invoke(Function.java:405)
    at org.kohsuke.stapler.interceptor.RequirePOST$Processor.invoke(RequirePOST.java:77)
    at org.kohsuke.stapler.PreInvokeInterceptedFunction.invoke(PreInvokeInterceptedFunction.java:26)
    at org.kohsuke.stapler.Function.bindAndInvoke(Function.java:208)
    at org.kohsuke.stapler.Function.bindAndInvokeAndServeResponse(Function.java:141)
    at org.kohsuke.stapler.MetaClass$11.doDispatch(MetaClass.java:536)
    at org.kohsuke.stapler.NameBasedDispatcher.dispatch(NameBasedDispatcher.java:58)

The last part of the logs stay:

java.io.EOFException: unexpected stream termination
    at hudson.remoting.ChannelBuilder.negotiate(ChannelBuilder.java:464)
    at hudson.remoting.ChannelBuilder.build(ChannelBuilder.java:409)
    at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:432)
    at hudson.slaves.SlaveComputer.setChannel(SlaveComputer.java:399)
    at io.jenkins.docker.connector.DockerComputerAttachConnector$DockerAttachLauncher.launch(DockerComputerAttachConnector.java:321)
    at hudson.slaves.DelegatingComputerLauncher.launch(DelegatingComputerLauncher.java:63)
    at io.jenkins.docker.connector.DockerDelegatingComputerLauncher.launch(DockerDelegatingComputerLauncher.java:37)
    at hudson.slaves.SlaveComputer.lambda$_connect$0(SlaveComputer.java:293)
    at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
    at jenkins.security.ImpersonatingExecutorService$2.call(ImpersonatingExecutorService.java:80)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

and in jenkins logs I see:

96a29780b14e340c1667f2 for node Jenkins JDK11 agent-00000a8utz442 from image: jenkins/agent:alpine
2022-01-27 22:56:32.628+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2): Jan 27, 2022 10:56:32 PM org.jenkinsci.remoting.engine.WorkDirManager setupLogging
INFO: Using /agent.log as an agent error log destination; output log will not be generated
2022-01-27 22:56:32.628+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2): Exception in thread "main"
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2): java.io.FileNotFoundException: /agent.log (Permission denied)
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2):    at java.base/java.io.FileOutputStream.open0(Native Method)
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2):    at java.base/java.io.FileOutputStream.open(Unknown Source)
2022-01-27 22:56:32.629+0000 [id=188]   INFO    i.j.d.c.DockerMultiplexedInputStream#readInternal: stderr from Jenkins JDK11 agent-00000a8utz442 (4611c8568d1b73e6a8b7e54613f7ef06c79210f03a96a29780b14e340c1667f2):    at java.base/java.io.FileOutputStream.<init>(Unknown Source)

Which is actually not that much info either.


问:
Github Actions: how to run a workflow created on a non-master branch from the workflow_dispatch event?
Can someone help me understand the behaviour of the Github Actions tab? As somebody new to Actions working on a third party repo I would like to be able to create an action on a branch and execute it on the workflow_dispatch event.  I have not succeeded in doing this but I have discovered the following:

The Action tab will change the branch where it finds workflows and action code based on the branch relating to the last executed workflow.  e.g. if some workflow is executed from the Action tab using the Run Workflow button and the Use Workflow From dropdown is set to some branch, Branch-A, then the contents of the Workflows panel on the left hand side of the Actions tab will be taken from Branch-A's version of .github/.

The This workflow has a workflow_dispatch event trigger. text does not change with the branch. It seems to be taken from master. Alternatively, it may be being taken from the last set of results. I have not tested for that because either way it is not helpful behaviour.

The workaround is the execute on a push event which is OK but that seems out of kilter with Github's high standards of design.

Does the above sound a) about right and b) whichever way you look at it, not optimal behaviour? Or, is there a better approach to building and testing actions?

答:
You can run your workflow through the GitHub CLI, but you will first need to make sure it's run before.

gh workflow list
```
<p>If your workflow isn't in that list (by name), then add <code>pull_request:</code> and create a pull request so that the workflow is registered, once.</p>
<pre class="lang-yaml prettyprint-override"><code>name: 'My Workflow'
on:
  workflow_dispatch:
    inputs:
      parameter:
        description: My Parameter
  pull_request: -- Add this here
...
</code>```

Once you've created a pull request, you should see 'My Workflow' when you run gh workflow list. Once that's done, you can remove the added line.

Finally, now run:

gh workflow run 'My Workflow' --ref my-branch -f parameter=value
```

This should run your workflow dispatch from a feature branch.

Body:
You can run your workflow through the GitHub CLI, but you will first need to make sure it's run before.

gh workflow list

If your workflow isn't in that list (by name), then add pull_request: and create a pull request so that the workflow is registered, once.

name: 'My Workflow'
on:
  workflow_dispatch:
    inputs:
      parameter:
        description: My Parameter
  pull_request: -- Add this here
...

Once you've created a pull request, you should see 'My Workflow' when you run gh workflow list. Once that's done, you can remove the added line.

Finally, now run:

gh workflow run 'My Workflow' --ref my-branch -f parameter=value

This should run your workflow dispatch from a feature branch.


问:
How do I find the maximum path sum with path indication?
I have to find the maximum path sum starting from top right to bottom left of the matrix.

Therefore this is what I was asked to do:

Given an mxn grid filled with numbers, find a path from top left to
bottom right, which maximizes the sum of all numbers along its path,
also i can only move either down or right.

So I had this on a coding interview recently and I passed it, but in the middle of the interview the guy asked me to also show the path along with the result

Example:

```<code>grid = [[1,10]
       ,[2,3]]

output: 14, right,down
</code>```

So I came up with a solution:

```<code>    function matrix(grid) {
    var m = grid.length;
    var n = grid[0].length;

    if(!m || !n) return grid;

    for (let i = 0; i < m; i++){
        for (let j = 0; j < n; j++){
            // grid[0][0] itself contains the min path sum
            if (i === 0 && j === 0) continue;
            // first row: grid[i][j] = previous grid(left) + current value
            if (i === 0) grid[i][j] += grid[i][j-1];
            // first column: grid[i][j] = previous grid(top) + current value
            else if (j === 0) grid[i][j] += grid[i-1][j];
            // grid[i][j] = get the min of previous grid(top/left) + current value
            else grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
        }
    };
    return grid[n - 1][m - 1];
};

const grid = [[1,10],[2,3]];

console.log(matrix(grid));
</code>```

What I tried during the interview was to add the given grid and the result of the maximum numbers on each step on a variable each and then try to subtract the numbers that was calculated in the la line on my 2nd for loop compare it with the number in the original grid and if it match then push 'down' or 'right' to an empty array and then simply return the result and the array.

Example:

```<code>grid = [[1,10]
       ,[2,3]]

oldGrid = grid

arr == []

loop
on each iteration

grid[1] - oldGrid[1] = oldgrid[0]
                                   {for rows}
add "right" to arr

or

grid[2] - oldgrid[2] = oldgrid[0]
                                   {for cols}
add "down" to arr

return result and arr
</code>```

so this is what i've come up with

```<code>    function matrix(grid) {
    var m = grid.length;
    var n = grid[0].length;
    var showDir = [];

    if(!m || !n) return grid;

    for (let i = 0; i < m; i++){
        for (let j = 0; j < n; j++){
            // grid[0][0] itself contains the min path sum
            if (i === 0 && j === 0) continue;
            // first row: grid[i][j] = previous grid(left) + current value
            if (i === 0) grid[i][j] += grid[i][j-1];
            // first column: grid[i][j] = previous grid(top) + current value
            else if (j === 0) grid[i][j] += grid[i-1][j];
            // grid[i][j] = get the min of previous grid(top/left) + current value
            else{
                let direction, max;
                if(grid[i][j-1]>grid[i-1][j]){
                    direction = "R"
                    max = grid[i][j-1]
                    showDir.push(direction)
                }
                else{
                    direction = "D"
                    max = grid[i-1][j]
                    showDir.push(direction)
                }
                grid[i][j] += max;
            }
        };
    };
    return grid[n - 1][m - 1], showDir
};

    const grid = [[1,10],[2,3]];

    console.log(matrix(grid));
</code>```

the thing is with this it only output showDir not the grid and i don't
know why

I'm new to Javascript so please go easy on me

答:
You could iterate the diagonals and take the maximum value of either the upper item or the right one.

The final result is in bottom left item.

To get a path, you start from the end and choose the item with the next larger sum and take this position for the result set and get the next larger item's position until you reach the start item.

const
    exist = (i, j) => i >= 0 && i < size[0] && j >= 0 && j < size[1],
    array = [[1, 3, 4, 2, 5], [2, 4, 1, 7, 6], [9, 4, 1, 2, 1], [3, 5, 1, 1, 2], [3, 3, 7, 1, 4]],
    size = [array.length, array[0].length],
    sums = [],
    path = [];

// get sums
for (let k = 0, l = size[0] + size[1] - 1; k < l; k++) {
    let i = Math.min(k, size[0] - 1),
        j = k - i;

    while (exist(i, j)) {
        sums[i] ??= [];
        sums[i][j] = array[i][j] + Math.max(sums[i - 1]?.[j] || 0, sums[i][j - 1] || 0);
        i--; j++;
    }
}

// get path from max to start value
let i = size[0] - 1,
    j = size[1] - 1;

path.push([i, j]);
while (i || j) {
    if (!exist(i - 1, j) || exist(i, j - 1) && sums[i - 1][j] < sums[i][j - 1]) j--;
    else i--;
    path.unshift([i, j]);
}

path.forEach(([i, j]) => console.log(i, j, '->', sums[i][j]));
console.log('');
sums.forEach(a => console.log(...a.map(v => v.toString().padStart(3, ' '))));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Body:
I have to find the maximum path sum starting from top right to bottom left of the matrix.

Therefore this is what I was asked to do:

Given an mxn grid filled with numbers, find a path from top left to
bottom right, which maximizes the sum of all numbers along its path,
also i can only move either down or right.

So I had this on a coding interview recently and I passed it, but in the middle of the interview the guy asked me to also show the path along with the result

Example:

grid = [[1,10]
       ,[2,3]]

output: 14, right,down

So I came up with a solution:

    function matrix(grid) {
    var m = grid.length;
    var n = grid[0].length;

    if(!m || !n) return grid;

    for (let i = 0; i < m; i++){
        for (let j = 0; j < n; j++){
            // grid[0][0] itself contains the min path sum
            if (i === 0 && j === 0) continue;
            // first row: grid[i][j] = previous grid(left) + current value
            if (i === 0) grid[i][j] += grid[i][j-1];
            // first column: grid[i][j] = previous grid(top) + current value
            else if (j === 0) grid[i][j] += grid[i-1][j];
            // grid[i][j] = get the min of previous grid(top/left) + current value
            else grid[i][j] += Math.max(grid[i][j - 1], grid[i - 1][j]);
        }
    };
    return grid[n - 1][m - 1];
};

const grid = [[1,10],[2,3]];

console.log(matrix(grid));

What I tried during the interview was to add the given grid and the result of the maximum numbers on each step on a variable each and then try to subtract the numbers that was calculated in the la line on my 2nd for loop compare it with the number in the original grid and if it match then push 'down' or 'right' to an empty array and then simply return the result and the array.

Example:

grid = [[1,10]
       ,[2,3]]

oldGrid = grid

arr == []

loop
on each iteration

grid[1] - oldGrid[1] = oldgrid[0]
                                   {for rows}
add "right" to arr

or

grid[2] - oldgrid[2] = oldgrid[0]
                                   {for cols}
add "down" to arr

return result and arr

so this is what i've come up with

    function matrix(grid) {
    var m = grid.length;
    var n = grid[0].length;
    var showDir = [];

    if(!m || !n) return grid;

    for (let i = 0; i < m; i++){
        for (let j = 0; j < n; j++){
            // grid[0][0] itself contains the min path sum
            if (i === 0 && j === 0) continue;
            // first row: grid[i][j] = previous grid(left) + current value
            if (i === 0) grid[i][j] += grid[i][j-1];
            // first column: grid[i][j] = previous grid(top) + current value
            else if (j === 0) grid[i][j] += grid[i-1][j];
            // grid[i][j] = get the min of previous grid(top/left) + current value
            else{
                let direction, max;
                if(grid[i][j-1]>grid[i-1][j]){
                    direction = "R"
                    max = grid[i][j-1]
                    showDir.push(direction)
                }
                else{
                    direction = "D"
                    max = grid[i-1][j]
                    showDir.push(direction)
                }
                grid[i][j] += max;
            }
        };
    };
    return grid[n - 1][m - 1], showDir
};

    const grid = [[1,10],[2,3]];

    console.log(matrix(grid));

the thing is with this it only output showDir not the grid and i don't
know why

I'm new to Javascript so please go easy on me

Body:
You could iterate the diagonals and take the maximum value of either the upper item or the right one.

The final result is in bottom left item.

To get a path, you start from the end and choose the item with the next larger sum and take this position for the result set and get the next larger item's position until you reach the start item.

const
    exist = (i, j) => i >= 0 && i < size[0] && j >= 0 && j < size[1],
    array = [[1, 3, 4, 2, 5], [2, 4, 1, 7, 6], [9, 4, 1, 2, 1], [3, 5, 1, 1, 2], [3, 3, 7, 1, 4]],
    size = [array.length, array[0].length],
    sums = [],
    path = [];

// get sums
for (let k = 0, l = size[0] + size[1] - 1; k < l; k++) {
    let i = Math.min(k, size[0] - 1),
        j = k - i;

    while (exist(i, j)) {
        sums[i] ??= [];
        sums[i][j] = array[i][j] + Math.max(sums[i - 1]?.[j] || 0, sums[i][j - 1] || 0);
        i--; j++;
    }
}

// get path from max to start value
let i = size[0] - 1,
    j = size[1] - 1;

path.push([i, j]);
while (i || j) {
    if (!exist(i - 1, j) || exist(i, j - 1) && sums[i - 1][j] < sums[i][j - 1]) j--;
    else i--;
    path.unshift([i, j]);
}

path.forEach(([i, j]) => console.log(i, j, '->', sums[i][j]));
console.log('');
sums.forEach(a => console.log(...a.map(v => v.toString().padStart(3, ' '))));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
My Loop of the Loop is painstakingly slow
I have an object $Posts which contain a title, and a SimTitles field amongst a few others.  I need to compare each title to the other titles and give it a Similarity score in the SimTitles field.  So if I have 80 $Posts, it will need to cover 6400 re-iterations as each title needs to be scored vs the others.

Apart from the Measure-TitleSimilarity routine which I believe is optimized, can anyone see a way to improve the speed of this double loop that I am missing?

Edit: I have included the function Measure-TitleSimilarity.  I am actually passing the array to the function.  The whole topic of quantifying arrays for likeness is fascinating.  I have tried with Title.ToCharArray() which changes the magic number to a much higher number.  It also can produce a match with two completely different titles as long as the characters are the same.  (Ex: 'Mother Teresa' would closely match 'Earthmovers' or 'Thermometer' yet clearly not the same meaning).  Cosine Similarity if just one method but it seemed easiest to process.
@Mclayton and @bryancook - I see the light with your suggestion, but can't grasp tracking what no longer needs to be looked at for similar words.

```<code>Function Get-SimTitles([psobject]$NewPosts) {

  $CKTitles = $NewPosts.title

  foreach ($Ck in $CkTitles) {
    $NewPosts | & {
      process {
        if ((Measure-TitleSimilarity $Ck.split(' ') $_.title.split(' ') -gt .2) {
          $_.SimTitles = $_.SimTitles + 1
        }
      }
    }
  }
}

Function Measure-TitleSimilarity
{
## Based on VectorSimilarity by .AUTHOR Lee Holmes
## Modified slightly to match use

[CmdletBinding()]
param(

    [Parameter(Position = 0)]
    $Title1,

    [Parameter(Position = 1)]
    $Title2

)

$allkeys = @($Title1) + @($Title2) |  Sort-Object -Unique

$set1Hash = @{}
$set2Hash = @{}
$setsToProcess = @($Title1, $Set1Hash), @($Title2, $Set2Hash)

foreach($set in $setsToProcess)
{
    $set[0] | Foreach-Object {
         $value = 1
         $set[1][$_] = $value
    }
}

$dot = 0
$mag1 = 0
$mag2 = 0

foreach($key in $allkeys)
{
    $dot += $set1Hash[$key] * $set2Hash[$key]
    $mag1 +=  ($set1Hash[$key] * $set1Hash[$key])
    $mag2 +=  ($set2Hash[$key] * $set2Hash[$key])
}

$mag1 = [Math]::Sqrt($mag1)
$mag2 = [Math]::Sqrt($mag2)

return [Math]::Round($dot / ($mag1 * $mag2), 3)

}
</code>```

答:
Partial answer

This includes a couple of the suggestions from the comments:

Mathias R. Jessen - "You don't have to compare every title to every title - instead, you only need to compare all unique pairs"

my comment - "you could split your titles into word arrays once before you start comparing, and then loop over those, rather than splitting them every time"

```<code>$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

function ConvertTo-WordSets( [psobject] $Posts )
{

    # preprocess each post to break its title into word counts
    # so we don't need to do it every time we compare 2 posts

    foreach( $post in $Posts )
    {
        $set = new-object PSCustomObject -Property ([ordered] @{
            "Post"   = $post
            "Title"  = $post.Title.Trim()
            "Words"  = $null
            "Counts" = $null
        });
        $set.Words  = $set.Title.Split(" ");
        $set.Counts = $set.Words `
            | group-object `
            | foreach-object `
                -Begin   { $counts = @{} } `
                -Process { $counts.Add($_.Name, $_.Count) } `
                -End     { $counts };
        write-output $set;
    }

}

function Get-SimTitles( [psobject] $NewPosts )
{

    # instead of comparing every object to every object, just compare unique combinations
    # e.g. X compared to Y is the same as Y compared to X so score them both at the same time
    # (and we don't need to compare an object to itself either)

    for( $i = 0; $i -lt $NewPosts.Length; $i++ )
    {
        $left = $NewPosts[$i];
        for( $j = $i + 1; $j -lt $NewPosts.Length; $j++ )
        {
            $right = $NewPosts[$j];
            if ((Measure-TitleSimilarity2 $left $right) -gt .5)
            {
                $left.Post.SimTitles  = $left.Post.SimTitles + 1;
                $right.Post.SimTitles = $right.Post.SimTitles + 1;
            }
        }
    }

}

Function Measure-TitleSimilarity
{
    param
    (
        [Parameter(Position = 0)]
        $Left,
        [Parameter(Position = 1)]
        $Right
    )

    # we can use the pre-processed word counts now

    $allkeys = $Left.Words + $Right.Words | Sort-Object -Unique

    $dot = 0
    $mag1 = 0
    $mag2 = 0

    foreach($key in $allkeys)
    {
        $dot  += $Left.Counts[$key] * $Right.Counts[$key]
        $mag1 += $Left.Counts[$key] * $Left.Counts[$key]
        $mag2 += $Right.Counts[$key] * $Right.Counts[$key]
    }

    $mag1 = [Math]::Sqrt($mag1)
    $mag2 = [Math]::Sqrt($mag2)

    return [Math]::Round($dot / ($mag1 * $mag2), 3)

}
</code>```

Performance

Neither this nor the original are particularly fast for even moderately sized samples, but this one is about 4 times faster.

```<code># get some test data
$sentences = (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/SteveMansfield/MNREAD-sentences/master/XMNREAD01.txt").Content;
$sentences = $sentences.Trim("`n").Split("`n") | foreach-object { $_.Substring(1, $_.Length - 3) };

$posts = $sentences `
    | select-object -First 200 `
    | foreach-object {
        new-object PSCustomObject -Property ([ordered] @{
            "Title"     = $_
            "SimTitles" = 0
        })
    };
Measure-Command { Get-SimTitles $posts; }

# build some test data
$posts = $sentences `
    | select-object -First 200 `
    | foreach-object {
        new-object PSCustomObject -Property ([ordered] @{
            "Title"     = $_
            "SimTitles" = 0
        })
    };

Measure-Command {
    $wordSets = @( ConvertTo-WordSets $Posts );
    Get-SimTitles $wordSets;
}
</code>```

Size
Original
This one

10
0.2
0.02

20
0.4
0.1

50
1.9
0.5

100
8.7
1.9

200
38
9

500
246
82

(Times in seconds)

Body:
I have an object $Posts which contain a title, and a SimTitles field amongst a few others.  I need to compare each title to the other titles and give it a Similarity score in the SimTitles field.  So if I have 80 $Posts, it will need to cover 6400 re-iterations as each title needs to be scored vs the others.

Apart from the Measure-TitleSimilarity routine which I believe is optimized, can anyone see a way to improve the speed of this double loop that I am missing?

Edit: I have included the function Measure-TitleSimilarity.  I am actually passing the array to the function.  The whole topic of quantifying arrays for likeness is fascinating.  I have tried with Title.ToCharArray() which changes the magic number to a much higher number.  It also can produce a match with two completely different titles as long as the characters are the same.  (Ex: 'Mother Teresa' would closely match 'Earthmovers' or 'Thermometer' yet clearly not the same meaning).  Cosine Similarity if just one method but it seemed easiest to process.
@Mclayton and @bryancook - I see the light with your suggestion, but can't grasp tracking what no longer needs to be looked at for similar words.

Function Get-SimTitles([psobject]$NewPosts) {

  $CKTitles = $NewPosts.title

  foreach ($Ck in $CkTitles) {
    $NewPosts | & {
      process {
        if ((Measure-TitleSimilarity $Ck.split(' ') $_.title.split(' ') -gt .2) {
          $_.SimTitles = $_.SimTitles + 1
        }
      }
    }
  }
}

Function Measure-TitleSimilarity
{
## Based on VectorSimilarity by .AUTHOR Lee Holmes
## Modified slightly to match use

[CmdletBinding()]
param(

    [Parameter(Position = 0)]
    $Title1,

    [Parameter(Position = 1)]
    $Title2

)

$allkeys = @($Title1) + @($Title2) |  Sort-Object -Unique

$set1Hash = @{}
$set2Hash = @{}
$setsToProcess = @($Title1, $Set1Hash), @($Title2, $Set2Hash)

foreach($set in $setsToProcess)
{
    $set[0] | Foreach-Object {
         $value = 1
         $set[1][$_] = $value
    }
}

$dot = 0
$mag1 = 0
$mag2 = 0

foreach($key in $allkeys)
{
    $dot += $set1Hash[$key] * $set2Hash[$key]
    $mag1 +=  ($set1Hash[$key] * $set1Hash[$key])
    $mag2 +=  ($set2Hash[$key] * $set2Hash[$key])
}

$mag1 = [Math]::Sqrt($mag1)
$mag2 = [Math]::Sqrt($mag2)

return [Math]::Round($dot / ($mag1 * $mag2), 3)

}

Body:
Partial answer

This includes a couple of the suggestions from the comments:

Mathias R. Jessen - "You don't have to compare every title to every title - instead, you only need to compare all unique pairs"

my comment - "you could split your titles into word arrays once before you start comparing, and then loop over those, rather than splitting them every time"

$ErrorActionPreference = "Stop";
Set-StrictMode -Version "Latest";

function ConvertTo-WordSets( [psobject] $Posts )
{

    # preprocess each post to break its title into word counts
    # so we don't need to do it every time we compare 2 posts

    foreach( $post in $Posts )
    {
        $set = new-object PSCustomObject -Property ([ordered] @{
            "Post"   = $post
            "Title"  = $post.Title.Trim()
            "Words"  = $null
            "Counts" = $null
        });
        $set.Words  = $set.Title.Split(" ");
        $set.Counts = $set.Words `
            | group-object `
            | foreach-object `
                -Begin   { $counts = @{} } `
                -Process { $counts.Add($_.Name, $_.Count) } `
                -End     { $counts };
        write-output $set;
    }

}

function Get-SimTitles( [psobject] $NewPosts )
{

    # instead of comparing every object to every object, just compare unique combinations
    # e.g. X compared to Y is the same as Y compared to X so score them both at the same time
    # (and we don't need to compare an object to itself either)

    for( $i = 0; $i -lt $NewPosts.Length; $i++ )
    {
        $left = $NewPosts[$i];
        for( $j = $i + 1; $j -lt $NewPosts.Length; $j++ )
        {
            $right = $NewPosts[$j];
            if ((Measure-TitleSimilarity2 $left $right) -gt .5)
            {
                $left.Post.SimTitles  = $left.Post.SimTitles + 1;
                $right.Post.SimTitles = $right.Post.SimTitles + 1;
            }
        }
    }

}

Function Measure-TitleSimilarity
{
    param
    (
        [Parameter(Position = 0)]
        $Left,
        [Parameter(Position = 1)]
        $Right
    )

    # we can use the pre-processed word counts now

    $allkeys = $Left.Words + $Right.Words | Sort-Object -Unique

    $dot = 0
    $mag1 = 0
    $mag2 = 0

    foreach($key in $allkeys)
    {
        $dot  += $Left.Counts[$key] * $Right.Counts[$key]
        $mag1 += $Left.Counts[$key] * $Left.Counts[$key]
        $mag2 += $Right.Counts[$key] * $Right.Counts[$key]
    }

    $mag1 = [Math]::Sqrt($mag1)
    $mag2 = [Math]::Sqrt($mag2)

    return [Math]::Round($dot / ($mag1 * $mag2), 3)

}

Performance

Neither this nor the original are particularly fast for even moderately sized samples, but this one is about 4 times faster.

# get some test data
$sentences = (Invoke-WebRequest -Uri "https://raw.githubusercontent.com/SteveMansfield/MNREAD-sentences/master/XMNREAD01.txt").Content;
$sentences = $sentences.Trim("`n").Split("`n") | foreach-object { $_.Substring(1, $_.Length - 3) };

$posts = $sentences `
    | select-object -First 200 `
    | foreach-object {
        new-object PSCustomObject -Property ([ordered] @{
            "Title"     = $_
            "SimTitles" = 0
        })
    };
Measure-Command { Get-SimTitles $posts; }

# build some test data
$posts = $sentences `
    | select-object -First 200 `
    | foreach-object {
        new-object PSCustomObject -Property ([ordered] @{
            "Title"     = $_
            "SimTitles" = 0
        })
    };

Measure-Command {
    $wordSets = @( ConvertTo-WordSets $Posts );
    Get-SimTitles $wordSets;
}

Size
Original
This one

10
0.2
0.02

20
0.4
0.1

50
1.9
0.5

100
8.7
1.9

200
38
9

500
246
82

(Times in seconds)


问:
Get all subfolders of a specific public folder
I want to get all subfolders of a specific public subfolder.

The problem I face is that "Deep traversal queries are not allowed on public folders." so I am a bit lost at how to do that now.

Here is my code:

```<code>Function FindAllSubfolders(){
    $tfTargetidRoot = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)
    $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$tfTargetidRoot)

    $FolderPath = "/mydomain.com/parentfolder"
    $pfArray = $FolderPath.Split("/")
    for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
        $pfArray[$lint]
        $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
        $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint])
        $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
        if ($findFolderResults.TotalCount -gt 0){
            foreach($folder in $findFolderResults.Folders){
                $tfTargetFolder = $folder
            }
        }
    }

    $folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000)
    $folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
    $folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
    $folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
    $folderfindResults = $service.FindFolders($tfTargetFolder.id, $folderview)
    return $folderfindResults
}
</code>```

答: The only way to do this with EWS is you need to do a Shallow traversal of each folder, process the results if that subfolder has child folder then do a Shallow traversal of that child and so on until you get the whole tree. Public folders can get complicated eg if you then want to start access the content of the folder it possible that the child folder maybe located on different Public Folder mailboxes.</p>

Body:
I want to get all subfolders of a specific public subfolder.

The problem I face is that "Deep traversal queries are not allowed on public folders." so I am a bit lost at how to do that now.

Here is my code:

Function FindAllSubfolders(){
    $tfTargetidRoot = new-object  Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::PublicFoldersRoot)
    $tfTargetFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$tfTargetidRoot)

    $FolderPath = "/mydomain.com/parentfolder"
    $pfArray = $FolderPath.Split("/")
    for ($lint = 1; $lint -lt $pfArray.Length; $lint++) {
        $pfArray[$lint]
        $fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1)
        $SfSearchFilter = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.FolderSchema]::DisplayName,$pfArray[$lint])
        $findFolderResults = $service.FindFolders($tfTargetFolder.Id,$SfSearchFilter,$fvFolderView)
        if ($findFolderResults.TotalCount -gt 0){
            foreach($folder in $findFolderResults.Folders){
                $tfTargetFolder = $folder
            }
        }
    }

    $folderview = New-Object Microsoft.Exchange.WebServices.Data.FolderView(10000)
    $folderview.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.Webservices.Data.BasePropertySet]::FirstClassProperties)
    $folderview.PropertySet.Add([Microsoft.Exchange.Webservices.Data.FolderSchema]::DisplayName)
    $folderview.Traversal = [Microsoft.Exchange.Webservices.Data.FolderTraversal]::Deep
    $folderfindResults = $service.FindFolders($tfTargetFolder.id, $folderview)
    return $folderfindResults
}


问:
Vue 3 script setup prop validation typescript
I'm trying to replace my Vue 2 options API props object code with Vue 3 script setup syntax in typescript.

Existing:

```<code>type: {
  type: String,
  default: 'button',
  validator: (prop) => ['button', 'submit', 'reset'].includes(prop)
}
</code>```

I have this so far:

```<code><script lang="ts" setup>
interface Props {
  type?: string;
}

const props = withDefaults(defineProps<Props>(), { type: 'button' });
</script>
</code>```

but I can't find any info on how to handle prop validators in the script setup syntax

答:
For those also arriving from Google, and since the Vue docs aren't very clear on this, you can do a straight conversion using the Vue 2 style options format as well:</p>
```<code>const props = defineProps({
  type: {
    type: String,
    default: 'button',
    validator: (prop) => ['button', 'submit', 'reset'].includes(prop)
  }
})
</code>```

Body:
I'm trying to replace my Vue 2 options API props object code with Vue 3 script setup syntax in typescript.

Existing:

type: {
  type: String,
  default: 'button',
  validator: (prop) => ['button', 'submit', 'reset'].includes(prop)
}

I have this so far:

but I can't find any info on how to handle prop validators in the script setup syntax

Body:
For those also arriving from Google, and since the Vue docs aren't very clear on this, you can do a straight conversion using the Vue 2 style options format as well:

const props = defineProps({
  type: {
    type: String,
    default: 'button',
    validator: (prop) => ['button', 'submit', 'reset'].includes(prop)
  }
})


问:
How do you select the last cell in every row in a responsive grid layout?
I made a responsive grid layout where the number of columns adjusts automatically with this specification, template-rows are not explicit:

grid-template-columns: repeat(auto-fill, minmax(15em, 1fr));

Here is the website if you want to have a closer look(https://vahid1919.github.io/#explanation)

I created a psuedoclass that displays tags on the right-top corner whenever I hover on a card. What I could not figure out is how to write selectors so that the tags appear on the left-top corner if the card is the right-most card on the webpage. This is helpful incase I want to have a more descriptive(larger) element I want to display when a user hovers.

This is what site situation looks like I want the last cell in the row to display the tags on the left side. How do I select for that. Or if I can't, please point me to the right direction perhaps if I need to use Javascript...I'm fairly a noob at that.

答:
First, you'll need to add jQuery to your site's header with the following:

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</code>```

Then you can add the following script which will identify the last element with a class named "partners-grid-items", select the children of that element with a class name of "tags" and modify the css to position it to the left (you may need to tweak this part).

```<code>$(document).ready(function () {
      $('.partners-grid-items:last-child').children('.tags').css('right', '100%');
});
</code>```

PS - your last .tag for education doesn't have the same positioning as applied to the others in your css.

Body:
First, you'll need to add jQuery to your site's header with the following:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Then you can add the following script which will identify the last element with a class named "partners-grid-items", select the children of that element with a class name of "tags" and modify the css to position it to the left (you may need to tweak this part).

$(document).ready(function () {
      $('.partners-grid-items:last-child').children('.tags').css('right', '100%');
});

PS - your last .tag for education doesn't have the same positioning as applied to the others in your css.


问:
How to shorten scons compilation output
Currently i'm compiling my unittests for a big c++ project with scons (2.2.0).
The include paths combined has more than 10000 characters.
Scons is creating a temp file to handle this, but prints out the includepath for every compiled .c file.
I really do not like this and i think it is ugly, i already spent way to much time on this to resolve it but unfortunately i was not able to find a solution. Scons always prints:

```<code>Compiling TARGET
Using tempfile c:\users\....\temp\tmpqfgn4z.lnk for command line:
cl ... /I.. /I.. /I.. (in total 10k characters)
</code>```

i created a small example program to check why the CXXCOMSTR is not working (?)

```<code># SConstruct
env = Environment()
env['CXXCOMSTR'] = "Compiling $TARGET"
env['LINKCOMSTR'] = "Linking $TARGET"

env.Program(["hello.c"])
</code>```

If I compile this it leads to the following output

```<code># scons -Q
Compiling hello.obj
hello.c
Linking hello.exe
</code>```

I have the feeling the 2nd line (hello.c) is the issue. But im not able to get rid of it. my goal is to get just the following output

```<code># scons -Q
Compiling hello.obj
Linking hello.exe
</code>```

Edit: i found that there is an check in "scons-2.2.0\SCons\Platform_init_.py" to print this line or not. if i change it here manually it is doing what i want. But i cannot share this with other teammembers. Im not able to "import Scons" in my Sconstrict to set this print_actions variable.. Anyone knows how to do that?

```<code>if SCons.Action.print_actions:
        print("Using tempfile "+native_tmp+" for command line:\n"+
              str(cmd[0]) + " " + " ".join(args))
</code>```

答: This looks like an issue that's been addressed, the current code makes sure the relevant COMSTR variable isn't set before defining an output string mentioning the tempfile usage.  A change was made in a commit in 2014, using a version of SCons as old as 2.2 is problematic (and unsupported from the viewpoint of the SCons project).

Title: How to shorten scons compilation output

Body:
Currently i'm compiling my unittests for a big c++ project with scons (2.2.0).
The include paths combined has more than 10000 characters.
Scons is creating a temp file to handle this, but prints out the includepath for every compiled .c file.
I really do not like this and i think it is ugly, i already spent way to much time on this to resolve it but unfortunately i was not able to find a solution. Scons always prints:

Compiling TARGET
Using tempfile c:\users\....\temp\tmpqfgn4z.lnk for command line:
cl ... /I.. /I.. /I.. (in total 10k characters)

i created a small example program to check why the CXXCOMSTR is not working (?)

# SConstruct
env = Environment()
env['CXXCOMSTR'] = "Compiling $TARGET"
env['LINKCOMSTR'] = "Linking $TARGET"

env.Program(["hello.c"])

If I compile this it leads to the following output

# scons -Q
Compiling hello.obj
hello.c
Linking hello.exe

I have the feeling the 2nd line (hello.c) is the issue. But im not able to get rid of it. my goal is to get just the following output

# scons -Q
Compiling hello.obj
Linking hello.exe

Edit: i found that there is an check in "scons-2.2.0\SCons\Platform_init_.py" to print this line or not. if i change it here manually it is doing what i want. But i cannot share this with other teammembers. Im not able to "import Scons" in my Sconstrict to set this print_actions variable.. Anyone knows how to do that?

if SCons.Action.print_actions:
        print("Using tempfile "+native_tmp+" for command line:\n"+
              str(cmd[0]) + " " + " ".join(args))


问:
How to solve log4j2 CVE (CVE-2021-44228) issues for application under JBoss 7.x
I've some issues in porting some application running in a JBoss 7.1 environment from log4j to log4j2.

I've ported my SW to log4j2 (2.17.1), but that is not enough. I'm understanding that JBoss configuration changes - not so simple - are needed to obtain the applications run correctly and write log-data on the correct log-files.

Have you some hints to aid me?

Based on what I read on the Redhat portal [customer access only] I wonder if a port for front-end applications is necessary.

No version of JBoss EAP 6.x/7.x is vulnerable to CVE-2021-44228
currently thanks to the usage of JBoss Logging framework instead of
Log4J. Please refer to the security bulletin - RHSB-2021-009 for
further information on this vulnerability and impacted Red Hat
products. [...]  EAP 7.x's log manager does port in log4j JMSAppender
code so is similarly impacted by CVE-2021-4104 with enabled
JMSAppenders. But in further reviewing this vulnerability, we have
determined this can only be considered a true vulnerability when the
attacker has write access to the Log4j configuration to add a
JMSAppender to the attacker's JMS Broker.

答:
JBoss EAP 7.1 is not vulnerable or affected by this CVE. This version of JBoss EAP does not include log4j 2. JBoss EAP 7.4 does include the log4j-api, but does not include log4j-core and therefore it is also not vulnerable.

In short JBoss EAP is not vulnerable and there is nothing in its configuration you need to change.


问:
Django, Show certain media dirs to logged in users
I have an Django app where users can download files that was assigned to them. How can I be sure that only the user who is assigned the file may download that file. Because its in the media dir, any one can brows there, so is there a way of letting only the relevant user download the file?</p>

答:
I did the same thing one year ago.
I want only relevant users can download their photos:

```<code># urls.py
(r'^data/photos/(?P<path>.*)$','views.data_access'),
</code>```

my view 'data_access' gives the photo, or a 403 page

```<code># view data_access(request, path)
# [...code...]
if user_can_download:
        response = HttpResponse(mimetype="image/jpeg")
        response['Content-Disposition'] = 'attachment; filename=%s' % unicode(photo.image.name)
        response['X-Accel-Redirect'] = '/protected/'+ unicode(path)
        return response
else:
   return HttpResponseForbidden()
</code>```

Body:
I did the same thing one year ago.
I want only relevant users can download their photos:

# urls.py
(r'^data/photos/(?P<path>.*)$','views.data_access'),

my view 'data_access' gives the photo, or a 403 page

# view data_access(request, path)
# [...code...]
if user_can_download:
        response = HttpResponse(mimetype="image/jpeg")
        response['Content-Disposition'] = 'attachment; filename=%s' % unicode(photo.image.name)
        response['X-Accel-Redirect'] = '/protected/'+ unicode(path)
        return response
else:
   return HttpResponseForbidden()


问:
Postgres 12 - how to reduce size of wal-directory
I have upgraded postgres 9 to 12 with pgdump and restore it to new database. All seems to be ok. Afterwards I noticed, that size of ../12/main/ has grown a lot and most of it is in pg_wal-directory.
Size of ./base is 27GB and size of ./pg_wal is 61GB. On postgres 9 values were 31GB / 1GB (pg_xlog).

After some checking, postgres.conf-file shows default values as:

```<code># max_wal_size = 64GB
min_wal_size = 5GB
</code>```

I change value of max_wal_size to 4GB and removed comment

```<code>SHOW ALL;
</code>```

told

```<code>max_wal_size | 4GB
</code>```

But size of pg_wal stays on 61GB.
Is there some other parameter, I should change?

答:
Following on from jjanes' answer ...

If you have a server with very low traffic, a development server for example, have done something like a data import which generates a lot of writes, and so have a large number of wal segment files, the amount of storage consumed by wal segments may grow up to max_wal_size. If you reduce max_wal_size in the server config, the actual number of wal segment files won't drop until the server cycles through those old files.

Here's a function which will force the server to cycle through all of the existing segment files. It does this by repeatedly calling pg_switch_wal() to switch to a new wal segment and then checkpoint to force writing a checkpoint on the new wal segment.

In the scenario described this will trigger postgres to reduce the number of segment files down to the current max_wal_size and possibly below.

This may be counterproductive on a live server, particularly if you are doing wal archiving, so please only use this if your situation matches the description above.

Depending on how many wal segments you have, this may take some time to complete.

```<code>create or replace function pg_wal_cycle_all()
returns int language plpgsql
as $$
declare
    wal_count int;
    wal_seg varchar;
begin
    select count(*) - 1
    into wal_count
    from pg_ls_dir('pg_wal');

    for wal in 1..wal_count loop
        select pg_walfile_name(pg_switch_wal()) into wal_seg;
        raise notice 'segment %', wal_seg;
        checkpoint;
    end loop;
    return wal_count;
end;$$;
</code>```

Execute with:

```<code>select pg_wal_cycle_all();
</code>```

Body:
I have upgraded postgres 9 to 12 with pgdump and restore it to new database. All seems to be ok. Afterwards I noticed, that size of ../12/main/ has grown a lot and most of it is in pg_wal-directory.
Size of ./base is 27GB and size of ./pg_wal is 61GB. On postgres 9 values were 31GB / 1GB (pg_xlog).

After some checking, postgres.conf-file shows default values as:

# max_wal_size = 64GB
min_wal_size = 5GB

I change value of max_wal_size to 4GB and removed comment

SHOW ALL;

told

max_wal_size | 4GB

But size of pg_wal stays on 61GB.
Is there some other parameter, I should change?

Body:
Following on from jjanes' answer ...

If you have a server with very low traffic, a development server for example, have done something like a data import which generates a lot of writes, and so have a large number of wal segment files, the amount of storage consumed by wal segments may grow up to max_wal_size. If you reduce max_wal_size in the server config, the actual number of wal segment files won't drop until the server cycles through those old files.

Here's a function which will force the server to cycle through all of the existing segment files. It does this by repeatedly calling pg_switch_wal() to switch to a new wal segment and then checkpoint to force writing a checkpoint on the new wal segment.

In the scenario described this will trigger postgres to reduce the number of segment files down to the current max_wal_size and possibly below.

This may be counterproductive on a live server, particularly if you are doing wal archiving, so please only use this if your situation matches the description above.

Depending on how many wal segments you have, this may take some time to complete.

create or replace function pg_wal_cycle_all()
returns int language plpgsql
as $$
declare
    wal_count int;
    wal_seg varchar;
begin
    select count(*) - 1
    into wal_count
    from pg_ls_dir('pg_wal');

    for wal in 1..wal_count loop
        select pg_walfile_name(pg_switch_wal()) into wal_seg;
        raise notice 'segment %', wal_seg;
        checkpoint;
    end loop;
    return wal_count;
end;$$;

Execute with:

select pg_wal_cycle_all();