问:
I am getting FileNotFoundError when that file does exist in moviepy
code:

```<code>from moviepy.editor import *
import os

Pictures = []

Path = 'Pictures_To_Use'

#Adding Pics to the Pictures arrray
for pics in os.listdir(Path):
    clips = ImageClip(pics).set_duration(5)
    Pictures.append(Path + "/" + pics)

#UI
Title = input("Please input a title:")
print("-" * 36)
print("Title:" + Title)
print("-" * 36)
print("The Following Pictures will be Used:")
print(Pictures)
print("-" * 36)

#Export video
video = concatenate_videoclips(clips, method="compose")
video.write_videofile(Title, fps=30)

</code>```

error:

```<code>PS C:\Users\GeekZoid\Desktop\YTVideo Maker> python -u "c:\Users\GeekZoid\Desktop\YTVideo Maker\Main.py"
Traceback (most recent call last):
  File "c:\Users\GeekZoid\Desktop\YTVideo Maker\Main.py", line 10, in <module>
    clips = ImageClip(pics).set_duration(5)
            ^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\moviepy\video\VideoClip.py", line 889, in __init__
    img = imread(img)
          ^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\__init__.py", line 97, in imread
    return imread_v2(uri, format=format, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\v2.py", line 226, in imread
    with imopen(uri, "ri", **imopen_args) as file:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\core\imopen.py", line 113, in imopen
    request = Request(uri, io_mode, format_hint=format_hint, extension=extension)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\core\request.py", line 248, in __init__
    self._parse_uri(uri)
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\core\request.py", line 408, in _parse_uri
    raise FileNotFoundError("No such file: '%s'" % fn)
FileNotFoundError: No such file: 'C:\Users\GeekZoid\Desktop\YTVideo Maker\Meme1.jpg
</code>```

I have tried appending the File to an array as a path. I also tried using a for loop to run through the pictures array to set the duration of the pictures, But none of those solutions worked

Body:
code:

from moviepy.editor import *
import os

Pictures = []

Path = 'Pictures_To_Use'

#Adding Pics to the Pictures arrray
for pics in os.listdir(Path):
    clips = ImageClip(pics).set_duration(5)
    Pictures.append(Path + "/" + pics)

#UI
Title = input("Please input a title:")
print("-" * 36)
print("Title:" + Title)
print("-" * 36)
print("The Following Pictures will be Used:")
print(Pictures)
print("-" * 36)

#Export video
video = concatenate_videoclips(clips, method="compose")
video.write_videofile(Title, fps=30)

error:

PS C:\Users\GeekZoid\Desktop\YTVideo Maker> python -u "c:\Users\GeekZoid\Desktop\YTVideo Maker\Main.py"
Traceback (most recent call last):
  File "c:\Users\GeekZoid\Desktop\YTVideo Maker\Main.py", line 10, in <module>
    clips = ImageClip(pics).set_duration(5)
            ^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\moviepy\video\VideoClip.py", line 889, in __init__
    img = imread(img)
          ^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\__init__.py", line 97, in imread
    return imread_v2(uri, format=format, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\v2.py", line 226, in imread
    with imopen(uri, "ri", **imopen_args) as file:
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\core\imopen.py", line 113, in imopen
    request = Request(uri, io_mode, format_hint=format_hint, extension=extension)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\core\request.py", line 248, in __init__
    self._parse_uri(uri)
  File "C:\Users\GeekZoid\AppData\Local\Programs\Python\Python311\Lib\site-packages\imageio\core\request.py", line 408, in _parse_uri
    raise FileNotFoundError("No such file: '%s'" % fn)
FileNotFoundError: No such file: 'C:\Users\GeekZoid\Desktop\YTVideo Maker\Meme1.jpg

I have tried appending the File to an array as a path. I also tried using a for loop to run through the pictures array to set the duration of the pictures, But none of those solutions worked


来源: stackexchange

问:
Does WP7 or Mango support Vcard (vcf files) with photo?
I am trying to import a vcf file with a photo (encoding base64).
When I click on the vcf file through the web browser or the email, I get a dialog with the contacts details but the photo is not added.
I tried to create other vcf files using some online tools like this one [http://mobile.dangooli.com/vCard/]
but I get the same result, no photo is added.

Is there any way to add a contact with a photo by just clicking on a file?
Does wp7 or mango support another protocol for importing contacts with photos?

Or are the photos diregarded deliberately?

Thank you

ContentLicense: CC BY-SA 3.0


问:
Combine find and mongoexport in mongodb
I am new to MongoDB,
I have 3 collections, Order, Order_events and Order_tasks.
Each order_id in the Order collection has an entry in Order_Events and Order_tasks.

I am trying to write a shell script to use db.Order.find() and combine it with mongoexport to export collections Order_Events and Order_tasks,

According to the documentation for mongoexport , it needs --host or --uri. As I am already using the connection string for the find(),is it possible to combine the result of this find() to be used in a 'mongoexport` command?

Sample query inside my mongodb.sh file

```<code>mongo -u $user -p "$pass" "mongodb://$server/$db?readPreference=primaryPreferred"\
--authenticationDatabase $db\
--eval " try { var cursor = db.order.find( { 'state': { \$in: ['Failed','Rejected','Cancelled','Completed'] }},{'orderId':1,'state':1, '_id':0} ); while (cursor.hasNext()){
                   var value=cursor.next();
                   print(tojson(value.orderId));}}catch(e){print(e);}"
</code>```

I am getting syntax error when I write an export inside the while loop. I am assuming that this way is incorrect.

```<code>while (cursor.hasNext()){
                   var value=cursor.next();

   var id=value.orderId;
   print(id);
   mongoexport --collection=Order_Events --type=json --out=/application-backup/file.json
   }}catch(e){print(e);}"

Percona Server for MongoDB server version: v5.0.8-7
uncaught exception: SyntaxError: unexpected token: identifier :
@(shell eval):6:17
exiting with code -4

</code>```

if I just write mongoexport

```<code>while (cursor.hasNext()){
                   var value=cursor.next();

   var id=value.orderId;
   print(id);
   mongoexport
   }}catch(e){print(e);}"

Percona Server for MongoDB server version: v5.0.8-7
136dbc41-2020-40d9-9ad7-affbc215fcfb
ReferenceError: mongoexport is not defined

</code>```

UPDATE

I was able to execute this by running the find() first and storing the value to a text file, then reading the values into an export command

```<code>mongo -u $user -p "$pass" \
                  "mongodb://$server/$db?readPreference=primaryPreferred" \
                  --authenticationDatabase $authenticationDatabase \
                  --eval "
                    try {

                      var cursor = db.order.find({ 'state': { \$in: ['Failed','Rejected'] }},{'orderId':1,'state':1, '_id':0}).pretty()
                      while ( cursor.hasNext() ) {
                        var record = cursor.next();
                        var id=record.orderId;
                        print(id);
                      }
                    } catch(e) {
                      print(e);
                    }" > /application-backup/orderids.txt

                    echo "reading files"
                    file=$(cat /application-backup/orderids.txt)
                    for line in $file
                    do
                        #the generated text file contains strings that are irrelevant for the mongoexport command
                        pattern='^\{?[A-Z0-9a-z]{8}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{12}\}?$'
                        if [[ "$line" =~ $pattern ]]; then

                          mongoexport --db=$authenticationDatabase --collection=orderProcessEvent  --type=json  --out=/application-backup/orderProcessEvent-$line.json  --uri=$uriString -u $user -p $pass --query='{"orderId":"'$line'","eventCategory":"ORDER_LIFECYCLE_EVENT"}'
                        fi
                    done
</code>```

this gives an output like this

```<code>-rw-r--r--. 1 mongod bin   2121 Dec 21 14:57 orderProcessEvent-d1c3ddea-c9b8-41da-9250-dcf51848c55b.json
-rw-r--r--. 1 mongod bin   2494 Dec 21 14:57 orderProcessEvent-d2b9631a-1aac-4e79-ab2c-ab2594df21a8.json
-rw-r--r--. 1 mongod bin   2018 Dec 21 14:57 orderProcessEvent-d360c0af-921d-4f08-bd52-a138e04b3157.json
-rw-r--r--. 1 mongod bin   2018 Dec 21 14:57 orderProcessEvent-d42b33a3-4c45-410b-a988-3842eb24dbff.json
-rw-r--r--. 1 mongod bin   1647 Dec 21 14:57 orderProcessEvent-d5351941-8247-4679-aeb4-0fec3b225748.json
-rw-r--r--. 1 mongod bin   2019 Dec 21 14:57 orderProcessEvent-d92c3d87-5722-42d9-8133-a44b3125b368.json
-rw-r--r--. 1 mongod bin   1646 Dec 21 14:57 orderProcessEvent-d93fbe3c-8eab-4265-b7c3-b40e159cfd40.json
-rw-r--r--. 1 mongod bin      0 Dec 21 14:57 orderProcessEvent-d94185b8-b892-43d7-8f67-4955b1bf022b.json
</code>```

I still doubt if this is the correct approach

ContentLicense: CC BY-SA 4.0

Title: Combine find and mongoexport in mongodb

Body:
I am new to MongoDB,
I have 3 collections, Order, Order_events and Order_tasks.
Each order_id in the Order collection has an entry in Order_Events and Order_tasks.

I am trying to write a shell script to use db.Order.find() and combine it with mongoexport to export collections Order_Events and Order_tasks,

According to the documentation for mongoexport , it needs --host or --uri. As I am already using the connection string for the find(),is it possible to combine the result of this find() to be used in a 'mongoexport` command?

Sample query inside my mongodb.sh file

mongo -u $user -p "$pass" "mongodb://$server/$db?readPreference=primaryPreferred"\
--authenticationDatabase $db\
--eval " try { var cursor = db.order.find( { 'state': { \$in: ['Failed','Rejected','Cancelled','Completed'] }},{'orderId':1,'state':1, '_id':0} ); while (cursor.hasNext()){
                   var value=cursor.next();
                   print(tojson(value.orderId));}}catch(e){print(e);}"

I am getting syntax error when I write an export inside the while loop. I am assuming that this way is incorrect.

while (cursor.hasNext()){
                   var value=cursor.next();

   var id=value.orderId;
   print(id);
   mongoexport --collection=Order_Events --type=json --out=/application-backup/file.json
   }}catch(e){print(e);}"

Percona Server for MongoDB server version: v5.0.8-7
uncaught exception: SyntaxError: unexpected token: identifier :
@(shell eval):6:17
exiting with code -4

if I just write mongoexport

while (cursor.hasNext()){
                   var value=cursor.next();

   var id=value.orderId;
   print(id);
   mongoexport
   }}catch(e){print(e);}"

Percona Server for MongoDB server version: v5.0.8-7
136dbc41-2020-40d9-9ad7-affbc215fcfb
ReferenceError: mongoexport is not defined

UPDATE

I was able to execute this by running the find() first and storing the value to a text file, then reading the values into an export command

mongo -u $user -p "$pass" \
                  "mongodb://$server/$db?readPreference=primaryPreferred" \
                  --authenticationDatabase $authenticationDatabase \
                  --eval "
                    try {

                      var cursor = db.order.find({ 'state': { \$in: ['Failed','Rejected'] }},{'orderId':1,'state':1, '_id':0}).pretty()
                      while ( cursor.hasNext() ) {
                        var record = cursor.next();
                        var id=record.orderId;
                        print(id);
                      }
                    } catch(e) {
                      print(e);
                    }" > /application-backup/orderids.txt

                    echo "reading files"
                    file=$(cat /application-backup/orderids.txt)
                    for line in $file
                    do
                        #the generated text file contains strings that are irrelevant for the mongoexport command
                        pattern='^\{?[A-Z0-9a-z]{8}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{4}-[A-Z0-9a-z]{12}\}?$'
                        if [[ "$line" =~ $pattern ]]; then

                          mongoexport --db=$authenticationDatabase --collection=orderProcessEvent  --type=json  --out=/application-backup/orderProcessEvent-$line.json  --uri=$uriString -u $user -p $pass --query='{"orderId":"'$line'","eventCategory":"ORDER_LIFECYCLE_EVENT"}'
                        fi
                    done

this gives an output like this

-rw-r--r--. 1 mongod bin   2121 Dec 21 14:57 orderProcessEvent-d1c3ddea-c9b8-41da-9250-dcf51848c55b.json
-rw-r--r--. 1 mongod bin   2494 Dec 21 14:57 orderProcessEvent-d2b9631a-1aac-4e79-ab2c-ab2594df21a8.json
-rw-r--r--. 1 mongod bin   2018 Dec 21 14:57 orderProcessEvent-d360c0af-921d-4f08-bd52-a138e04b3157.json
-rw-r--r--. 1 mongod bin   2018 Dec 21 14:57 orderProcessEvent-d42b33a3-4c45-410b-a988-3842eb24dbff.json
-rw-r--r--. 1 mongod bin   1647 Dec 21 14:57 orderProcessEvent-d5351941-8247-4679-aeb4-0fec3b225748.json
-rw-r--r--. 1 mongod bin   2019 Dec 21 14:57 orderProcessEvent-d92c3d87-5722-42d9-8133-a44b3125b368.json
-rw-r--r--. 1 mongod bin   1646 Dec 21 14:57 orderProcessEvent-d93fbe3c-8eab-4265-b7c3-b40e159cfd40.json
-rw-r--r--. 1 mongod bin      0 Dec 21 14:57 orderProcessEvent-d94185b8-b892-43d7-8f67-4955b1bf022b.json

I still doubt if this is the correct approach


问:
Graphical tooltips in R
Is it possible to display a graphical tooltip in R? I have created a chart using plotly, and show, for instance, the asset allocation on the efficient frontier as a tooltip. I would like that info to be shown as a pie chart.

Efficient Frontier Example

At the moment, the asset allocation is displayed in a text tooltip. However, I would like to display the breakdown of asset allocation in a pie chart. This is the example code (copied from this useful site).

```<code>library(PortfolioAnalytics)
library(quantmod)
library(PerformanceAnalytics)
library(zoo)
library(plotly)
library(scales)

# Get data
getSymbols(c("MSFT", "NVDA", "IBM", "AAPL", "AMZN"),from = " 2015-01-01",src = 'yahoo')

# Assign to dataframe
# Get adjusted prices
prices.data <- merge.zoo(MSFT[,6], NVDA[,6], IBM[,6], AAPL[,6], AMZN[,6])

# Calculate returns
returns.data <- sapply(prices.data, CalculateReturns)

returns.data <- na.omit(returns.data)

# Set names
colnames(returns.data) <- c("MSFT", "NVDA", "IBM", "AAPL", "AMZN")

meanReturns <- colMeans(returns.data)
covMat <- cov(returns.data)

p <- portfolio.spec(assets = colnames(returns.data))
p <- add.constraint(p, type = "box", min = 0.05, max = 0.8)
p <- add.constraint(portfolio = p, type = "full_investment")
randomport<- random_portfolios(p, permutations = 50000, rp_method = "sample")

p <- add.constraint(portfolio = p, type = "full_investment")
p <- add.constraint(p, type="long_only")
# Get minimum variance portfolio
minvar.port <- add.objective(p, type = "risk", name = "var")

# Optimize
minvar.opt <- optimize.portfolio(returns.data, minvar.port, optimize_method = "random",
                                 rp = randomport)

# Generate maximum return portfolio
maxret.port <- add.objective(p, type = "return", name = "mean")

# Optimize
maxret.opt <- optimize.portfolio(returns.data, maxret.port, optimize_method = "random",
                                 rp = randomport)

minret <- min(meanReturns)
maxret <- max(meanReturns)
vec <- seq(minret, maxret, length.out = 100)

eff.frontier <- data.frame(Risk =vector("numeric", length(vec)) ,
                           Return = vector("numeric", length(vec)))

frontier.weights <- mat.or.vec(nr = length(vec), nc = ncol(returns.data))

colnames(frontier.weights) <- colnames(returns.data)

for(i in 1:length(vec)){

  # Creates a new portfolio object using p and adds mean as a constraint

  p <- add.constraint(p, type = "return", name = "mean", return_target = vec[i])

  # Creates a new portfolio object using p and adds var as an objective, i.e. minimizes var to obtain return target

  p <- add.objective(p, type = "risk", name = "var")

  eff.opt <- optimize.portfolio(returns.data, p, optimize_method = "ROI")

  eff.frontier$Risk[i] <- sqrt(t(eff.opt$weights) %*% covMat %*% eff.opt$weights)

  eff.frontier$Return[i] <- eff.opt$weights %*% meanReturns

  frontier.weights[i,] = eff.opt$weights

}

eff.frontier$Sharperatio <- eff.frontier$Return / eff.frontier$Risk

all.efficient<-as.data.frame(cbind(eff.frontier,frontier.weights))

p<-ggplot(NULL, aes(x,y)) +
  geom_point(data=all.efficient, aes(x=Risk, y = Return, label=percent(MSFT,0.01), label2=percent(NVDA,0.01), label3=percent(IBM,0.01), label4=percent(AAPL,0.01),label5=percent(AMZN,0.01)),color='red') +
  scale_y_continuous(labels = scales::percent) +
  scale_x_continuous(labels = scales::percent) +
  ggtitle("Efficient frontier") +
  theme(plot.title = element_text(hjust = 0.5))

ggplotly(p)
</code>```

Title: Graphical tooltips in R

Body:
Is it possible to display a graphical tooltip in R? I have created a chart using plotly, and show, for instance, the asset allocation on the efficient frontier as a tooltip. I would like that info to be shown as a pie chart.

Efficient Frontier Example

At the moment, the asset allocation is displayed in a text tooltip. However, I would like to display the breakdown of asset allocation in a pie chart. This is the example code (copied from this useful site).

library(PortfolioAnalytics)
library(quantmod)
library(PerformanceAnalytics)
library(zoo)
library(plotly)
library(scales)

# Get data
getSymbols(c("MSFT", "NVDA", "IBM", "AAPL", "AMZN"),from = " 2015-01-01",src = 'yahoo')

# Assign to dataframe
# Get adjusted prices
prices.data <- merge.zoo(MSFT[,6], NVDA[,6], IBM[,6], AAPL[,6], AMZN[,6])

# Calculate returns
returns.data <- sapply(prices.data, CalculateReturns)

returns.data <- na.omit(returns.data)

# Set names
colnames(returns.data) <- c("MSFT", "NVDA", "IBM", "AAPL", "AMZN")

meanReturns <- colMeans(returns.data)
covMat <- cov(returns.data)

p <- portfolio.spec(assets = colnames(returns.data))
p <- add.constraint(p, type = "box", min = 0.05, max = 0.8)
p <- add.constraint(portfolio = p, type = "full_investment")
randomport<- random_portfolios(p, permutations = 50000, rp_method = "sample")

p <- add.constraint(portfolio = p, type = "full_investment")
p <- add.constraint(p, type="long_only")
# Get minimum variance portfolio
minvar.port <- add.objective(p, type = "risk", name = "var")

# Optimize
minvar.opt <- optimize.portfolio(returns.data, minvar.port, optimize_method = "random",
                                 rp = randomport)

# Generate maximum return portfolio
maxret.port <- add.objective(p, type = "return", name = "mean")

# Optimize
maxret.opt <- optimize.portfolio(returns.data, maxret.port, optimize_method = "random",
                                 rp = randomport)

minret <- min(meanReturns)
maxret <- max(meanReturns)
vec <- seq(minret, maxret, length.out = 100)

eff.frontier <- data.frame(Risk =vector("numeric", length(vec)) ,
                           Return = vector("numeric", length(vec)))

frontier.weights <- mat.or.vec(nr = length(vec), nc = ncol(returns.data))

colnames(frontier.weights) <- colnames(returns.data)

for(i in 1:length(vec)){

  # Creates a new portfolio object using p and adds mean as a constraint

  p <- add.constraint(p, type = "return", name = "mean", return_target = vec[i])

  # Creates a new portfolio object using p and adds var as an objective, i.e. minimizes var to obtain return target

  p <- add.objective(p, type = "risk", name = "var")

  eff.opt <- optimize.portfolio(returns.data, p, optimize_method = "ROI")

  eff.frontier$Risk[i] <- sqrt(t(eff.opt$weights) %*% covMat %*% eff.opt$weights)

  eff.frontier$Return[i] <- eff.opt$weights %*% meanReturns

  frontier.weights[i,] = eff.opt$weights

}

eff.frontier$Sharperatio <- eff.frontier$Return / eff.frontier$Risk

all.efficient<-as.data.frame(cbind(eff.frontier,frontier.weights))

p<-ggplot(NULL, aes(x,y)) +
  geom_point(data=all.efficient, aes(x=Risk, y = Return, label=percent(MSFT,0.01), label2=percent(NVDA,0.01), label3=percent(IBM,0.01), label4=percent(AAPL,0.01),label5=percent(AMZN,0.01)),color='red') +
  scale_y_continuous(labels = scales::percent) +
  scale_x_continuous(labels = scales::percent) +
  ggtitle("Efficient frontier") +
  theme(plot.title = element_text(hjust = 0.5))

ggplotly(p)


问:
Full props declaration (with defaults and validators) in Vue 3 + TypeScript +
```
<p>Here is the same declaration, but with <code>age</code> having default value:</p>
<pre class="lang-typescript prettyprint-override"><code>// <script setup lang="ts">
withDefaults(defineProps<{
  name: string,
  age?: number
}>(), {
  age: 20
})
// </script>
</code>```

My main question is: is there a way to incorporate validators in this new syntax? Or whenever I need to add a validator, I need to roll back to the old syntax, i.e.:

//
```
<p>I've found similar topics where some suggest to use both generic types and pass parameters to defineProps like this:</p>
<pre class="lang-typescript prettyprint-override"><code>// <script setup lang="ts">
defineProps<{
  age: number
}>({
  age: {
    validator(value: number) => value > 0
  }
})
// </script>
</code>```

But this approach doesn't work and immediately falls with the error: defineProps has both a type-only props and an argument. (eslintvue/valid-define-props)

Title: Full props declaration (with defaults and validators) in Vue 3 + TypeScript + <script setup>

Body:
So here is a basic example of modern Vue 3 props declaration with

Here is the same declaration, but with age having default value:

//

My main question is: is there a way to incorporate validators in this new syntax? Or whenever I need to add a validator, I need to roll back to the old syntax, i.e.:

//

I've found similar topics where some suggest to use both generic types and pass parameters to defineProps like this:

//

But this approach doesn't work and immediately falls with the error: defineProps has both a type-only props and an argument. (eslintvue/valid-define-props)


问:
Alignment Issue with fluent-ui ChoiceGroup if dir="rtl", what could be the CSS to fix this?
```<code>const { ChoiceGroup, IChoiceGroupOption, ThemeProvider, initializeIcons } = window.FluentUIReact;

// Initialize icons in case this example uses them
initializeIcons();

const options: IChoiceGroupOption[] = [
  { key: 'A', text: 'Option A' },
  { key: 'B', text: 'Option B' },
  { key: 'C', text: 'Option C' },
  { key: 'D', text: 'Option D' },
];

const horizontalChoiceGroupStyles = { flexContainer: { display: 'flex', flexDirection: 'row' } };

const ChoiceGroupBasicExample: React.FunctionComponent = () => {
  return <ChoiceGroup dir="rtl" defaultSelectedKey="B" options={options} onChange={_onChange} label="Pick one" required={true}
  styles={horizontalChoiceGroupStyles}/>;
};

function _onChange(ev: React.FormEvent<HTMLInputElement>, option: IChoiceGroupOption): void {
  console.dir(option);
}

const ChoiceGroupBasicExampleWrapper = () => <ThemeProvider><ChoiceGroupBasicExample /></ThemeProvider>;
ReactDOM.render(<ChoiceGroupBasicExampleWrapper />, document.getElementById('content'))
</code>```

it will show output as below

Please refer to below codepen for more details

https://codepen.io/pravindahale/pen/eYjYaQG

Body:
const { ChoiceGroup, IChoiceGroupOption, ThemeProvider, initializeIcons } = window.FluentUIReact;

// Initialize icons in case this example uses them
initializeIcons();

const options: IChoiceGroupOption[] = [
  { key: 'A', text: 'Option A' },
  { key: 'B', text: 'Option B' },
  { key: 'C', text: 'Option C' },
  { key: 'D', text: 'Option D' },
];

const horizontalChoiceGroupStyles = { flexContainer: { display: 'flex', flexDirection: 'row' } };

const ChoiceGroupBasicExample: React.FunctionComponent = () => {
  return <ChoiceGroup dir="rtl" defaultSelectedKey="B" options={options} onChange={_onChange} label="Pick one" required={true}
  styles={horizontalChoiceGroupStyles}/>;
};

function _onChange(ev: React.FormEvent<HTMLInputElement>, option: IChoiceGroupOption): void {
  console.dir(option);
}

const ChoiceGroupBasicExampleWrapper = () => <ThemeProvider><ChoiceGroupBasicExample /></ThemeProvider>;
ReactDOM.render(<ChoiceGroupBasicExampleWrapper />, document.getElementById('content'))

it will show output as below

Please refer to below codepen for more details

https://codepen.io/pravindahale/pen/eYjYaQG


问:
Vitest - TypeError: Cannot set property 'id' of undefined - Vuejs
I encountered a problem using Vitest while mounting a component to test it.

I thought that res.data.data.id on line 160 was causing the problem, but I tried to comment the line and the problem persists.

Also I tried to mount other components but it gives me the same error.

test code:

```<code>import { mount } from "@vue/test-utils";
import { describe, expect, test, it } from "vitest";
import Login from "../views/Login.vue";
import OrderItemsList from "../components/orders/OrderItemsList.vue";

describe("Login Test", async () => {
  test("Verifica che le credenziali di input rispettino i criteri", async () => {
    const validateInput = (s: String = ""): boolean => s.length > 0;

    const username = "*****";
    const password = "*****";

    expect(validateInput(username)).toBe(true);
    expect(validateInput(password)).toBe(true);

    const wrapper = mount(Login); // <---------------

    /*
    wrapper.get('[name="serverIpAddress"]').setValue("localhost");
    //wrapper.setData({ username: ' '.repeat(7) })
    wrapper.get('[name="serverIpAddress"]').trigger("keyup.enter");
    //wrapper.get('[id="serverButton"]').trigger("click");
    wrapper.get('[name="username"]').setValue(username);
    wrapper.get('[name="password"]').setValue(password);
    wrapper.get('[name="password"]').trigger("keyup.enter");
    //expect(typeof localStorage.getItem("currentUserId")).toEqual("number");
    //*/
  });
});
</code>```

Component login code:

```<code><template>
  <v-main>
    <v-container fluid fill-height>
      <v-layout align-center justify-center>
        <v-flex xs12 sm8 md5>
          <v-card class="elevation-12">
            <v-toolbar dark color="primary">
              <v-toolbar-title>Entra in Velocissimo</v-toolbar-title>
            </v-toolbar>

            <v-stepper v-model="stepper" vertical>
              <v-stepper-step :complete="stepper > 1" step="1">
                Server<span v-html="serverHostText"></span>
              </v-stepper-step>

              <v-stepper-content step="1" class="text-left">
                <br />
                <v-btn elevation="2" v-on:click="useAsServer()"
                  >Attiva server
                </v-btn>
                <br />
                <br />
                <br />

                oppure inserisci l'indirizzo ip del server

                <br />
                <br />

                <v-text-field
                  v-model.trim="serverIpAddress"
                  name="serverIpAddress"
                  label="Indirizzo IP"
                  placeholder="192.168.1.X"
                  v-on:keyup.enter="goTo(2)"
                  autofocus
                ></v-text-field>

                <br />

                <v-btn color="primary" @click="goTo(2)"> Avanti </v-btn>
              </v-stepper-content>

              <v-stepper-step :complete="stepper > 2" step="2">
                Login
              </v-stepper-step>

              <v-stepper-content step="2" class="text-left">
                <form ref="form" @submit.prevent="login()">
                  <v-text-field
                    ref="usernameInput"
                    v-model.trim="username"
                    name="username"
                    label="Username"
                    type="text"
                    placeholder="username"
                    prepend-icon="mdi-account"
                    required
                    :disabled="loading"
                    autocomplete="username"
                  ></v-text-field>

                  <v-text-field
                    ref="passwordInput"
                    v-model.trim="password"
                    name="password"
                    label="Password"
                    type="password"
                    placeholder="password"
                    prepend-icon="mdi-key"
                    autocomplete="current-password"
                    required
                    :disabled="loading"
                    v-on:keyup.enter="login()"
                  ></v-text-field>

                  <div class="red--text">{{ errorMessage }}</div>
                </form>

                <v-btn
                  :loading="loading"
                  :disabled="loading"
                  color="primary"
                  @click="login()"
                >
                  Accedi
                </v-btn>

                <v-btn text @click="backToServer()" :disabled="loading">
                  Indietro
                </v-btn>
              </v-stepper-content>
            </v-stepper>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </v-main>
</template>

<script lang="ts">
import { Component, Ref, Vue } from "vue-property-decorator";
import { LoginRequest } from "@/db-webserver/pluto-api/RequestResponse";
import { LocalDBWSApi, MainDBWSApi } from "@/modules/dbws-api";
import { wrap } from "@/db-webserver/starter/WebserverHelper";
import { AxiosResponse } from "axios";
import router from "@/router";
import { DBWSManager } from "@/modules/dbws-manager/electron";
import { LocalConfiguration } from "@/modules/local-configuration";
import { Auth } from "@/modules/auth";
import { routeName } from "@/router/types";
import { ApiResponse } from "@/modules/dbws-api/DBWSApiClass";

@Component
export default class Login extends Vue {
  @Ref("usernameInput") usernameInput: HTMLInputElement;
  @Ref("passwordInput") passwordInput: HTMLInputElement;

  private stepper = 1;
  private serverIpAddress: string = "";
  private username = "";
  private password = "";
  private errorMessage = "";
  private isUseAsServer = false;
  private loading = false;

  public async login(): Promise<void> {
    this.loading = true;

    this.blurAllInputs();

    const ipAddress = this.isUseAsServer ? "localhost" : this.serverIpAddress;
    await LocalConfiguration.setDBWSHost(ipAddress);
    await MainDBWSApi.setup(ipAddress);

    await DBWSManager.start();

    const credentials: LoginRequest = {
      email: this.username,
      password: this.password,
    };

    await wrap(
      async () => {
        const res = await MainDBWSApi.login(credentials);

        await Auth.login({ plutoToken: res.data.data.token });

        if (this.isUseAsServer) {
          await DBWSManager.configurePlutoInstance(res.data.data);
          await DBWSManager.syncAllData();
        } else {
          await DBWSManager.configurePlutoInstance(res.data.data, LocalDBWSApi);
          await DBWSManager.syncPrintData(LocalDBWSApi);
        }

        await DBWSManager.enableContinuousSync();

        await LocalConfiguration.setIsDBWSServer(this.isUseAsServer);
        await LocalConfiguration.setCurrentUserId(res.data.data.id);

        await router.push({ name: routeName.ORDERS_LIST });
      },
      {
        errorWithResponse: (res: AxiosResponse<ApiResponse<any>>) => {
          this.errorMessage = "Errore: " + res.data.message;
        },
        serviceUnavailable: () => {
          this.errorMessage =
            "Errore: controlla la connessione al server locale";
        },
      }
    );

    this.loading = false;
  }

  public goTo(step: number) {
    this.stepper = step;

    if (step == 2) {
      this.errorMessage = "";
      this.usernameInput.focus();
    }
  }

  public blurAllInputs() {
    this.usernameInput.blur();
    this.passwordInput.blur();
  }

  public useAsServer() {
    this.isUseAsServer = true;
    this.goTo(2);
    this.serverIpAddress = "Questo dispositivo";
  }

  public backToServer() {
    if (this.isUseAsServer) {
      this.serverIpAddress = "";
    }

    this.isUseAsServer = false;
    this.goTo(1);
  }

  get serverHostText(): string {
    if (this.stepper === 1) {
      return "";
    }

    let text: string;
    if (this.isUseAsServer) {
      text = "Questo dispositivo";
    } else {
      text = this.serverIpAddress;
    }

    return `: <i>${text}</i>`;
  }
}
</script>
</code>```

VERSIONS:
"@vitejs/plugin-vue": "^3.2.0",
"vitest": "^0.25.8",
"@babel/preset-typescript": "^7.18.6",

Body:
I encountered a problem using Vitest while mounting a component to test it.

I thought that res.data.data.id on line 160 was causing the problem, but I tried to comment the line and the problem persists.

Also I tried to mount other components but it gives me the same error.

test code:

import { mount } from "@vue/test-utils";
import { describe, expect, test, it } from "vitest";
import Login from "../views/Login.vue";
import OrderItemsList from "../components/orders/OrderItemsList.vue";

describe("Login Test", async () => {
  test("Verifica che le credenziali di input rispettino i criteri", async () => {
    const validateInput = (s: String = ""): boolean => s.length > 0;

    const username = "*****";
    const password = "*****";

    expect(validateInput(username)).toBe(true);
    expect(validateInput(password)).toBe(true);

    const wrapper = mount(Login); // <---------------

    /*
    wrapper.get('[name="serverIpAddress"]').setValue("localhost");
    //wrapper.setData({ username: ' '.repeat(7) })
    wrapper.get('[name="serverIpAddress"]').trigger("keyup.enter");
    //wrapper.get('[id="serverButton"]').trigger("click");
    wrapper.get('[name="username"]').setValue(username);
    wrapper.get('[name="password"]').setValue(password);
    wrapper.get('[name="password"]').trigger("keyup.enter");
    //expect(typeof localStorage.getItem("currentUserId")).toEqual("number");
    //*/
  });
});

Component login code:

<template>
  <v-main>
    <v-container fluid fill-height>
      <v-layout align-center justify-center>
        <v-flex xs12 sm8 md5>
          <v-card class="elevation-12">
            <v-toolbar dark color="primary">
              <v-toolbar-title>Entra in Velocissimo</v-toolbar-title>
            </v-toolbar>

            <v-stepper v-model="stepper" vertical>
              <v-stepper-step :complete="stepper > 1" step="1">
                Server
              </v-stepper-step>

              <v-stepper-content step="1" class="text-left">

                <v-btn elevation="2" v-on:click="useAsServer()"
                  >Attiva server
                </v-btn>

                oppure inserisci l'indirizzo ip del server

                <v-text-field
                  v-model.trim="serverIpAddress"
                  name="serverIpAddress"
                  label="Indirizzo IP"
                  placeholder="192.168.1.X"
                  v-on:keyup.enter="goTo(2)"
                  autofocus
                ></v-text-field>

                <v-btn color="primary" @click="goTo(2)"> Avanti </v-btn>
              </v-stepper-content>

              <v-stepper-step :complete="stepper > 2" step="2">
                Login
              </v-stepper-step>

              <v-stepper-content step="2" class="text-left">
                <form ref="form" @submit.prevent="login()">
                  <v-text-field
                    ref="usernameInput"
                    v-model.trim="username"
                    name="username"
                    label="Username"
                    type="text"
                    placeholder="username"
                    prepend-icon="mdi-account"
                    required
                    :disabled="loading"
                    autocomplete="username"
                  ></v-text-field>

                  <v-text-field
                    ref="passwordInput"
                    v-model.trim="password"
                    name="password"
                    label="Password"
                    type="password"
                    placeholder="password"
                    prepend-icon="mdi-key"
                    autocomplete="current-password"
                    required
                    :disabled="loading"
                    v-on:keyup.enter="login()"
                  ></v-text-field>

{{ errorMessage }}

                </form>

                <v-btn
                  :loading="loading"
                  :disabled="loading"
                  color="primary"
                  @click="login()"
                >
                  Accedi
                </v-btn>

                <v-btn text @click="backToServer()" :disabled="loading">
                  Indietro
                </v-btn>
              </v-stepper-content>
            </v-stepper>
          </v-card>
        </v-flex>
      </v-layout>
    </v-container>
  </v-main>
</template>

VERSIONS:
"@vitejs/plugin-vue": "^3.2.0",
"vitest": "^0.25.8",
"@babel/preset-typescript": "^7.18.6",


问:
Swiper slider dynamic pagination
I'm using swiper slider and don't know how to get rid of the empty space when the slider comes to the first or last element, can you tell me please
https://monosnap.com/file/jLTCNd8CIT82h6WNqGbP5qxVKWkS8d

Tried find some property in Swiper slider API and make styles

{
"loop": true,
"slidesPerView": 3,
"observer": true,
"loopFillGroupWithBlank": true,
"slidesPerGroup": 1,
"initialSlide": 3,
"navigation": {
"nextEl": ".collection-slider-2-swiper-button-next",
"prevEl": ".collection-slider-2-swiper-button-prev"
},
"pagination": {
"el": ".swiper-pagination",
"dynamicBullets": true
},
"breakpoints": {
"320": {
"slidesPerView": 2,
"spaceBetween": 20,
"pagination": {
"type": "progressbar"
}
},
"1024": {
"slidesPerView": 2,
"pagination": {
"type": "bullets"
}
},
"1440": {
"slidesPerView": 3,
"spaceBetween": 30
}
}
}

Title: Swiper slider dynamic pagination


问:
Not able to get Real Director from Imdb API - Android
I am using this Imdb API from this movie credit documentation.

Everything ok except Real Director name.

Here I am trying to get Director name: Crew > name.
But In API multiple name id that is not real Director.

Here is my code:
`

```<code>var jsonArray1=jsonObject.getJSONArray("crew")
for (j in 0..jsonArray1.length()-1){

    var jsonObj=jsonArray1.getJSONObject(j)
    /*id2=jsonObj.getString("id")
    var dd=jsonObj.getString("name")
    text1.setText(dd)*/
    var name1=jsonObj.getString("name")
    var img1="https://image.tmdb.org/t/p/w500/"+jsonObj.getString("profile_path")
    arrayList1.add(ItemViewModel2(img1,name1))
    var adapter=Demo_Adapter2(arrayList1,applicationContext)
    recyclerView1.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
    recyclerView1.adapter=adapter
</code>```

`
from this code Api showing

Movie name: Black Adam
Director: Tre Ryan

But Real Director is Jaume Collet-Serra.

How Can I get Real director from this IMDB API?

Now, I trying and get this:
Movie name: Black Adam
Director: Tre Ryan

I expecting:
Movie name: Black Adam
Director: Jaume COllet-Serra

Body:
I am using this Imdb API from this movie credit documentation.

Everything ok except Real Director name.

Here I am trying to get Director name: Crew > name.
But In API multiple name id that is not real Director.

Here is my code:
`

var jsonArray1=jsonObject.getJSONArray("crew")
for (j in 0..jsonArray1.length()-1){

    var jsonObj=jsonArray1.getJSONObject(j)
    /*id2=jsonObj.getString("id")
    var dd=jsonObj.getString("name")
    text1.setText(dd)*/
    var name1=jsonObj.getString("name")
    var img1="https://image.tmdb.org/t/p/w500/"+jsonObj.getString("profile_path")
    arrayList1.add(ItemViewModel2(img1,name1))
    var adapter=Demo_Adapter2(arrayList1,applicationContext)
    recyclerView1.layoutManager = LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
    recyclerView1.adapter=adapter

`
from this code Api showing

Movie name: Black Adam
Director: Tre Ryan

But Real Director is Jaume Collet-Serra.

How Can I get Real director from this IMDB API?

Now, I trying and get this:
Movie name: Black Adam
Director: Tre Ryan

I expecting:
Movie name: Black Adam
Director: Jaume COllet-Serra


问:
how to get a parent object in an array of objects?
I have an object in javascript:

```<code>{
    name: "General",
    icon: "general",
    children: [
      {
        name: "Line 1",
        icon: "line",
        children: [
          {
            name: "Area 1",
            icon: "area",
            children: [
              { name: "Y", icon: "x" },
              { name: "Z", icon: "z" },
            ],
          },
          { name: "Area 2", icon: "line" },
        ],
      },
      {
        name: "Line 2,
        icon: "line",
        children: [{ name: "Area 3", icon: "area" }],
      },
    ],
  },

</code>```

I am trying to do hierarchical structure filtering. After entering the name of the node in the search input, the hierarchical structure should disappear and a div should appear with the name of the node and the path in the hierarchy e.g. searche: Area 1,

Area1      |       General -> Line1.

Is there any way to get information about an object that is a parent in a structure?
Or should I just give each element an id and a parenId to refer to the parent

Body:
I have an object in javascript:

{
    name: "General",
    icon: "general",
    children: [
      {
        name: "Line 1",
        icon: "line",
        children: [
          {
            name: "Area 1",
            icon: "area",
            children: [
              { name: "Y", icon: "x" },
              { name: "Z", icon: "z" },
            ],
          },
          { name: "Area 2", icon: "line" },
        ],
      },
      {
        name: "Line 2,
        icon: "line",
        children: [{ name: "Area 3", icon: "area" }],
      },
    ],
  },

I am trying to do hierarchical structure filtering. After entering the name of the node in the search input, the hierarchical structure should disappear and a div should appear with the name of the node and the path in the hierarchy e.g. searche: Area 1,

Area1      |       General -> Line1.

Is there any way to get information about an object that is a parent in a structure?
Or should I just give each element an id and a parenId to refer to the parent


问:
How to make a call through Bluetooth on an another phone?
I have a cheap smartphone that can make calls, I also have an iPhone 12 which cannot make calls because it takes a hefty fee to make a phone support sim card where i live.

Can I make calls through iPhone 12 by connecting it to the cheap smartphone via Bluetooth?

the same way one can make calls through their smart watch.


问:
is the a way to get more than 5000 candles
Here am using deriv/binary.com's API to stream through previous data. I realized I can only get 5000 ticks or candles...4999 precisely.

In the code below count is the number of candles I want

```<code>package Concrete;

import org.json.JSONArray;
import org.json.JSONObject;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;

@ClientEndpoint
public class WsClient {

    private  double cc;
    private  double cl;
    private  double ch;
    private  double co;
    private  double epoch;

    @OnOpen
    public void onOpen(Session session) throws java.io.IOException {
        //  session.getBasicRemote().sendText("{\"ticks\": \"R_100\"}");
        session.getBasicRemote().sendText("{\"ticks_history\": \"CRASH1000\",\"end\": \"latest\",\"style\": \"candles\"," +
                "\"granularity\" : 60,\"adjust_start_time\": 1,\"count\": 2066400}");
    }

    @OnMessage
    public void onMessage(String message) {
        JSONObject messageJSONObject = new JSONObject(message);
        JSONArray recs = messageJSONObject.getJSONArray("candles");

        for (int i = 0; i < recs.length(); ++i) {
            JSONObject rec = recs.getJSONObject(i);

            cc = rec.getDouble("close");
            cl = rec.getDouble("low");
            ch = rec.getDouble("high");
            co = rec.getDouble("open");
            epoch = rec.getDouble("epoch");
            System.out.println("close " + cc);

        }
    }

    public static void main(String[] args)
            throws IOException, DeploymentException, InterruptedException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3?app_id=1089");
        Session session = container.connectToServer(WsClient.class, apiUri);
        while (session.isOpen()) {
            // receive ticks
        }
    }
}
</code>```

what I want to actually do is get all data for the pair.
I would like to know how to go on about this.

The reason why I want all data is because I want the user to be able to zoom out and view from the beginning like trading view.

I went through the API forum and the was a thread which "You might be able to do it in chunks using consecutive date ranges?" was the given solution.

Body:
Here am using deriv/binary.com's API to stream through previous data. I realized I can only get 5000 ticks or candles...4999 precisely.

In the code below count is the number of candles I want

package Concrete;

import org.json.JSONArray;
import org.json.JSONObject;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;

@ClientEndpoint
public class WsClient {

    private  double cc;
    private  double cl;
    private  double ch;
    private  double co;
    private  double epoch;

    @OnOpen
    public void onOpen(Session session) throws java.io.IOException {
        //  session.getBasicRemote().sendText("{\"ticks\": \"R_100\"}");
        session.getBasicRemote().sendText("{\"ticks_history\": \"CRASH1000\",\"end\": \"latest\",\"style\": \"candles\"," +
                "\"granularity\" : 60,\"adjust_start_time\": 1,\"count\": 2066400}");
    }

    @OnMessage
    public void onMessage(String message) {
        JSONObject messageJSONObject = new JSONObject(message);
        JSONArray recs = messageJSONObject.getJSONArray("candles");

        for (int i = 0; i < recs.length(); ++i) {
            JSONObject rec = recs.getJSONObject(i);

            cc = rec.getDouble("close");
            cl = rec.getDouble("low");
            ch = rec.getDouble("high");
            co = rec.getDouble("open");
            epoch = rec.getDouble("epoch");
            System.out.println("close " + cc);

        }
    }

    public static void main(String[] args)
            throws IOException, DeploymentException, InterruptedException {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3?app_id=1089");
        Session session = container.connectToServer(WsClient.class, apiUri);
        while (session.isOpen()) {
            // receive ticks
        }
    }
}

what I want to actually do is get all data for the pair.
I would like to know how to go on about this.

The reason why I want all data is because I want the user to be able to zoom out and view from the beginning like trading view.

I went through the API forum and the was a thread which "You might be able to do it in chunks using consecutive date ranges?" was the given solution.


问:
Appending to tibble in FOR loop R
I am trying to create a list of all possible IP addresses in the UK, so I can plot them on a map for a data science project I am working on.

I have tried to simplify the code as much as possible, basically I have a created a blank tibble to use in the for loop, but it does not appear to get any data appended to it.

Guessing I have done the append part of the FOR LOOP incorrectly.

```<code>#install libraries
library(iptools)
library(dplyr)
library(tidyverse)

#creating a list of ip ranges for processing
ip_ranges <- list("2.96.0.0/13", "2.120.0.0/13", "2.216.0.0/13")

#converting list into dataframe
ip_ranges_to_process <- do.call(rbind.data.frame, ip_ranges)
colnames(ip_ranges_to_process) <- c("ip.ranges")

#creating a blank tibble for use in for loop
UK_ip_addresses_df <- tibble(
  var_name_1 = character()
)

new_df <- tibble(
  var_name_1 = character()
)

#for loop to generate all possible ip addresses in ranges
for(i in 1:nrow(ip_ranges_to_process)){
  ip_numbers <- range_generate(ip_ranges_to_process$ip.ranges[i])
  new_df <- ip_numbers %>%
    map_df(as_tibble)
  UK_ip_addresses_df[i,] <- new_df
}

</code>```

Any suggestions would be welcome. Sorry I am pretty new to programming.

Title: Appending to tibble in FOR loop R

Body:
I am trying to create a list of all possible IP addresses in the UK, so I can plot them on a map for a data science project I am working on.

I have tried to simplify the code as much as possible, basically I have a created a blank tibble to use in the for loop, but it does not appear to get any data appended to it.

Guessing I have done the append part of the FOR LOOP incorrectly.

#install libraries
library(iptools)
library(dplyr)
library(tidyverse)

#creating a list of ip ranges for processing
ip_ranges <- list("2.96.0.0/13", "2.120.0.0/13", "2.216.0.0/13")

#converting list into dataframe
ip_ranges_to_process <- do.call(rbind.data.frame, ip_ranges)
colnames(ip_ranges_to_process) <- c("ip.ranges")

#creating a blank tibble for use in for loop
UK_ip_addresses_df <- tibble(
  var_name_1 = character()
)

new_df <- tibble(
  var_name_1 = character()
)

#for loop to generate all possible ip addresses in ranges
for(i in 1:nrow(ip_ranges_to_process)){
  ip_numbers <- range_generate(ip_ranges_to_process$ip.ranges[i])
  new_df <- ip_numbers %>%
    map_df(as_tibble)
  UK_ip_addresses_df[i,] <- new_df
}

Any suggestions would be welcome. Sorry I am pretty new to programming.


问:
Convert PIVOT to PostgreSQL
I am translating a script to PostgreSQL and I have a problem translating PIVOT, because there isn't that function on Postgres.

the script is:

```<code>UPDATE XYZ A
SET (A.YX1,YX2,A.YX3,A.YX4,A.YX5,A.YX6,A.YX7,A.YX8,A.YX9,A.YX10) =

(SELECT  X1,X2,X3,X4,X5,X6,X7,X8,X9,10
    FROM
    ((select X1,X2,X3,X4,X5,X6,X7,X8,X9,X10
         from XYPZ )
    PIVOT
    ( MAX(CONTROLLO) FOR LIVELLO IN
     ('X1' AS "X1",'X2' AS "X2" ,'X3' AS "X3",'X4' AS "X4",'X5' AS "X5",'X6' AS "X6",'X7' AS "X7",'X8' AS "X8",'X9' AS "X9",'X10' AS "X10")) B
);
</code>```

A way to translate this update

Title: Convert PIVOT to PostgreSQL

Body:
I am translating a script to PostgreSQL and I have a problem translating PIVOT, because there isn't that function on Postgres.

the script is:

UPDATE XYZ A
SET (A.YX1,YX2,A.YX3,A.YX4,A.YX5,A.YX6,A.YX7,A.YX8,A.YX9,A.YX10) =

(SELECT  X1,X2,X3,X4,X5,X6,X7,X8,X9,10
    FROM
    ((select X1,X2,X3,X4,X5,X6,X7,X8,X9,X10
         from XYPZ )
    PIVOT
    ( MAX(CONTROLLO) FOR LIVELLO IN
     ('X1' AS "X1",'X2' AS "X2" ,'X3' AS "X3",'X4' AS "X4",'X5' AS "X5",'X6' AS "X6",'X7' AS "X7",'X8' AS "X8",'X9' AS "X9",'X10' AS "X10")) B
);

A way to translate this update


问:
Set virtual address of section to custom byte
I'm trying to put a small boot loader into the mbr of an exfat drive, but I'm having trouble getting ld to set the virtual address correctly.

according to the ExFat Specification, I need to put the bootloader at  byte 0x78 (120). So I set the location counter to 0x7C78. But when I used readelf on the result, I found that ld put the virtual address at 0x7C80 instead.

This is sadly not what I want, so I tried to set the virtual address to different values and found that ld will always put the section with a 16 byte alignment. e.g. at 0x7C70 and 0x7C80

My question is: Is there any way to disable/override this alignment, and put my section at the specific address

The boot code

```<code>bits 16

global boot
boot:
    mov ax, 0x0202
    mov bx, 0x7E00
    mov cx, 0x0002
    mov dx, 0x0080
    int 0x13
    jmp 0x0000:0x7e00

times 388-($-$$) db 0x00
dw 0xAA55
</code>```

The linkerscript

```<code>OUTPUT_FORMAT("binary")

SECTIONS {
    . = 0x7c78;
    .text :
    {
        *.mbr.o(.text)
    }

    .text :
    {
        *.o(.text)
    }
}
</code>```

The readelf result

```<code>     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS src/boot/boot.mbr.s
     2: 0000000000000000     0 SECTION LOCAL  DEFAULT    4 .debug_info
     3: 0000000000000000     0 SECTION LOCAL  DEFAULT    5 .debug_abbrev
     4: 0000000000000000     0 SECTION LOCAL  DEFAULT    6 .debug_line
     5: 0000000000007c93     1 OBJECT  LOCAL  DEFAULT    1 boot.end
     6: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS src/boot/boot.s
     7: 0000000000007e10     0 SECTION LOCAL  DEFAULT    2 .text
wrong > 0000000000007c80     0 NOTYPE  GLOBAL DEFAULT    1 boot
     9: 0000000000007e10     0 NOTYPE  GLOBAL DEFAULT    2 stage2
</code>```

I used these flags to call nasm:

```<code>nasm -felf64 -g -F dwarf -o boot.mbr.o boot.mbr.s
</code>```

and these flags to call ld

```<code>i386-elf-gcc -nostdlib -n -Wl,--oformat=elf64-little -T linker.ld -o boot.elf boot.mbr.o
</code>```

Body:
I'm trying to put a small boot loader into the mbr of an exfat drive, but I'm having trouble getting ld to set the virtual address correctly.

according to the ExFat Specification, I need to put the bootloader at  byte 0x78 (120). So I set the location counter to 0x7C78. But when I used readelf on the result, I found that ld put the virtual address at 0x7C80 instead.

This is sadly not what I want, so I tried to set the virtual address to different values and found that ld will always put the section with a 16 byte alignment. e.g. at 0x7C70 and 0x7C80

My question is: Is there any way to disable/override this alignment, and put my section at the specific address

The boot code

bits 16

global boot
boot:
    mov ax, 0x0202
    mov bx, 0x7E00
    mov cx, 0x0002
    mov dx, 0x0080
    int 0x13
    jmp 0x0000:0x7e00

times 388-($-$$) db 0x00
dw 0xAA55

The linkerscript

OUTPUT_FORMAT("binary")

SECTIONS {
    . = 0x7c78;
    .text :
    {
        *.mbr.o(.text)
    }

    .text :
    {
        *.o(.text)
    }
}

The readelf result

     0: 0000000000000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS src/boot/boot.mbr.s
     2: 0000000000000000     0 SECTION LOCAL  DEFAULT    4 .debug_info
     3: 0000000000000000     0 SECTION LOCAL  DEFAULT    5 .debug_abbrev
     4: 0000000000000000     0 SECTION LOCAL  DEFAULT    6 .debug_line
     5: 0000000000007c93     1 OBJECT  LOCAL  DEFAULT    1 boot.end
     6: 0000000000000000     0 FILE    LOCAL  DEFAULT  ABS src/boot/boot.s
     7: 0000000000007e10     0 SECTION LOCAL  DEFAULT    2 .text
wrong > 0000000000007c80     0 NOTYPE  GLOBAL DEFAULT    1 boot
     9: 0000000000007e10     0 NOTYPE  GLOBAL DEFAULT    2 stage2

I used these flags to call nasm:

nasm -felf64 -g -F dwarf -o boot.mbr.o boot.mbr.s

and these flags to call ld

i386-elf-gcc -nostdlib -n -Wl,--oformat=elf64-little -T linker.ld -o boot.elf boot.mbr.o


问:
How to keep the same order of custom media actions in Automotive OS?
I want to use custom next/previous actions instead of the native ones. So I started by removing the native ones by allowing only needed actions:

```<code>private inner class CustomQueueNavigator(
        mediaSession: MediaSessionCompat
    ) : TimelineQueueNavigator(mediaSession) {

        override fun getSupportedQueueNavigatorActions(player: Player): Long {
            return PlaybackStateCompat.ACTION_PLAY or
                    PlaybackStateCompat.ACTION_PAUSE or
                    PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM or
                    PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
        }
    }
</code>```

And then I added my custom actions:

```<code> MediaSessionConnector(mediaSession).setCustomActionProviders(object :
                MediaSessionConnector.CustomActionProvider {
                override fun onCustomAction(player: Player, action: String, extras: Bundle?) {}

                override fun getCustomAction(player: Player): PlaybackStateCompat.CustomAction? {
                    return PlaybackStateCompat.CustomAction.Builder(
                        "SKIP_TO_PREVIOUS_ACTION",
                        "previous",
                        if (!isFirst)
                            R.drawable.ic_previous_with_padding
                        else R.drawable.ic_previous_disabled_with_padding
                    ).build()
                }
            },
        object : MediaSessionConnector.CustomActionProvider {
                override fun onCustomAction(player: Player, action: String, extras: Bundle?) {}

                override fun getCustomAction(player: Player): PlaybackStateCompat.CustomAction? {
                    return PlaybackStateCompat.CustomAction.Builder(
                        "SKIP_TO_NEXT_ACTION",
                        "next",
                        if (!isLast)
                            R.drawable.ic_next_with_padding
                        else R.drawable.ic_next_disabled_with_padding
                    ).build()
                }
            }

</code>```

Results:

In app:

In home:

As you observed, the buttons in the home section in the automotive are inverted, how can I keep the same order as in the app?

Body:
I want to use custom next/previous actions instead of the native ones. So I started by removing the native ones by allowing only needed actions:

private inner class CustomQueueNavigator(
        mediaSession: MediaSessionCompat
    ) : TimelineQueueNavigator(mediaSession) {

        override fun getSupportedQueueNavigatorActions(player: Player): Long {
            return PlaybackStateCompat.ACTION_PLAY or
                    PlaybackStateCompat.ACTION_PAUSE or
                    PlaybackStateCompat.ACTION_SKIP_TO_QUEUE_ITEM or
                    PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID
        }
    }

And then I added my custom actions:

 MediaSessionConnector(mediaSession).setCustomActionProviders(object :
                MediaSessionConnector.CustomActionProvider {
                override fun onCustomAction(player: Player, action: String, extras: Bundle?) {}

                override fun getCustomAction(player: Player): PlaybackStateCompat.CustomAction? {
                    return PlaybackStateCompat.CustomAction.Builder(
                        "SKIP_TO_PREVIOUS_ACTION",
                        "previous",
                        if (!isFirst)
                            R.drawable.ic_previous_with_padding
                        else R.drawable.ic_previous_disabled_with_padding
                    ).build()
                }
            },
        object : MediaSessionConnector.CustomActionProvider {
                override fun onCustomAction(player: Player, action: String, extras: Bundle?) {}

                override fun getCustomAction(player: Player): PlaybackStateCompat.CustomAction? {
                    return PlaybackStateCompat.CustomAction.Builder(
                        "SKIP_TO_NEXT_ACTION",
                        "next",
                        if (!isLast)
                            R.drawable.ic_next_with_padding
                        else R.drawable.ic_next_disabled_with_padding
                    ).build()
                }
            }

Results:

In app:

In home:

As you observed, the buttons in the home section in the automotive are inverted, how can I keep the same order as in the app?


问:
React Carousel and onClick events
I'm making a small imdb clone in reactJS and I just managed to add a carousel to the component that renders out movies. The problem is that the clickevent for each movie doesn't work anymore. What's the simplest way to solve this without rewriting the entire component?

I could add a onclick event to the carousel but then i have to return all the neccessary data from the movie component and later send it to moviePage which seems redundant

Home.js

import { React } from "react";
import SearchBox from "./components/SearchBox";
import Movie from "./components/Movie";
import { Carousel } from "react-responsive-carousel";
function Home(props) {
  return (

        <SearchBox
          searchValue={props.searchValue}
          setSearchValue={props.setSearchValue}
        />

Movies

        <Carousel onClickItem={console.log("you pressed")}>
          {props.data.map((movie, index) => {
            return (
              <Movie
                key={movie.id}
                movie={movie}
                placeMovie={props.placeMovie}
                index={index}
              />
            );
          })}
        </Carousel>

Recently viewed

        {props.latestView.map((n) => {
          return (

          );
        })}

  );
}

export default Home;
```
<p>Movie.js</p>
<pre class="lang-js prettyprint-override"><code>import React from "react";
import { NavLink } from "react-router-dom";

export default function Movie(props) {
  const handleClick = () => {
    props.placeMovie(props.index);
  };

  return (
    <div className="image-container d-flex justify-content-start m-3">
      <div>
        <NavLink onClick={handleClick} to={`/MoviePage`}>
          <img
            className="image-list"
            src={"https://image.tmdb.org/t/p/w500" + props.movie.backdrop_path}
            alt={props.movie.path}
          />
        </NavLink>

        <h4 class="font-weight-bold">{props.movie.title}</h4>
        <h5 class="font-weight-light">Score:{props.movie.vote_average}</h5>
      </div>
    </div>
  );
}
</code>```

Heres the moviepage that displays more info when you click on a movie item

import React from "react";
function MoviePage(props) {
  return (

{props.movie.title}

{props.movie.overview}

            Language: {props.movie.original_language}

            Release date: {props.movie.release_date}

  );
}

export default MoviePage;
```

Title: React Carousel and onClick events

Body:
I'm making a small imdb clone in reactJS and I just managed to add a carousel to the component that renders out movies. The problem is that the clickevent for each movie doesn't work anymore. What's the simplest way to solve this without rewriting the entire component?

I could add a onclick event to the carousel but then i have to return all the neccessary data from the movie component and later send it to moviePage which seems redundant

Home.js

import { React } from "react";
import SearchBox from "./components/SearchBox";
import Movie from "./components/Movie";
import { Carousel } from "react-responsive-carousel";
function Home(props) {
  return (

        <SearchBox
          searchValue={props.searchValue}
          setSearchValue={props.setSearchValue}
        />

Movies

        <Carousel onClickItem={console.log("you pressed")}>
          {props.data.map((movie, index) => {
            return (
              <Movie
                key={movie.id}
                movie={movie}
                placeMovie={props.placeMovie}
                index={index}
              />
            );
          })}
        </Carousel>

Recently viewed

        {props.latestView.map((n) => {
          return (

          );
        })}

  );
}

export default Home;

Movie.js

import React from "react";
import { NavLink } from "react-router-dom";

export default function Movie(props) {
  const handleClick = () => {
    props.placeMovie(props.index);
  };

  return (

        <NavLink onClick={handleClick} to={`/MoviePage`}>

        </NavLink>

{props.movie.title}

Score:{props.movie.vote_average}

  );
}

Heres the moviepage that displays more info when you click on a movie item

import React from "react";
function MoviePage(props) {
  return (

{props.movie.title}

{props.movie.overview}

            Language: {props.movie.original_language}

            Release date: {props.movie.release_date}

  );
}

export default MoviePage;


问:
remotemysql.com cannot connect with python neither on the site manually
I try to reach to my remotemysql database with my Python script which worked fine first, now it doesn't connect anymore so I went to remotemysql.com/login.php but it gives an error

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

anyone know if its only for me or if remotemysql.com is having problems?
my code for Python should also be fine.
these are random credentials in my code btw.

```<code>try:
    conn = mysql.connector.connect(
      host='remotemysql.com',
      database='thydfc2',
      user='thydfc2',
      password=os.environ.get('databasepass'))

  except Error as e:
    print(e)
  if conn.is_connected():
      mycursor = conn.cursor()```
```

Body:
I try to reach to my remotemysql database with my Python script which worked fine first, now it doesn't connect anymore so I went to remotemysql.com/login.php but it gives an error

Connection failed: SQLSTATE[HY000] [2002] No such file or directory

anyone know if its only for me or if remotemysql.com is having problems?
my code for Python should also be fine.
these are random credentials in my code btw.

try:
    conn = mysql.connector.connect(
      host='remotemysql.com',
      database='thydfc2',
      user='thydfc2',
      password=os.environ.get('databasepass'))

  except Error as e:
    print(e)
  if conn.is_connected():
      mycursor = conn.cursor()```


问:
How to access java runtime variables like java.lang.Runtime.getRuntime().maxMemory() for pyspark executors?
The question is all there is. I want a way to check the java runtime variables for the executor jvm created but I am working with pyspark. How can I access java.lang.Runtime.getRuntime().maxMemory() if I am working with pyspark?

based on the comment I have tried to run the following code but both approaches are unsuccessful

```<code>#created a RDD
l = sc.range(100)
</code>```

Now, I have to run func = sc._gateway.jvm.java.lang.Runtime.getRuntime().maxMemory() on each executor. So, I do the following

```<code>l.map(lambda x:sc._gateway.jvm.java.lang.Runtime.getRuntime().maxMemory()).collect()
</code>```

Which results in

```<code>Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.
</code>```

The spark context can only be used on the driver

I also tried

```<code>func = sc._gateway.jvm.java.lang.Runtime.getRuntime()
l.map(lambda x:func.maxMemory()).collect()
</code>```

which results in the following error

```<code>TypeError: cannot pickle '_thread.RLock' object
</code>```

Body:
The question is all there is. I want a way to check the java runtime variables for the executor jvm created but I am working with pyspark. How can I access java.lang.Runtime.getRuntime().maxMemory() if I am working with pyspark?

based on the comment I have tried to run the following code but both approaches are unsuccessful

#created a RDD
l = sc.range(100)

Now, I have to run func = sc._gateway.jvm.java.lang.Runtime.getRuntime().maxMemory() on each executor. So, I do the following

l.map(lambda x:sc._gateway.jvm.java.lang.Runtime.getRuntime().maxMemory()).collect()

Which results in

Exception: It appears that you are attempting to reference SparkContext from a broadcast variable, action, or transformation. SparkContext can only be used on the driver, not in code that it run on workers. For more information, see SPARK-5063.

The spark context can only be used on the driver

I also tried

func = sc._gateway.jvm.java.lang.Runtime.getRuntime()
l.map(lambda x:func.maxMemory()).collect()

which results in the following error

TypeError: cannot pickle '_thread.RLock' object


问:
how to replace numeric characters with their equivalent alphabetical strings, 0 replaced by Zero, 1 replaced by One and so on?
im iterating over a list defined values.yaml, but the field im filling using the list contents doesn't accept numerical characters, so i want to replace numerical characters if found inside the range function, is there anyway to do that?

i didn't find a helm template function that offers this specific function

i tried ChatGPT lol ,it gave me examples of ways i can do it but it didn't work for me, kept saying that it can't recognize the functions used.

here's what it recommended

`

```<code>{{- import "strings" as strings -}}
{{- $newString := "" -}}
{{- $chars := "abcdefghijklmnopqrstuvwxyz" -}}
{{- range $i, $char := strings.split (string .Values.myString) "" -}}
  {{- if reFind `[0-9]` $char -}}
    {{- $newString = print $newString (index $chars (int $char)) -}}
  {{- else -}}
    {{- $newString = print $newString $char -}}
  {{- end -}}
{{- end -}}
</code>```

`

Body:
im iterating over a list defined values.yaml, but the field im filling using the list contents doesn't accept numerical characters, so i want to replace numerical characters if found inside the range function, is there anyway to do that?

i didn't find a helm template function that offers this specific function

i tried ChatGPT lol ,it gave me examples of ways i can do it but it didn't work for me, kept saying that it can't recognize the functions used.

here's what it recommended

`

{{- import "strings" as strings -}}
{{- $newString := "" -}}
{{- $chars := "abcdefghijklmnopqrstuvwxyz" -}}
{{- range $i, $char := strings.split (string .Values.myString) "" -}}
  {{- if reFind `[0-9]` $char -}}
    {{- $newString = print $newString (index $chars (int $char)) -}}
  {{- else -}}
    {{- $newString = print $newString $char -}}
  {{- end -}}
{{- end -}}

`


问:
C struct Function return value output error
I'm practicing string in C language and I'm posting a question because I got an unwanted result.

I saved the string in the order of 123, 456, 789, but //Here output is 789,789, 789.

I would appreciate it if you could point out the wrong part.

Thank you for reading it.

```<code>#include <stdio.h>
#include <stdlib.h>

typedef struct Que
{
    char *s;
    int t;
} QUE;
QUE que[50];
int wp;
void push(char *s)
{
    que[wp].s = s;
    printf("que[wp].s = %s\n",que[wp].s);
    wp++;
}

int cnt = 0;

char * input(char *str)
{
    static char arr[3];

    if(cnt == 0)
    {
        arr[0] = '1';
        arr[1] = '2';
        arr[2] = '3';
    }
    else if(cnt==1)
    {
        arr[0] = '4';
        arr[1] = '5';
        arr[2] = '6';
    }
    else if(cnt==2)
    {
        arr[0] = '7';
        arr[1] = '8';
        arr[2] = '9';
    }

    cnt++;

    return arr;
}

void Temp()
{
    char *a = "123";

    for(int i=0; i<3; i++)
    {
        char *Nchk = malloc(sizeof(char)*3);

        Nchk = input(a);
        printf("Nchk = %s\n",Nchk);
        push(Nchk);
        free(Nchk);
    }

    // Here...!!
    printf("%s\n",que[0].s);
    printf("%s\n",que[1].s);
    printf("%s\n",que[2].s);
}

int main(void){
    int ans = -1;
    Temp();
    return 0;
}
</code>```

//Here...!
I was also expecting the queue value to be 123, 456, 789.

Body:
I'm practicing string in C language and I'm posting a question because I got an unwanted result.

I saved the string in the order of 123, 456, 789, but //Here output is 789,789, 789.

I would appreciate it if you could point out the wrong part.

Thank you for reading it.

#include <stdio.h>
#include <stdlib.h>

typedef struct Que
{
    char *s;
    int t;
} QUE;
QUE que[50];
int wp;
void push(char *s)
{
    que[wp].s = s;
    printf("que[wp].s = %s\n",que[wp].s);
    wp++;
}

int cnt = 0;

char * input(char *str)
{
    static char arr[3];

    if(cnt == 0)
    {
        arr[0] = '1';
        arr[1] = '2';
        arr[2] = '3';
    }
    else if(cnt==1)
    {
        arr[0] = '4';
        arr[1] = '5';
        arr[2] = '6';
    }
    else if(cnt==2)
    {
        arr[0] = '7';
        arr[1] = '8';
        arr[2] = '9';
    }

    cnt++;

    return arr;
}

void Temp()
{
    char *a = "123";

    for(int i=0; i<3; i++)
    {
        char *Nchk = malloc(sizeof(char)*3);

        Nchk = input(a);
        printf("Nchk = %s\n",Nchk);
        push(Nchk);
        free(Nchk);
    }

    // Here...!!
    printf("%s\n",que[0].s);
    printf("%s\n",que[1].s);
    printf("%s\n",que[2].s);
}

int main(void){
    int ans = -1;
    Temp();
    return 0;
}

//Here...!
I was also expecting the queue value to be 123, 456, 789.


问:
Data insert from front-end duplicate data can't protected in WordPress
At first, I created a custom template and wrote the following script.

I was trying to protect duplicate values using isset but didn't get the solution and logic working. Can you tell me how to fix it?

if ( isset( $_POST['submit'] ) ) {
    if ( 'POST' == $_SERVER['REQUEST_METHOD'] && ! empty( $_POST['action'] ) ) {
        if ( isset( $_POST['title'] ) ) {
            $title = $_POST['title'];
        } else {
            echo 'Please enter a title';
        }
        if ( isset( $_POST['description'] ) ) {
            $description = $_POST['description'];
        } else {
            echo 'Please enter the content';
        }

        $post = array(
            'post_title'   => $title,
            'post_content' => $description,
            'post_status'  => 'draft',
            'post_type'    => 'portfolio',
        );
        $pid  = wp_insert_post( $post );
    }
}

?>
<form action="" method="post">

        Titolo

        <input type="text" id="title" value="" tabindex="1" size="20" name="title" />

        Testo

        <textarea id="description" tabindex="3" name="description" cols="50" rows="6"></textarea>

        <input type="submit" value="submit" id="submit" name="submit"/>

    <input type="hidden" name="post_type" id="post_type" value="domande" />
    <input type="hidden" name="action" value="post" />
    <?php wp_nonce_field( 'new-post' ); ?>
</form>
```


问:
Face expression recognize using deepface shows error "list index out of range"
This is my code:

```<code>import cv2
from deepface import DeepFace
import numpy as np

face_cascade_name = cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml'  # getting a haarcascade xml file
face_cascade = cv2.CascadeClassifier()  # processing it for our project
if not face_cascade.load(cv2.samples.findFile(face_cascade_name)):  # adding a fallback event
    print("Error loading xml file")

video = cv2.VideoCapture(0)  # requisting the input from the webcam or camera

while video.isOpened():  # checking if are getting video feed and using it
    _, frame = video.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # changing the video to grayscale to make the face analisis work properly
    face = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

    for x, y, w, h in face:
        img = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 1)  # making a recentangle to show up and detect the face and setting it position and colour

        # making a try and except condition in case of any errors
    # try:
        analyze = DeepFace.analyze(frame, actions=['emotions'])  # same thing is happing here as the previous example, we are using the analyze class from deepface and using ‘frame’ as input
        print(analyze['dominant_emotion'])  # here we will only go print out the dominant emotion also explained in the previous example
        # except:
        #     print("no face")

        # this is the part where we display the output to the user
        cv2.imshow('video', frame)
        key = cv2.waitKey(1)
        if key == ord('q'):  # here we are specifying the key which will stop the loop and stop all the processes going
            break
    video.release()
</code>```

The error I'm facing while running the code:

```<code>Traceback (most recent call last):
  File "D:\workspace\python\face_expression_detect\program.py", line 23, in <module>
    analyze = DeepFace.analyze(frame, actions=['emotions'])  # same thing is happing here as the previous example, we are using the analyze class from deepface and using ‘frame’ as input
  File "D:\workspace\python\face_expression_detect\facerecog\lib\site-packages\deepface\DeepFace.py", line 452, in analyze
    resp_obj["region"][parameter] = int(region[i]) #int cast is for the exception - object of type 'float32' is not JSON serializable
IndexError: list index out of range
</code>```

How to handle this error?

Body:
This is my code:

import cv2
from deepface import DeepFace
import numpy as np

face_cascade_name = cv2.data.haarcascades + 'haarcascade_frontalface_alt.xml'  # getting a haarcascade xml file
face_cascade = cv2.CascadeClassifier()  # processing it for our project
if not face_cascade.load(cv2.samples.findFile(face_cascade_name)):  # adding a fallback event
    print("Error loading xml file")

video = cv2.VideoCapture(0)  # requisting the input from the webcam or camera

while video.isOpened():  # checking if are getting video feed and using it
    _, frame = video.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)  # changing the video to grayscale to make the face analisis work properly
    face = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

    for x, y, w, h in face:
        img = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 1)  # making a recentangle to show up and detect the face and setting it position and colour

        # making a try and except condition in case of any errors
    # try:
        analyze = DeepFace.analyze(frame, actions=['emotions'])  # same thing is happing here as the previous example, we are using the analyze class from deepface and using ‘frame’ as input
        print(analyze['dominant_emotion'])  # here we will only go print out the dominant emotion also explained in the previous example
        # except:
        #     print("no face")

        # this is the part where we display the output to the user
        cv2.imshow('video', frame)
        key = cv2.waitKey(1)
        if key == ord('q'):  # here we are specifying the key which will stop the loop and stop all the processes going
            break
    video.release()

The error I'm facing while running the code:

Traceback (most recent call last):
  File "D:\workspace\python\face_expression_detect\program.py", line 23, in <module>
    analyze = DeepFace.analyze(frame, actions=['emotions'])  # same thing is happing here as the previous example, we are using the analyze class from deepface and using ‘frame’ as input
  File "D:\workspace\python\face_expression_detect\facerecog\lib\site-packages\deepface\DeepFace.py", line 452, in analyze
    resp_obj["region"][parameter] = int(region[i]) #int cast is for the exception - object of type 'float32' is not JSON serializable
IndexError: list index out of range

How to handle this error?


问:
IOS uses css to make repeated animation, which flashes when the repetition starts
When the ios terminal uses css to do repeated animation beyond the screen, it will flash at the beginning of the repetition

I tried

-webkit-backface-visibility: hidden;

```<code>    <div class="box">
        <div class="content-box" v-for="(item, index) in [1, 1]">
            <div v-for="(listitem, listindex) in list" class="list-item">
                {{listitem.text}}
            </div>
        </div>
    </div>
   <style>
        .box {
          display: flex;
          flex-direction: row;
          animation: test 8s linear 0s infinite normal;
        }
        .content-box {
          display: flex;
          flex-direction: column;
          min-width: 100vw;
        }
        .list-item {
          white-space: nowrap;
          padding: 10px 24px;

          margin-right: 20px;
          background: #F5F6F9;
          border-radius: 32px;
          display: flex;
          flex-direction: row;
          align-items: center;
          justify-content: center;
        }
   </style>
</code>```

Body:
When the ios terminal uses css to do repeated animation beyond the screen, it will flash at the beginning of the repetition

I tried

-webkit-backface-visibility: hidden;

                {{listitem.text}}


问:
Window becomes black when there are multi QOpenGLWIdget
I am developing application with QT5.11 and VTK8.2.   There are 2 sub windows in the qmdiarea. Each of the windows has a QOpenGLWidget. First it behaves very well.

enter image description here

When I try to scroll the mdi area, one of the window becomes black.
enter image description here

I have spent a lot of time on it. However there is no progress. Can someone give me some tip about the issue?
Any help is appreciate.
Thanks

I have done a lot of research about the issue.  First I suspect that the margin of the layout which holds the widget is not set 0. But it's the cause because the issue is still there even after I set the margin to 0. Then I search about the QOpenGLWidget and did some research about QOffscreenSurface and QSurfaceFormat. But I feel very frustrated because I can't figure out what causes the issue.


问:
Is there a single word that means "upsert or delete"?
I've written a function that upserts a row in to my database and deletes it if it's blank. I'm struggling to name it. If it only upserted, I'd just call it that. And if it only deleted, I'd just call it that. Like how "upsert" combines "update" and "insert", is there a word that includes "delete" in that grouping?</p>


问:
from plotly express figure to image without saving it to use it on STREAMLIT
I want to be able to use this image on my streamlit website as a .png format without having to saving it any where

Dummy code:

import streamlit as st

import plotly.express as px
wide_df = px.data.medals_wide()

fig = px.bar(wide_df, x="nation", y=["gold", "silver", "bronze"], title="Wide-Form Input, relabelled",
            labels={"value": "count", "variable": "medal"})
fig.show()
```

Right now, I would save the image on a temp folder and then read this image from another file.

I want to pass this "image" to the other function without having to save it.

Body:
I want to be able to use this image on my streamlit website as a .png format without having to saving it any where

Dummy code:

import streamlit as st

import plotly.express as px
wide_df = px.data.medals_wide()

fig = px.bar(wide_df, x="nation", y=["gold", "silver", "bronze"], title="Wide-Form Input, relabelled",
            labels={"value": "count", "variable": "medal"})
fig.show()

Right now, I would save the image on a temp folder and then read this image from another file.

I want to pass this "image" to the other function without having to save it.


问:
Angular project files extension changes on Migration from view engine to ivy angular 13
I have few angular libraries in my angular project. We will rollup all the files contains code related to my components, services, libraries and generate a loader file. Also there is a libs file that is generated using rollup with all the third party libraries.
These two libs.js and loader.js files will be used in the index.html to load it as a webapp.

After migrating to angular 13 ivy, it is generating esm modules with .mjs file extensions. I tried to combine all the .mjs files and tried to generate a loader.mjs file now.

Also add script with

```<code><script type="module" src="libs.mjs" ></script>
<script type="module" src="loader.mjs" ></script>
</code>```

this throws error on running the webapp as identifiers has already been declared. I had combined all the files into single file and it is not possible to resolve these issues in the combined file. I end up resolving each issue in every file.

How to handle using .mjs files ?
Is this a proper approach?
I need to convert .mjs back to .js files and work with .js files as I was doing before ?

Body:
I have few angular libraries in my angular project. We will rollup all the files contains code related to my components, services, libraries and generate a loader file. Also there is a libs file that is generated using rollup with all the third party libraries.
These two libs.js and loader.js files will be used in the index.html to load it as a webapp.

After migrating to angular 13 ivy, it is generating esm modules with .mjs file extensions. I tried to combine all the .mjs files and tried to generate a loader.mjs file now.

Also add script with

this throws error on running the webapp as identifiers has already been declared. I had combined all the files into single file and it is not possible to resolve these issues in the combined file. I end up resolving each issue in every file.

How to handle using .mjs files ?
Is this a proper approach?
I need to convert .mjs back to .js files and work with .js files as I was doing before ?


问:
decrement/increment operator not working in javascript
I was working on an algorithm on hackerrank and was wondering why my answer was not correct.

Here is the function

```<code>function diagonalDifference(arr) {
// Write your code here

let first = 0
let second = 0
let endArr = arr.length-1
for(let i=0;i<arr.length;i++){
    first += arr[i][i]
    second += arr[i][endArr]
    console.log(endArr)
    endArr = endArr--
}

let result = Math.abs(first-second)
console.log(result)
return result
</code>```

}

it was not until I changed the statement endArr = endArr-- to endArr = endArr-1 that I got my desired answer.

I would let to know why. I thought -- meant decrementing by 1?

Body:
I was working on an algorithm on hackerrank and was wondering why my answer was not correct.

Here is the function

function diagonalDifference(arr) {
// Write your code here

let first = 0
let second = 0
let endArr = arr.length-1
for(let i=0;i<arr.length;i++){
    first += arr[i][i]
    second += arr[i][endArr]
    console.log(endArr)
    endArr = endArr--
}

let result = Math.abs(first-second)
console.log(result)
return result

}

it was not until I changed the statement endArr = endArr-- to endArr = endArr-1 that I got my desired answer.

I would let to know why. I thought -- meant decrementing by 1?


问:
nextJS upload image to external cloud
```<code>import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import formidable from "formidable"
var fs = require('fs');
var FormData = require('form-data');

export const config = {
api: {
  bodyParser: false, // Defaults to true. Setting this to false disables body parsing and allows you to consume the request body as stream or raw-body.
},
};

const readFile = (req: NextApiRequest, res: NextApiResponse<any>) => {
const options = {
  uploadDir: `./public/upload`,
  keepExtensions: true,
}
const form = formidable(options)
return new Promise((resolve, reject) => {
    form.parse(req, async (err, fields, files) => {
        if(err) reject(err)
        resolve({fields, files})
        var bodyData = new FormData();
        bodyData.append('files', fs.createReadStream("./public/upload/"+files.file.newFilename));
        var myHeaders = new Headers();
        myHeaders.append("Authorization", "xxxxxxxxxxx");
        myHeaders.append("Content-Type", "multipart/form-data");
        const result = await fetch('https://xxxxxxxxxxxxx', {
            method: 'POST',
            headers: myHeaders,
            body: bodyData,
        })
        const data = await result.json()
        if(data){
            res.send(data)
        }
        res.send(bodyData)
    })
})
</code>```

}

```<code>const handler: NextApiHandler = async (req, res) => {
await readFile(req, res)
}

export default handler
</code>```

Here this is my code, and when i call this, return me Failed to Fetch

I try lot of things lot really working, the variable files returns me well the file who i send in my body.

Title: nextJS upload image to external cloud

Body:
import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import formidable from "formidable"
var fs = require('fs');
var FormData = require('form-data');

export const config = {
api: {
  bodyParser: false, // Defaults to true. Setting this to false disables body parsing and allows you to consume the request body as stream or raw-body.
},
};

const readFile = (req: NextApiRequest, res: NextApiResponse<any>) => {
const options = {
  uploadDir: `./public/upload`,
  keepExtensions: true,
}
const form = formidable(options)
return new Promise((resolve, reject) => {
    form.parse(req, async (err, fields, files) => {
        if(err) reject(err)
        resolve({fields, files})
        var bodyData = new FormData();
        bodyData.append('files', fs.createReadStream("./public/upload/"+files.file.newFilename));
        var myHeaders = new Headers();
        myHeaders.append("Authorization", "xxxxxxxxxxx");
        myHeaders.append("Content-Type", "multipart/form-data");
        const result = await fetch('https://xxxxxxxxxxxxx', {
            method: 'POST',
            headers: myHeaders,
            body: bodyData,
        })
        const data = await result.json()
        if(data){
            res.send(data)
        }
        res.send(bodyData)
    })
})

}

const handler: NextApiHandler = async (req, res) => {
await readFile(req, res)
}

export default handler

Here this is my code, and when i call this, return me Failed to Fetch

I try lot of things lot really working, the variable files returns me well the file who i send in my body.


问:
Same shape/size of training set and validation set with history.history() function
I am referring to the code for Regression analysis. The validation_split is set at 0.05:

# fit the network
history = model.fit(seq_array, label_array, epochs=100, batch_size=200, validation_split=0.05, verbose=2,
          callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=0, mode='min'),
                       keras.callbacks.ModelCheckpoint(model_path,monitor='val_loss', save_best_only=True, mode='min', verbose=0)]
          )

# list all data in history
print(history.history.keys())
```
<p>Then I plot the R2 value:</p>
<pre class="lang-py prettyprint-override"><code># summarize history for R^2
fig_acc = plt.figure(figsize=(10, 10))
plt.plot(history.history['r2_keras'])
plt.plot(history.history['val_r2_keras'])
plt.title('model r^2')
plt.ylabel('R^2')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
fig_acc.savefig("model_r2.png")
</code>```

My question is: why history.history['r2_keras'] and history.history['val_r2_keras'] have the same number of elements when validation_split is set at 0.05.

Body:
I am referring to the code for Regression analysis. The validation_split is set at 0.05:

# fit the network
history = model.fit(seq_array, label_array, epochs=100, batch_size=200, validation_split=0.05, verbose=2,
          callbacks = [keras.callbacks.EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=0, mode='min'),
                       keras.callbacks.ModelCheckpoint(model_path,monitor='val_loss', save_best_only=True, mode='min', verbose=0)]
          )

# list all data in history
print(history.history.keys())

Then I plot the R2 value:

# summarize history for R^2
fig_acc = plt.figure(figsize=(10, 10))
plt.plot(history.history['r2_keras'])
plt.plot(history.history['val_r2_keras'])
plt.title('model r^2')
plt.ylabel('R^2')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
fig_acc.savefig("model_r2.png")

My question is: why history.history['r2_keras'] and history.history['val_r2_keras'] have the same number of elements when validation_split is set at 0.05.


问:
When data is processed in the .done() function, how do I remove the beforesend() function?
I'm learning jquery because it's widely used in my current company. I'm having trouble with the following code. I can add the beforesend() function when the form is submitted with the message 'submitting,' but I can't remove it when the data is processed in the .done() function. Please help.

Thanks in advance!

This is my code:

```<code>   <!-- post form data -->
    <script>
        $(document).ready(function() {
            $(".startup_form").on("submit", function(event) {
                event.preventDefault();
                let formData = $(this).serialize();
                $.ajax({
                    type: "POST",
                    url: "bot/company_crawler.php",
                    data: formData,
                    dataType: "json",
                    encode: true,
                    beforeSend: function() {
                        $("#submitBtn").attr('disabled','disabled');
                        $("#loading").removeClass('hide');
                        $("#loading").addClass('show');
                    }
                }).done(function(data) {
                    $("#submitBtn").removeAttr('disabled');
                    $("#loading").addClass('hide');
                    $("#loading").removeClass('show');
                    console.log(data);
                });
            });
        });
    </script>
    <!-- ./post form data -->
</code>```


问:
Clicking on odoo menu show `Document empty` error
I am getting the following error on odoo 15.0 when clicking on menu Time Off/Approvals/Time Off

This menu is linked to the action

```<code>open_view_holiday_status
</code>```

from odoo module's hr_holidays which in turn is linked to the view tree

```<code>view_holiday_status_normal_tree
</code>```

I have extended that view the following way in a module named hr_holidays_base:

```<code>    <record id="holiday_status_base_tree" model="ir.ui.view">
        <field name="name">hr.holidays.status.tree</field>
        <field name="model">hr.leave.type</field>
        <field name="inherit_id" ref="hr_holidays.view_holiday_status_normal_tree" />
        <field name="priority" eval="1" />
        <field name="arch" type="xml">
            <field name='display_name' position="after">
                <field
                    name="max_leaves"
                    invisible="not context.get('active_id',False)"
                />
                <field
                    name="leaves_taken"
                    invisible="not context.get('active_id',False)"
                />
                <field
                    name="remaining_leaves"
                    invisible=" not context.get('active_id',False)"
                />
            </field>
        </field>
    </record>
</code>```

Note: i have a second view tree extending from it too:

```<code>    <record id="secondary_holiday_status_base_tree" model="ir.ui.view">
        <field name="name">secondary.hr.holidays.status.tree</field>
        <field name="model">hr.leave.type</field>
        <field name="inherit_id" ref="hr_holidays_base.holiday_status_base_tree" />
        <field name="mode">primary</field>
        <field name="priority" eval="15" />
        <field name="arch" type="xml">
            <field name="company_id" position="attributes">
                <attribute name="invisible">1</attribute>
            </field>
        </field>
    </record>
</code>```

Now getting the error:

Error:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/odoo/http.py", line 643, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/local/lib/python3.10/dist-packages/odoo/http.py", line 301, in _handle_exception
    raise exception.with_traceback(None) from new_cause
  File "<string>", line 1
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1
</code>```

What could go wrong? any hint maybe?

I have tried following the execution of every step by step. I have searched these defined views from the UI and they work well individually. The only issue is when trying on that menu and this is where it shows the error

Body:
I am getting the following error on odoo 15.0 when clicking on menu Time Off/Approvals/Time Off

This menu is linked to the action

open_view_holiday_status

from odoo module's hr_holidays which in turn is linked to the view tree

view_holiday_status_normal_tree

I have extended that view the following way in a module named hr_holidays_base:

    <record id="holiday_status_base_tree" model="ir.ui.view">
        <field name="name">hr.holidays.status.tree</field>
        <field name="model">hr.leave.type</field>
        <field name="inherit_id" ref="hr_holidays.view_holiday_status_normal_tree" />
        <field name="priority" eval="1" />
        <field name="arch" type="xml">
            <field name='display_name' position="after">
                <field
                    name="max_leaves"
                    invisible="not context.get('active_id',False)"
                />
                <field
                    name="leaves_taken"
                    invisible="not context.get('active_id',False)"
                />
                <field
                    name="remaining_leaves"
                    invisible=" not context.get('active_id',False)"
                />
            </field>
        </field>
    </record>

Note: i have a second view tree extending from it too:

    <record id="secondary_holiday_status_base_tree" model="ir.ui.view">
        <field name="name">secondary.hr.holidays.status.tree</field>
        <field name="model">hr.leave.type</field>
        <field name="inherit_id" ref="hr_holidays_base.holiday_status_base_tree" />
        <field name="mode">primary</field>
        <field name="priority" eval="15" />
        <field name="arch" type="xml">
            <field name="company_id" position="attributes">
                <attribute name="invisible">1</attribute>
            </field>
        </field>
    </record>

Now getting the error:

Error:

Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/odoo/http.py", line 643, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/local/lib/python3.10/dist-packages/odoo/http.py", line 301, in _handle_exception
    raise exception.with_traceback(None) from new_cause
  File "<string>", line 1
lxml.etree.XMLSyntaxError: Document is empty, line 1, column 1

What could go wrong? any hint maybe?

I have tried following the execution of every step by step. I have searched these defined views from the UI and they work well individually. The only issue is when trying on that menu and this is where it shows the error