问:
Why `None` is printed in Google colab when I try to print a list?
I have two lists, sentences and tags, which are actually list of lists.

When I try to print

```<code>print(sentences[1]), print(tags[1])
</code>```

output comes as

```<code>['Made', 'it', 'back', 'home', 'to', 'GA', '.', 'It', 'sucks', 'not', 'to', 'be', 'at', 'Disney', 'world', ',', 'but', 'its', 'good', 'to', 'be', 'home', '.', 'Time', 'to', 'start', 'planning', 'the', 'next', 'Disney', 'World', 'trip', '.']
['O', 'O', 'O', 'O', 'O', 'loc', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'facility', 'facility', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'facility', 'facility', 'O', 'O']
(None, None)
</code>```

I can't work out why None is getting printed.

答:
Because x, y creates a tuple which the notebook tries to evaluate (and therefore every element in the tuple is evaluated).

Since print returns None, you are getting the tuple (None, None) as an output.

In order to remedy this put each print call on its own line instead of creating the tuple.

Body:
I have two lists, sentences and tags, which are actually list of lists.

When I try to print

print(sentences[1]), print(tags[1])

output comes as

['Made', 'it', 'back', 'home', 'to', 'GA', '.', 'It', 'sucks', 'not', 'to', 'be', 'at', 'Disney', 'world', ',', 'but', 'its', 'good', 'to', 'be', 'home', '.', 'Time', 'to', 'start', 'planning', 'the', 'next', 'Disney', 'World', 'trip', '.']
['O', 'O', 'O', 'O', 'O', 'loc', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'facility', 'facility', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'facility', 'facility', 'O', 'O']
(None, None)

I can't work out why None is getting printed.


来源: stackexchange

问:
Powershell - Find computers with a specific username logged in
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

```<code>Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }
</code>```

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

答:
Here's is an alternative method that does not iterarte all computers in the domain, but it relies on all users have their Home directories redirected to a network share.

If that is the case in your domain, try:

```<code># enter the SamAccountName of the user you are looking for
$user = 'SamAccountName'

# the UNC (\\Server\Share) name of the network share where all user homedirectories are
$usersHomePath = '\\HomesServer\HomesShare$'

# split the UNC path to get the server name and share name in separate variables
$server, $share = $usersHomePath.TrimStart("\") -split '\\'

$result = Get-CimInstance -ClassName Win32_ServerConnection -ComputerName $server |
            Where-Object { $_.ShareName -eq $share -and $user -eq $_.UserName } |
            Select-Object @{Name = "SamAccountName"; Expression = { $_.UserName }},
                          @{Name = "ComputerName"; Expression = {(([System.Net.Dns]::GetHostEntry($_.ComputerName).HostName) -split "\.")[0]}}

#output in console
$result
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've been trying to figure out a powershell script that doing a search of all computers
with a specific username logged in.

so far I've found a way looking via all computers the 'explorer.exe' process and owner

Also I found this script:

Function Get-Username {
    Clear-Host
    $Global:Username = Read-Host "Enter Username"
    if ($Username -eq $null){
        Write-Host "Username cannot be blank, please enter a Username"
        Get-Username
    }
    $UserCheck = Get-ADUser $Username
    if ($UserCheck -eq $null){
        Write-Host "Invalid Username, please verify this is the logon id for the account"
        Get-Username
    }
}
Get-Username

Function Get-Computername {
    Clear-Host
    $Global:Prefix = Read-Host "Enter Computername"
    Clear-Host
}
Get-Computername

$computers = Get-ADComputer -Filter {Enabled -eq 'true' -and SamAccountName -like $Prefix}
$CompCount = $Computers.Count
Write-Host "Searching for $Username on $Prefix on $CompCount Computers`n"

foreach ($comp in $computers){
    $Computer = $comp.Name
    $Reply = $null
    $Reply = test-connection $Computer -count 1 -quiet
    if($Reply -eq 'True'){
        if($Computer -eq $env:COMPUTERNAME){
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -computer $Computer -Filter "Name = 'explorer.exe'"
        }
        else{
            $proc = gwmi win32_process -ErrorAction SilentlyContinue -Credential $Credential -computer $Computer -Filter "Name = 'explorer.exe'"
        }

            $progress++
            ForEach ($p in $proc) {
                $temp = ($p.GetOwner()).User
                Write-Progress -activity "Working..." -status "Status: $progress of $CompCount Computers checked" -PercentComplete (($progress/$Computers.Count)*100)
                if ($temp -eq $Username){
                write-host "$Username is logged on $Computer"
                }
            }
        }
    }

This is not my script, only trying to use it.

this script can take a very long long time, trying to run on about 300 machines, it can take for 20 minutes run.

now im not sure, which part is taking most of the time, im thinking either the gwmi win32 process, that checking on each machine if the process 'explorer.exe' is on
or the part test-connection that trying to ping each machine first, and then check for the 'explorer.exe' process.

for your knowledge, is there any faster way with powershell script to do this kind of checkup?
to search for a specific username on which machines logged on?

Thanks in advance for any help!

Body:
Here's is an alternative method that does not iterarte all computers in the domain, but it relies on all users have their Home directories redirected to a network share.

If that is the case in your domain, try:

# enter the SamAccountName of the user you are looking for
$user = 'SamAccountName'

# the UNC (\\Server\Share) name of the network share where all user homedirectories are
$usersHomePath = '\\HomesServer\HomesShare$'

# split the UNC path to get the server name and share name in separate variables
$server, $share = $usersHomePath.TrimStart("\") -split '\\'

$result = Get-CimInstance -ClassName Win32_ServerConnection -ComputerName $server |
            Where-Object { $_.ShareName -eq $share -and $user -eq $_.UserName } |
            Select-Object @{Name = "SamAccountName"; Expression = { $_.UserName }},
                          @{Name = "ComputerName"; Expression = {(([System.Net.Dns]::GetHostEntry($_.ComputerName).HostName) -split "\.")[0]}}

#output in console
$result


问:
I'm trying to write a program that reverses an array and it keeps saying I can not convert int * to int. How do I fix that?
```<code>int* reverse_Array(int size, int* arr)
{
    int* areverse[10];

    int s = 0;

    for (int c = 10; c > 0; c--)

        arr[c] = areverse[s]; // the issue happens here with the =

    return areverse[s];
}
</code>```

The issue happens with the = between arr[c] and areverse[s]

I tried a couple fixes but each one doesn't really fix it.

I am writing code that should reverse a array
"(using a function by returning a pointer/array)"

答:
If you're "allowed" to use vectors, you can use a simple example like this.

#include <vector>
#include <algorithm>

template<typename T>
std::vector<T> reverse_array(const std::vector<T>& array)
{
    std::vector<T> t = array;
    std::reverse(array.begin(), array.end());
    return t;
}
```

Body:
int* reverse_Array(int size, int* arr)
{
    int* areverse[10];

    int s = 0;

    for (int c = 10; c > 0; c--)

        arr[c] = areverse[s]; // the issue happens here with the =

    return areverse[s];
}

The issue happens with the = between arr[c] and areverse[s]

I tried a couple fixes but each one doesn't really fix it.

I am writing code that should reverse a array
"(using a function by returning a pointer/array)"


问:
Events that fire when a hosted service's deployment slot changes (Swap VIP)
I have a few settings in my applications that rely on the deployment slot. I understand the penalties and implications such a design decision incurs, but the decision is final and works for our case.

What I would like to know is what events fire when you change a hosted service's Deployment Slot (if any)? The RoleEnvironmentTopologyChange looked correct, but in the decsription it says it fires when the number of instances changes, so that's not what I'm looking for.

The reason I need it is to invalidate the cache that is holding the slot - that is further passed on to the resolver that gets the data specific to the deployment slot.

答: There's no event that fires during a VIP swap. If you want to change something when you swap, I would recommend making a config setting and changing that before you do the swap.</p>

ContentLicense: CC BY-SA 3.0


问:
A proper wrapper for console.log with correct line number?
I'm developing an application and placing a global isDebug switch. I would like to wrap console.log for more convenient usage.

```<code>//isDebug controls the entire site.
var isDebug = true;

//debug.js
function debug(msg, level){
    var Global = this;
    if(!(Global.isDebug && Global.console && Global.console.log)){
        return;
    }
    level = level||'info';
    Global.console.log(level + ': '+ msg);
}

//main.js
debug('Here is a msg.');
</code>```

Then I get this result in Firefox console.

```<code>info: Here is a msg.                       debug.js (line 8)
</code>```

What if I want to log with line number where debug() gets called, like info: Here is a msg.      main.js (line 2)?

答:
With modern javascript and the use of getters, you could write something like this:

```<code>window.Logger = {
    debugMode: true,
    get info() {
        if ( window.Logger.debugMode ) {
            return window.console.info.bind( window.console );
        } else {
            return () => {};
        }
    }
}
</code>```

The nice part about it is that you can have both static and computed values printed out, together with correct line numbers. You could even define multiple logger with different settings:

```<code>class LoggerClz {
    name = null;
    debugMode = true;
    constructor( name ) { this.name = name; }
    get info() {
        if ( this.debugMode ) {
            return window.console.info.bind( window.console, 'INFO', new Date().getTime(), this.name );
        } else {
            return () => {};
        }
    }
}

const Logger1 = new LoggerClz( 'foo' );
const Logger2 = new LoggerClz( 'bar' );

function test() {
    Logger1.info( '123' ); // INFO 1644750929128 foo 123 [script.js:18]
    Logger2.info( '456' ); // INFO 1644750929128 bar 456 [script.js:19]
}
test();
</code>```

Body:
I'm developing an application and placing a global isDebug switch. I would like to wrap console.log for more convenient usage.

//isDebug controls the entire site.
var isDebug = true;

//debug.js
function debug(msg, level){
    var Global = this;
    if(!(Global.isDebug && Global.console && Global.console.log)){
        return;
    }
    level = level||'info';
    Global.console.log(level + ': '+ msg);
}

//main.js
debug('Here is a msg.');

Then I get this result in Firefox console.

info: Here is a msg.                       debug.js (line 8)

What if I want to log with line number where debug() gets called, like info: Here is a msg.      main.js (line 2)?

Body:
With modern javascript and the use of getters, you could write something like this:

window.Logger = {
    debugMode: true,
    get info() {
        if ( window.Logger.debugMode ) {
            return window.console.info.bind( window.console );
        } else {
            return () => {};
        }
    }
}

The nice part about it is that you can have both static and computed values printed out, together with correct line numbers. You could even define multiple logger with different settings:

class LoggerClz {
    name = null;
    debugMode = true;
    constructor( name ) { this.name = name; }
    get info() {
        if ( this.debugMode ) {
            return window.console.info.bind( window.console, 'INFO', new Date().getTime(), this.name );
        } else {
            return () => {};
        }
    }
}

const Logger1 = new LoggerClz( 'foo' );
const Logger2 = new LoggerClz( 'bar' );

function test() {
    Logger1.info( '123' ); // INFO 1644750929128 foo 123 [script.js:18]
    Logger2.info( '456' ); // INFO 1644750929128 bar 456 [script.js:19]
}
test();


问:
how to debug and test retry logic of API client in Python
I've just developed the primitive API client for Instagram based on "requests" library. The next goal is to implement retry logic for 400+ and 500+ error codes. There is a bunch of examples how to do this, but I'm wondering how to test the solution.
Should it be some function which randomly decides weither to pass request to API portal or to return some error code instead?
Or maybe there is somewhere on earth the unreliable API to practice on?
or some server that genarates errors intentionally?</p>

答:
You can use this startup script to create a small HTTP server:

```<code>from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        code = self.path.split('/')[1]

        # do stuff here
        self.send_response(int(code))
        self.send_header("Content-type", "text/html")
        self.end_headers()

if __name__ == '__main__':
    webServer = HTTPServer((hostName, serverPort), MyServer)
    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass
    webServer.server_close()
</code>```

How to use:

```<code>import requests

r = requests.get('http://localhost:8080/403')
print(r.status_code)

# Output
403
</code>```

Body:
You can use this startup script to create a small HTTP server:

from http.server import BaseHTTPRequestHandler, HTTPServer
hostName = "localhost"
serverPort = 8080

class MyServer(BaseHTTPRequestHandler):
    def do_GET(self):
        code = self.path.split('/')[1]

        # do stuff here
        self.send_response(int(code))
        self.send_header("Content-type", "text/html")
        self.end_headers()

if __name__ == '__main__':
    webServer = HTTPServer((hostName, serverPort), MyServer)
    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass
    webServer.server_close()

How to use:

import requests

r = requests.get('http://localhost:8080/403')
print(r.status_code)

# Output
403


问:
Vaadin @PWA annotation not recognized
I'm working with Vaadin 14 and Springboot. I want to make a PWA, but @PWA annotation is simply not working as expected.  I defined it in the Application.java:

```<code>@PWA(name = "Long name",
    shortName = "Name",
    offlinePath="offline.html",
    offlineResources = "./images/icon.png",
    description = "description")
</code>```

But the install prompt does not appear. I cheked the Application tab in the DevTools, but neither the service worker nor the manifest is created.

I have made other PWAs previously, but this never happened... I don't know what is wrong here.

答: Your browser needs to access it from an HTTPS link. If you're on localhost, you can simulate this by going to chrome://flags/ search Insecure origins treated as secure and enter the url. For example:

Title: Vaadin @PWA annotation not recognized

Body:
I'm working with Vaadin 14 and Springboot. I want to make a PWA, but @PWA annotation is simply not working as expected.  I defined it in the Application.java:

@PWA(name = "Long name",
    shortName = "Name",
    offlinePath="offline.html",
    offlineResources = "./images/icon.png",
    description = "description")

But the install prompt does not appear. I cheked the Application tab in the DevTools, but neither the service worker nor the manifest is created.

I have made other PWAs previously, but this never happened... I don't know what is wrong here.


问:
Having trouble converting this require statement into an import statement
I have a require statement in my script.

const packageJsonVersion = require('../package.json').version;

If I try and run the script I get an error saying I need to convert it to an import statement.

I changed the code to import { version as packageJsonVersion } from '../package.json' but when I run the script I get the following error.

TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".json" for /home/alex/_code/connect/package.json

I'm not sure how to get around this.

答:
It depends on what environment you're doing this in.

Right now, browsers don't natively support JSON modules (though it's coming).

If you're doing this with a bundler, you need to be sure to tell the bundler how to handle the .json extension.

If you're doing this in Node.js, you need the JSON module notation (assert {type: "json"}).

Separately, though, JSON modules won't support named exports (this is mentioned by both links above). You'll have to import the default and then use the version property on it:

```<code>import data from "../package.json" assert { type: "json" };
const packageJsonVersion = data.version;
</code>```

Body:
It depends on what environment you're doing this in.

Right now, browsers don't natively support JSON modules (though it's coming).

If you're doing this with a bundler, you need to be sure to tell the bundler how to handle the .json extension.

If you're doing this in Node.js, you need the JSON module notation (assert {type: "json"}).

Separately, though, JSON modules won't support named exports (this is mentioned by both links above). You'll have to import the default and then use the version property on it:

import data from "../package.json" assert { type: "json" };
const packageJsonVersion = data.version;


问:
PHP send variable value external webpage
I'm currently trying to send the two variable values, $incorrect and $correct from a form.

I have tried to use $_POST[] to create this functionality, yet it doesn't work!

Could anyone help me when creating such a functionality  ?

page1.php

```<code><form action="testresult.php" method="POST">
    <label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
    <input type="text" id="question1_answer" name="question1_answer" required><br><br>

    <label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
    <input type="text" id="question2_answer" name="question2_answer" required><br><br>

    <label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
    <input type="text" id="question3_answer" name="question3_answer" required><br><br>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>

<?php
        if(isset($_POST["submitAnswers"])){
            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

        }
    ?>
</code>```

And on the receiving end
page2.php

```<code><html>
    <head>
    <title>Results</title>
    </head>
    <body>
        <?php
        $correct = $_POST['correct'];
        $incorrect = $_POST['incorrect'];

        echo $correct."test ".$incorrect;
        ?>
    </body>
</html>
</code>```

答:
The Form action you've set to your testresult.php. So surely the form will carry all of its data to that page. But you are trying to get the data on the same page as if(isset($_POST["submitAnswers"])) where is the form; what actually should exist in that testresult.php page. So should be like this:

index.php or something.php

```<code><form action="testresult.php" method="POST">
    <label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
    <input type="text" id="question1_answer" name="question1_answer" required><br><br>

    <label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
    <input type="text" id="question2_answer" name="question2_answer" required><br><br>

    <label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
    <input type="text" id="question3_answer" name="question3_answer" required><br><br>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>
</code>```

testresult.php

```<code><?php

// questions array that is called in the form's page should be
   called here too to get the questions and comparisons.

    if (isset($_POST['submitAnswers'])) {
    $correct = 0;
    $incorrect = 0;
    $qn1_ans = $_POST['question1_answer'];
    $qn2_ans = $_POST['question2_answer'];
    $qn3_ans = $_POST['question3_answer'];

    if ($qn1_ans == $array_answer[$question_num_array[0]]) {
        $correct++;
    } else {
        $incorrect++;
    }

    if ($qn2_ans == $array_answer[$question_num_array[1]]) {
        $correct++;
    } else {
        $incorrect++;
    }

    if ($qn3_ans == $array_answer[$question_num_array[2]]) {
        $correct++;
    } else {
        $incorrect++;
    }
}
?>
<html>

<head>
    <title>Results</title>
</head>

<body>
    <?php
    $correct = $_POST['correct'];
    $incorrect = $_POST['incorrect'];

    echo $correct . 'test ' . $incorrect;
    ?>
</body>

</html>
</code>```

Body:
I'm currently trying to send the two variable values, $incorrect and $correct from a form.

I have tried to use $_POST[] to create this functionality, yet it doesn't work!

Could anyone help me when creating such a functionality  ?

page1.php

<form action="testresult.php" method="POST">
    Question 1: <?php echo $array_question[$question_num_array[0]] ?>

    <input type="text" id="question1_answer" name="question1_answer" required>

    Question 2: <?php echo $array_question[$question_num_array[1]] ?>

    <input type="text" id="question2_answer" name="question2_answer" required>

    Question 3: <?php echo $array_question[$question_num_array[2]] ?>

    <input type="text" id="question3_answer" name="question3_answer" required>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>

<?php
        if(isset($_POST["submitAnswers"])){
            $correct = 0;
            $incorrect = 0;
            $qn1_ans = $_POST['question1_answer'];
            $qn2_ans = $_POST['question2_answer'];
            $qn3_ans = $_POST['question3_answer'];

            if ($qn1_ans == $array_answer[$question_num_array[0]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn2_ans == $array_answer[$question_num_array[1]]){ $correct ++; }
            else { $incorrect ++; }

            if ($qn3_ans == $array_answer[$question_num_array[2]]){ $correct ++; }
            else { $incorrect ++; }

        }
    ?>

And on the receiving end
page2.php

    <title>Results</title>

        <?php
        $correct = $_POST['correct'];
        $incorrect = $_POST['incorrect'];

        echo $correct."test ".$incorrect;
        ?>

Body:
The Form action you've set to your testresult.php. So surely the form will carry all of its data to that page. But you are trying to get the data on the same page as if(isset($_POST["submitAnswers"])) where is the form; what actually should exist in that testresult.php page. So should be like this:

index.php or something.php

<form action="testresult.php" method="POST">
    <label for="qn1">Question 1: <?php echo $array_question[$question_num_array[0]] ?></label><br>
    <input type="text" id="question1_answer" name="question1_answer" required><br><br>

    <label for="qn2">Question 2: <?php echo $array_question[$question_num_array[1]] ?></label><br>
    <input type="text" id="question2_answer" name="question2_answer" required><br><br>

    <label for="qn3">Question 3: <?php echo $array_question[$question_num_array[2]] ?></label><br>
    <input type="text" id="question3_answer" name="question3_answer" required><br><br>

    <input type="hidden" name="correct" id="correct" value="<?php $correct ?>" />
    <input type="hidden" name="incorrect" id="incorrect" value="<?php $incorrect ?>" />

    <input type="submit" name="submitAnswers" value="Submit">
</form>

testresult.php

<?php

// questions array that is called in the form's page should be
   called here too to get the questions and comparisons.

    if (isset($_POST['submitAnswers'])) {
    $correct = 0;
    $incorrect = 0;
    $qn1_ans = $_POST['question1_answer'];
    $qn2_ans = $_POST['question2_answer'];
    $qn3_ans = $_POST['question3_answer'];

    if ($qn1_ans == $array_answer[$question_num_array[0]]) {
        $correct++;
    } else {
        $incorrect++;
    }

    if ($qn2_ans == $array_answer[$question_num_array[1]]) {
        $correct++;
    } else {
        $incorrect++;
    }

    if ($qn3_ans == $array_answer[$question_num_array[2]]) {
        $correct++;
    } else {
        $incorrect++;
    }
}
?>
<html>

<head>
    <title>Results</title>
</head>

<body>
    <?php
    $correct = $_POST['correct'];
    $incorrect = $_POST['incorrect'];

    echo $correct . 'test ' . $incorrect;
    ?>
</body>

</html>


问:
Sum all specified fields in a collection
I am using PHP to access a MongoDB collection in which I have recorded purchases of my shop.

Example document:

```<code>{"_id":{"$oid":"61ff011a5b55479726fe5208"},"monthYear":"2-2022","timestamp":{"$date":"2022-02-05T22:58:34.952Z"},"productIndex":"x","productPriceUSD":10,"customerName":"x","customerID":"x","notes":"x","__v":0}
</code>```

Now I want to add the value of field "productPriceUSD" from all documents in the collection and get a sum at the end.

Maybe someone can help me?

That's my start:
I know, it probably does not make any sense.

```<code>$client = new MongoDB\Client(
    'xxx'
);

$sumtotal = function() use ($client)
{
    $collection = $client->database->purchases;

    $options = [];

    $filter = [
        ['$group' => [
            '_id' => '$_id',
            'productPriceUSD' => [
                '$sum' => [
                    '$cond' => [ [ '$gt' => [ '$productPriceUSD',  0 ] ], '$productPriceUSD', 0 ],
            ],
        ]],
    ]];

    $result = $collection->aggregate($filter, $options);

};
</code>```

答:
Here two pipelines you need

```<code>{
  $group: {
    _id: "",
    total: { $sum: "$productPriceUSD" }
   }
 },
 {
    $project: {
      _id: 0,
      total: "$total"
  }
 }
</code>```

Playground link: https://mongoplayground.net/p/8OTGkK7wLIp

Body:
I am using PHP to access a MongoDB collection in which I have recorded purchases of my shop.

Example document:

{"_id":{"$oid":"61ff011a5b55479726fe5208"},"monthYear":"2-2022","timestamp":{"$date":"2022-02-05T22:58:34.952Z"},"productIndex":"x","productPriceUSD":10,"customerName":"x","customerID":"x","notes":"x","__v":0}

Now I want to add the value of field "productPriceUSD" from all documents in the collection and get a sum at the end.

Maybe someone can help me?

That's my start:
I know, it probably does not make any sense.

$client = new MongoDB\Client(
    'xxx'
);

$sumtotal = function() use ($client)
{
    $collection = $client->database->purchases;

    $options = [];

    $filter = [
        ['$group' => [
            '_id' => '$_id',
            'productPriceUSD' => [
                '$sum' => [
                    '$cond' => [ [ '$gt' => [ '$productPriceUSD',  0 ] ], '$productPriceUSD', 0 ],
            ],
        ]],
    ]];

    $result = $collection->aggregate($filter, $options);

};

Body:
Here two pipelines you need

{
  $group: {
    _id: "",
    total: { $sum: "$productPriceUSD" }
   }
 },
 {
    $project: {
      _id: 0,
      total: "$total"
  }
 }

Playground link: https://mongoplayground.net/p/8OTGkK7wLIp


问:
UIButton selection color
I'm using a UIButton as a pressable imageView. Right now when I press the button the background image is still visible but a gray, transparent layer is on top of the image. How do I change the color of this layer?

I've tried setting the setBackgroundImage:forState: but all that does is replace the current image with another image.

Note

I'm able to do this with a tableview row using the following code:

```<code>// Custom selectionStyle color
UIView *v = [[[UIView alloc] init] autorelease];
v.backgroundColor = [UIColor myBlue];
groupCell.selectedBackgroundView = v;
</code>```

答:
Apple's approach is to expect you to provide an image that is tinted accordingly. So if you wanted to change that gray overlay to red you would need to call setBackgroundImage:forState: and supply an appropriately tinted image that would be swapped in.

Unfortunately there is no direct access in the SDK/API that will let you change the default highlight color - just the image.

Title: UIButton selection color

Body:
I'm using a UIButton as a pressable imageView. Right now when I press the button the background image is still visible but a gray, transparent layer is on top of the image. How do I change the color of this layer?

I've tried setting the setBackgroundImage:forState: but all that does is replace the current image with another image.

Note

I'm able to do this with a tableview row using the following code:

// Custom selectionStyle color
UIView *v = [[[UIView alloc] init] autorelease];
v.backgroundColor = [UIColor myBlue];
groupCell.selectedBackgroundView = v;


问:
Join range of row using arrayformula

I have a range of data on column A and B. In Column D , i have a reference for the shotID. I want to make a list for the artist involved for specific shotID.

In E2 i use this :

```<code>=JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2))
</code>```

then copy down to E3,E4. It works as i expected, but i want to do it using array formula. So only use single formula in E2 and that doesn't work that simple :

```<code>=arrayformula( JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2:D4)) )
</code>```

How can i do this ?

答:
take:

```<code>=ARRAYFORMULA(REGEXREPLACE(TRIM(SPLIT(SUBSTITUTE(
 FLATTEN(QUERY(TRANSPOSE(QUERY(QUERY(SPLIT(
 FLATTEN(A2:A&"×"&B2:B&","&"×"&B2:B), "×"),
 "select Col1,max(Col2) where Col2 is not null group by Col1 pivot Col3"),
 "offset 1", 0)),,9^9)), " ", "×", 1), "×")), ",$", ))
</code>```

Title: Join range of row using arrayformula

Body:
I have a range of data on column A and B. In Column D , i have a reference for the shotID. I want to make a list for the artist involved for specific shotID.

In E2 i use this :

=JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2))

then copy down to E3,E4. It works as i expected, but i want to do it using array formula. So only use single formula in E2 and that doesn't work that simple :

=arrayformula( JOIN( "," , FILTER($B$2:$B, $A$2:$A= D2:D4)) )

How can i do this ?

Body:
take:

=ARRAYFORMULA(REGEXREPLACE(TRIM(SPLIT(SUBSTITUTE(
 FLATTEN(QUERY(TRANSPOSE(QUERY(QUERY(SPLIT(
 FLATTEN(A2:A&"×"&B2:B&","&"×"&B2:B), "×"),
 "select Col1,max(Col2) where Col2 is not null group by Col1 pivot Col3"),
 "offset 1", 0)),,9^9)), " ", "×", 1), "×")), ",$", ))


问:
In R, nested loops don't return the expected result while reading through multiple files
Objective: calculate correlation coefficients between 2 variables for multiple files that meet the custom criterion for complete cases (threshold argument).

Data: 332 .csv files in a specified directory.

Desired output: vector with correlation coefficients for the files.

Code:

```<code> correl <- function(directory = "~/specdata/specdatacsv", threshold = 0) {
  filelist <- list.files(path = directory, pattern = ".csv", full.names = TRUE)
  nobs <- numeric()
  corrvector <- numeric()

  for(i in length(filelist)) {
    data <- read.csv(filelist[i])
    nobs <- sum(complete.cases(data))
    if (nobs <= threshold) { next
    } else {
      nitrate <- as.vector(data$nitrate)
      sulfate <- as.vector(data$sulfate)
      goodSulfate <- complete.cases(sulfate)
      goodNitrate <- complete.cases(nitrate)
      icorr <- cor(goodNitrate, goodSulfate)
      corrvector <- c(corrvector, icorr)
    }
  }
  corrvector
}
</code>```

The output for the threshold 150 should return:

```<code>[1] -0.01895754 -0.14051254 -0.04389737 -0.06815956 -0.12350667 -0.07588814
</code>```

But instead the empty corrvector gets returned. Please, help me find the mistake I've made.

答:
As per the comment by @stefan, the problem is here:

```<code>for(i in length(filelist))
</code>```

So, if the length of filelist is 332, this is the same as:

```<code>for(i in 332)
</code>```

whereas you would actually want

```<code>for(i in 1:332)
</code>```

This can easily be achieved with either:

```<code>for (i in 1:length(filelist)) {
  print(i)
}
</code>```

or

```<code>for (i in seq_along(filelist)) {
  print(i)
}
</code>```

Body:
Objective: calculate correlation coefficients between 2 variables for multiple files that meet the custom criterion for complete cases (threshold argument).

Data: 332 .csv files in a specified directory.

Desired output: vector with correlation coefficients for the files.

Code:

 correl <- function(directory = "~/specdata/specdatacsv", threshold = 0) {
  filelist <- list.files(path = directory, pattern = ".csv", full.names = TRUE)
  nobs <- numeric()
  corrvector <- numeric()

  for(i in length(filelist)) {
    data <- read.csv(filelist[i])
    nobs <- sum(complete.cases(data))
    if (nobs <= threshold) { next
    } else {
      nitrate <- as.vector(data$nitrate)
      sulfate <- as.vector(data$sulfate)
      goodSulfate <- complete.cases(sulfate)
      goodNitrate <- complete.cases(nitrate)
      icorr <- cor(goodNitrate, goodSulfate)
      corrvector <- c(corrvector, icorr)
    }
  }
  corrvector
}

The output for the threshold 150 should return:

[1] -0.01895754 -0.14051254 -0.04389737 -0.06815956 -0.12350667 -0.07588814

But instead the empty corrvector gets returned. Please, help me find the mistake I've made.

Body:
As per the comment by @stefan, the problem is here:

for(i in length(filelist))

So, if the length of filelist is 332, this is the same as:

for(i in 332)

whereas you would actually want

for(i in 1:332)

This can easily be achieved with either:

for (i in 1:length(filelist)) {
  print(i)
}

or

for (i in seq_along(filelist)) {
  print(i)
}


问:
Download values of list from json file with 2 objects
I want to create simple game and i need to get values from json or change them.
I have 3 classes.

```<code>public class Person
{
    public string Specjality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> people { get; set; }
    public List<Monster> monsters { get; set; }
}
</code>```

Json file

```<code>{
  "Person": [
    {
      "Speciality": "Archer",
      "PWZ": 432742,
      "Name": "Charlie",
      "Surname": "Evans",
      "Items": [
        "Bow",
        "Arrow",
      ]
    },
    {
      "Speciality": "Soldier",
      "PWZ": 432534879,
      "Name": "Harry",
      "Surname": "Thomas",
      "Items": [
        "Gun",
        "Knife",
     ]
    }
  ],
  "Monster": [
    {
      "Name": "Papua",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    },
    {
     "Name": "Geot",
      "Skills": [
        "Run",
        "Push",
      ]
    }
  ]
}
</code>```

My first problem is how to deserialize it, next how to print chosen values (for examples Skills of first Monster) on the screen and how to change some values (for example change "Jump" from Monster Skills to "Teleport" or change Name of Person). Thanks for all answers.

答:
You're very close.  To deserialize update the following:

Update/fix spelling/typo in Person class
```<code>public string Speciality { get; set; }
</code>```

Update Root property names (the names should match the Json):
```<code>public class Root
{
    public List<Person> Person { get; set; }
    public List<Monster> Monster { get; set; }
}
</code>```

Deserialize to Root class:
```<code>var result = JsonSerializer.Deserialize<Root>(json);
</code>```

Now, there's also an issue with trailing commas in your Json string. I got this error:

The JSON array contains a trailing comma at the end which is not
supported in this mode. Change the reader options.

You can fix the Json string (remove the trailing commas in the arrays), or if you're using System.Text.Json to deserialize you can apply the AllowTrailingCommas option:

```<code>var options = new JsonSerializerOptions { AllowTrailingCommas = true };
var result = JsonSerializer.Deserialize<Root>(json, options);
</code>```

To display the values:

```<code>// iterate over Person/Monster collection
foreach (var person in result.Person)
    Console.WriteLine($"Name: {person.Name}, Items: {string.Join(", ", person.Items)}");

foreach (var monster in result.Monster)
    Console.WriteLine($"Name: {monster.Name}, Skills: {string.Join(", ", monster.Skills)}");
</code>```

To modify an item you would just modify the Person or Monster instance, then serialize again:

```<code>// update name:
result.Person[0].Name = "Alan";
// serialize if you need to:
string json = JsonSerializer.Serialize(result);
</code>```

Body:
I want to create simple game and i need to get values from json or change them.
I have 3 classes.

public class Person
{
    public string Specjality { get; set; }
    public int PWZ { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public List<string> Items { get; set; }
}

public class Monster
{
    public string Name { get; set; }
    public List<string> Skills { get; set; }
}

public class Root
{
    public List<Person> people { get; set; }
    public List<Monster> monsters { get; set; }
}

Json file

{
  "Person": [
    {
      "Speciality": "Archer",
      "PWZ": 432742,
      "Name": "Charlie",
      "Surname": "Evans",
      "Items": [
        "Bow",
        "Arrow",
      ]
    },
    {
      "Speciality": "Soldier",
      "PWZ": 432534879,
      "Name": "Harry",
      "Surname": "Thomas",
      "Items": [
        "Gun",
        "Knife",
     ]
    }
  ],
  "Monster": [
    {
      "Name": "Papua",
      "Skills": [
        "Jump",
        "SlowWalk",
      ]
    },
    {
     "Name": "Geot",
      "Skills": [
        "Run",
        "Push",
      ]
    }
  ]
}

My first problem is how to deserialize it, next how to print chosen values (for examples Skills of first Monster) on the screen and how to change some values (for example change "Jump" from Monster Skills to "Teleport" or change Name of Person). Thanks for all answers.

Body:
You're very close.  To deserialize update the following:

Update/fix spelling/typo in Person class

public string Speciality { get; set; }

Update Root property names (the names should match the Json):

public class Root
{
    public List<Person> Person { get; set; }
    public List<Monster> Monster { get; set; }
}

Deserialize to Root class:

var result = JsonSerializer.Deserialize<Root>(json);

Now, there's also an issue with trailing commas in your Json string. I got this error:

The JSON array contains a trailing comma at the end which is not
supported in this mode. Change the reader options.

You can fix the Json string (remove the trailing commas in the arrays), or if you're using System.Text.Json to deserialize you can apply the AllowTrailingCommas option:

var options = new JsonSerializerOptions { AllowTrailingCommas = true };
var result = JsonSerializer.Deserialize<Root>(json, options);

To display the values:

// iterate over Person/Monster collection
foreach (var person in result.Person)
    Console.WriteLine($"Name: {person.Name}, Items: {string.Join(", ", person.Items)}");

foreach (var monster in result.Monster)
    Console.WriteLine($"Name: {monster.Name}, Skills: {string.Join(", ", monster.Skills)}");

To modify an item you would just modify the Person or Monster instance, then serialize again:

// update name:
result.Person[0].Name = "Alan";
// serialize if you need to:
string json = JsonSerializer.Serialize(result);


问:
What recursive function can I use to substitute the characters in a string by the greatest character on its right?
I got this exercise (it's not homework or an assignment, just practice) that asks for a program that replaces the characters in a string by the greatest character on the right using recursive functions, no loops allowed.

If I have a string acbcba the function has to return ccccba.

One thing I've tried with the loops for the string is this, to maybe try to turn it into a recursion if it worked:

```<code>void nextGreatest(char *str, int size)
{
  int max_from_right =  str[size-1];

  str[size-1] = -1;
  for(int i = size-2; i >= 0; i--)
  {
    int temp = str[i];
    str[i] = max_from_right;
    if(max_from_right < temp)
       max_from_right = temp;
  }
}

Output: cccba
</code>```

I think the issue is that it doesn't count the characters that don't have to be replaced.

There was also another example using python I found and tried to change to C (MAX is a macro from here):

```<code>void nextGreatest(char *arr, int rev_i, int maxnum){
        if (rev_i == strlen(arr) - 1){
            arr[0] = maxnum;
            return;
        }
        int i = strlen(arr) - 1 - rev_i;
        arr[i], maxnum = maxnum, MAX(maxnum, arr[i]);
        return nextGreatest(arr, rev_i + 1, maxnum);
}

Output: ~bccba
</code>```

答:
think on it as an induction.
first define the recursive function well
the function get an arr of chars and switch the letter to the greatest from right.(you can define whatever you want)
we will do the recursive on the length of the arr(we can call it n, same as induction)

base: n=0 , array with only null charecter, just return the arr.
step: lets say if we send arr with length n-1 the function will work so what we nees to do for n? we simply need to look ob the first letter and check what is greatest from right and switch to it.

lets look on example:  for acbcba, if we call on smaller arr, cbcba, the return will be cccba(since we assume it works for n-1), now we need to solve for n, so now we have arr acccba, so we look on the first letter and aee what is greatest from it, and then return it.

now try to code it.

Body:
I got this exercise (it's not homework or an assignment, just practice) that asks for a program that replaces the characters in a string by the greatest character on the right using recursive functions, no loops allowed.

If I have a string acbcba the function has to return ccccba.

One thing I've tried with the loops for the string is this, to maybe try to turn it into a recursion if it worked:

void nextGreatest(char *str, int size)
{
  int max_from_right =  str[size-1];

  str[size-1] = -1;
  for(int i = size-2; i >= 0; i--)
  {
    int temp = str[i];
    str[i] = max_from_right;
    if(max_from_right < temp)
       max_from_right = temp;
  }
}

Output: cccba

I think the issue is that it doesn't count the characters that don't have to be replaced.

There was also another example using python I found and tried to change to C (MAX is a macro from here):

void nextGreatest(char *arr, int rev_i, int maxnum){
        if (rev_i == strlen(arr) - 1){
            arr[0] = maxnum;
            return;
        }
        int i = strlen(arr) - 1 - rev_i;
        arr[i], maxnum = maxnum, MAX(maxnum, arr[i]);
        return nextGreatest(arr, rev_i + 1, maxnum);
}

Output: ~bccba


问:
Azure Service Bus managed identity in Visual Studio returning 401 - Token issuer is invalid
I'm attempting to access Azure Service Bus using a managed identity from my code. At the moment I'm just trying this locally.

When I debug my code I get the following error

System.UnauthorizedAccessException: Put token failed. status-code: 401, status-description: InvalidIssuer: Token issuer is invalid

Here is my service bus instance

Here is my user with Azure Service Bus Data Owner permissions

And here is my code

_client = new ServiceBusClient("oconnorevents.servicebus.windows.net", new DefaultAzureCredential());
```

I am logged into Visual Studio as the same user added to the service bus. I also tried logging in via the CLI but it didn't help.

Where am I going wrong here?

I've looked at this similar recent question here but the solutions proposed didn't work for me.

答:
Specify the exact tenant id by adding the following key to local.settings.json.

```<code>"AZURE_TENANT_ID": "your tenant id"
</code>```

I tried to create an azure function that receives messages from a service bus queue using a managed identity trigger and it worked for me.

Body:
I'm attempting to access Azure Service Bus using a managed identity from my code. At the moment I'm just trying this locally.

When I debug my code I get the following error

System.UnauthorizedAccessException: Put token failed. status-code: 401, status-description: InvalidIssuer: Token issuer is invalid

Here is my service bus instance

Here is my user with Azure Service Bus Data Owner permissions

And here is my code

_client = new ServiceBusClient("oconnorevents.servicebus.windows.net", new DefaultAzureCredential());

I am logged into Visual Studio as the same user added to the service bus. I also tried logging in via the CLI but it didn't help.

Where am I going wrong here?

I've looked at this similar recent question here but the solutions proposed didn't work for me.

Body:
Specify the exact tenant id by adding the following key to local.settings.json.

"AZURE_TENANT_ID": "your tenant id"

I tried to create an azure function that receives messages from a service bus queue using a managed identity trigger and it worked for me.


问:
Reverse an array containing random numbers. How?
My assignment is to create an array with random numbers and then reverse the order in C#.

I managed to generate the random array, but how do i reverse it?

For example the output should look like this

15334
43351

```<code>int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i++)

{
    Random random = new Random();
    int num = random.Next(TalArray.Length);

    Console.WriteLine(num);
}
</code>```

Thanks in advance! :)

答:
Have you tried
Documentation

public static void Main()
    {
        int[] TalArray = new int[5];
        var arr = new int[TalArray.Length];
        for (int i = 0; i < TalArray.Length; i++)
        {
            Random random = new Random();
            int num = random.Next(TalArray.Length);
            arr[i] = num;
            Console.WriteLine(num);
        }

        Array.Reverse(arr);
        for (int i = 0; i < arr.Length; i++)
        {
            Console.WriteLine(arr[i]);
        }
    }
```

Working example dotnet fiddle

Body:
My assignment is to create an array with random numbers and then reverse the order in C#.

I managed to generate the random array, but how do i reverse it?

For example the output should look like this

15334
43351

int[] TalArray = new int[5];
var arr = new int[TalArray.Length];
for (int i = 0; i < TalArray.Length; i++)

{
    Random random = new Random();
    int num = random.Next(TalArray.Length);

    Console.WriteLine(num);
}

Thanks in advance! :)

Body:
Have you tried
Documentation

public static void Main()
    {
        int[] TalArray = new int[5];
        var arr = new int[TalArray.Length];
        for (int i = 0; i < TalArray.Length; i++)
        {
            Random random = new Random();
            int num = random.Next(TalArray.Length);
            arr[i] = num;
            Console.WriteLine(num);
        }

        Array.Reverse(arr);
        for (int i = 0; i < arr.Length; i++)
        {
            Console.WriteLine(arr[i]);
        }
    }

Working example dotnet fiddle


答:
Here is a solution with Array.Reverse:</p>
```<code>var arr = new int[5];
for (int i = 0; i < arr.Length; i++)
  {
     arr[i] = new Random().Next(0, arr.Length);
  }
var revArr = arr.Reverse();
Console.WriteLine(String.Join("", arr ) + string.Join("", revArr));
</code>```

Title: Reverse an array containing random numbers. How?

Body:
Here is a solution with Array.Reverse:

var arr = new int[5];
for (int i = 0; i < arr.Length; i++)
  {
     arr[i] = new Random().Next(0, arr.Length);
  }
var revArr = arr.Reverse();
Console.WriteLine(String.Join("", arr ) + string.Join("", revArr));


问:
TypeORM does not create tables, columns etc
I have set up a system with typeorm (https://github.com/typeorm/typeorm) and NestJs (https://github.com/nestjs/nest), but TypeORM isn't creating the tables or columns. My setup is like this:

import {UserPassword} from '../user/user-password.entity';
import {User} from '../user/user.entity';

createConnection({
    type: 'mysql',
    host: 'typeorm2.cn32tstd6wqk.eu-central-1.rds.amazonaws.com',
    port: 1234,
    username: 'username',
    password: 'password',
    database: 'dbname',
    entities: [
      // __dirname + '/../**/*.entity{.ts,.js}'
      UserPassword,
      User
    ]
  })
```
<p>And the entities are:</p>
<pre class="lang-ts prettyprint-override"><code>import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';

@Entity()
export class UserPassword {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  hash: string;

  @Column()
  algorithm: string;

}
</code>```

and

import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';
import {UserPassword} from './user-password.entity';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 35 })
  firstName: string;

  @Column({ length: 35 })
  lastName: string;

  @Column({ length: 50})
  mail: string;

  @OneToOne(type => UserPassword)
  @JoinColumn()
  password: UserPassword;

}
```
<p>Then I try to create a user like this:</p>
<pre class="lang-ts prettyprint-override"><code>// ... some code
await this.userPasswordRepository.save(userPassword);
return await this.userRepository.save(user);
</code>```

But I get the following error:

QueryFailedError: ER_NO_SUCH_TABLE: Table 'typeorm2.user_password' doesn't exist

When I insert the table manually then I get the error:

QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'hash' in 'field list'

So it seems like TypeORM doesn't generate the tables / columns. Does anyone know why this could be?

答:
I had a stupid issue.

All the configuration was correct, just my entity file was not saved after all the changes.

Should definitely turn on auto save.

Body:
I have set up a system with typeorm (https://github.com/typeorm/typeorm) and NestJs (https://github.com/nestjs/nest), but TypeORM isn't creating the tables or columns. My setup is like this:

import {UserPassword} from '../user/user-password.entity';
import {User} from '../user/user.entity';

createConnection({
    type: 'mysql',
    host: 'typeorm2.cn32tstd6wqk.eu-central-1.rds.amazonaws.com',
    port: 1234,
    username: 'username',
    password: 'password',
    database: 'dbname',
    entities: [
      // __dirname + '/../**/*.entity{.ts,.js}'
      UserPassword,
      User
    ]
  })

And the entities are:

import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';

@Entity()
export class UserPassword {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  hash: string;

  @Column()
  algorithm: string;

}

and

import {Entity, Column, PrimaryGeneratedColumn, OneToOne, JoinColumn} from 'typeorm';
import {UserPassword} from './user-password.entity';

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ length: 35 })
  firstName: string;

  @Column({ length: 35 })
  lastName: string;

  @Column({ length: 50})
  mail: string;

  @OneToOne(type => UserPassword)
  @JoinColumn()
  password: UserPassword;

}

Then I try to create a user like this:

// ... some code
await this.userPasswordRepository.save(userPassword);
return await this.userRepository.save(user);

But I get the following error:

QueryFailedError: ER_NO_SUCH_TABLE: Table 'typeorm2.user_password' doesn't exist

When I insert the table manually then I get the error:

QueryFailedError: ER_BAD_FIELD_ERROR: Unknown column 'hash' in 'field list'

So it seems like TypeORM doesn't generate the tables / columns. Does anyone know why this could be?


问:
Border around UITextView
How do you add a border around a UITextView (like a UITextField)? I want to allow users to type multiple lines, but unfortunately a UITextField does not support this. Is there an easy way to do this in code or do I need to create one in Photoshop?</p>

答:
If you do a quick search, you'll find several answers. Example:

How to style UITextview to like Rounded Rect text field?

Title: Border around UITextView


问:
notepad++ pythonscript mark words
I am trying to build a pythonscript macro for notepad++ which automates a highlighting feature of the search dialog for several words.

Unfortunately I could not find the necessary function for "highlighting". The script should do the same as if I use the Ctrl+F dialog, check "Wrap around" and press "Mark All".

This one is similar, alghough it does not use a pythonscript:
notepad++ mark style with macro

With the available documentation I could do the following:

```<code># Function for marking a line if a certain pattern was found
def bookmarks(lineText, lineNumber, totalLines):
    patterns = ['word1','word2']
    for p in patterns:
        if lineText.find(p) > -1:
            editor.markerAdd(lineNumber, 24)
    return 1

# mark interesting lines:
editor.markerDeleteAll(24);
editor.forEachLine(bookmarks);
</code>```

This will create bookmarks for all lines containing "word1" or "word2" in the current file. However I would like to highlight the ocurrances as with "Mark All" and I would like to do it in all opened files.

Maybe I am missing a documentation resource or it is because I don't know python well. At least I could not find a suitable function to highlight matches. I did use google and I consulted the following documentation pages.
Also any hint on more valuable documentation is apreciated!

http://npppythonscript.sourceforge.net/docs/latest/index.html
http://sourceforge.net/p/npppythonscript/wiki/Home/

答:
This is a old topic, but for people that still use "pythonscript macros" in Notepad++, I found a way to mimic the behaviour of search and replace Mark-All.

You need to use scintillia indicators to highlight words of interest. See the reference to learn about scintillia indicators.

You first need to chose a indicator number (~32 available). Be advised that indicators are shared with NPP and linters across defined ranges that i dont know about, so i found myself using the 20th because it just worked. Avoid 1-9 range and the 19th and 29th.

Then you can use the documentation to setup the style of your indicator. Finaly apply the indicator using wraped method editor.indicatorFillRange(start, lengthFill).

Here a script that highlight regex matches using python re module.

from Npp import editor, notepad
import re

patern = notepad.prompt('Please insert a valid python regex', 'regex highlighter', '')

# Highlight matches
for match in re.finditer(patern, editor.getText()):
    editor.indicSetStyle(20, 8)
    editor.indicSetFore(20, (192, 0, 0))
    editor.indicSetAlpha(20, 50)

    editor.setIndicatorCurrent(20)
    editor.indicatorFillRange(match.start(), match.end() - match.start())

# clear the mess
#    editor.setIndicatorCurrent(20)
#    editor.indicatorClearRange(0, editor.getLength())
```

side note: documentation of NPP Python Script is available in your local files Notepad++/plugins/PythonScript/doc/scintilla.html.

Title: notepad++ pythonscript mark words

Body:
I am trying to build a pythonscript macro for notepad++ which automates a highlighting feature of the search dialog for several words.

Unfortunately I could not find the necessary function for "highlighting". The script should do the same as if I use the Ctrl+F dialog, check "Wrap around" and press "Mark All".

This one is similar, alghough it does not use a pythonscript:
notepad++ mark style with macro

With the available documentation I could do the following:

# Function for marking a line if a certain pattern was found
def bookmarks(lineText, lineNumber, totalLines):
    patterns = ['word1','word2']
    for p in patterns:
        if lineText.find(p) > -1:
            editor.markerAdd(lineNumber, 24)
    return 1

# mark interesting lines:
editor.markerDeleteAll(24);
editor.forEachLine(bookmarks);

This will create bookmarks for all lines containing "word1" or "word2" in the current file. However I would like to highlight the ocurrances as with "Mark All" and I would like to do it in all opened files.

Maybe I am missing a documentation resource or it is because I don't know python well. At least I could not find a suitable function to highlight matches. I did use google and I consulted the following documentation pages.
Also any hint on more valuable documentation is apreciated!

http://npppythonscript.sourceforge.net/docs/latest/index.html
http://sourceforge.net/p/npppythonscript/wiki/Home/

Body:
This is a old topic, but for people that still use "pythonscript macros" in Notepad++, I found a way to mimic the behaviour of search and replace Mark-All.

You need to use scintillia indicators to highlight words of interest. See the reference to learn about scintillia indicators.

You first need to chose a indicator number (~32 available). Be advised that indicators are shared with NPP and linters across defined ranges that i dont know about, so i found myself using the 20th because it just worked. Avoid 1-9 range and the 19th and 29th.

Then you can use the documentation to setup the style of your indicator. Finaly apply the indicator using wraped method editor.indicatorFillRange(start, lengthFill).

Here a script that highlight regex matches using python re module.

from Npp import editor, notepad
import re

patern = notepad.prompt('Please insert a valid python regex', 'regex highlighter', '')

# Highlight matches
for match in re.finditer(patern, editor.getText()):
    editor.indicSetStyle(20, 8)
    editor.indicSetFore(20, (192, 0, 0))
    editor.indicSetAlpha(20, 50)

    editor.setIndicatorCurrent(20)
    editor.indicatorFillRange(match.start(), match.end() - match.start())

# clear the mess
#    editor.setIndicatorCurrent(20)
#    editor.indicatorClearRange(0, editor.getLength())

side note: documentation of NPP Python Script is available in your local files Notepad++/plugins/PythonScript/doc/scintilla.html.


问:
Keras TextVectorization adapt throws AttributeError
I'm trying to apply text categorization using Keras. I have imported my data as a Pandas dataframe and have converted it to a tf.Dataset. The problem is that I cannot use the TextVectorization layer of Keras as the below code throws this error:

AttributeError: 'NoneType' object has no attribute 'ndims'

My CSV's headers:

Class Index : int32

Title: string

Description: string

What have I missed ? Below is my code:

import re
import string
import tensorflow as tf
import pandas as pd
from tensorflow import keras

def create_dataset(csv_file, batch_size):
    df = pd.read_csv(csv_file)
    labels = df.pop('Class Index').transform(lambda x: x - 1)

    n_labels = len(pd.unique(labels))

    ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))
    ds = ds.batch(batch_size)
    ds = ds.shuffle(10000)

    return ds, n_labels

def load_data(data_dir, batch_size):
    train_ds, n_labels = create_dataset(data_dir + '/train.csv', batch_size)
    train_total_batches = len(train_ds)

    raw_test_ds, _ = create_dataset(data_dir + '/test.csv', batch_size)

    raw_train_ds = train_ds.take(int(round(0.8 * train_total_batches)));
    raw_val_ds = train_ds.skip(int(round(0.8 * train_total_batches))).take(int(round(0.2 * train_total_batches)));

    return raw_train_ds, raw_val_ds, raw_test_ds, n_labels

raw_train_ds, raw_val_ds, raw_test_ds, n_labels = load_data('.', 64)

def custom_standardization(input_data):
    lowercase = tf.strings.lower(input_data)
    stripped_backslash = tf.strings.regex_replace(lowercase, "\'", '' '')
    return tf.strings.regex_replace(stripped_backslash, '[%s]' % re.escape(string.punctuation), '')

max_features = 5000
sequence_length = 250

vectorize_layer = keras.layers.experimental.preprocessing.TextVectorization(
    standardize=custom_standardization,
    max_tokens=max_features,
    output_mode='int',
    output_sequence_length=sequence_length)

train_text = raw_train_ds.map(lambda x, y: x)
vectorize_layer.adapt(train_text)

```
<p>EDIT 1: Sample from <code>train_test</code>:</p>
```{'Title': <tf.Tensor: shape=(64,), dtype=string, numpy=
array([b'Malaysia testing 3 people for bird flu; says outbreak isolated',
       b"Kroger's Profit Climbs, Misses Forecast (Reuters)",
       b'Blasts Shake Najaf as U.S. Planes Attack Rebels',
       ...(omitted)
       b'Kerry Camp Makes Video to Defuse Attacks (AP)'], dtype=object)>, 'Description': <tf.Tensor: shape=(64,), dtype=string, numpy=
array([b'Malaysian officials on Saturday were testing three people who fell ill in a village hit by the deadly H5N1 bird flu strain, after international health officials warned that the virus appeared to be entrenched in parts of ',
       b'Reuters - Kroger Co. , the top U.S.\\grocer, on Tuesday said quarterly profit rose 29 percent as it\\kept a tight rein on expenses and sales rebounded.',
       b' NAJAF, Iraq (Reuters) - Strong blasts were heard in the  besieged city of Najaf early Sunday as U.S. military planes  unleashed cannon and howitzer fire and a heavy firefight  erupted.',
       b'Manny Ramirez homered and drove in five runs as the Red Sox earned their fifth straight victory.',
      ...(omitted)
      dtype=object)>}
```

答:
Since you are using a internal dictionary, you can try something like this:

import tensorflow as tf

d ={"Title": ["Malaysia testing 3 people for bird flu; says outbreak isolate",
           "Kroger's Profit Climbs, Misses Forecast (Reuters)",
           "Blasts Shake Najaf as U.S. Planes Attack Rebels"],
 "Description": [
                 "Kerry Camp Makes Video to Defuse Attacks (AP)",
                 "Malaysian officials on Saturday were testing three people who fell ill in a village hit by the deadly H5N1 bird flu strain, after international health officials warned that the virus appeared to be entrenched in parts of ",
                 " NAJAF, Iraq (Reuters) - Strong blasts were heard in the  besieged city of Najaf early Sunday as U.S. military planes  unleashed cannon and howitzer fire and a heavy firefight  erupted."
 ]}

train_text = tf.data.Dataset.from_tensor_slices(d).batch(2)

max_features = 5000
sequence_length = 250

vectorize_layer = tf.keras.layers.TextVectorization(
    max_tokens=max_features,
    output_mode='int',
    output_sequence_length=sequence_length)

#This example assumes that you have already excluded the labels.
#train_text = raw_train_ds.map(lambda x, y: x)

train_text = train_text.map(lambda x: tf.concat([x['Title'], x['Description']], axis=0))
vectorize_layer.adapt(train_text)
```

This example assumes that you have already excluded the labels.

Body:
I'm trying to apply text categorization using Keras. I have imported my data as a Pandas dataframe and have converted it to a tf.Dataset. The problem is that I cannot use the TextVectorization layer of Keras as the below code throws this error:

AttributeError: 'NoneType' object has no attribute 'ndims'

My CSV's headers:

Class Index : int32

Title: string

Description: string

What have I missed ? Below is my code:

import re
import string
import tensorflow as tf
import pandas as pd
from tensorflow import keras

def create_dataset(csv_file, batch_size):
    df = pd.read_csv(csv_file)
    labels = df.pop('Class Index').transform(lambda x: x - 1)

    n_labels = len(pd.unique(labels))

    ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))
    ds = ds.batch(batch_size)
    ds = ds.shuffle(10000)

    return ds, n_labels

def load_data(data_dir, batch_size):
    train_ds, n_labels = create_dataset(data_dir + '/train.csv', batch_size)
    train_total_batches = len(train_ds)

    raw_test_ds, _ = create_dataset(data_dir + '/test.csv', batch_size)

    raw_train_ds = train_ds.take(int(round(0.8 * train_total_batches)));
    raw_val_ds = train_ds.skip(int(round(0.8 * train_total_batches))).take(int(round(0.2 * train_total_batches)));

    return raw_train_ds, raw_val_ds, raw_test_ds, n_labels

raw_train_ds, raw_val_ds, raw_test_ds, n_labels = load_data('.', 64)

def custom_standardization(input_data):
    lowercase = tf.strings.lower(input_data)
    stripped_backslash = tf.strings.regex_replace(lowercase, "\'", '' '')
    return tf.strings.regex_replace(stripped_backslash, '[%s]' % re.escape(string.punctuation), '')

max_features = 5000
sequence_length = 250

vectorize_layer = keras.layers.experimental.preprocessing.TextVectorization(
    standardize=custom_standardization,
    max_tokens=max_features,
    output_mode='int',
    output_sequence_length=sequence_length)

train_text = raw_train_ds.map(lambda x, y: x)
vectorize_layer.adapt(train_text)

EDIT 1: Sample from train_test:

{'Title': <tf.Tensor: shape=(64,), dtype=string, numpy=
array([b'Malaysia testing 3 people for bird flu; says outbreak isolated',
       b"Kroger's Profit Climbs, Misses Forecast (Reuters)",
       b'Blasts Shake Najaf as U.S. Planes Attack Rebels',
       ...(omitted)
       b'Kerry Camp Makes Video to Defuse Attacks (AP)'], dtype=object)>, 'Description': <tf.Tensor: shape=(64,), dtype=string, numpy=
array([b'Malaysian officials on Saturday were testing three people who fell ill in a village hit by the deadly H5N1 bird flu strain, after international health officials warned that the virus appeared to be entrenched in parts of ',
       b'Reuters - Kroger Co. , the top U.S.\\grocer, on Tuesday said quarterly profit rose 29 percent as it\\kept a tight rein on expenses and sales rebounded.',
       b' NAJAF, Iraq (Reuters) - Strong blasts were heard in the  besieged city of Najaf early Sunday as U.S. military planes  unleashed cannon and howitzer fire and a heavy firefight  erupted.',
       b'Manny Ramirez homered and drove in five runs as the Red Sox earned their fifth straight victory.',
      ...(omitted)
      dtype=object)>}

Body:
Since you are using a internal dictionary, you can try something like this:

import tensorflow as tf

d ={"Title": ["Malaysia testing 3 people for bird flu; says outbreak isolate",
           "Kroger's Profit Climbs, Misses Forecast (Reuters)",
           "Blasts Shake Najaf as U.S. Planes Attack Rebels"],
 "Description": [
                 "Kerry Camp Makes Video to Defuse Attacks (AP)",
                 "Malaysian officials on Saturday were testing three people who fell ill in a village hit by the deadly H5N1 bird flu strain, after international health officials warned that the virus appeared to be entrenched in parts of ",
                 " NAJAF, Iraq (Reuters) - Strong blasts were heard in the  besieged city of Najaf early Sunday as U.S. military planes  unleashed cannon and howitzer fire and a heavy firefight  erupted."
 ]}

train_text = tf.data.Dataset.from_tensor_slices(d).batch(2)

max_features = 5000
sequence_length = 250

vectorize_layer = tf.keras.layers.TextVectorization(
    max_tokens=max_features,
    output_mode='int',
    output_sequence_length=sequence_length)

#This example assumes that you have already excluded the labels.
#train_text = raw_train_ds.map(lambda x, y: x)

train_text = train_text.map(lambda x: tf.concat([x['Title'], x['Description']], axis=0))
vectorize_layer.adapt(train_text)

This example assumes that you have already excluded the labels.


问:
Build error domain=com.apple.CoreSimulator.SimError, code=405
I can build on my iOS 15 emulator with no problems, but when building on my iOS 15 Device connected to xcode 13. I get the error:

error Failed to launch the app on simulator, An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):
Unable to lookup in current state: Shutdown.

Any ideas?

Console:

```<code>success Successfully built the app
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:iOS Simulator, id:dvtdevice-DVTiOSDeviceSimulatorPlaceholder-iphonesimulator:placeholder, name:Any iOS Simulator Device }
{ platform:iOS Simulator, id:CECA2B5E-D9A0-4A52-8947-BF0838EBEDD6, OS:15.0, name:iPhone 8 }
{ platform:iOS Simulator, id:4B8F148A-C39B-42B8-B982-82759A99BAF9, OS:15.0, name:iPhone 8 Plus }
{ platform:iOS Simulator, id:8853D49D-06EB-4542-AE09-EFD94DC045D6, OS:15.0, name:iPhone 11 }
{ platform:iOS Simulator, id:1F7B80D0-0CFE-4D4F-AF69-260D8F0D785C, OS:15.0, name:iPhone 11 Pro }
{ platform:iOS Simulator, id:7AF2F670-7D7B-4C0D-B1A2-DDD9A8DC0554, OS:15.0, name:iPhone 11 Pro Max }
{ platform:iOS Simulator, id:5A36169B-4CE3-4E54-AC1D-8E2550EAAF61, OS:15.0, name:iPhone 12 }
{ platform:iOS Simulator, id:DA7C5083-DE28-40C8-83D3-7BA678311561, OS:15.0, name:iPhone 12 Pro }
{ platform:iOS Simulator, id:C012CD47-9A6D-4B88-B209-4777EE57BD2A, OS:15.0, name:iPhone 12 Pro Max }
{ platform:iOS Simulator, id:3C64ECA5-9EE0-4D2C-A0C9-82CAD36AE094, OS:15.0, name:iPhone 12 mini }
{ platform:iOS Simulator, id:DBA58C7D-41CB-44B2-99FA-F07E5CB829B5, OS:15.0, name:iPhone 13 }
{ platform:iOS Simulator, id:B43092DC-8F33-47BD-8429-A4D35C7FD7B8, OS:15.0, name:iPhone 13 Pro }
{ platform:iOS Simulator, id:E587AD8C-D9B6-4683-9251-6D0F5DF50A57, OS:15.0, name:iPhone 13 Pro Max }
{ platform:iOS Simulator, id:1A7AC21A-A578-40A7-9C81-53B7F90CAED6, OS:15.0, name:iPhone 13 mini }
{ platform:iOS Simulator, id:352BE540-010B-4A15-B67D-965A884BB20D, OS:15.0, name:iPhone SE (2nd generation) }
{ platform:iOS Simulator, id:24BBBFF1-FF95-453D-A952-66D3A93D611D, OS:15.0, name:iPod touch (7th generation) }
{ platform:iOS, id:dvtdevice-DVTiPhonePlaceholder-iphoneos:placeholder, name:Any iOS Device }
{ platform:iOS Simulator, id:75F7457E-C581-4247-A1DC-E92CA319A693, OS:15.0, name:iPad (9th generation) }
{ platform:iOS Simulator, id:1482EAA0-8637-4D49-A091-B604208127BB, OS:15.0, name:iPad Air (4th generation) }
{ platform:iOS Simulator, id:38D1E279-3D1E-4248-8B9D-76A3480D1CF0, OS:15.0, name:iPad Pro (9.7-inch) }
{ platform:iOS Simulator, id:54079569-B96E-4570-A076-732A2DED9E49, OS:15.0, name:iPad Pro (11-inch) (3rd generation) }
{ platform:iOS Simulator, id:A0CBCD90-C028-420B-9D6F-07E6EDA643FC, OS:15.0, name:iPad Pro (12.9-inch) (5th generation) }
{ platform:iOS Simulator, id:E034D4B3-770E-4AD1-8573-DF7984340F16, OS:15.0, name:iPad mini (6th generation) }
info Installing "/Users/mattharris/Library/Developer/Xcode/DerivedData/myracnative-glxuojrfejxbhqgircpjgklctbto/Build/Products/Debug-iphonesimulator/myracnative.app"
An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):
Unable to lookup in current state: Shutdown
</code>```

答:
Open xcode go to -> preferences -> Locations

and set Relative in Derived Data:

Body:
I can build on my iOS 15 emulator with no problems, but when building on my iOS 15 Device connected to xcode 13. I get the error:

error Failed to launch the app on simulator, An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):
Unable to lookup in current state: Shutdown.

Any ideas?

Console:

success Successfully built the app
--- xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:iOS Simulator, id:dvtdevice-DVTiOSDeviceSimulatorPlaceholder-iphonesimulator:placeholder, name:Any iOS Simulator Device }
{ platform:iOS Simulator, id:CECA2B5E-D9A0-4A52-8947-BF0838EBEDD6, OS:15.0, name:iPhone 8 }
{ platform:iOS Simulator, id:4B8F148A-C39B-42B8-B982-82759A99BAF9, OS:15.0, name:iPhone 8 Plus }
{ platform:iOS Simulator, id:8853D49D-06EB-4542-AE09-EFD94DC045D6, OS:15.0, name:iPhone 11 }
{ platform:iOS Simulator, id:1F7B80D0-0CFE-4D4F-AF69-260D8F0D785C, OS:15.0, name:iPhone 11 Pro }
{ platform:iOS Simulator, id:7AF2F670-7D7B-4C0D-B1A2-DDD9A8DC0554, OS:15.0, name:iPhone 11 Pro Max }
{ platform:iOS Simulator, id:5A36169B-4CE3-4E54-AC1D-8E2550EAAF61, OS:15.0, name:iPhone 12 }
{ platform:iOS Simulator, id:DA7C5083-DE28-40C8-83D3-7BA678311561, OS:15.0, name:iPhone 12 Pro }
{ platform:iOS Simulator, id:C012CD47-9A6D-4B88-B209-4777EE57BD2A, OS:15.0, name:iPhone 12 Pro Max }
{ platform:iOS Simulator, id:3C64ECA5-9EE0-4D2C-A0C9-82CAD36AE094, OS:15.0, name:iPhone 12 mini }
{ platform:iOS Simulator, id:DBA58C7D-41CB-44B2-99FA-F07E5CB829B5, OS:15.0, name:iPhone 13 }
{ platform:iOS Simulator, id:B43092DC-8F33-47BD-8429-A4D35C7FD7B8, OS:15.0, name:iPhone 13 Pro }
{ platform:iOS Simulator, id:E587AD8C-D9B6-4683-9251-6D0F5DF50A57, OS:15.0, name:iPhone 13 Pro Max }
{ platform:iOS Simulator, id:1A7AC21A-A578-40A7-9C81-53B7F90CAED6, OS:15.0, name:iPhone 13 mini }
{ platform:iOS Simulator, id:352BE540-010B-4A15-B67D-965A884BB20D, OS:15.0, name:iPhone SE (2nd generation) }
{ platform:iOS Simulator, id:24BBBFF1-FF95-453D-A952-66D3A93D611D, OS:15.0, name:iPod touch (7th generation) }
{ platform:iOS, id:dvtdevice-DVTiPhonePlaceholder-iphoneos:placeholder, name:Any iOS Device }
{ platform:iOS Simulator, id:75F7457E-C581-4247-A1DC-E92CA319A693, OS:15.0, name:iPad (9th generation) }
{ platform:iOS Simulator, id:1482EAA0-8637-4D49-A091-B604208127BB, OS:15.0, name:iPad Air (4th generation) }
{ platform:iOS Simulator, id:38D1E279-3D1E-4248-8B9D-76A3480D1CF0, OS:15.0, name:iPad Pro (9.7-inch) }
{ platform:iOS Simulator, id:54079569-B96E-4570-A076-732A2DED9E49, OS:15.0, name:iPad Pro (11-inch) (3rd generation) }
{ platform:iOS Simulator, id:A0CBCD90-C028-420B-9D6F-07E6EDA643FC, OS:15.0, name:iPad Pro (12.9-inch) (5th generation) }
{ platform:iOS Simulator, id:E034D4B3-770E-4AD1-8573-DF7984340F16, OS:15.0, name:iPad mini (6th generation) }
info Installing "/Users/mattharris/Library/Developer/Xcode/DerivedData/myracnative-glxuojrfejxbhqgircpjgklctbto/Build/Products/Debug-iphonesimulator/myracnative.app"
An error was encountered processing the command (domain=com.apple.CoreSimulator.SimError, code=405):
Unable to lookup in current state: Shutdown


问:
Cannot get property value
<pre class="lang-java prettyprint-override"><code>@Configuration
public class WebFluxConfig {

    @Bean
    public WebClient getWebClient(@Value("${spring.webflux.base-path}") String baseUrl) {
        return WebClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }
}
</code>```
<p>added in application.properties</p>
<pre class="lang-none prettyprint-override"><code>spring.webflux.base-path = https://example/api/ (no the real API)
</code>```

答: worked with static.webflux.base-path to get the path from application.properties</p>

Title: Cannot get property value

Body:
@Configuration
public class WebFluxConfig {

    @Bean
    public WebClient getWebClient(@Value("${spring.webflux.base-path}") String baseUrl) {
        return WebClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }
}

added in application.properties

spring.webflux.base-path = https://example/api/ (no the real API)


问:
Parse error when parsing manifest. Discontinuing installation
I have an apk that installs fine on all my devices except on an old Samsung Galaxy J5 (and on a Huawei Y3).

I had copy the APK on the device via USB and try to install it with the "my files" app. The log is as follows:

```<code>02-08 11:36:56.226 1647-1674/? D/ActivityManager:  Launching com.google.android.packageinstaller, updated priority
02-08 11:36:56.226 1647-1647/? D/GameManagerService: NotifyRunnable. pkg: com.google.android.packageinstaller, type: 4, isMinimized: false, isTunableApp: false
02-08 11:36:56.226 1647-1647/? D/GameManagerService: unexpected mPrevNotiType: -1
02-08 11:36:56.246 1647-1836/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:843 com.android.server.policy.PhoneWindowManager.notifyToSSRM:9071 com.android.server.policy.PhoneWindowManager.access$2100:330 com.android.server.policy.PhoneWindowManager$PolicyHandler.handleMessage:1268 android.os.Handler.dispatchMessage:102
02-08 11:36:56.246 19954-19954/? W/PackageInstaller: Parse error when parsing manifest. Discontinuing installation
</code>```

Did anybody come across something like that as well?
I´ve checked the option that I can install APK from unknown sources so that can´t be the problem. And I´ve tried to install it from SD-card or internal memory with no success.

答: If somebody comes around the same problem. I was able to fix it by not using the signing function in Androidstudio but by manually using jarsigner and zipalign from java and the android-sdk-tools.</p>

Body:
I have an apk that installs fine on all my devices except on an old Samsung Galaxy J5 (and on a Huawei Y3).

I had copy the APK on the device via USB and try to install it with the "my files" app. The log is as follows:

02-08 11:36:56.226 1647-1674/? D/ActivityManager:  Launching com.google.android.packageinstaller, updated priority
02-08 11:36:56.226 1647-1647/? D/GameManagerService: NotifyRunnable. pkg: com.google.android.packageinstaller, type: 4, isMinimized: false, isTunableApp: false
02-08 11:36:56.226 1647-1647/? D/GameManagerService: unexpected mPrevNotiType: -1
02-08 11:36:56.246 1647-1836/? W/ContextImpl: Calling a method in the system process without a qualified user: android.app.ContextImpl.sendBroadcast:843 com.android.server.policy.PhoneWindowManager.notifyToSSRM:9071 com.android.server.policy.PhoneWindowManager.access$2100:330 com.android.server.policy.PhoneWindowManager$PolicyHandler.handleMessage:1268 android.os.Handler.dispatchMessage:102
02-08 11:36:56.246 19954-19954/? W/PackageInstaller: Parse error when parsing manifest. Discontinuing installation

Did anybody come across something like that as well?
I´ve checked the option that I can install APK from unknown sources so that can´t be the problem. And I´ve tried to install it from SD-card or internal memory with no success.


问:
When converting from SVN to Git, how do I put the revision number in the commit message?
We will be converting our repository from Subversion to Git, but would like to be able to retain the SVN revision number as comments in the bug tracker regularly reference it.

We will be using git svn clone and the process described in John Albin's blog.

Is there a way to include the revision number in the commit message?  I'd prefer to do it during the clone, but a post-processing step would be acceptable.

Yes, I know about git svn find-rev, but that requires the SVN repository stick around and the user has network access to it.

答:
git svn does this by default: it normally includes a line in every commit message that has the SVN revision number (and some other data) for that commit.

However, the link you posted has you cloning with --no-metadata, which tells git svn not to append the git-svn-id line.


问:
New NextJS project not displaying images
I have a page located here: project/pages/index.js
The under project/images/logo.png

Now in my index.js i have this  however I get a 404

How do I use images in NextJs?

My next.config.js looks like this:

```<code>module.exports = {
  reactStrictMode: true,
}

</code>```

答:
you must put image in Public folder and in Src img write "/logo.png"

if you work on Nextjs , stady Image/Next

Body:
I have a page located here: project/pages/index.js
The under project/images/logo.png

Now in my index.js i have this  however I get a 404

How do I use images in NextJs?

My next.config.js looks like this:

module.exports = {
  reactStrictMode: true,
}


问:
How to expose mysql port?
I'm trying to expose the port 3310 to allow remote MySQL connection. So far, I have this configuration:

```<code>  database:
    container_name: sfapi_db
    restart: always
    ports:
      - 3310:3306
    build:
      context: ./docker/database
    environment:
      - MYSQL_DATABASE=${DB_NAME}
      - MYSQL_USER=${DB_USER}
      - MYSQL_PASSWORD=${DB_PWD}
      - MYSQL_ROOT_PASSWORD=${DB_PWD_ROOT}
    volumes:
      - dbdata:/var/lib/mysql
      - type: bind
        source: ./docker/database/my.cnf
        target: /etc/mysql/my.cnf
</code>```

and this is the Dockerfile:

```<code>FROM mariadb:latest

CMD ["mysqld"]

EXPOSE 3310
</code>```

here the my.cnf:

```<code>[client-server]
# Port or socket location where to connect
port = 3310
socket = /run/mysqld/mysqld.sock

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/
</code>```

when I run docker-compose up --build -d and access to the container list, I get:

I also opened the port on the server using sudo ufw allow 3310. Also, I cannot use the port 3306 'cause it's used by another container, that's why I'm using 3310.

For some reason, when I go there and check if the port 3310 is opened, I always get that is closed.

How can I fix this?

答:
If the my.cnf resides in the container. Then the port used should be 3306

```<code>[client-server]
# Port or socket location where to connect
port = 3306
socket = /run/mysqld/mysqld.sock
</code>```

Since in the context of the container, this is the port that exposes mysql.

So what probably happens is that you expose 3306 but the container has assigned 3310 for the mysql server. Thus 3306 is indeed closed.

Title: How to expose mysql port?

Body:
I'm trying to expose the port 3310 to allow remote MySQL connection. So far, I have this configuration:

  database:
    container_name: sfapi_db
    restart: always
    ports:
      - 3310:3306
    build:
      context: ./docker/database
    environment:
      - MYSQL_DATABASE=${DB_NAME}
      - MYSQL_USER=${DB_USER}
      - MYSQL_PASSWORD=${DB_PWD}
      - MYSQL_ROOT_PASSWORD=${DB_PWD_ROOT}
    volumes:
      - dbdata:/var/lib/mysql
      - type: bind
        source: ./docker/database/my.cnf
        target: /etc/mysql/my.cnf

and this is the Dockerfile:

FROM mariadb:latest

CMD ["mysqld"]

EXPOSE 3310

here the my.cnf:

[client-server]
# Port or socket location where to connect
port = 3310
socket = /run/mysqld/mysqld.sock

# Import all .cnf files from configuration directory
!includedir /etc/mysql/conf.d/
!includedir /etc/mysql/mariadb.conf.d/

when I run docker-compose up --build -d and access to the container list, I get:

I also opened the port on the server using sudo ufw allow 3310. Also, I cannot use the port 3306 'cause it's used by another container, that's why I'm using 3310.

For some reason, when I go there and check if the port 3310 is opened, I always get that is closed.

How can I fix this?

Body:
If the my.cnf resides in the container. Then the port used should be 3306

[client-server]
# Port or socket location where to connect
port = 3306
socket = /run/mysqld/mysqld.sock

Since in the context of the container, this is the port that exposes mysql.

So what probably happens is that you expose 3306 but the container has assigned 3310 for the mysql server. Thus 3306 is indeed closed.


问:
Python sqlalchemy and mySQL stored procedure always returns 0 (out param only)
I am trying to get the ROW_COUNT() from a MySQL stored procedure into python.

here is what I got, but I don't know what I am missing.

```<code>DELIMITER //
CREATE OR REPLACE PROCEDURE sp_refresh_mytable(
    OUT row_count INT
)
BEGIN
    DECLARE exit handler for SQLEXCEPTION
        BEGIN
            ROLLBACK;
        END;
    DECLARE exit handler for SQLWARNING
        BEGIN
            ROLLBACK;
        END;
    DECLARE exit handler FOR NOT FOUND
        BEGIN
            ROLLBACK;
        END;

    START TRANSACTION;
    DELETE FROM mytable;

    INSERT INTO mytable
    (
          col1
        , col2
    )
    SELECT
          col1
        , col2
    FROM othertable
    ;
    SET row_count =  ROW_COUNT();
    COMMIT;
END //

DELIMITER ;
</code>```

If I call this in via normal SQL like follows I get the correct row_count of the insert operation (e.g. 26 rows inserted):

```<code>CALL sp_refresh_mytable(@rowcount);
select @rowcount as t;
-- output: 26
</code>```

Then in python/mysqlalchemy:

```<code>def call_procedure(engine, function_name, params=None):
    connection = engine.raw_connection()
    try:
        cursor = connection.cursor()
        result = cursor.callproc('sp_refresh_mytable', [0])
        ## try result outputs
        resultfetch = cursor.fetchone()
        logger.info(result)
        logger.info(result[0])
        logger.info(resultfetch)
        cursor.close()
        connection.commit()
        connection.close()
        logger.info(f"Running procedure {function_name} success!")
        return result
    except Exception as e:
        logger.error(f"Running procedure {function_name} failed!")
        logger.exception(e)
        return None
    finally:
        connection.close()
</code>```

So I tried logging different variations of getting the out value, but it is always 0 or None.

```<code>[INFO] db_update    [0]
[INFO] db_update    0
[INFO] db_update    None
</code>```

What am I missing?

Thanks!

答:
I just wanted to add another piece of code, since I was trying to get callproc to work (using sqlalchemy) with multiple in- and out-params.

For this case I went with the callproc method using a raw connection [solution b) in my previous answer], since this functions accepts params as a list.

It could probably be done more elegantly or more pythonic in some parts, but it was mainly for getting it to work and I will probably create a function from this so I can use it for generically calling a SP with multiple in and out params.

I included comments in the code below to make it easier to understand what is going on.

In my case I decided to put the out-params in a dict so I can pass it along to the calling app in case I need to react to the results. Of course you could also include the in-params which could make sense for error logging maybe.

```<code>## some in params
function_name   = 'sp_upsert'
in_param1       = 'my param 1'
in_param2       = 'abcdefg'
in_param3       = 'some-name'
in_param4       = 'some display name'
in_params = [in_param1, in_param1, in_param1, in_param1]
## out params
out_params = [
     'out1_row_count'
    ,'out2_row_count'
    ,'out3_row_count'
    ,'out4_row_count_ins'
    ,'out5_row_count_upd'
]
params = copy(in_params)
## adding the outparams as integers from out_params indices
params.extend([i for i, x in enumerate(out_params)])
## the params list will look like
## ['my param 1', 'abcdefg', 'some-name', 'some display name', 0, 1, 2, 3, 4]
logger.info(params)
## build query to get results from callproc (including in and out params)
res_qry_params = []
for i in range(len(params)):
    res_qry_params.append(f"@_{function_name}_{i}")
res_qry = f"SELECT  {', '.join(res_qry_params)}"
## the query to fetch the results (in and out params) will look like
## SELECT  @_sp_upsert_0, @_sp_upsert_1, @_sp_upsert_2, @_sp_upsert_3, @_sp_upsert_4, @_sp_upsert_5, @_sp_upsert_6, @_sp_upsert_7, @_sp_upsert_8
logger.info(res_qry)
try:
    connection = engine.raw_connection()
    ## calling the sp
    cursor = connection.cursor()
    cursor.callproc(function_name, params)
    ## get the results (includes in and out params), the 0/1 in the end are the row_counts from the sp
    ## fetchone is enough since all results come as on result record like
    ## ('my param 1', 'abcdefg', 'some-name', 'some display name', 1, 0, 1, 1, 0)
    cursor.execute(res_qry)
    results = cursor.fetchone()
    logger.info(results)
    ## adding just the out params to a dict
    res_dict = {}
    for i, element in enumerate(out_params):
        res_dict.update({
            element: results[i + len(in_params)]
            })
    ## the result dict in this case only contains the out param results and will look like
    ## { 'out1_row_count': 1,
    ##   'out2_row_count': 0,
    ##   'out3_row_count': 1,
    ##   'out4_row_count_ins': 1,
    ##   'out5_row_count_upd': 0}
    logger.info(pformat(res_dict, indent=2, sort_dicts=False))
    cursor.close()
    connection.commit()
    logger.debug(f"Running procedure {function_name} success!")
except Exception as e:
    logger.error(f"Running procedure {function_name} failed!")
    logger.exception(e)
</code>```

Just to complete the picture, here is a shortened version of my stored procedure. After BEGIN I declare some error handlers I set the out params to default 0, otherwise they could also return as NULL/None if not set by the procedure (e.g. because no insert was made):

```<code>DELIMITER //
CREATE OR REPLACE PROCEDURE sp_upsert(
    IN in_param1 VARCHAR(32),
    IN in_param2 VARCHAR(250),
    IN in_param3 VARCHAR(250),
    IN in_param4 VARCHAR(250),
    OUT out1_row_count INTEGER,
    OUT out2_row_count INTEGER,
    OUT out3_row_count INTEGER,
    OUT out4_row_count_ins INTEGER,
    OUT out5_row_count_upd INTEGER
)
BEGIN
    -- declare variables, do NOT declare the out params here!
    DECLARE dummy INTEGER DEFAULT 0;

    -- declare error handlers (e.g. continue handler for not found)
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET dummy = 1;

    -- set out params defaulting to 0
    SET out1_row_count = 0;
    SET out2_row_count = 0;
    SET out3_row_count = 0;
    SET out4_row_count_ins = 0;
    SET out5_row_count_upd = 0;

    -- do inserts and updates and set the outparam variables accordingly
    INSERT INTO some_table ...;
    SET out1_row_count = ROW_COUNT();

    -- commit if no errors
    COMMIT;
END //
DELIMITER ;
</code>```

Body:
I am trying to get the ROW_COUNT() from a MySQL stored procedure into python.

here is what I got, but I don't know what I am missing.

DELIMITER //
CREATE OR REPLACE PROCEDURE sp_refresh_mytable(
    OUT row_count INT
)
BEGIN
    DECLARE exit handler for SQLEXCEPTION
        BEGIN
            ROLLBACK;
        END;
    DECLARE exit handler for SQLWARNING
        BEGIN
            ROLLBACK;
        END;
    DECLARE exit handler FOR NOT FOUND
        BEGIN
            ROLLBACK;
        END;

    START TRANSACTION;
    DELETE FROM mytable;

    INSERT INTO mytable
    (
          col1
        , col2
    )
    SELECT
          col1
        , col2
    FROM othertable
    ;
    SET row_count =  ROW_COUNT();
    COMMIT;
END //

DELIMITER ;

If I call this in via normal SQL like follows I get the correct row_count of the insert operation (e.g. 26 rows inserted):

CALL sp_refresh_mytable(@rowcount);
select @rowcount as t;
-- output: 26

Then in python/mysqlalchemy:

def call_procedure(engine, function_name, params=None):
    connection = engine.raw_connection()
    try:
        cursor = connection.cursor()
        result = cursor.callproc('sp_refresh_mytable', [0])
        ## try result outputs
        resultfetch = cursor.fetchone()
        logger.info(result)
        logger.info(result[0])
        logger.info(resultfetch)
        cursor.close()
        connection.commit()
        connection.close()
        logger.info(f"Running procedure {function_name} success!")
        return result
    except Exception as e:
        logger.error(f"Running procedure {function_name} failed!")
        logger.exception(e)
        return None
    finally:
        connection.close()

So I tried logging different variations of getting the out value, but it is always 0 or None.

[INFO] db_update    [0]
[INFO] db_update    0
[INFO] db_update    None

What am I missing?

Thanks!

Body:
I just wanted to add another piece of code, since I was trying to get callproc to work (using sqlalchemy) with multiple in- and out-params.

For this case I went with the callproc method using a raw connection [solution b) in my previous answer], since this functions accepts params as a list.

It could probably be done more elegantly or more pythonic in some parts, but it was mainly for getting it to work and I will probably create a function from this so I can use it for generically calling a SP with multiple in and out params.

I included comments in the code below to make it easier to understand what is going on.

In my case I decided to put the out-params in a dict so I can pass it along to the calling app in case I need to react to the results. Of course you could also include the in-params which could make sense for error logging maybe.

## some in params
function_name   = 'sp_upsert'
in_param1       = 'my param 1'
in_param2       = 'abcdefg'
in_param3       = 'some-name'
in_param4       = 'some display name'
in_params = [in_param1, in_param1, in_param1, in_param1]
## out params
out_params = [
     'out1_row_count'
    ,'out2_row_count'
    ,'out3_row_count'
    ,'out4_row_count_ins'
    ,'out5_row_count_upd'
]
params = copy(in_params)
## adding the outparams as integers from out_params indices
params.extend([i for i, x in enumerate(out_params)])
## the params list will look like
## ['my param 1', 'abcdefg', 'some-name', 'some display name', 0, 1, 2, 3, 4]
logger.info(params)
## build query to get results from callproc (including in and out params)
res_qry_params = []
for i in range(len(params)):
    res_qry_params.append(f"@_{function_name}_{i}")
res_qry = f"SELECT  {', '.join(res_qry_params)}"
## the query to fetch the results (in and out params) will look like
## SELECT  @_sp_upsert_0, @_sp_upsert_1, @_sp_upsert_2, @_sp_upsert_3, @_sp_upsert_4, @_sp_upsert_5, @_sp_upsert_6, @_sp_upsert_7, @_sp_upsert_8
logger.info(res_qry)
try:
    connection = engine.raw_connection()
    ## calling the sp
    cursor = connection.cursor()
    cursor.callproc(function_name, params)
    ## get the results (includes in and out params), the 0/1 in the end are the row_counts from the sp
    ## fetchone is enough since all results come as on result record like
    ## ('my param 1', 'abcdefg', 'some-name', 'some display name', 1, 0, 1, 1, 0)
    cursor.execute(res_qry)
    results = cursor.fetchone()
    logger.info(results)
    ## adding just the out params to a dict
    res_dict = {}
    for i, element in enumerate(out_params):
        res_dict.update({
            element: results[i + len(in_params)]
            })
    ## the result dict in this case only contains the out param results and will look like
    ## { 'out1_row_count': 1,
    ##   'out2_row_count': 0,
    ##   'out3_row_count': 1,
    ##   'out4_row_count_ins': 1,
    ##   'out5_row_count_upd': 0}
    logger.info(pformat(res_dict, indent=2, sort_dicts=False))
    cursor.close()
    connection.commit()
    logger.debug(f"Running procedure {function_name} success!")
except Exception as e:
    logger.error(f"Running procedure {function_name} failed!")
    logger.exception(e)

Just to complete the picture, here is a shortened version of my stored procedure. After BEGIN I declare some error handlers I set the out params to default 0, otherwise they could also return as NULL/None if not set by the procedure (e.g. because no insert was made):

DELIMITER //
CREATE OR REPLACE PROCEDURE sp_upsert(
    IN in_param1 VARCHAR(32),
    IN in_param2 VARCHAR(250),
    IN in_param3 VARCHAR(250),
    IN in_param4 VARCHAR(250),
    OUT out1_row_count INTEGER,
    OUT out2_row_count INTEGER,
    OUT out3_row_count INTEGER,
    OUT out4_row_count_ins INTEGER,
    OUT out5_row_count_upd INTEGER
)
BEGIN
    -- declare variables, do NOT declare the out params here!
    DECLARE dummy INTEGER DEFAULT 0;

    -- declare error handlers (e.g. continue handler for not found)
    DECLARE CONTINUE HANDLER FOR NOT FOUND SET dummy = 1;

    -- set out params defaulting to 0
    SET out1_row_count = 0;
    SET out2_row_count = 0;
    SET out3_row_count = 0;
    SET out4_row_count_ins = 0;
    SET out5_row_count_upd = 0;

    -- do inserts and updates and set the outparam variables accordingly
    INSERT INTO some_table ...;
    SET out1_row_count = ROW_COUNT();

    -- commit if no errors
    COMMIT;
END //
DELIMITER ;