问:
SELECT DISTINCT ON expressions must match initial ORDER BY expressions in typeorm query
I have a query that I want get rows with unique item_id and sort them according to timestamp.

But I get this error everytime from this code

    const boxPreviewActivities = await this.activityLogEntryRepository

      .createQueryBuilder('activityLogEntry')
      .where("activityLogEntry.activity = 'BOX_PREVIEW'")
      .andWhere('activityLogEntry.projectId = :projectId', { projectId })
      .andWhere('activityLogEntry.userSub = :userSub', { userSub: user?.sub })
      .andWhere((qb) => {
        const subQuery = qb
          .subQuery()
          .select(
            "DISTINCT activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'"
          )
          .from(ActivityLogEntryEntity, 'activityLogEntry')
          .where("activityLogEntry.activity = 'BOX_DELETE'")
          .getQuery();
        return `activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' NOT IN (${subQuery})`;
      })
      .distinctOn([
        "activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' ",
      ])

      .orderBy('activityLogEntry.timestamp', 'DESC')
      .limit(limitNumber)
      .getMany();

    return boxPreviewActivities;
  }

```
<p>** ERROR [ExceptionsHandler] SELECT DISTINCT ON expressions must match initial ORDER BY expressions
QueryFailedError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions**</p>
<p>if I add this two order functions at the and, I dont get error but my query not sorting according to timestamp, instead sort only with item_id. Actually I only want to sort according to timestamp. How can I refactor my query to make it working ?</p>
<pre class="lang-js prettyprint-override"><code>  .orderBy(
        "activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'",
        'DESC'
      )
      .addOrderBy('activityLogEntry.timestamp', 'DESC')
</code>```

Body:
I have a query that I want get rows with unique item_id and sort them according to timestamp.

But I get this error everytime from this code

    const boxPreviewActivities = await this.activityLogEntryRepository

      .createQueryBuilder('activityLogEntry')
      .where("activityLogEntry.activity = 'BOX_PREVIEW'")
      .andWhere('activityLogEntry.projectId = :projectId', { projectId })
      .andWhere('activityLogEntry.userSub = :userSub', { userSub: user?.sub })
      .andWhere((qb) => {
        const subQuery = qb
          .subQuery()
          .select(
            "DISTINCT activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'"
          )
          .from(ActivityLogEntryEntity, 'activityLogEntry')
          .where("activityLogEntry.activity = 'BOX_DELETE'")
          .getQuery();
        return `activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' NOT IN (${subQuery})`;
      })
      .distinctOn([
        "activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id' ",
      ])

      .orderBy('activityLogEntry.timestamp', 'DESC')
      .limit(limitNumber)
      .getMany();

    return boxPreviewActivities;
  }

** ERROR [ExceptionsHandler] SELECT DISTINCT ON expressions must match initial ORDER BY expressions
QueryFailedError: SELECT DISTINCT ON expressions must match initial ORDER BY expressions**

if I add this two order functions at the and, I dont get error but my query not sorting according to timestamp, instead sort only with item_id. Actually I only want to sort according to timestamp. How can I refactor my query to make it working ?

  .orderBy(
        "activityLogEntry.originalData ::jsonb -> 'source' ->> 'item_id'",
        'DESC'
      )
      .addOrderBy('activityLogEntry.timestamp', 'DESC')


来源: stackexchange

问:
How to get specific month's previous year week start and end date with given date?
I need to find the specific week's start date and specific week's end date from previous year from the current date which differs with season.

If Season='Summer', get November 3rd Week's start date and March 2nd Week's end date.

If Season='Autumn', get March 3rd Week's start date and June 2nd Week's end date.

If Season='Winter', get June 3rd Week's start date and November 2nd Week's end date.

For Example:
If the current date is 14-12-2022 and Season='Summer', then the start date should be '15-11-2021' and end date should be '12-03-2022'.

How to achieve this in python? Like is there any datetime functions available ?

ContentLicense: CC BY-SA 4.0


问:
How to read file with okio inside commanMain module in a Kotlin Multiplatform Project?
I am trying to read/write files in the commonMain module.

I created a new Kotlin Multiplatform App for Android and iOS using the Android Studio Wizard. (New -> New Project ... -> Koltin Multiplatform App)

Then I added okio as dependency to common in the shared/build.gradle.kts file.

```<code>    sourceSets {
        val okio = "3.3.0"
        val commonMain by getting {
            dependencies {
                implementation("com.squareup.okio:okio:$okio")
            }
        }
        ...
</code>```

In the module commonMain I cannot access FileSystem.SYSTEM (Unresolved Reference: SYSTEM) and therefore not read or write any files.

In the module iOSMain and androidMain I can access FileSystem.SYSTEM. Is this expected behaviour? This would require me to write an expected/actual mapping for all okio apis. Or is there an other way?

Or do I need to configure my project differently to be able to access FileSystem.SYSTEM inside the commonMain-Module?

shared/build.gradle

```<code>plugins {
    kotlin("multiplatform")
    kotlin("native.cocoapods")
    id("com.android.library")
}

kotlin {
    android()
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    cocoapods {
        summary = "Some description for the Shared Module"
        homepage = "Link to the Shared Module homepage"
        version = "1.0"
        ios.deploymentTarget = "14.1"
        podfile = project.file("../iosApp/Podfile")
        framework {
            baseName = "shared"
        }
    }

    sourceSets {
        val okio = "3.3.0"
        val commonMain by getting {
            dependencies {
                implementation("com.squareup.okio:okio:$okio")
            }
        }
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test"))
            }
        }
        val androidMain by getting
        val androidTest by getting
        val iosX64Main by getting
        val iosArm64Main by getting
        val iosSimulatorArm64Main by getting
        val iosMain by creating {
            dependsOn(commonMain)
            iosX64Main.dependsOn(this)
            iosArm64Main.dependsOn(this)
            iosSimulatorArm64Main.dependsOn(this)
        }
        val iosX64Test by getting
        val iosArm64Test by getting
        val iosSimulatorArm64Test by getting
        val iosTest by creating {
            dependsOn(commonTest)
            iosX64Test.dependsOn(this)
            iosArm64Test.dependsOn(this)
            iosSimulatorArm64Test.dependsOn(this)
        }
    }
}

android {
    namespace = "de.pixel.kmmpodstryout"
    compileSdk = 32
    defaultConfig {
        minSdk = 21
        targetSdk = 32
    }
}
</code>```

Greetings.kt in commonMain from the sample app generated by the wizard:

```<code>package de.pixel.kmmpodstryout

import okio.FileSystem
import okio.Path.Companion.toPath

class Greeting {
    private val platform: Platform = getPlatform()

    fun greet(): String {
        val path = "helloworld.txt".toPath()

        FileSystem.SYSTEM <--- "Unresolved Reference SYSTEM"

        return "Hello, ${platform.name} ${readFile()}!"
    }
}
</code>```

Body:
I am trying to read/write files in the commonMain module.

I created a new Kotlin Multiplatform App for Android and iOS using the Android Studio Wizard. (New -> New Project ... -> Koltin Multiplatform App)

Then I added okio as dependency to common in the shared/build.gradle.kts file.

    sourceSets {
        val okio = "3.3.0"
        val commonMain by getting {
            dependencies {
                implementation("com.squareup.okio:okio:$okio")
            }
        }
        ...

In the module commonMain I cannot access FileSystem.SYSTEM (Unresolved Reference: SYSTEM) and therefore not read or write any files.

In the module iOSMain and androidMain I can access FileSystem.SYSTEM. Is this expected behaviour? This would require me to write an expected/actual mapping for all okio apis. Or is there an other way?

Or do I need to configure my project differently to be able to access FileSystem.SYSTEM inside the commonMain-Module?

shared/build.gradle

plugins {
    kotlin("multiplatform")
    kotlin("native.cocoapods")
    id("com.android.library")
}

kotlin {
    android()
    iosX64()
    iosArm64()
    iosSimulatorArm64()

    cocoapods {
        summary = "Some description for the Shared Module"
        homepage = "Link to the Shared Module homepage"
        version = "1.0"
        ios.deploymentTarget = "14.1"
        podfile = project.file("../iosApp/Podfile")
        framework {
            baseName = "shared"
        }
    }

    sourceSets {
        val okio = "3.3.0"
        val commonMain by getting {
            dependencies {
                implementation("com.squareup.okio:okio:$okio")
            }
        }
        val commonTest by getting {
            dependencies {
                implementation(kotlin("test"))
            }
        }
        val androidMain by getting
        val androidTest by getting
        val iosX64Main by getting
        val iosArm64Main by getting
        val iosSimulatorArm64Main by getting
        val iosMain by creating {
            dependsOn(commonMain)
            iosX64Main.dependsOn(this)
            iosArm64Main.dependsOn(this)
            iosSimulatorArm64Main.dependsOn(this)
        }
        val iosX64Test by getting
        val iosArm64Test by getting
        val iosSimulatorArm64Test by getting
        val iosTest by creating {
            dependsOn(commonTest)
            iosX64Test.dependsOn(this)
            iosArm64Test.dependsOn(this)
            iosSimulatorArm64Test.dependsOn(this)
        }
    }
}

android {
    namespace = "de.pixel.kmmpodstryout"
    compileSdk = 32
    defaultConfig {
        minSdk = 21
        targetSdk = 32
    }
}

Greetings.kt in commonMain from the sample app generated by the wizard:

package de.pixel.kmmpodstryout

import okio.FileSystem
import okio.Path.Companion.toPath

class Greeting {
    private val platform: Platform = getPlatform()

    fun greet(): String {
        val path = "helloworld.txt".toPath()

        FileSystem.SYSTEM <--- "Unresolved Reference SYSTEM"

        return "Hello, ${platform.name} ${readFile()}!"
    }
}


问:
Updating Live Activities without using push notifications
I have a progress indicator in the Live Activity that should update every 15 minutes. I know that the way to go is using Push Notifications but they are not an option for me.

I have seen Apps on the Appstore and even the native timer update their live activities when push notifications are not enabled and even background App fetch is disabled.

In Apple's docs, it is mentioned that you can update or end a Live Activity from your app while it runs in the background — for example, by using Background Tasks.

Background Tasks do not work for me since they are unreliable. However, I have the Audio, Airplay, and Picture in Picture Background mode activated (For purposes other than the Live Activity) and so when I run this code:

```<code>timer = Timer(timeInterval: 1, repeats: true, block: { [weak self] (timer) in
    guard let self = self else { return }

    self.value += 1
    let state = TempAttributes.ContentState(timer: self.value)
    Task { @MainActor in
       await deliveryActivity.update(using: state)
    }
})

RunLoop.main.add(timer!, forMode: .common)
</code>```

It technically should work and when I add a break point in the timer, it gets called and the value gets updated but the Live Activity UI does not.

This works on 16.2 but unfortunately it does not work on 16.1! Any ideas why?

Body:
I have a progress indicator in the Live Activity that should update every 15 minutes. I know that the way to go is using Push Notifications but they are not an option for me.

I have seen Apps on the Appstore and even the native timer update their live activities when push notifications are not enabled and even background App fetch is disabled.

In Apple's docs, it is mentioned that you can update or end a Live Activity from your app while it runs in the background — for example, by using Background Tasks.

Background Tasks do not work for me since they are unreliable. However, I have the Audio, Airplay, and Picture in Picture Background mode activated (For purposes other than the Live Activity) and so when I run this code:

timer = Timer(timeInterval: 1, repeats: true, block: { [weak self] (timer) in
    guard let self = self else { return }

    self.value += 1
    let state = TempAttributes.ContentState(timer: self.value)
    Task { @MainActor in
       await deliveryActivity.update(using: state)
    }
})

RunLoop.main.add(timer!, forMode: .common)

It technically should work and when I add a break point in the timer, it gets called and the value gets updated but the Live Activity UI does not.

This works on 16.2 but unfortunately it does not work on 16.1! Any ideas why?


问:
'SequentialFeatureSelector' object has no attribute 'ranking_'
everyone,

I would like to sort the best features that I'm getting from SequentialFeatureSelector based on their ranks.

But I get this error:
'SequentialFeatureSelector' object has no attribute 'ranking_'

Can you help me to solve it and sort my features based on their importance?

```<code>`import pandas as pd
df=pd.read_csv('')

#Deviding X and Y
Y=df.iloc[:,-1:]
X = df[df.columns.drop(Y)]

#Selecting the K best features
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor()
sfs = SequentialFeatureSelector(model, n_features_to_select=5)
fit = sfs.fit(X, Y)

#Selecting them and showing them in a dataframe
names = X.columns.values

ranking = sfs.ranking_
names_scores = list(zip(names, ranking))
ns_df = pd.DataFrame(data = names_scores, columns=['Feature_names', 'ranks'])
L=ns_df.sort_values('ranks', ascending=False)
L`
</code>```

Body:
everyone,

I would like to sort the best features that I'm getting from SequentialFeatureSelector based on their ranks.

But I get this error:
'SequentialFeatureSelector' object has no attribute 'ranking_'

Can you help me to solve it and sort my features based on their importance?

`import pandas as pd
df=pd.read_csv('')

#Deviding X and Y
Y=df.iloc[:,-1:]
X = df[df.columns.drop(Y)]

#Selecting the K best features
from sklearn.feature_selection import SequentialFeatureSelector
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor()
sfs = SequentialFeatureSelector(model, n_features_to_select=5)
fit = sfs.fit(X, Y)

#Selecting them and showing them in a dataframe
names = X.columns.values

ranking = sfs.ranking_
names_scores = list(zip(names, ranking))
ns_df = pd.DataFrame(data = names_scores, columns=['Feature_names', 'ranks'])
L=ns_df.sort_values('ranks', ascending=False)
L`


问:
Control re-rendering or whole app when a store updates
Here is my App.js component where i use a provider that wrap the whole app and render on any update in my store state

```<code>import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import store  from './redux/index';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
      <BrowserRouter>
        <Provider store={store}>
        <Routes>
          <Route path="/*" element={<App />} />
        </Routes>
        </Provider>
    </BrowserRouter>
);

reportWebVitals();
</code>```

and here is my action

```<code>export const ProductListAction = ({endpoint, key='', method, data, params, isload, message=false}) =>{
    return async (dispatch) =>{
     try {
      if(isload){
        dispatch({ type: 'ISLOADING', payload: {loading:true, key} });
      }
       await endpoint && fetchrequest({isload, endpoint: endpoint, method, data, params}).then((response) => {
          if(response.data.success===true){
            isload&&  dispatch({ type: "SUCCESS", payload: response.data.message, message});
          }
          else{
            isload&& dispatch({ type: "ONERROR", payload: response.data.message, message});
          }
          dispatch({ type: key, payload: response || {} });
       }).catch((err) => {
        isload&& dispatch({ type: "ONERROR", payload: err?.response?.data?.message ,message});
      })
     } catch (error) {
      isload&& dispatch({ type: "ONERROR", payload: error?.response?.data?.message});
     }
    }
 };
</code>```

now the problem is that when my whole app renders the times that how many API calls I want my current app renders only one time regarding how many api calls.

Body:
Here is my App.js component where i use a provider that wrap the whole app and render on any update in my store state

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import store  from './redux/index';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
      <BrowserRouter>
        <Provider store={store}>
        <Routes>
          <Route path="/*" element={<App />} />
        </Routes>
        </Provider>
    </BrowserRouter>
);

reportWebVitals();

and here is my action

export const ProductListAction = ({endpoint, key='', method, data, params, isload, message=false}) =>{
    return async (dispatch) =>{
     try {
      if(isload){
        dispatch({ type: 'ISLOADING', payload: {loading:true, key} });
      }
       await endpoint && fetchrequest({isload, endpoint: endpoint, method, data, params}).then((response) => {
          if(response.data.success===true){
            isload&&  dispatch({ type: "SUCCESS", payload: response.data.message, message});
          }
          else{
            isload&& dispatch({ type: "ONERROR", payload: response.data.message, message});
          }
          dispatch({ type: key, payload: response || {} });
       }).catch((err) => {
        isload&& dispatch({ type: "ONERROR", payload: err?.response?.data?.message ,message});
      })
     } catch (error) {
      isload&& dispatch({ type: "ONERROR", payload: error?.response?.data?.message});
     }
    }
 };

now the problem is that when my whole app renders the times that how many API calls I want my current app renders only one time regarding how many api calls.


问:
Redocly CLI command not found
I am trying to use Redocly CLI to split an OpenAPI definition file.

It was working last night but doesn't work this morning.

When I try to run a redocly command, for example:

```<code>redocly lint openapi.yaml
</code>```

the output I get is:

```<code>zsh: command not found: redocly
</code>```

Redocly CLI is installed globally.

I tried to install it again.

This is the command I used as shown in the Redocly documentation:

```<code>npm install @redocly/cli -g
</code>```

And the output in the terminal is:

```<code>changed 256 packages, and audited 257 packages in 10s

31 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities
</code>```

Any assistance would be helpful.

Title: Redocly CLI command not found

Body:
I am trying to use Redocly CLI to split an OpenAPI definition file.

It was working last night but doesn't work this morning.

When I try to run a redocly command, for example:

redocly lint openapi.yaml

the output I get is:

zsh: command not found: redocly

Redocly CLI is installed globally.

I tried to install it again.

This is the command I used as shown in the Redocly documentation:

npm install @redocly/cli -g

And the output in the terminal is:

changed 256 packages, and audited 257 packages in 10s

31 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Any assistance would be helpful.


问:
STOMP mock server with Angular
I've an Angular app that successfully commnunicate with on a STOMP Websocket provided by a Springboot server.
For some reasons, I need to have a mock server to be able to run Angular without the springboot server.
I tried diffferents solutions but I cant get it to work. Currently, I'm using "stomp-broker-js" but as soon as the client try to connect it crash. I don't want to change the Angular code cause it works well with the real server.

Here's my mock server code:

```<code>const http = require("http");
const StompServer = require("stomp-broker-js");
const node_static = require("node-static");
const static_directory = new node_static.Server(__dirname);

const server = http.createServer((request, response) => {
  console.log(request.url);
  static_directory.serve(request, response);
});
const stompServer = new StompServer({
  server: server,
  debug: console.log,
  path: "/updates",
  protocol: "sockjs",
  heartbeat: [2000, 2000],
});

console.log(" [*] Listening on 0.0.0.0:3000");
server.listen(3000, "localhost");

stompServer.subscribe("/echo", (msg, headers) => {
  var topic = headers.destination;
  console.log(`topic:${topic} messageType: ${typeof msg}`, msg, headers);
  stompServer.send("/echo", headers, `Hello from server! ${msg}`);
});
</code>```

Here's the log:

```<code>node MobiusStompWSMockServer.js
SockJS v0.3.24 bound to "/updates"
 [*] Listening on 0.0.0.0:3000
GET /updates 1ms (unfinished)
node:events:368
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TCP.onStreamRead (node:internal/stream_base_commons:220:20)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}
</code>```

And in the client side, it crash in client.js:

The network shows "connection: upgrade" and the server shows "unfinished".

For the angular part, I used "rx-stomp", exactly like indicated in https://stomp-js.github.io/guide/rx-stomp/rx-stomp-with-angular.html.

Does someone have an idea or have succesfully mock a spring boot stomp websocket?

Thanks for your help!

Title: STOMP mock server with Angular

Body:
I've an Angular app that successfully commnunicate with on a STOMP Websocket provided by a Springboot server.
For some reasons, I need to have a mock server to be able to run Angular without the springboot server.
I tried diffferents solutions but I cant get it to work. Currently, I'm using "stomp-broker-js" but as soon as the client try to connect it crash. I don't want to change the Angular code cause it works well with the real server.

Here's my mock server code:

const http = require("http");
const StompServer = require("stomp-broker-js");
const node_static = require("node-static");
const static_directory = new node_static.Server(__dirname);

const server = http.createServer((request, response) => {
  console.log(request.url);
  static_directory.serve(request, response);
});
const stompServer = new StompServer({
  server: server,
  debug: console.log,
  path: "/updates",
  protocol: "sockjs",
  heartbeat: [2000, 2000],
});

console.log(" [*] Listening on 0.0.0.0:3000");
server.listen(3000, "localhost");

stompServer.subscribe("/echo", (msg, headers) => {
  var topic = headers.destination;
  console.log(`topic:${topic} messageType: ${typeof msg}`, msg, headers);
  stompServer.send("/echo", headers, `Hello from server! ${msg}`);
});

Here's the log:

node MobiusStompWSMockServer.js
SockJS v0.3.24 bound to "/updates"
 [*] Listening on 0.0.0.0:3000
GET /updates 1ms (unfinished)
node:events:368
      throw er; // Unhandled 'error' event
      ^

Error: read ECONNRESET
    at TCP.onStreamRead (node:internal/stream_base_commons:220:20)
Emitted 'error' event on Socket instance at:
    at emitErrorNT (node:internal/streams/destroy:157:8)
    at emitErrorCloseNT (node:internal/streams/destroy:122:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21) {
  errno: -4077,
  code: 'ECONNRESET',
  syscall: 'read'
}

And in the client side, it crash in client.js:

The network shows "connection: upgrade" and the server shows "unfinished".

For the angular part, I used "rx-stomp", exactly like indicated in https://stomp-js.github.io/guide/rx-stomp/rx-stomp-with-angular.html.

Does someone have an idea or have succesfully mock a spring boot stomp websocket?

Thanks for your help!


问:
Error: {"message": "user.check is not a function" } in postman
There Is My Code ~

```<code>    const user = new User(req.body, rules);
    const matched = await user.check();
    if (!matched) {
      return res.status(404).send(user.errors)
    }
</code>```

I'm fairly new to Node.js and I am having some issues.

May I know what is wrong with my code?

Body:
There Is My Code ~

    const user = new User(req.body, rules);
    const matched = await user.check();
    if (!matched) {
      return res.status(404).send(user.errors)
    }

I'm fairly new to Node.js and I am having some issues.

May I know what is wrong with my code?


问:
Python: Why can't I access variables in an IF that I declared right before / at the start of the file?
I have a created a variable at the start of my program, and another in a def before an important IF. However, I keep running into problems with reading & writing them.

I have the following code snippet:

```<code>#(...)
move_to = "finishedImages"
amount_moved = 0

def put_in(is_training:bool, file:Path):
    pthstr = file.__str__()
    target = move_to
    if is_training:
        target = target + "/train" # Makes a local instead!
    else:
        target = target + "/test" # Makes a local instead!

    shutil.move(file, move_to )
    shutil.move(pthstr[:len(pthstr) - 3] + "jpg", move_to)
    amount_moved += 1 # Can't even read amount_moved!
#(...)
</code>```

My problem is that the IF does not override the target variable but insted creates a new local one, despite the fact it can read it. In effect, these lines become useless as my program continues to use the old target value.

Furthermore, the amount_moved cannot be accessed.

I'm more used to other languages where the scope system is rather simple such as Java, help!

Body:
I have a created a variable at the start of my program, and another in a def before an important IF. However, I keep running into problems with reading & writing them.

I have the following code snippet:

#(...)
move_to = "finishedImages"
amount_moved = 0

def put_in(is_training:bool, file:Path):
    pthstr = file.__str__()
    target = move_to
    if is_training:
        target = target + "/train" # Makes a local instead!
    else:
        target = target + "/test" # Makes a local instead!

    shutil.move(file, move_to )
    shutil.move(pthstr[:len(pthstr) - 3] + "jpg", move_to)
    amount_moved += 1 # Can't even read amount_moved!
#(...)

My problem is that the IF does not override the target variable but insted creates a new local one, despite the fact it can read it. In effect, these lines become useless as my program continues to use the old target value.

Furthermore, the amount_moved cannot be accessed.

I'm more used to other languages where the scope system is rather simple such as Java, help!


问:
How to connect two activities in Android Studio?
I am trying to create a lonin page where you enter your email address and password. If they are correct you will be taken to another page (activity) but my app keeps crashing and I have tried everything but still stuck here.

My code is below, thank you in advance.

```<code>
</code>```
```<code>class MainActivity : AppCompatActivity() {

    @SuppressLint("MissingInflatedId", "WrongViewCast")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btn = findViewById<Button>(R.id.btn1)
        val email = findViewById<TextView>(R.id.email)
        val password = findViewById<TextView>(R.id.password)

        fun onClick(view: View) {
            if (email.toString() == "safin" || password.toString() == "hallo") {
                btn.setOnClickListener {
                    startActivity(Intent(this, MainActivity2::class.java))
                }
            } else {
                email.error = "Your Email and your Password did not match!"
                password.error = "Your Password and your Email did not match!"
            }

        }

    }

</code>```

Body:
I am trying to create a lonin page where you enter your email address and password. If they are correct you will be taken to another page (activity) but my app keeps crashing and I have tried everything but still stuck here.

My code is below, thank you in advance.

class MainActivity : AppCompatActivity() {

    @SuppressLint("MissingInflatedId", "WrongViewCast")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val btn = findViewById<Button>(R.id.btn1)
        val email = findViewById<TextView>(R.id.email)
        val password = findViewById<TextView>(R.id.password)

        fun onClick(view: View) {
            if (email.toString() == "safin" || password.toString() == "hallo") {
                btn.setOnClickListener {
                    startActivity(Intent(this, MainActivity2::class.java))
                }
            } else {
                email.error = "Your Email and your Password did not match!"
                password.error = "Your Password and your Email did not match!"
            }

        }

    }


问:
Returning values from different rows in a stored procedure as different values
I have a stored procedure:

```<code>`SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER    PROCEDURE [ebs].[DB_Task_ONEYCRPRaport]
    --@startDate      DATE,
    --@endDate      DATE

AS
BEGIN

SELECT DISTINCT
CAST(A.ExternalMerchantId as varchar) "Merchant_guid", -- ok
CAST(C.CreatedOn AS DATE) "Purchase_date", --ok
CAST(C.CreatedOn AS TIME) "Purchase_hour", --ok
C.ContractNo "Funding_reference",--ok
APP.OrderNo "External_reference", --ok
A.CustomerInternalId "Customer_external_code",--ok
CASE WHEN I.TotalAmountToPay = 0 THEN '-' ELSE '+' END "Total_amount_symbol",--ok
CASE WHEN I.TotalAmountToPay = 0 THEN I.TotalAmountToRecover ELSE I.TotalAmountToPay END "Total_amount"
from ebs.Account as A
JOIN ebs.FTOS_CB_Contract AS C ON A.Accountid = C.CustomerId
JOIN ebs.FTOS_CB_BankAccount AS BA ON BA.FTOS_CB_BankAccountid = C.MainBankAccountId
JOIN ebs.FTOS_CB_BankAccountOperation AS BAO ON BAO.BankAccountId = BA.FTOS_CB_BankAccountid
JOIN Ebs.FTOS_CMB_Currency AS CU ON CU.FTOS_CMB_Currencyid = C.CurrencyId
JOIN ebs.FTOS_TPM_Invoice AS I ON I.BankAccountId = BA.FTOS_CB_BankAccountid
JOIN ebs.FTOS_TPM_InvoiceDetail AS ID ON ID.InvoiceId = I.FTOS_TPM_Invoiceid
JOIN ebs.FTOS_BNKAP_Application AS APP ON APP.ContractId = ID.ContractId
JOIN ebs.FTOS_CB_Payment AS P ON I.FTOS_TPM_Invoiceid=P.InvoiceId
JOIN ebs.FTOS_BP_BankingProduct AS BP ON BP.FTOS_BP_BankingProductid=(SELECT CO.ProductId from ebs.FTOS_CB_Contract AS CO where CO.FTOS_CB_Contractid = ID.ContractId)
JOIN ebs.FTOS_TPM_PreInvoiceDetail AS PID ON PID.ContractId = C.FTOS_CB_Contractid
left JOIN ebs.FTOS_ONEY_ICE_Repayment as R ON P.PaymentNo = R.PaymentNo
left JOIN ebs.FTOS_ONEY_ICE_Repayment_Details AS RD ON RD.FTOS_ONEY_ICE_Repaymentid = R.FTOS_ONEY_ICE_Repaymentid -- detalii plati efectuate
left JOIN ebs.FTOS_ONEY_ICE_Libra_ReceivedPayments AS RP ON RP.FTOS_CB_Contractid = C.FTOS_CB_Contractid --and DATEPART(week, C.CreatedOn) = DATEPART(week, GETDATE()) take current week results

END`
</code>```

I have another table where commissions are stored, the problem is I don't know how to select them in my stored procedure if they are on separate columns:

Here is the test query:

```<code>SELECT PID.*
FROM [ebs].[FTOS_TPM_PreInvoiceDetail] as PID
WHERE PID.Name = 'name'
</code>```

Basically for this example I want those values 20 and 5 to be selected in my stored procedures as two different values, how can I achieve that?

I tried created another stored procedure, but I think is a very bad idea.

Body:
I have a stored procedure:

`SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER    PROCEDURE [ebs].[DB_Task_ONEYCRPRaport]
    --@startDate      DATE,
    --@endDate      DATE

AS
BEGIN

SELECT DISTINCT
CAST(A.ExternalMerchantId as varchar) "Merchant_guid", -- ok
CAST(C.CreatedOn AS DATE) "Purchase_date", --ok
CAST(C.CreatedOn AS TIME) "Purchase_hour", --ok
C.ContractNo "Funding_reference",--ok
APP.OrderNo "External_reference", --ok
A.CustomerInternalId "Customer_external_code",--ok
CASE WHEN I.TotalAmountToPay = 0 THEN '-' ELSE '+' END "Total_amount_symbol",--ok
CASE WHEN I.TotalAmountToPay = 0 THEN I.TotalAmountToRecover ELSE I.TotalAmountToPay END "Total_amount"
from ebs.Account as A
JOIN ebs.FTOS_CB_Contract AS C ON A.Accountid = C.CustomerId
JOIN ebs.FTOS_CB_BankAccount AS BA ON BA.FTOS_CB_BankAccountid = C.MainBankAccountId
JOIN ebs.FTOS_CB_BankAccountOperation AS BAO ON BAO.BankAccountId = BA.FTOS_CB_BankAccountid
JOIN Ebs.FTOS_CMB_Currency AS CU ON CU.FTOS_CMB_Currencyid = C.CurrencyId
JOIN ebs.FTOS_TPM_Invoice AS I ON I.BankAccountId = BA.FTOS_CB_BankAccountid
JOIN ebs.FTOS_TPM_InvoiceDetail AS ID ON ID.InvoiceId = I.FTOS_TPM_Invoiceid
JOIN ebs.FTOS_BNKAP_Application AS APP ON APP.ContractId = ID.ContractId
JOIN ebs.FTOS_CB_Payment AS P ON I.FTOS_TPM_Invoiceid=P.InvoiceId
JOIN ebs.FTOS_BP_BankingProduct AS BP ON BP.FTOS_BP_BankingProductid=(SELECT CO.ProductId from ebs.FTOS_CB_Contract AS CO where CO.FTOS_CB_Contractid = ID.ContractId)
JOIN ebs.FTOS_TPM_PreInvoiceDetail AS PID ON PID.ContractId = C.FTOS_CB_Contractid
left JOIN ebs.FTOS_ONEY_ICE_Repayment as R ON P.PaymentNo = R.PaymentNo
left JOIN ebs.FTOS_ONEY_ICE_Repayment_Details AS RD ON RD.FTOS_ONEY_ICE_Repaymentid = R.FTOS_ONEY_ICE_Repaymentid -- detalii plati efectuate
left JOIN ebs.FTOS_ONEY_ICE_Libra_ReceivedPayments AS RP ON RP.FTOS_CB_Contractid = C.FTOS_CB_Contractid --and DATEPART(week, C.CreatedOn) = DATEPART(week, GETDATE()) take current week results

END`

I have another table where commissions are stored, the problem is I don't know how to select them in my stored procedure if they are on separate columns:

Here is the test query:

SELECT PID.*
FROM [ebs].[FTOS_TPM_PreInvoiceDetail] as PID
WHERE PID.Name = 'name'

Basically for this example I want those values 20 and 5 to be selected in my stored procedures as two different values, how can I achieve that?

I tried created another stored procedure, but I think is a very bad idea.


问:
Cognito save user data in cognito
I'm trying to save related user's data in Cognito, things like details about the user, such  as about section, age, status, and I want other users to see this information, can I store this data on Cognito, or maybe I need to save this in DynamoDB and relate it to the user in Cognito</p>

Title: Cognito save user data in cognito


问:
serialize/deserialize xml with uknownw elements
lets say i have model structure like this

```<code><MyObject>
    <Files>
        <File>1</File>
        <File>2</File>
    </Files>
    <Directories>
        <File>3</file>
    </Directories>
</<MyObject>
</code>```

when i want to add some new file to Files - it is easy, i just have to to create model and deserialize it to this model:

```<code>class MyObject
{
    List<Files> Files
    List<Files> Directories
}
</code>```

Then just Files.Add(new File(...)
and then serialize it again - it will work

But i dont know how to handle situation, where i would not know all the elemenets existing in xml file - i know that there are only files and directories (like above) and would like only to modify them - but i have to leave the rest alone - f.e. after i add new file to files/directories and i will again serialize it and write to xml, i would like to have serialized xml files with attributess that are left i don't know them

let say the xml file would looks like

```<code><MyObject>
    <Files>
        <File>1</File>
        <File>2</File>
    </Files>
    <Directories>
        <File>3</file>
    </Directories>
    <SomeAttrib1> ... </SomeAttrib1>
    <SomeAttrib2> ... </SomeAttrib2>
</<MyObject>
</code>```

And i dont know that xml contains SomeAttrib1, SomeAttrib2 (in case i would know, i would just add to model

```<code>Object SomeAttrib1
</code>```

and it would be serialized

but in case i cant be sure what will be included in xml file - what should i do?

I Use c# with System.Xml.Serialization;

Body:
lets say i have model structure like this

<MyObject>
    <Files>
        <File>1</File>
        <File>2</File>
    </Files>
    <Directories>
        <File>3</file>
    </Directories>
</<MyObject>

when i want to add some new file to Files - it is easy, i just have to to create model and deserialize it to this model:

class MyObject
{
    List<Files> Files
    List<Files> Directories
}

Then just Files.Add(new File(...)
and then serialize it again - it will work

But i dont know how to handle situation, where i would not know all the elemenets existing in xml file - i know that there are only files and directories (like above) and would like only to modify them - but i have to leave the rest alone - f.e. after i add new file to files/directories and i will again serialize it and write to xml, i would like to have serialized xml files with attributess that are left i don't know them

let say the xml file would looks like

<MyObject>
    <Files>
        <File>1</File>
        <File>2</File>
    </Files>
    <Directories>
        <File>3</file>
    </Directories>
    <SomeAttrib1> ... </SomeAttrib1>
    <SomeAttrib2> ... </SomeAttrib2>
</<MyObject>

And i dont know that xml contains SomeAttrib1, SomeAttrib2 (in case i would know, i would just add to model

Object SomeAttrib1

and it would be serialized

but in case i cant be sure what will be included in xml file - what should i do?

I Use c# with System.Xml.Serialization;


问:
User sessions/authentication using GO/Gin
[Pet Project] I'm using Gin framework with github.com/gin-contrib/sessions and github.com/gin-contrib/sessions/cookies. None of the pages should be accessed if you are not logged in(except sign in/up). How to check if user is logged in or not? I find sessions/cookies documentation quite poor(my opinion). Any help with that? Or a better choice to check sessions?

I am able to store a session, yet I don't understand how it actually is stored, where and what information is saved. By what do sessions differ and why am I still able to access pages if I set authenticated="false"?

Storing a sessions:

```<code>func StoreSession() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)

        session.Set("authenticated", "true")
        session.Save()
    }
}
</code>```

Checking a session:

```<code>func CheckSession() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)

        if session.Get("authenticated") != "true" {
            c.AbortWithStatus(http.StatusUnauthorized)
        }

        c.Next()
    }
}
</code>```

Logging out:

```<code>func Logout() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)

        session.Set("authenticated", "false")
        session.Save()
    }
}
</code>```

I feel like I'm using sessions quite incorrectly, although I don't find definitions in documentation or how should I use them in a correct way. Any help, tips or articles related to that topic?

Body:
[Pet Project] I'm using Gin framework with github.com/gin-contrib/sessions and github.com/gin-contrib/sessions/cookies. None of the pages should be accessed if you are not logged in(except sign in/up). How to check if user is logged in or not? I find sessions/cookies documentation quite poor(my opinion). Any help with that? Or a better choice to check sessions?

I am able to store a session, yet I don't understand how it actually is stored, where and what information is saved. By what do sessions differ and why am I still able to access pages if I set authenticated="false"?

Storing a sessions:

func StoreSession() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)

        session.Set("authenticated", "true")
        session.Save()
    }
}

Checking a session:

func CheckSession() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)

        if session.Get("authenticated") != "true" {
            c.AbortWithStatus(http.StatusUnauthorized)
        }

        c.Next()
    }
}

Logging out:

func Logout() gin.HandlerFunc {
    return func(c *gin.Context) {
        session := sessions.Default(c)

        session.Set("authenticated", "false")
        session.Save()
    }
}

I feel like I'm using sessions quite incorrectly, although I don't find definitions in documentation or how should I use them in a correct way. Any help, tips or articles related to that topic?


问:
Limit MaxResult of Object Detection
```<code># Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util

# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
    """Camera object that controls video streaming from the Picamera"""
    def __init__(self,resolution=(640,480),framerate=30):
        # Initialize the PiCamera and the camera image stream
        self.stream = cv2.VideoCapture(0)
        ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
        ret = self.stream.set(3,resolution[0])
        ret = self.stream.set(4,resolution[1])

        # Read first frame from the stream
        (self.grabbed, self.frame) = self.stream.read()

    # Variable to control when the camera is stopped
        self.stopped = False

    def start(self):
    # Start the thread that reads frames from the video stream
        Thread(target=self.update,args=()).start()
        return self

    def update(self):
        # Keep looping indefinitely until the thread is stopped
        while True:
            # If the camera is stopped, stop the thread
            if self.stopped:
                # Close camera resources
                self.stream.release()
                return

            # Otherwise, grab the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
    # Return the most recent frame
        return self.frame

    def stop(self):
    # Indicate that the camera and thread should be stopped
        self.stopped = True

# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
                    default='/home/pi/TensorFlow')
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
                    default='edgetpu.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
                    default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
                    default=0.4)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
                    default='640x480')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
                    default=True,
                    #required=True,
                    action='store_true')

args = parser.parse_args()

MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu

# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
    from tflite_runtime.interpreter import Interpreter
    if use_TPU:
        from tflite_runtime.interpreter import load_delegate
else:
    from tensorflow.lite.python.interpreter import Interpreter
    if use_TPU:
        from tensorflow.lite.python.interpreter import load_delegate

GRAPH_NAME = 'edgetpu.tflite'

# Get path to current working directory
CWD_PATH = os.getcwd()

# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)

# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
    labels = [line.strip() for line in f.readlines()]

# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
    del(labels[0])

# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
    interpreter = Interpreter(model_path=PATH_TO_CKPT,
                              experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
    print(PATH_TO_CKPT)
else:
    interpreter = Interpreter(model_path=PATH_TO_CKPT)

interpreter.allocate_tensors()

# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]

floating_model = (input_details[0]['dtype'] == np.float32)

input_mean = 127.5
input_std = 127.5

# Check output layer name to determine if this model was created with TF2 or TF1,
# because outputs are ordered differently for TF2 and TF1 models
outname = output_details[0]['name']

if ('StatefulPartitionedCall' in outname): # This is a TF2 model
    boxes_idx, classes_idx, scores_idx = 1, 3, 0
else: # This is a TF1 model
    boxes_idx, classes_idx, scores_idx = 0, 1, 2

# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()

# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)

#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:

    # Start timer (for calculating frame rate)
    t1 = cv2.getTickCount()

    # Grab frame from video stream
    frame1 = videostream.read()
    frame1 = cv2.flip(frame1,0)
    # Acquire frame and resize to expected shape [1xHxWx3]
    frame = frame1.copy()
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_resized = cv2.resize(frame_rgb, (width, height))
    input_data = np.expand_dims(frame_resized, axis=0)

    # Normalize pixel values if using a floating model (i.e. if model is non-quantized)
    if floating_model:
        input_data = (np.float32(input_data) - input_mean) / input_std

    # Perform the actual detection by running the model with the image as input
    interpreter.set_tensor(input_details[0]['index'],input_data)
    interpreter.invoke()

    # Retrieve detection results
    boxes = interpreter.get_tensor(output_details[boxes_idx]['index'])[0] # Bounding box coordinates of detected objects
    classes = interpreter.get_tensor(output_details[classes_idx]['index'])[0] # Class index of detected objects
    scores = interpreter.get_tensor(output_details[scores_idx]['index'])[0] # Confidence of detected objects

    # Loop over all detections and draw detection box if confidence is above minimum threshold
    for i in range(len(scores)):
        if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):

            # Get bounding box coordinates and draw box
            # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
            ymin = int(max(1,(boxes[i][0] * imH)))
            xmin = int(max(1,(boxes[i][1] * imW)))
            ymax = int(min(imH,(boxes[i][2] * imH)))
            xmax = int(min(imW,(boxes[i][3] * imW)))

            cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)

            # Draw label
            object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
            label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
            labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
            label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
            cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
            cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text

             # Draw circle in center
            xcenter = xmin + (int(round((xmax - xmin) / 2)))
            ycenter = ymin + (int(round((ymax - ymin) / 2)))
            cv2.circle(frame, (xcenter, ycenter), 5, (0,0,255), thickness=-1)

            # Print info
            print('Object ' + str(i) + ': ' + object_name + ' at (' + str(xcenter) + ', ' + str(ycenter) + ')')

    # Draw framerate in corner of frame
    cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)

    # All the results have been drawn on the frame, so it's time to display it.
    cv2.imshow('Object detector', frame)

    # Press 'q' to quit
    if cv2.waitKey(1) == ord('q'):
        break

# Clean up
cv2.destroyAllWindows()
videostream.stop()
</code>```

I would like to try something in this code but i can't limit the detection to 1 at a time

The object detection and the model itself are good but i want to limit the result to 1 instead of  multiple

this is the whole code i get from the internet

i also tried to add (parse.addArgument --maxResult) but i don't know how to run it in the tflite_runtime

i am new to the codes in python and in using RPi

Title: Limit MaxResult of Object Detection

Body:
# Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util

# Define VideoStream class to handle streaming of video from webcam in separate processing thread
# Source - Adrian Rosebrock, PyImageSearch: https://www.pyimagesearch.com/2015/12/28/increasing-raspberry-pi-fps-with-python-and-opencv/
class VideoStream:
    """Camera object that controls video streaming from the Picamera"""
    def __init__(self,resolution=(640,480),framerate=30):
        # Initialize the PiCamera and the camera image stream
        self.stream = cv2.VideoCapture(0)
        ret = self.stream.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*'MJPG'))
        ret = self.stream.set(3,resolution[0])
        ret = self.stream.set(4,resolution[1])

        # Read first frame from the stream
        (self.grabbed, self.frame) = self.stream.read()

    # Variable to control when the camera is stopped
        self.stopped = False

    def start(self):
    # Start the thread that reads frames from the video stream
        Thread(target=self.update,args=()).start()
        return self

    def update(self):
        # Keep looping indefinitely until the thread is stopped
        while True:
            # If the camera is stopped, stop the thread
            if self.stopped:
                # Close camera resources
                self.stream.release()
                return

            # Otherwise, grab the next frame from the stream
            (self.grabbed, self.frame) = self.stream.read()

    def read(self):
    # Return the most recent frame
        return self.frame

    def stop(self):
    # Indicate that the camera and thread should be stopped
        self.stopped = True

# Define and parse input arguments
parser = argparse.ArgumentParser()
parser.add_argument('--modeldir', help='Folder the .tflite file is located in',
                    default='/home/pi/TensorFlow')
parser.add_argument('--graph', help='Name of the .tflite file, if different than detect.tflite',
                    default='edgetpu.tflite')
parser.add_argument('--labels', help='Name of the labelmap file, if different than labelmap.txt',
                    default='labelmap.txt')
parser.add_argument('--threshold', help='Minimum confidence threshold for displaying detected objects',
                    default=0.4)
parser.add_argument('--resolution', help='Desired webcam resolution in WxH. If the webcam does not support the resolution entered, errors may occur.',
                    default='640x480')
parser.add_argument('--edgetpu', help='Use Coral Edge TPU Accelerator to speed up detection',
                    default=True,
                    #required=True,
                    action='store_true')

args = parser.parse_args()

MODEL_NAME = args.modeldir
GRAPH_NAME = args.graph
LABELMAP_NAME = args.labels
min_conf_threshold = float(args.threshold)
resW, resH = args.resolution.split('x')
imW, imH = int(resW), int(resH)
use_TPU = args.edgetpu

# Import TensorFlow libraries
# If tflite_runtime is installed, import interpreter from tflite_runtime, else import from regular tensorflow
# If using Coral Edge TPU, import the load_delegate library
pkg = importlib.util.find_spec('tflite_runtime')
if pkg:
    from tflite_runtime.interpreter import Interpreter
    if use_TPU:
        from tflite_runtime.interpreter import load_delegate
else:
    from tensorflow.lite.python.interpreter import Interpreter
    if use_TPU:
        from tensorflow.lite.python.interpreter import load_delegate

GRAPH_NAME = 'edgetpu.tflite'

# Get path to current working directory
CWD_PATH = os.getcwd()

# Path to .tflite file, which contains the model that is used for object detection
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,GRAPH_NAME)

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,MODEL_NAME,LABELMAP_NAME)

# Load the label map
with open(PATH_TO_LABELS, 'r') as f:
    labels = [line.strip() for line in f.readlines()]

# Have to do a weird fix for label map if using the COCO "starter model" from
# https://www.tensorflow.org/lite/models/object_detection/overview
# First label is '???', which has to be removed.
if labels[0] == '???':
    del(labels[0])

# Load the Tensorflow Lite model.
# If using Edge TPU, use special load_delegate argument
if use_TPU:
    interpreter = Interpreter(model_path=PATH_TO_CKPT,
                              experimental_delegates=[load_delegate('libedgetpu.so.1.0')])
    print(PATH_TO_CKPT)
else:
    interpreter = Interpreter(model_path=PATH_TO_CKPT)

interpreter.allocate_tensors()

# Get model details
input_details = interpreter.get_input_details()
output_details = interpreter.get_output_details()
height = input_details[0]['shape'][1]
width = input_details[0]['shape'][2]

floating_model = (input_details[0]['dtype'] == np.float32)

input_mean = 127.5
input_std = 127.5

# Check output layer name to determine if this model was created with TF2 or TF1,
# because outputs are ordered differently for TF2 and TF1 models
outname = output_details[0]['name']

if ('StatefulPartitionedCall' in outname): # This is a TF2 model
    boxes_idx, classes_idx, scores_idx = 1, 3, 0
else: # This is a TF1 model
    boxes_idx, classes_idx, scores_idx = 0, 1, 2

# Initialize frame rate calculation
frame_rate_calc = 1
freq = cv2.getTickFrequency()

# Initialize video stream
videostream = VideoStream(resolution=(imW,imH),framerate=30).start()
time.sleep(1)

#for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
while True:

    # Start timer (for calculating frame rate)
    t1 = cv2.getTickCount()

    # Grab frame from video stream
    frame1 = videostream.read()
    frame1 = cv2.flip(frame1,0)
    # Acquire frame and resize to expected shape [1xHxWx3]
    frame = frame1.copy()
    frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    frame_resized = cv2.resize(frame_rgb, (width, height))
    input_data = np.expand_dims(frame_resized, axis=0)

    # Normalize pixel values if using a floating model (i.e. if model is non-quantized)
    if floating_model:
        input_data = (np.float32(input_data) - input_mean) / input_std

    # Perform the actual detection by running the model with the image as input
    interpreter.set_tensor(input_details[0]['index'],input_data)
    interpreter.invoke()

    # Retrieve detection results
    boxes = interpreter.get_tensor(output_details[boxes_idx]['index'])[0] # Bounding box coordinates of detected objects
    classes = interpreter.get_tensor(output_details[classes_idx]['index'])[0] # Class index of detected objects
    scores = interpreter.get_tensor(output_details[scores_idx]['index'])[0] # Confidence of detected objects

    # Loop over all detections and draw detection box if confidence is above minimum threshold
    for i in range(len(scores)):
        if ((scores[i] > min_conf_threshold) and (scores[i] <= 1.0)):

            # Get bounding box coordinates and draw box
            # Interpreter can return coordinates that are outside of image dimensions, need to force them to be within image using max() and min()
            ymin = int(max(1,(boxes[i][0] * imH)))
            xmin = int(max(1,(boxes[i][1] * imW)))
            ymax = int(min(imH,(boxes[i][2] * imH)))
            xmax = int(min(imW,(boxes[i][3] * imW)))

            cv2.rectangle(frame, (xmin,ymin), (xmax,ymax), (10, 255, 0), 2)

            # Draw label
            object_name = labels[int(classes[i])] # Look up object name from "labels" array using class index
            label = '%s: %d%%' % (object_name, int(scores[i]*100)) # Example: 'person: 72%'
            labelSize, baseLine = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 2) # Get font size
            label_ymin = max(ymin, labelSize[1] + 10) # Make sure not to draw label too close to top of window
            cv2.rectangle(frame, (xmin, label_ymin-labelSize[1]-10), (xmin+labelSize[0], label_ymin+baseLine-10), (255, 255, 255), cv2.FILLED) # Draw white box to put label text in
            cv2.putText(frame, label, (xmin, label_ymin-7), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 0), 2) # Draw label text

             # Draw circle in center
            xcenter = xmin + (int(round((xmax - xmin) / 2)))
            ycenter = ymin + (int(round((ymax - ymin) / 2)))
            cv2.circle(frame, (xcenter, ycenter), 5, (0,0,255), thickness=-1)

            # Print info
            print('Object ' + str(i) + ': ' + object_name + ' at (' + str(xcenter) + ', ' + str(ycenter) + ')')

    # Draw framerate in corner of frame
    cv2.putText(frame,'FPS: {0:.2f}'.format(frame_rate_calc),(30,50),cv2.FONT_HERSHEY_SIMPLEX,1,(255,255,0),2,cv2.LINE_AA)

    # All the results have been drawn on the frame, so it's time to display it.
    cv2.imshow('Object detector', frame)

    # Press 'q' to quit
    if cv2.waitKey(1) == ord('q'):
        break

# Clean up
cv2.destroyAllWindows()
videostream.stop()

I would like to try something in this code but i can't limit the detection to 1 at a time

The object detection and the model itself are good but i want to limit the result to 1 instead of  multiple

this is the whole code i get from the internet

i also tried to add (parse.addArgument --maxResult) but i don't know how to run it in the tflite_runtime

i am new to the codes in python and in using RPi


问:
How can i restrict login to a certain places only? I don't want my users to be login everywhere but the location I choose
Better block mobile data connection first. Before communicate to ur server check device connected IP & Ur wifi address same. If its true, continue to serve data. Make sure device connect via only wifi.</p>


问:
Duplicat data exctraction issue from PDF using python
Good day,

I'm trying to extract quantity,product codes and the document number from pdf document lines using regex and sorting them with nametuples.

My script is stuck in some form of loop.
The pdf document only has one document number  but for each product code there will be a quantity.
What am I doing wrong?

PLease see attached image.

Below is my script:

```<code>import re
import csv
import itertools
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
from collections import namedtuple
import datetime

# Prompt user to select PDF file to scrape
root = Tk()
root.withdraw()
filepath = askopenfilename()

# Define regex pattern to match lines with 1-3 digits followed by a period
digit_pattern = re.compile(r'^(?P<digit>\d{1,3})\.\s*$')

# Define regex pattern to match Product codes
product_code_pattern = re.compile(r'^(600[0-9]{10})')

# Define regex pattern to match Document Numbers
document_number_pattern = re.compile(r"^\d{3}#0*\d{9}$")

# Initialize PDF resource manager and text converter
rsrcmgr = PDFResourceManager()
sio = StringIO()
codec = 'utf-8'
laparams = LAParams()
converter = TextConverter(rsrcmgr, sio, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, converter)

# Extract text from PDF and search for lines that match the pattern
with open(filepath, 'rb') as file:
    for page in PDFPage.get_pages(file):
        interpreter.process_page(page)
    lines = sio.getvalue().splitlines()
    digit_matches = [line for line in lines if digit_pattern.match(line) and digit_pattern.search(line).group('digit')!='0']
    product_code_matches = [line for line in lines if product_code_pattern.match(line)]
    document_number_matches = [line for line in lines if document_number_pattern.match(line)]

# Create namedtuples and add matches
Invoice = namedtuple('Invoice','qty product_code document_number')
invoice = []
for digit_match, product_code_match, document_number_match in itertools.product(digit_matches, product_code_matches, document_number_matches):
    invoice.append(Invoice(digit_match, product_code_match,document_number_match))

# Save results to CSV file with current date and timestamp
now = datetime.datetime.now()
filename = f"Output_{now.strftime('%Y-%m-%d %H-%M-%S')}.csv"
with open(filename, mode='w', newline='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(Invoice._fields)
    for row in invoice:
        writer.writerow(row)
# Clean up
converter.close()
sio.close()
print(f'Scraped data saved to {filename}')

</code>```

I want to scrape quantity,product code and document number from pdf documents and have them sorted with namedtuples

Below are the output data using the print statement:

Invoice(qty='24.', product_code='6005277000108', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000788', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000115', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000122', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839056', document_number='228#000009083')
Invoice(qty='24.', product_code='6009888389102', document_number='228#000009083')
Invoice(qty='24.', product_code='6009888389119', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277001501', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839100', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000023', document_number='228#000009083')
Invoice(qty='24.', product_code='6009888389157', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839322', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839902', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839940', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839872', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839797', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839827', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839421', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839414', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839957', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839759', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277009453', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839742', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000108', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000788', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000115', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000122', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839056', document_number='228#000009083')
Invoice(qty='10.', product_code='6009888389102', document_number='228#000009083')
Invoice(qty='10.', product_code='6009888389119', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277001501', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839100', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000023', document_number='228#000009083')
Invoice(qty='10.', product_code='6009888389157', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839322', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839902', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839940', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839872', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839797', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839827', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839421', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839414', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839957', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839759', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277009453', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839742', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000108', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000788', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000115', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000122', document_number='228#000009083')
Invoice(qty='20.', product_code='6009880839056', document_number='228#000009083')
Invoice(qty='20.', product_code='6009888389102', document_number='228#000009083')
Invoice(qty='20.', product_code='6009888389119', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277001501', document_number='228#000009083')

so basicly it repeats qty until all the product codes has been scraped and then moves onto the next QTY and starts at the top with the product codes .

Body:
Good day,

I'm trying to extract quantity,product codes and the document number from pdf document lines using regex and sorting them with nametuples.

My script is stuck in some form of loop.
The pdf document only has one document number  but for each product code there will be a quantity.
What am I doing wrong?

PLease see attached image.

Below is my script:

import re
import csv
import itertools
from tkinter import Tk
from tkinter.filedialog import askopenfilename
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from io import StringIO
from collections import namedtuple
import datetime

# Prompt user to select PDF file to scrape
root = Tk()
root.withdraw()
filepath = askopenfilename()

# Define regex pattern to match lines with 1-3 digits followed by a period
digit_pattern = re.compile(r'^(?P<digit>\d{1,3})\.\s*$')

# Define regex pattern to match Product codes
product_code_pattern = re.compile(r'^(600[0-9]{10})')

# Define regex pattern to match Document Numbers
document_number_pattern = re.compile(r"^\d{3}#0*\d{9}$")

# Initialize PDF resource manager and text converter
rsrcmgr = PDFResourceManager()
sio = StringIO()
codec = 'utf-8'
laparams = LAParams()
converter = TextConverter(rsrcmgr, sio, codec=codec, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, converter)

# Extract text from PDF and search for lines that match the pattern
with open(filepath, 'rb') as file:
    for page in PDFPage.get_pages(file):
        interpreter.process_page(page)
    lines = sio.getvalue().splitlines()
    digit_matches = [line for line in lines if digit_pattern.match(line) and digit_pattern.search(line).group('digit')!='0']
    product_code_matches = [line for line in lines if product_code_pattern.match(line)]
    document_number_matches = [line for line in lines if document_number_pattern.match(line)]

# Create namedtuples and add matches
Invoice = namedtuple('Invoice','qty product_code document_number')
invoice = []
for digit_match, product_code_match, document_number_match in itertools.product(digit_matches, product_code_matches, document_number_matches):
    invoice.append(Invoice(digit_match, product_code_match,document_number_match))

# Save results to CSV file with current date and timestamp
now = datetime.datetime.now()
filename = f"Output_{now.strftime('%Y-%m-%d %H-%M-%S')}.csv"
with open(filename, mode='w', newline='') as file:
    writer = csv.writer(file, delimiter=',')
    writer.writerow(Invoice._fields)
    for row in invoice:
        writer.writerow(row)
# Clean up
converter.close()
sio.close()
print(f'Scraped data saved to {filename}')

I want to scrape quantity,product code and document number from pdf documents and have them sorted with namedtuples

Below are the output data using the print statement:

Invoice(qty='24.', product_code='6005277000108', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000788', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000115', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000122', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839056', document_number='228#000009083')
Invoice(qty='24.', product_code='6009888389102', document_number='228#000009083')
Invoice(qty='24.', product_code='6009888389119', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277001501', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839100', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277000023', document_number='228#000009083')
Invoice(qty='24.', product_code='6009888389157', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839322', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839902', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839940', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839872', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839797', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839827', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839421', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839414', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839957', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839759', document_number='228#000009083')
Invoice(qty='24.', product_code='6005277009453', document_number='228#000009083')
Invoice(qty='24.', product_code='6009880839742', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000108', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000788', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000115', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000122', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839056', document_number='228#000009083')
Invoice(qty='10.', product_code='6009888389102', document_number='228#000009083')
Invoice(qty='10.', product_code='6009888389119', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277001501', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839100', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277000023', document_number='228#000009083')
Invoice(qty='10.', product_code='6009888389157', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839322', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839902', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839940', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839872', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839797', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839827', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839421', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839414', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839957', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839759', document_number='228#000009083')
Invoice(qty='10.', product_code='6005277009453', document_number='228#000009083')
Invoice(qty='10.', product_code='6009880839742', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000108', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000788', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000115', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277000122', document_number='228#000009083')
Invoice(qty='20.', product_code='6009880839056', document_number='228#000009083')
Invoice(qty='20.', product_code='6009888389102', document_number='228#000009083')
Invoice(qty='20.', product_code='6009888389119', document_number='228#000009083')
Invoice(qty='20.', product_code='6005277001501', document_number='228#000009083')

so basicly it repeats qty until all the product codes has been scraped and then moves onto the next QTY and starts at the top with the product codes .


问:
Does sequelize 7.0.0-alpha.4 prevent sql injection with mysql raw query?
I am using below code for update but i need to prevent sql injection in this query.

```<code>const query1 = `UPDATE Table SET name='xyz' WHERE id=1`;
const saveEditPost = await sequelizeWrite.query(query1, { type: sequelizeWrite.QueryTypes.UPDATE });
</code>```

How to prevent sql injection in the code using sequelize? i have used sequelize in my entire projects to change the package will be a challenge.

Body:
I am using below code for update but i need to prevent sql injection in this query.

const query1 = `UPDATE Table SET name='xyz' WHERE id=1`;
const saveEditPost = await sequelizeWrite.query(query1, { type: sequelizeWrite.QueryTypes.UPDATE });

How to prevent sql injection in the code using sequelize? i have used sequelize in my entire projects to change the package will be a challenge.


问:
Azure Scale Set Could not find the modules: 'Az.Accounts' with Version: ''
We created a Windows 2022 Data Centre Edition Scale Set set up as a Dev Ops agent pool yesterday.

I have an Agent Job that uses this agent pool. This job has a single inline Azure Powershell task.

Task Version: 5.*

Inline Script:

```<code>Write-Output "STUFF WORKS"
</code>```

Azure Powershell Version: "Latest installed version

This gives me the error:

```<code>2023-01-13T10:15:17.6969002Z ##[error]Could not find the modules: 'Az.Accounts' with Version: ''. If the module was recently installed, retry after restarting the Azure Pipelines task agent.
2023-01-13T10:15:19.3308359Z ##[error]PowerShell exited with code '1'.
</code>```

with the whole stage output being:

```<code>2023-01-13T10:15:12.2607076Z ##[section]Starting: Test Task
2023-01-13T10:15:12.2806115Z ==============================================================================
2023-01-13T10:15:12.2806386Z Task         : Azure PowerShell
2023-01-13T10:15:12.2806528Z Description  : Run a PowerShell script within an Azure environment
2023-01-13T10:15:12.2806753Z Version      : 5.209.0
2023-01-13T10:15:12.2806898Z Author       : Microsoft Corporation
2023-01-13T10:15:12.2807054Z Help         : https://aka.ms/azurepowershelltroubleshooting
2023-01-13T10:15:12.2807227Z ==============================================================================
2023-01-13T10:15:15.3504901Z Generating script.
2023-01-13T10:15:15.3776658Z ========================== Starting Command Output ===========================
2023-01-13T10:15:15.4059002Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\a\_temp\7baa15ed-a6fe-44a4-a586-ee2342cb9868.ps1'"
2023-01-13T10:15:17.0046974Z Added TLS 1.2 in session.
2023-01-13T10:15:17.6969002Z ##[error]Could not find the modules: 'Az.Accounts' with Version: ''. If the module was recently installed, retry after restarting the Azure Pipelines task agent.
2023-01-13T10:15:19.3308359Z ##[error]PowerShell exited with code '1'.
2023-01-13T10:15:19.7131608Z Added TLS 1.2 in session.
2023-01-13T10:15:21.5490716Z ##[section]Finishing: Test Task
</code>```

Any idea what I am doing wrong?

By my understanding the 2022 image already includes all of the expected modules so I've made no attempt to install them on the VM manually (something I would like to avoid)

Edit

It appears the behaviour of an Azure Powershell task for an Azure Pipeline Agent is different to a self hosted Scale Set Agent.

Azure Pipelines Output

```<code>2023-01-16T10:37:38.6306969Z ##[section]Starting: Azure PowerShell
2023-01-16T10:37:38.6580681Z ==============================================================================
2023-01-16T10:37:38.6581062Z Task         : Azure PowerShell
2023-01-16T10:37:38.6581238Z Description  : Run a PowerShell script within an Azure environment
2023-01-16T10:37:38.6581486Z Version      : 5.209.0
2023-01-16T10:37:38.6581645Z Author       : Microsoft Corporation
2023-01-16T10:37:38.6581853Z Help         : https://aka.ms/azurepowershelltroubleshooting
2023-01-16T10:37:38.6582079Z ==============================================================================
2023-01-16T10:37:41.3655258Z Az version 8.3.0 not avaiable locally on the agent. Downloading dynamically.
2023-01-16T10:37:44.8252804Z
2023-01-16T10:37:44.8266994Z 7-Zip [64] 16.00 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-10
2023-01-16T10:37:44.8269675Z
2023-01-16T10:37:44.8270653Z Scanning the drive for archives:
2023-01-16T10:37:44.8271434Z 1 file, 67255559 bytes (65 MiB)
2023-01-16T10:37:44.8271762Z
2023-01-16T10:37:44.8273450Z Extracting archive: C:\Modules\az_8.3.0.zip
2023-01-16T10:38:01.5690462Z --
2023-01-16T10:38:01.5691333Z Path = C:\Modules\az_8.3.0.zip
2023-01-16T10:38:01.5691869Z Type = zip
2023-01-16T10:38:01.5692380Z Physical Size = 67255559
2023-01-16T10:38:01.5692646Z
2023-01-16T10:38:01.5737463Z Everything is Ok
2023-01-16T10:38:01.5738875Z
2023-01-16T10:38:01.5739352Z Folders: 81
2023-01-16T10:38:01.5739804Z Files: 1282
2023-01-16T10:38:01.5740267Z Size:       319427095
2023-01-16T10:38:01.5740807Z Compressed: 67255559
2023-01-16T10:38:01.6565020Z Generating script.
2023-01-16T10:38:01.7303016Z ========================== Starting Command Output ===========================
2023-01-16T10:38:01.7659410Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\500f8cc1-703a-4fd9-a989-b5dd273da179.ps1'"
2023-01-16T10:38:04.3997844Z Added TLS 1.2 in session.
2023-01-16T10:38:05.4501759Z ##[command]Import-Module -Name C:\Modules\az_8.3.0\Az.Accounts\2.10.0\Az.Accounts.psd1 -Global
2023-01-16T10:38:06.9713804Z WARNING: Both Az and AzureRM modules were detected on this machine. Az and AzureRM modules cannot be imported in the
2023-01-16T10:38:06.9716098Z same session or used in the same script or runbook. If you are running PowerShell in an environment you control you can
2023-01-16T10:38:06.9716799Z  use the 'Uninstall-AzureRm' cmdlet to remove all AzureRm modules from your machine. If you are running in Azure
2023-01-16T10:38:06.9717481Z Automation, take care that none of your runbooks import both Az and AzureRM modules. More information can be found
2023-01-16T10:38:06.9721294Z here: https://aka.ms/azps-migration-guide
2023-01-16T10:38:11.2344046Z ##[command]Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
2023-01-16T10:38:16.0123806Z ##[command]Clear-AzContext -Scope Process
2023-01-16T10:38:16.2401459Z ##[command]Connect-AzAccount -ServicePrincipal -Tenant a76dcc71-5c97-4ed5-aa1f-0da680d1cac6 -Credential System.Management.Automation.PSCredential -Environment AzureCloud @processScope
2023-01-16T10:38:19.6273814Z ##[command] Set-AzContext -SubscriptionId 74fcd14b-fee9-4a50-9473-80759d0fd501 -TenantId a76dcc71-5c97-4ed5-aa1f-0da680d1cac6
2023-01-16T10:38:20.1588404Z Hello World!
2023-01-16T10:38:20.5851719Z Added TLS 1.2 in session.
2023-01-16T10:38:23.8606507Z ##[section]Finishing: Azure PowerShell
</code>```

Self Hosted Scale Set

```<code>2023-01-16T10:31:31.7097135Z ##[section]Starting: Azure PowerShell
2023-01-16T10:31:31.7201130Z ==============================================================================
2023-01-16T10:31:31.7201358Z Task         : Azure PowerShell
2023-01-16T10:31:31.7201494Z Description  : Run a PowerShell script within an Azure environment
2023-01-16T10:31:31.7201678Z Version      : 5.209.0
2023-01-16T10:31:31.7201792Z Author       : Microsoft Corporation
2023-01-16T10:31:31.7201928Z Help         : https://aka.ms/azurepowershelltroubleshooting
2023-01-16T10:31:31.7202096Z ==============================================================================
2023-01-16T10:31:33.1732716Z Generating script.
2023-01-16T10:31:33.1983231Z ========================== Starting Command Output ===========================
2023-01-16T10:31:33.2192281Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\a\_temp\4d87de77-f8f7-42fa-a3c9-b74c90364e48.ps1'"
2023-01-16T10:31:35.1895949Z Added TLS 1.2 in session.
2023-01-16T10:31:35.7608704Z ##[error]Could not find the modules: 'Az.Accounts' with Version: '8.3.0'. If the module was recently installed, retry after restarting the Azure Pipelines task agent.
2023-01-16T10:31:35.9925131Z ##[error]PowerShell exited with code '1'.
2023-01-16T10:31:36.1584011Z Added TLS 1.2 in session.
2023-01-16T10:31:37.3200590Z ##[section]Finishing: Azure PowerShell
</code>```

Notice that the former makes an attempt to install Az via Extracting archive: C:\Modules\az_8.3.0.zip where as the latter doesn't.

Body:
We created a Windows 2022 Data Centre Edition Scale Set set up as a Dev Ops agent pool yesterday.

I have an Agent Job that uses this agent pool. This job has a single inline Azure Powershell task.

Task Version: 5.*

Inline Script:

Write-Output "STUFF WORKS"

Azure Powershell Version: "Latest installed version

This gives me the error:

2023-01-13T10:15:17.6969002Z ##[error]Could not find the modules: 'Az.Accounts' with Version: ''. If the module was recently installed, retry after restarting the Azure Pipelines task agent.
2023-01-13T10:15:19.3308359Z ##[error]PowerShell exited with code '1'.

with the whole stage output being:

2023-01-13T10:15:12.2607076Z ##[section]Starting: Test Task
2023-01-13T10:15:12.2806115Z ==============================================================================
2023-01-13T10:15:12.2806386Z Task         : Azure PowerShell
2023-01-13T10:15:12.2806528Z Description  : Run a PowerShell script within an Azure environment
2023-01-13T10:15:12.2806753Z Version      : 5.209.0
2023-01-13T10:15:12.2806898Z Author       : Microsoft Corporation
2023-01-13T10:15:12.2807054Z Help         : https://aka.ms/azurepowershelltroubleshooting
2023-01-13T10:15:12.2807227Z ==============================================================================
2023-01-13T10:15:15.3504901Z Generating script.
2023-01-13T10:15:15.3776658Z ========================== Starting Command Output ===========================
2023-01-13T10:15:15.4059002Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\a\_temp\7baa15ed-a6fe-44a4-a586-ee2342cb9868.ps1'"
2023-01-13T10:15:17.0046974Z Added TLS 1.2 in session.
2023-01-13T10:15:17.6969002Z ##[error]Could not find the modules: 'Az.Accounts' with Version: ''. If the module was recently installed, retry after restarting the Azure Pipelines task agent.
2023-01-13T10:15:19.3308359Z ##[error]PowerShell exited with code '1'.
2023-01-13T10:15:19.7131608Z Added TLS 1.2 in session.
2023-01-13T10:15:21.5490716Z ##[section]Finishing: Test Task

Any idea what I am doing wrong?

By my understanding the 2022 image already includes all of the expected modules so I've made no attempt to install them on the VM manually (something I would like to avoid)

Edit

It appears the behaviour of an Azure Powershell task for an Azure Pipeline Agent is different to a self hosted Scale Set Agent.

Azure Pipelines Output

2023-01-16T10:37:38.6306969Z ##[section]Starting: Azure PowerShell
2023-01-16T10:37:38.6580681Z ==============================================================================
2023-01-16T10:37:38.6581062Z Task         : Azure PowerShell
2023-01-16T10:37:38.6581238Z Description  : Run a PowerShell script within an Azure environment
2023-01-16T10:37:38.6581486Z Version      : 5.209.0
2023-01-16T10:37:38.6581645Z Author       : Microsoft Corporation
2023-01-16T10:37:38.6581853Z Help         : https://aka.ms/azurepowershelltroubleshooting
2023-01-16T10:37:38.6582079Z ==============================================================================
2023-01-16T10:37:41.3655258Z Az version 8.3.0 not avaiable locally on the agent. Downloading dynamically.
2023-01-16T10:37:44.8252804Z
2023-01-16T10:37:44.8266994Z 7-Zip [64] 16.00 : Copyright (c) 1999-2016 Igor Pavlov : 2016-05-10
2023-01-16T10:37:44.8269675Z
2023-01-16T10:37:44.8270653Z Scanning the drive for archives:
2023-01-16T10:37:44.8271434Z 1 file, 67255559 bytes (65 MiB)
2023-01-16T10:37:44.8271762Z
2023-01-16T10:37:44.8273450Z Extracting archive: C:\Modules\az_8.3.0.zip
2023-01-16T10:38:01.5690462Z --
2023-01-16T10:38:01.5691333Z Path = C:\Modules\az_8.3.0.zip
2023-01-16T10:38:01.5691869Z Type = zip
2023-01-16T10:38:01.5692380Z Physical Size = 67255559
2023-01-16T10:38:01.5692646Z
2023-01-16T10:38:01.5737463Z Everything is Ok
2023-01-16T10:38:01.5738875Z
2023-01-16T10:38:01.5739352Z Folders: 81
2023-01-16T10:38:01.5739804Z Files: 1282
2023-01-16T10:38:01.5740267Z Size:       319427095
2023-01-16T10:38:01.5740807Z Compressed: 67255559
2023-01-16T10:38:01.6565020Z Generating script.
2023-01-16T10:38:01.7303016Z ========================== Starting Command Output ===========================
2023-01-16T10:38:01.7659410Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'D:\a\_temp\500f8cc1-703a-4fd9-a989-b5dd273da179.ps1'"
2023-01-16T10:38:04.3997844Z Added TLS 1.2 in session.
2023-01-16T10:38:05.4501759Z ##[command]Import-Module -Name C:\Modules\az_8.3.0\Az.Accounts\2.10.0\Az.Accounts.psd1 -Global
2023-01-16T10:38:06.9713804Z WARNING: Both Az and AzureRM modules were detected on this machine. Az and AzureRM modules cannot be imported in the
2023-01-16T10:38:06.9716098Z same session or used in the same script or runbook. If you are running PowerShell in an environment you control you can
2023-01-16T10:38:06.9716799Z  use the 'Uninstall-AzureRm' cmdlet to remove all AzureRm modules from your machine. If you are running in Azure
2023-01-16T10:38:06.9717481Z Automation, take care that none of your runbooks import both Az and AzureRM modules. More information can be found
2023-01-16T10:38:06.9721294Z here: https://aka.ms/azps-migration-guide
2023-01-16T10:38:11.2344046Z ##[command]Clear-AzContext -Scope CurrentUser -Force -ErrorAction SilentlyContinue
2023-01-16T10:38:16.0123806Z ##[command]Clear-AzContext -Scope Process
2023-01-16T10:38:16.2401459Z ##[command]Connect-AzAccount -ServicePrincipal -Tenant a76dcc71-5c97-4ed5-aa1f-0da680d1cac6 -Credential System.Management.Automation.PSCredential -Environment AzureCloud @processScope
2023-01-16T10:38:19.6273814Z ##[command] Set-AzContext -SubscriptionId 74fcd14b-fee9-4a50-9473-80759d0fd501 -TenantId a76dcc71-5c97-4ed5-aa1f-0da680d1cac6
2023-01-16T10:38:20.1588404Z Hello World!
2023-01-16T10:38:20.5851719Z Added TLS 1.2 in session.
2023-01-16T10:38:23.8606507Z ##[section]Finishing: Azure PowerShell

Self Hosted Scale Set

2023-01-16T10:31:31.7097135Z ##[section]Starting: Azure PowerShell
2023-01-16T10:31:31.7201130Z ==============================================================================
2023-01-16T10:31:31.7201358Z Task         : Azure PowerShell
2023-01-16T10:31:31.7201494Z Description  : Run a PowerShell script within an Azure environment
2023-01-16T10:31:31.7201678Z Version      : 5.209.0
2023-01-16T10:31:31.7201792Z Author       : Microsoft Corporation
2023-01-16T10:31:31.7201928Z Help         : https://aka.ms/azurepowershelltroubleshooting
2023-01-16T10:31:31.7202096Z ==============================================================================
2023-01-16T10:31:33.1732716Z Generating script.
2023-01-16T10:31:33.1983231Z ========================== Starting Command Output ===========================
2023-01-16T10:31:33.2192281Z ##[command]"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\a\_temp\4d87de77-f8f7-42fa-a3c9-b74c90364e48.ps1'"
2023-01-16T10:31:35.1895949Z Added TLS 1.2 in session.
2023-01-16T10:31:35.7608704Z ##[error]Could not find the modules: 'Az.Accounts' with Version: '8.3.0'. If the module was recently installed, retry after restarting the Azure Pipelines task agent.
2023-01-16T10:31:35.9925131Z ##[error]PowerShell exited with code '1'.
2023-01-16T10:31:36.1584011Z Added TLS 1.2 in session.
2023-01-16T10:31:37.3200590Z ##[section]Finishing: Azure PowerShell

Notice that the former makes an attempt to install Az via Extracting archive: C:\Modules\az_8.3.0.zip where as the latter doesn't.


问:
"Uncaught ReferenceError: global is not defined" with Vite
I'm getting the error from the title in my Vue app with Vite. I seem to have tried everything that I could find online but nothing really seems to work in my case.

The problem started when I installed aws-sdk to connect to my linode bucket storage, and importing it like import aws from 'aws-sdk'.

I tried almost everything from this issue, and quite a few variants from that in vite.config.js that I found elsewhere.

When using the following in my vite.config.js it works in dev:

```<code>define: {
   global: "window",
},
</code>```

But gives me the following error in prod:

```<code>[vite]: Rollup failed to resolve import "aws-sdk" from "/var/www/html/kwigy/src/linode.js".
[...]
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
[...]
</code>```

And that doesn't seem to be a good solution anyway according to what I found online.

Adding a script to the  tag or making a file that imports the said script in main.js also works in dev but gives the same error in prod.

I also tried to install requirejs, to use it as const aws = require('aws-sdk') but I have to admit I do not really understand how to configure that from the docs.

Does anybody have a solution to my problem? I have been stuck for a full day on this now.

Body:
I'm getting the error from the title in my Vue app with Vite. I seem to have tried everything that I could find online but nothing really seems to work in my case.

The problem started when I installed aws-sdk to connect to my linode bucket storage, and importing it like import aws from 'aws-sdk'.

I tried almost everything from this issue, and quite a few variants from that in vite.config.js that I found elsewhere.

When using the following in my vite.config.js it works in dev:

define: {
   global: "window",
},

But gives me the following error in prod:

[vite]: Rollup failed to resolve import "aws-sdk" from "/var/www/html/kwigy/src/linode.js".
[...]
If you do want to externalize this module explicitly add it to
`build.rollupOptions.external`
[...]

And that doesn't seem to be a good solution anyway according to what I found online.

Adding a script to the  tag or making a file that imports the said script in main.js also works in dev but gives the same error in prod.

I also tried to install requirejs, to use it as const aws = require('aws-sdk') but I have to admit I do not really understand how to configure that from the docs.

Does anybody have a solution to my problem? I have been stuck for a full day on this now.


问:
My App was suspended in background state by iOS when there is an active VoIP Call
I develop a VoIP call application. The problematic scenario is like below

App is in background state and the device is locked

App receives a    VoIP Push for an incoming call

App reports an incomingCall to the    CallKit and I start a
background task for 10 seconds

User answers the    call

Call is established and I end the background task (so it was active for just 10 secs)

After 13 secs of incoming call received, iOS suspends my app and
the call ends.

So, I would expect iOS to not suspend my app when there is an active CallKit call.
What would be wrong here, What would you suggest?

Here are what background modes I use in the app

Thanks in advance for your help in advance.


问:
GCP Cloud SQL (PostgreSQL) Backups remain after deleting the isntance
We have recently started using GCP Cloud SQL, and have been testing backup and restores.  We have done the following and seem to have backups that are not associated with an instance, and we can't remove them.

We created a database and have started using it.
We created a backup schedule for the database backup and wanted to test the restoration process.
We created a clone of the database, and then tested a restore from the original backup.  This was all fine and worked as expected.
We left the clone running for a few days, then decided that it was not needed anymore.
We deleted the clone, but by this point, it had created a few backups.
If we run the

```<code>gcloud sql backups list --instance -
</code>```

It shows all backups, including 3 from the deleted instance, this is strange, as backups are supposed to be removed when the instance is deleted (if they are automated).  If try to run

```<code>gcloud sql backups delete [ID]
</code>```

I get a http403 error saying not authorized (I am a GCP admin, so have all permissions)

We have tried re-creating the instance with the same name, but the backups are presumably linked via an ID, not name.

Does anyone know:

a) Will we be changed for this?
b) Is there a way to delete these
c) it may well be a legitimate scenario to want to keep backups, and may be restore them later.  the restoration process does not work for these orphaned backups, we have tried
d) I found this post, does anyone know if Google have progressed this?

Any help on this would be much appreciated.

Body:
We have recently started using GCP Cloud SQL, and have been testing backup and restores.  We have done the following and seem to have backups that are not associated with an instance, and we can't remove them.

We created a database and have started using it.
We created a backup schedule for the database backup and wanted to test the restoration process.
We created a clone of the database, and then tested a restore from the original backup.  This was all fine and worked as expected.
We left the clone running for a few days, then decided that it was not needed anymore.
We deleted the clone, but by this point, it had created a few backups.
If we run the

gcloud sql backups list --instance -

It shows all backups, including 3 from the deleted instance, this is strange, as backups are supposed to be removed when the instance is deleted (if they are automated).  If try to run

gcloud sql backups delete [ID]

I get a http403 error saying not authorized (I am a GCP admin, so have all permissions)

We have tried re-creating the instance with the same name, but the backups are presumably linked via an ID, not name.

Does anyone know:

a) Will we be changed for this?
b) Is there a way to delete these
c) it may well be a legitimate scenario to want to keep backups, and may be restore them later.  the restoration process does not work for these orphaned backups, we have tried
d) I found this post, does anyone know if Google have progressed this?

Any help on this would be much appreciated.


问:
Apply a function to each edge in a MultiDiGraph in networkx library
As the title suggests, I'm wondering if there's a way to use a function on each edge of a MultiDiGraph without resorting to a loop cycle, like what I would do with a pandas dataframe and apply() function.

One solution that comes to mind is converting the graph into a pandas dataframe and then using apply(), but this is something I would prefer to avoid, if not absolutely necessary.