问:
Getting Error: read ECONNRESET while trying to send code through Postman Desktop agent
I'm trying to send data through Postman Desktop Agent to localhost:27017/articles. My mongod server is running. Tried hotspot on my phone as well as my home internet connection.   I dont think the internet is the issue. I don't have a VPN nor do I require one. I'm 99% sure my code is correct. I'm getting in the Postman console "Error: read ECONNRESET"  As well, I scoured the internet for a solution but nothing to my situtation.

`

```<code>//jshint version:6

var express = require('express');
var bodyParser = require('body-parser');
const mongoose = require('mongoose');
let ejs = require('ejs');

//express setup
const app = express();

//EJS setup with express
app.set('view engine', 'ejs');

//body parser setup
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

app.use(express.urlencoded({
  extended: true
}));

app.use(bodyParser.json());

//Mongoose setup
mongoose.set("strictQuery", false);

main().catch(err => console.log(err));

var db = {};
var settings = {
  reconnectTries: Number.MAX_VALUE,
  autoReconnect: true
};
async function main() {
  await mongoose.connect("mongodb://localhost:27017/wikiDB", settings, function(err, dbref) {
      if (!err) {
        console.log("Mongdb connected (new code)");
        db = dbref;
      } else {
        console.log("Error while connecting to mongDB" + err);
      }
  });
}

const articleSchema = new mongoose.Schema({
  title: String,
  content: String
});

const Article = mongoose.model("Article", articleSchema);

async function save(err){
  if (!err){
    const article = await article.save();
    console.log(article + " saved");
  }else{
    console.log(err);
  }
}

app.get("/articles", function(req, res) {
  Article.find(function(err, foundArticles) {
    if (!err) {
      res.send(foundArticles);
    } else {
      res.send(err)
    }

  });
});

app.post("/articles", function(req, res) {
  console.log("post request")
  console.log(req.body.title);
  console.log(req.body.content);

});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

</code>```

`

I tried calling the internet company to see if there was a proxy or something that i know nothing about that was blocking the transfer from Postman to localhost... I tried error catching in my mongoose.connect(...) function. No problems there. Seems to running fine as you can see in the screenshot of Hyperterminal loaded up. I tried restarting mongod server.    I read the ECONNRESET error on the postman community portal. I didnt see anything I needed to change. Restful application working on localhost:3000

Body:
I'm trying to send data through Postman Desktop Agent to localhost:27017/articles. My mongod server is running. Tried hotspot on my phone as well as my home internet connection.   I dont think the internet is the issue. I don't have a VPN nor do I require one. I'm 99% sure my code is correct. I'm getting in the Postman console "Error: read ECONNRESET"  As well, I scoured the internet for a solution but nothing to my situtation.

`

//jshint version:6

var express = require('express');
var bodyParser = require('body-parser');
const mongoose = require('mongoose');
let ejs = require('ejs');

//express setup
const app = express();

//EJS setup with express
app.set('view engine', 'ejs');

//body parser setup
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: true
}));
app.use(express.static("public"));

app.use(express.urlencoded({
  extended: true
}));

app.use(bodyParser.json());

//Mongoose setup
mongoose.set("strictQuery", false);

main().catch(err => console.log(err));

var db = {};
var settings = {
  reconnectTries: Number.MAX_VALUE,
  autoReconnect: true
};
async function main() {
  await mongoose.connect("mongodb://localhost:27017/wikiDB", settings, function(err, dbref) {
      if (!err) {
        console.log("Mongdb connected (new code)");
        db = dbref;
      } else {
        console.log("Error while connecting to mongDB" + err);
      }
  });
}

const articleSchema = new mongoose.Schema({
  title: String,
  content: String
});

const Article = mongoose.model("Article", articleSchema);

async function save(err){
  if (!err){
    const article = await article.save();
    console.log(article + " saved");
  }else{
    console.log(err);
  }
}

app.get("/articles", function(req, res) {
  Article.find(function(err, foundArticles) {
    if (!err) {
      res.send(foundArticles);
    } else {
      res.send(err)
    }

  });
});

app.post("/articles", function(req, res) {
  console.log("post request")
  console.log(req.body.title);
  console.log(req.body.content);

});

app.listen(3000, function() {
  console.log("Server started on port 3000");
});

`

I tried calling the internet company to see if there was a proxy or something that i know nothing about that was blocking the transfer from Postman to localhost... I tried error catching in my mongoose.connect(...) function. No problems there. Seems to running fine as you can see in the screenshot of Hyperterminal loaded up. I tried restarting mongod server.    I read the ECONNRESET error on the postman community portal. I didnt see anything I needed to change. Restful application working on localhost:3000


来源: stackexchange

问:
Sortable column headers based off dynamic input?
Firstly I'd like to apologize for the topic question... I simply couldn't think of a question. Mainly because I don't know what I am looking for. I just need a hint or a pointer to the general direction of how to solve my problem. I think this is where my inexperience with the web shows a little... Anyway!

So what I have right now is a drop down with users in it. Select the user, and info comes up in 4 columns. That info needs to be sortable from the column headers. I can do both things independently from each other (the selection and the sorting), but I think the post/submit of the dropdown happens before I can save the variables to be passed in the URL, so I can't get it to behave properly.

So here's the code:

```<code><form action="" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
  User: <select name="user_id">
<?php foreach($users as $user): ?>
<option value="<?php echo $user['id']; ?>" <?php echo ($user_id == $user['id'] ? 'selected' : ''); ?>><?php echo $user['name']; ?></option>
<?php endforeach ?>
</select>
<input type="submit" name="submit" value="Select">
</form>

<table id="one-column-emphasis" summary="All Accounts">
<thead>
<tr>
<th style="width:20%"><a href="index.php?module=task_queue_list_per_user&action=view_list&sort=name">Name</a></th>
<th style="width:10%"><a href="index.php?module=task_queue_list_per_user&action=view_list&sort=priority">Priority</a></th>
<th style="width:10%"><a href="index.php?module=task_queue_list_per_user&action=view_list&sort=created_date">Date Created</a></th>
<th style="width:10%"><a href="index.php?module=task_queue_list_per_user&action=view_list&sort=created_date">Age</a></th>
</tr>
</thead>
</code>```

What I think is happening is that the submit happens before the variables can be set to send to the database file. If I have a user selected and click on the column header to sort it, it takes me back to the default where there is no user selected.

Any ideas, tips or help?
Thanks

ContentLicense: CC BY-SA 3.0

Body:
Firstly I'd like to apologize for the topic question... I simply couldn't think of a question. Mainly because I don't know what I am looking for. I just need a hint or a pointer to the general direction of how to solve my problem. I think this is where my inexperience with the web shows a little... Anyway!

So what I have right now is a drop down with users in it. Select the user, and info comes up in 4 columns. That info needs to be sortable from the column headers. I can do both things independently from each other (the selection and the sorting), but I think the post/submit of the dropdown happens before I can save the variables to be passed in the URL, so I can't get it to behave properly.

So here's the code:

<form action="" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>">
  User: <select name="user_id">
<?php foreach($users as $user): ?>
<option value="<?php echo $user['id']; ?>" <?php echo ($user_id == $user['id'] ? 'selected' : ''); ?>><?php echo $user['name']; ?></option>
<?php endforeach ?>
</select>
<input type="submit" name="submit" value="Select">
</form>

Name
Priority
Date Created
Age

What I think is happening is that the submit happens before the variables can be set to send to the database file. If I have a user selected and click on the column header to sort it, it takes me back to the default where there is no user selected.

Any ideas, tips or help?
Thanks


问:
Merge SVG shapes or paths
I am trying to create custom map geographies using 30k underlying SVG paths/shapes.

I want to merge shapes of same colour and then create and outline border for the merged SVG shapes/paths.

It would be great if you could guide me on how to do this. Wasn’t able to find any solution yet.

One way was to hide the outlines but if the colour of two neighbouring boundaries is same we would not be able to distinguish the two geographies.

Thanks in advance

ContentLicense: CC BY-SA 4.0

Title: Merge SVG shapes or paths


问:
How to prepend data to .nc file?
So I was given some code which downloads some new data, checks the existing file for equality, and if needed slices the new data and appends the most recently collected data, and skips if not. This script can be run manually or on a timer.

The code is netCDF4 is perfectly capable of appending data, but I can't seem to figure out how to prepend data.

The codes was designed to append with:

```<code>net_array[ last_index : ] = new_data[ slice_index : ]
</code>```

But prepending doesn't work with

```<code>net_array[ : first_index ] = new_data[ : slice_index ]
</code>```

So how do?

Title: How to prepend data to .nc file?

Body:
So I was given some code which downloads some new data, checks the existing file for equality, and if needed slices the new data and appends the most recently collected data, and skips if not. This script can be run manually or on a timer.

The code is netCDF4 is perfectly capable of appending data, but I can't seem to figure out how to prepend data.

The codes was designed to append with:

net_array[ last_index : ] = new_data[ slice_index : ]

But prepending doesn't work with

net_array[ : first_index ] = new_data[ : slice_index ]

So how do?


问:
ValueError: Input 0 of layer "conv1d" is incompatible with the layer: expected min_ndim=3, found ndim=2. Full shape received: (None, 172)
```<code>print("x: ", x_train.shape)
print("x: ", x_test.shape)
print("y: ", y_train.shape)
print("y: ", y_test.shape)
</code>```

........................output..............................
x:  (172, 1177)
x:  (30, 1177)
y:  (172,)
y:  (30,)

......................................

```<code>from keras.models import Sequential
import keras
from keras.layers import Conv1D
model = Sequential()
y_train1 = y_train
y_test1 = y_test
# Conv1:
model.add(keras.layers.Conv1D(filters = 32, kernel_size=1,strides = 1, activation='relu', input_shape=(128,1)))
# Conv2:
model.add(keras.layers.Conv1D(filters = 32, kernel_size=1,strides = 1, activation='relu'))
# Pool1:
model.add(keras.layers.MaxPool1D(pool_size=(3), strides = 1))
# BN1:
model.add(keras.layers.BatchNormalization())
# Conv3:
model.add(keras.layers.Conv1D(filters = 64, kernel_size=1,strides = 1, activation='relu'))
# Conv4:
model.add(keras.layers.Conv1D(filters = 64, kernel_size=1,strides = 1, activation='relu'))
# Pool2:
model.add(keras.layers.MaxPool1D(pool_size=(3), strides = 1))
# BN2:
model.add(keras.layers.BatchNormalization())

model.add(keras.layers.Conv1D(filters = 128, kernel_size=1,strides = 1, activation='relu'))
# Conv6:
model.add(keras.layers.Conv1D(filters = 128, kernel_size=1,strides = 1, activation='relu'))
# Pool3:
model.add(keras.layers.GlobalMaxPooling1D())
# BN4:
model.add(keras.layers.BatchNormalization())

import tensorflow as tf
model.add(tf.keras.layers.Flatten())
# Dense1:
model.add(keras.layers.Dense(units=256, activation='relu',use_bias=True))
# Dense2:
model.add(keras.layers.Dense(units=128, activation='relu',use_bias=True))
# BN3:
model.add(keras.layers.BatchNormalization())
# Dense3:
model.add(keras.layers.Dense(units=16, activation='softmax',use_bias=True))
model.compile(optimizer = "adam", loss = tf.losses.binary_crossentropy, metrics = ['accuracy'])
#
# epochs = 50
# batch_size = 64
# model.save("my_model.h5")
model.summary()

</code>```

.........................................output............................................

```<code>Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 conv1d (Conv1D)             (None, 128, 32)           64

 conv1d_1 (Conv1D)           (None, 128, 32)           1056

 max_pooling1d (MaxPooling1D  (None, 126, 32)          0
 )

 batch_normalization (BatchN  (None, 126, 32)          128
 ormalization)

 conv1d_2 (Conv1D)           (None, 126, 64)           2112

 conv1d_3 (Conv1D)           (None, 126, 64)           4160

 max_pooling1d_1 (MaxPooling  (None, 124, 64)          0
 1D)

 batch_normalization_1 (Batc  (None, 124, 64)          256
 hNormalization)

 conv1d_4 (Conv1D)           (None, 124, 128)          8320

 conv1d_5 (Conv1D)           (None, 124, 128)          16512

 global_max_pooling1d (Globa  (None, 128)              0
 lMaxPooling1D)

 batch_normalization_2 (Batc  (None, 128)              512
 hNormalization)

 flatten (Flatten)           (None, 128)               0

 dense (Dense)               (None, 256)               33024

 dense_1 (Dense)             (None, 128)               32896

 batch_normalization_3 (Batc  (None, 128)              512
 hNormalization)

 dense_2 (Dense)             (None, 16)                2064

=================================================================
Total params: 101,616
Trainable params: 100,912
Non-trainable params: 704
_________________________________________________________________
Epoch 1/43

</code>```
```<code>model_history = model.fit(x_train,y_train1, batch_size=32, epochs=43, verbose=1)
</code>```

....................................................Error...........................................

```<code>Traceback (most recent call last):
  File "C:\Users\rulzem\PycharmProjects\fyp preprocessing\main.py", line 453, in <module>
    model_history = model.fit(x_train,y_train1, batch_size=32, epochs=43, verbose=1)
  File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\rulzem\AppData\Local\Temp\__autograph_generated_fileqs1j0crv.py", line 15, in tf__train_function
    retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:

    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1249, in train_function  *
        return step_function(self, iterator)
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1233, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1222, in run_step  **
        outputs = model.train_step(data)
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1023, in train_step
        y_pred = self(x, training=True)
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\input_spec.py", line 295, in assert_input_compatibility
        raise ValueError(

    **ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 128, 1), found shape=(None, 1177)**

</code>```

I am applying CNN model but at the time of model fitting i am getting errror, i tried many solutions but no one work

Body:
print("x: ", x_train.shape)
print("x: ", x_test.shape)
print("y: ", y_train.shape)
print("y: ", y_test.shape)

........................output..............................
x:  (172, 1177)
x:  (30, 1177)
y:  (172,)
y:  (30,)

......................................

from keras.models import Sequential
import keras
from keras.layers import Conv1D
model = Sequential()
y_train1 = y_train
y_test1 = y_test
# Conv1:
model.add(keras.layers.Conv1D(filters = 32, kernel_size=1,strides = 1, activation='relu', input_shape=(128,1)))
# Conv2:
model.add(keras.layers.Conv1D(filters = 32, kernel_size=1,strides = 1, activation='relu'))
# Pool1:
model.add(keras.layers.MaxPool1D(pool_size=(3), strides = 1))
# BN1:
model.add(keras.layers.BatchNormalization())
# Conv3:
model.add(keras.layers.Conv1D(filters = 64, kernel_size=1,strides = 1, activation='relu'))
# Conv4:
model.add(keras.layers.Conv1D(filters = 64, kernel_size=1,strides = 1, activation='relu'))
# Pool2:
model.add(keras.layers.MaxPool1D(pool_size=(3), strides = 1))
# BN2:
model.add(keras.layers.BatchNormalization())

model.add(keras.layers.Conv1D(filters = 128, kernel_size=1,strides = 1, activation='relu'))
# Conv6:
model.add(keras.layers.Conv1D(filters = 128, kernel_size=1,strides = 1, activation='relu'))
# Pool3:
model.add(keras.layers.GlobalMaxPooling1D())
# BN4:
model.add(keras.layers.BatchNormalization())

import tensorflow as tf
model.add(tf.keras.layers.Flatten())
# Dense1:
model.add(keras.layers.Dense(units=256, activation='relu',use_bias=True))
# Dense2:
model.add(keras.layers.Dense(units=128, activation='relu',use_bias=True))
# BN3:
model.add(keras.layers.BatchNormalization())
# Dense3:
model.add(keras.layers.Dense(units=16, activation='softmax',use_bias=True))
model.compile(optimizer = "adam", loss = tf.losses.binary_crossentropy, metrics = ['accuracy'])
#
# epochs = 50
# batch_size = 64
# model.save("my_model.h5")
model.summary()

.........................................output............................................

Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #
=================================================================
 conv1d (Conv1D)             (None, 128, 32)           64

 conv1d_1 (Conv1D)           (None, 128, 32)           1056

 max_pooling1d (MaxPooling1D  (None, 126, 32)          0
 )

 batch_normalization (BatchN  (None, 126, 32)          128
 ormalization)

 conv1d_2 (Conv1D)           (None, 126, 64)           2112

 conv1d_3 (Conv1D)           (None, 126, 64)           4160

 max_pooling1d_1 (MaxPooling  (None, 124, 64)          0
 1D)

 batch_normalization_1 (Batc  (None, 124, 64)          256
 hNormalization)

 conv1d_4 (Conv1D)           (None, 124, 128)          8320

 conv1d_5 (Conv1D)           (None, 124, 128)          16512

 global_max_pooling1d (Globa  (None, 128)              0
 lMaxPooling1D)

 batch_normalization_2 (Batc  (None, 128)              512
 hNormalization)

 flatten (Flatten)           (None, 128)               0

 dense (Dense)               (None, 256)               33024

 dense_1 (Dense)             (None, 128)               32896

 batch_normalization_3 (Batc  (None, 128)              512
 hNormalization)

 dense_2 (Dense)             (None, 16)                2064

=================================================================
Total params: 101,616
Trainable params: 100,912
Non-trainable params: 704
_________________________________________________________________
Epoch 1/43

model_history = model.fit(x_train,y_train1, batch_size=32, epochs=43, verbose=1)

....................................................Error...........................................

Traceback (most recent call last):
  File "C:\Users\rulzem\PycharmProjects\fyp preprocessing\main.py", line 453, in <module>
    model_history = model.fit(x_train,y_train1, batch_size=32, epochs=43, verbose=1)
  File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
    raise e.with_traceback(filtered_tb) from None
  File "C:\Users\rulzem\AppData\Local\Temp\__autograph_generated_fileqs1j0crv.py", line 15, in tf__train_function
    retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:

    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1249, in train_function  *
        return step_function(self, iterator)
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1233, in step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1222, in run_step  **
        outputs = model.train_step(data)
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\training.py", line 1023, in train_step
        y_pred = self(x, training=True)
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\utils\traceback_utils.py", line 70, in error_handler
        raise e.with_traceback(filtered_tb) from None
    File "E:\BS-IT\semester no.7\Final Year Project- Capstone I\preprocessing\lib\site-packages\keras\engine\input_spec.py", line 295, in assert_input_compatibility
        raise ValueError(

    **ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 128, 1), found shape=(None, 1177)**

I am applying CNN model but at the time of model fitting i am getting errror, i tried many solutions but no one work


问:
How to paginate Laravel Analytics Collection data
I am using Laravel Analytics and calling Analytics data, I am trying to paginate the data but cannot:

Controller:

```<code>public function analytics()
{
    $analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(1))->paginate(10);
    $no = 0;
    return view('admin.analytics',compact(['analyticsData', 'TotalVisitors', 'no']));
}
</code>```

Views:

```<code><table class="table table-hover">
    <thead>
      <tr>
        <th>S.No.</th>
        <th scope="col">Date</th>
        <th scope="col">Visitors</th>
        <th scope="col">PageTitle</th>
        <th scope="col">PageViews</th>
      </tr>
    </thead>
      <tbody>
        @foreach ($analyticsData->sortBy('pageViews')->reverse() as $data)
        <tr>
          <td>{{ ++$no }}</td>
          <td>{{ $data['date'] }}</td>
          <td>{{ $data['visitors'] }}</td>
          <td>{{ $data['pageTitle'] }}</td>
          <td>{{ $data['pageViews'] }}</td>
        </tr>
        @endforeach
      </tbody>
</table>
 @if( $analyticsData->count() != 0 )
 {{ $analyticsData->links('pagination::bootstrap-4') }}
 @endif
</code>```

But I get an error: Method Illuminate\Support\Collection::paginate does not exist.

```<code>dd($analyticsData);
</code>```

gives me:

Body:
I am using Laravel Analytics and calling Analytics data, I am trying to paginate the data but cannot:

Controller:

public function analytics()
{
    $analyticsData = Analytics::fetchVisitorsAndPageViews(Period::days(1))->paginate(10);
    $no = 0;
    return view('admin.analytics',compact(['analyticsData', 'TotalVisitors', 'no']));
}

Views:

        S.No.
        Date
        Visitors
        PageTitle
        PageViews

        @foreach ($analyticsData->sortBy('pageViews')->reverse() as $data)

          {{ ++$no }}
          {{ $data['date'] }}
          {{ $data['visitors'] }}
          {{ $data['pageTitle'] }}
          {{ $data['pageViews'] }}

        @endforeach

 @if( $analyticsData->count() != 0 )
 {{ $analyticsData->links('pagination::bootstrap-4') }}
 @endif

But I get an error: Method Illuminate\Support\Collection::paginate does not exist.

dd($analyticsData);

gives me:


问:
Displaying multi lines in Material Button Toggle Group
I cannot display the multi lines in a single button, that I wanna do it like this wanted design below:

But it only ends up like this failed design below:

.

But I can't do anything in the android studio, in which I have tried multiple solutions using the
 or putting this

<string name="sedentary">Sedentary\n(no exercises)</string>
```

In string values, it doesn't work like I want in the image above. I used the Material Button Toggle Group, because it's the only function that could group the buttons nicely. So, is there any way that I could fix this?

Body:
I cannot display the multi lines in a single button, that I wanna do it like this wanted design below:

But it only ends up like this failed design below:

.

But I can't do anything in the android studio, in which I have tried multiple solutions using the
 or putting this

<string name="sedentary">Sedentary\n(no exercises)</string>

In string values, it doesn't work like I want in the image above. I used the Material Button Toggle Group, because it's the only function that could group the buttons nicely. So, is there any way that I could fix this?


问:
Python:ValueError: invalid literal for int() with base 10:
I have developed code for reversing number which was on leetcode.
I runned it on python idle it worked fine. But when i am trying to run it on leetcode it throws this error : ValueError: invalid literal for int() with base 10:
code on idle:

```<code>def Reverse(x):
    s_num = str(x)  //converting int to str
    r_num = s_num[::-1] //reversing str
    l= r_num
    temp = 0
    for i in range(l):
        num =(int(int(r_num[i]))*(10**(l-i-1)))+temp
        temp = num
    return num
print(Reverse(1212))

</code>```

code on leetcode:

```<code>class Solution:
    def reverse(self,x):
        s_num = str(x)
        r_num = s_num[: : -1]
        l= int(len(r_num))
        temp = 0
        for i in range(l):
            num = int(int(r_num[i]))  //showing error here
            mul = 10**(l-i-1)
            total = num*mul
        return total
</code>```

i tried converting string to integer twice

Body:
I have developed code for reversing number which was on leetcode.
I runned it on python idle it worked fine. But when i am trying to run it on leetcode it throws this error : ValueError: invalid literal for int() with base 10:
code on idle:

def Reverse(x):
    s_num = str(x)  //converting int to str
    r_num = s_num[::-1] //reversing str
    l= r_num
    temp = 0
    for i in range(l):
        num =(int(int(r_num[i]))*(10**(l-i-1)))+temp
        temp = num
    return num
print(Reverse(1212))

code on leetcode:

class Solution:
    def reverse(self,x):
        s_num = str(x)
        r_num = s_num[: : -1]
        l= int(len(r_num))
        temp = 0
        for i in range(l):
            num = int(int(r_num[i]))  //showing error here
            mul = 10**(l-i-1)
            total = num*mul
        return total

i tried converting string to integer twice


问:
NodeJS deployment
So, I'm running into port issues on Heroku. It is my first time deploying an app, and from the bugs that I've received it looks like have some port issues.

I have a nodejs project that I need to deploy. The project consists of three servers running on seperate ports. It's setup in the way that you just need to run npm run start and it starts the three different servers. The start scripts runs nodemon start.js and the start.js file looks like this

```<code>app_server();
rest_server();
auth_server();
</code>```

I understand that Heroku assigns a port through an environment variable to the first server that starts running (in this case app server), but other servers then run into problems and the project won't work properly on heroku. How should I proceed in deploying the whole project and not just one server. Thanks!

Title: NodeJS deployment

Body:
So, I'm running into port issues on Heroku. It is my first time deploying an app, and from the bugs that I've received it looks like have some port issues.

I have a nodejs project that I need to deploy. The project consists of three servers running on seperate ports. It's setup in the way that you just need to run npm run start and it starts the three different servers. The start scripts runs nodemon start.js and the start.js file looks like this

app_server();
rest_server();
auth_server();

I understand that Heroku assigns a port through an environment variable to the first server that starts running (in this case app server), but other servers then run into problems and the project won't work properly on heroku. How should I proceed in deploying the whole project and not just one server. Thanks!


问:
Why does an error occur when a line of code is repeatedly executed to the 4、50th time?
```<code>def main():
    …
    data = df.loc['correct_times', (df.loc['ans'] > np.percentile(df.loc['ans'], 80))]
    …
</code>```

I repeat my function hundreds of times. It takes about 30 seconds to execute a function, but every time I run it about 4 or 50 times, I get the following error in that string of code

UFuncTypeError: Cannot cast ufunc 'subtract' output from dtype('O') to dtype('float64') with casting rule 'same_kind'

What is the possible reason?

I use jupyterlab to run the program, the system is ubuntu, I have monitored the usage of each device, and it seems to be all right

Body:
def main():
    …
    data = df.loc['correct_times', (df.loc['ans'] > np.percentile(df.loc['ans'], 80))]
    …

I repeat my function hundreds of times. It takes about 30 seconds to execute a function, but every time I run it about 4 or 50 times, I get the following error in that string of code

UFuncTypeError: Cannot cast ufunc 'subtract' output from dtype('O') to dtype('float64') with casting rule 'same_kind'

What is the possible reason?

I use jupyterlab to run the program, the system is ubuntu, I have monitored the usage of each device, and it seems to be all right


问:
Android Service : java.lang.IllegalStateException: Calling View methods on another thread than the UI thread
I have been searching and trying many things from few days but nothing worked..

I have an appwidget. It has a Service and an Activity(launched when clicked on the button of widget).
This app widget loads webpage in it and shows it inside widget.

The page is loaded using service.
However after page is loaded, I want to open my app and launch a webview activity. But whenever I do that the app crashes saying : mywebService : java.lang.IllegalStateException: Calling View methods on another thread than the UI thread

I have tried running activity inside runonui runnable thread and inside Handler also. But nothing works.
Please any help is greatly Appreciated.

The service is attached below
Plesae help me~~

```<code>public class mywebService extends Service {
    public static final String BROADCASTRECIVER_MM_WIDGETS_FINISH = "BROADCASTRECIVER_MM_WIDGETS_FINISH";
    public static final String FILE_PREFIX = "mm_widget_";
    public static final Integer NOTIFICATION_ID = 123123;
    public static final String PARAM_DESKTOPMODE = "desktopmode";
    public static final String PARAM_FILE = "thumbnail";
    public static final String PARAM_HEIGHT = "height";
    public static final String PARAM_ID_WIDGET = "ID_WIDGET";
    public static final String PARAM_ID_WIDGET_APP = "PARAM_ID_WIDGET_APP";
    public static final String PARAM_JAVASCRIPT = "javascript";
    public static final String PARAM_TIMPOCARGA = "tiempocarga";
    public static final String PARAM_URL = "file_location";
    public static final String PARAM_WIDTH = "width";
    private static final mywebService instance = null;
    public static Boolean isRunning = false;

    public static Boolean isRunningtakeWebviewmyweb = false;

    public final String TAG = Utils.TAG_LOG;

    public Integer id_widget_app = 0;

    public Integer mID_Widget = 0;
    private ServiceHandler mServiceHandler;

    public Integer tiempoCarga = 1000;

    public mm_WidgetWebView webview;

    public String wholeAppLanguage;

    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onDestroy() {
//        this.stopService();
    }

    public static String getmm_WidgetFileName(Integer num) {
        return FILE_PREFIX + num.toString().trim() + ".png";
    }

    private final class ServiceHandler extends Handler {
        public int currentStartId;
        public boolean webviewmywebTaken = false;
        public   boolean redirect = false, loadingFinished = true;

        public ServiceHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message message) {
            try {
//                Utils.initInApp(mywebService.this.getBaseContext());
                final Intent intent = (Intent) message.obj;
                Integer unused = mywebService.this.mID_Widget = Integer.valueOf(intent.getIntExtra(mywebService.PARAM_ID_WIDGET, 0));
                Integer unused2 = mywebService.this.tiempoCarga = Integer.valueOf(intent.getIntExtra(mywebService.PARAM_TIMPOCARGA, 1000));
                Integer unused3 = mywebService.this.id_widget_app = Integer.valueOf(intent.getIntExtra(mywebService.PARAM_ID_WIDGET_APP, 0));
                this.currentStartId = message.arg1;
                mm_WidgetWebView unused4 = mywebService.this.webview = new mm_WidgetWebView(mywebService.this.getBaseContext());
                Log.i(mywebService.this.TAG, "Creating WebView");
                int intExtra = intent.getIntExtra(mywebService.PARAM_HEIGHT, Resources.getSystem().getDisplayMetrics().heightPixels);
                int intExtra2 = intent.getIntExtra(mywebService.PARAM_WIDTH, Resources.getSystem().getDisplayMetrics().widthPixels);
                mywebService.this.webview.measure(intExtra2, intExtra);
                mywebService.this.webview.layout(0, 0, intExtra2, intExtra);
                mywebService.this.webview.getSettings().setJavaScriptEnabled(true);
                mywebService.this.webview.getSettings().setDomStorageEnabled(true);
                Hawk.init(mywebService.this).build();

                Utils.setDesktopMode(mywebService.this.webview, false);

                mywebService.this.webview.setWebViewClient( new WebViewClient(){
                    @Override
                    public void onPageFinished(WebView view, String url) {

                        if (!redirect) {
                            loadingFinished = true;

                            //todo hide all things
                            Hawk.put("intentmyweb",intent);
                            String loadingUrl= mywebService.this.webview.getUrl();
                            ServiceHandler.this.takeWebviewmyweb(intent.getStringExtra(mywebService.PARAM_FILE));
                            mywebService.this.webview.loadUrl("javascript: (function(){window.scrollTo(0,0)})();");
}
                        else {
                            redirect = false;

                        }
                    }
                });

                //todo----------- Interface to get value from page and assign it to java variable step 3

                mywebService.this.webview.addJavascriptInterface(new WebAppInterface(getApplicationContext()), "Android");

                mywebService.this.webview.loadUrl(intent.getStringExtra(mywebService.PARAM_URL));
//                Toast.makeText(mywebService.this, "loading url", Toast.LENGTH_SHORT).show();
                Log.i(mywebService.this.TAG, "Loading URL: " + intent.getStringExtra(mywebService.PARAM_URL));

            }

            catch (Exception e3) {
                e3.printStackTrace();
                try {
                    stopService();
                } catch (Exception e4) {
                    e4.printStackTrace();
                }
            }

        }

        public void takeWebviewmyweb(final String str) { String str2=str;
            if (!mywebService.isRunningtakeWebviewmyweb.booleanValue()) {
                Log.i(mywebService.this.TAG, "Page finished, getting thumbnail");
                Boolean unused = mywebService.isRunningtakeWebviewmyweb = true;
                new Thread(new Runnable() {
                    public void run() {
                        Bitmap bitmap;
                        try {
                            if (mywebService.this.tiempoCarga.intValue() < 1000) {
                                Integer unused = mywebService.this.tiempoCarga = 1000;
                            }
                            TimeUnit.MILLISECONDS.sleep((long) mywebService.this.tiempoCarga.intValue());
                        } catch (Exception e) {
                            Log.e(mywebService.this.TAG, "InterruptedException when taking webview myweb ", e);
                        }
                        Hawk.init(mywebService.this).build();
                        String file_name =  Hawk.get("widg_file_name","1.png" );

                        String str;
                        str = mywebService.this.getFilesDir().getAbsolutePath() + File.separator + "mm_Widget" + File.separator + str2;
                        Log.e("SS Service "," Bitmap "+str2+"------------------------------------------------------");

                        bitmap = Utils.getBitmapFromView(mywebService.this.getBaseContext(), mywebService.this.webview);

                        Log.e("Str is : ",str);
                        ServiceHandler.this.webviewmywebTaken = true;
                        ServiceHandler.this.saveBitmapToFile(bitmap, new File(str));
                        ServiceHandler.this.stopService();
                        Log.i(mywebService.this.TAG, "sendBroadcast BROADCASTRECIVER_MM_WIDGETS_FINISH");
                        Intent intent = new Intent(mywebService.BROADCASTRECIVER_MM_WIDGETS_FINISH);
                        intent.putExtra(mywebService.PARAM_ID_WIDGET, mywebService.this.mID_Widget);
                        intent.putExtra(mywebService.PARAM_ID_WIDGET_APP, mywebService.this.id_widget_app);
                        intent.putExtra("appWidgetId", mywebService.this.id_widget_app);
                        mywebService.this.sendBroadcast(intent);
                    }
                }).start();
            }

//            int id= android.os.Process.myPid();
//            Log.e("I'm Killing :",String.valueOf(id));
//            android.os.Process.killProcess(id);
        }

        public void saveBitmapToFile(Bitmap bitmap, File file) {
            Log.i(mywebService.this.TAG, "sendBroadcast saveBitmapToFile");
            if (bitmap != null) {
                file.getParentFile().mkdirs();
                try {
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bufferedOutputStream);
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    Log.e(mywebService.this.TAG, "IoException while saving bitmap to file", e);
                }

                Log.i(mywebService.this.TAG, "Saved Bitmap to file: " + file.getPath());
            }
        }

        public void stopService() {
            if (this.webviewmywebTaken) {
                Log.i(mywebService.this.TAG, "Service stopped, with startId " + this.currentStartId + " completed");
                if (Build.VERSION.SDK_INT >= 26) {
                    mywebService.this.stopForeground(true);
                } else {
                    mywebService.this.stopSelf(this.currentStartId);
                }
                mywebService.isRunning = false;

            }
        }
    }

    public void onCreate() {
        try {
            if (Utils.thread == null) {
                Utils.thread = new HandlerThread("WebpagemywebService", 10);
                Utils.thread.start();
            }
            this.mServiceHandler = new ServiceHandler(Utils.thread.getLooper());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void cancelNotificationForeground(Context context) {
        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID.intValue());
    }

    public int onStartCommand(Intent intent, int i, int i2) {
        isRunning = true;
        isRunningtakeWebviewmyweb = false;
        if (Build.VERSION.SDK_INT >= 26) {
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(new NotificationChannel("mm_Widget", "mm_Widget", NotificationManager.IMPORTANCE_MIN));
            Notification build = new NotificationCompat.Builder(this, "mm_Widget").setContentTitle("").setContentText("").build();
            Integer num = NOTIFICATION_ID;
            ((NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE)).cancel(num.intValue());
            startForeground(num.intValue(), build);
        }
        Message obtainMessage = this.mServiceHandler.obtainMessage();
        obtainMessage.arg1 = i2;
        obtainMessage.obj = intent;
        this.mServiceHandler.sendMessage(obtainMessage);
        return START_NOT_STICKY;
    }

}
</code>```

Here is full logcat

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.naroda.walking, PID: 4656
    android.view.InflateException: Binary XML file line #34 in com.naroda.walking:layout/fragment_input_wordfest: Binary XML file line #34 in com.naroda.walking:layout/fragment_input_wordfest: Error inflating class android.webkit.WebView
    Caused by: android.view.InflateException: Binary XML file line #34 in com.naroda.walking:layout/fragment_input_wordfest: Error inflating class android.webkit.WebView
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:881)
        at android.view.LayoutInflater.createView(LayoutInflater.java:803)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:957)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:977)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1031)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:988)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1150)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:709)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:547)
        at com.naroda.walking.Fragment.WordFest_Fragments.InputScore.onCreateView(InputScore.java:107)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1899)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1817)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1760)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2985)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2895)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:263)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:351)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1456)
        at android.app.Activity.performStart(Activity.java:8210)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3765)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2260)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:210)
        at android.os.Looper.loop(Looper.java:299)
        at android.app.ActivityThread.main(ActivityThread.java:8168)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1037)
     Caused by: java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
        at com.android.webview.chromium.WebViewChromium.b(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:25)
        at com.android.webview.chromium.WebViewChromium.init(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:92)
2022-12-25 11:05:04.680 4656-4656/com.naroda.walking E/AndroidRuntime:     at android.webkit.WebView.<init>(WebView.java:443)
        at android.webkit.WebView.<init>(WebView.java:363)
        at android.webkit.WebView.<init>(WebView.java:345)
        at android.webkit.WebView.<init>(WebView.java:332)
            ... 40 more
2022-12-25 11:05:04.680 4656-5011/com.naroda.walking E/AndroidRuntime: FATAL EXCEPTION: WebpageScreenshotService
    Process: com.naroda.walking, PID: 4656
    java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
        at com.android.webview.chromium.WebViewChromium.b(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:12)
        at com.android.webview.chromium.WebViewChromium.init(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:92)
        at android.webkit.WebView.<init>(WebView.java:443)
        at android.webkit.WebView.<init>(WebView.java:363)
        at android.webkit.WebView.<init>(WebView.java:345)
        at android.webkit.WebView.<init>(WebView.java:332)
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:881)
        at android.view.LayoutInflater.createView(LayoutInflater.java:803)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:957)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:977)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1031)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:988)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1150)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:709)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:547)
        at com.naroda.walking.Fragment.WordFest_Fragments.InputScore.onCreateView(InputScore.java:107)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1899)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1817)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1760)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2985)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2895)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:263)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:351)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1456)
        at android.app.Activity.performStart(Activity.java:8210)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3765)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2260)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:210)
        at android.os.Looper.loop(Looper.java:299)
        at android.app.ActivityThread.main(ActivityThread.java:8168)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1037)
2022-12-25 11:05:04.684 4656-4656/com.naroda.walking D/OOMEventManagerFK: checkEventAndDumpForJE: 0
2022-12-25 11:05:04.684 4656-5011/com.naroda.walking D/OOMEventManagerFK: checkEventAndDumpForJE: 0
2022-12-25 11:05:04.690 4656-4656/com.naroda.walking I/Process: Sending signal. PID: 4656 SIG: 9
</code>```

Body:
I have been searching and trying many things from few days but nothing worked..

I have an appwidget. It has a Service and an Activity(launched when clicked on the button of widget).
This app widget loads webpage in it and shows it inside widget.

The page is loaded using service.
However after page is loaded, I want to open my app and launch a webview activity. But whenever I do that the app crashes saying : mywebService : java.lang.IllegalStateException: Calling View methods on another thread than the UI thread

I have tried running activity inside runonui runnable thread and inside Handler also. But nothing works.
Please any help is greatly Appreciated.

The service is attached below
Plesae help me~~

public class mywebService extends Service {
    public static final String BROADCASTRECIVER_MM_WIDGETS_FINISH = "BROADCASTRECIVER_MM_WIDGETS_FINISH";
    public static final String FILE_PREFIX = "mm_widget_";
    public static final Integer NOTIFICATION_ID = 123123;
    public static final String PARAM_DESKTOPMODE = "desktopmode";
    public static final String PARAM_FILE = "thumbnail";
    public static final String PARAM_HEIGHT = "height";
    public static final String PARAM_ID_WIDGET = "ID_WIDGET";
    public static final String PARAM_ID_WIDGET_APP = "PARAM_ID_WIDGET_APP";
    public static final String PARAM_JAVASCRIPT = "javascript";
    public static final String PARAM_TIMPOCARGA = "tiempocarga";
    public static final String PARAM_URL = "file_location";
    public static final String PARAM_WIDTH = "width";
    private static final mywebService instance = null;
    public static Boolean isRunning = false;

    public static Boolean isRunningtakeWebviewmyweb = false;

    public final String TAG = Utils.TAG_LOG;

    public Integer id_widget_app = 0;

    public Integer mID_Widget = 0;
    private ServiceHandler mServiceHandler;

    public Integer tiempoCarga = 1000;

    public mm_WidgetWebView webview;

    public String wholeAppLanguage;

    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onDestroy() {
//        this.stopService();
    }

    public static String getmm_WidgetFileName(Integer num) {
        return FILE_PREFIX + num.toString().trim() + ".png";
    }

    private final class ServiceHandler extends Handler {
        public int currentStartId;
        public boolean webviewmywebTaken = false;
        public   boolean redirect = false, loadingFinished = true;

        public ServiceHandler(Looper looper) {
            super(looper);
        }

        public void handleMessage(Message message) {
            try {
//                Utils.initInApp(mywebService.this.getBaseContext());
                final Intent intent = (Intent) message.obj;
                Integer unused = mywebService.this.mID_Widget = Integer.valueOf(intent.getIntExtra(mywebService.PARAM_ID_WIDGET, 0));
                Integer unused2 = mywebService.this.tiempoCarga = Integer.valueOf(intent.getIntExtra(mywebService.PARAM_TIMPOCARGA, 1000));
                Integer unused3 = mywebService.this.id_widget_app = Integer.valueOf(intent.getIntExtra(mywebService.PARAM_ID_WIDGET_APP, 0));
                this.currentStartId = message.arg1;
                mm_WidgetWebView unused4 = mywebService.this.webview = new mm_WidgetWebView(mywebService.this.getBaseContext());
                Log.i(mywebService.this.TAG, "Creating WebView");
                int intExtra = intent.getIntExtra(mywebService.PARAM_HEIGHT, Resources.getSystem().getDisplayMetrics().heightPixels);
                int intExtra2 = intent.getIntExtra(mywebService.PARAM_WIDTH, Resources.getSystem().getDisplayMetrics().widthPixels);
                mywebService.this.webview.measure(intExtra2, intExtra);
                mywebService.this.webview.layout(0, 0, intExtra2, intExtra);
                mywebService.this.webview.getSettings().setJavaScriptEnabled(true);
                mywebService.this.webview.getSettings().setDomStorageEnabled(true);
                Hawk.init(mywebService.this).build();

                Utils.setDesktopMode(mywebService.this.webview, false);

                mywebService.this.webview.setWebViewClient( new WebViewClient(){
                    @Override
                    public void onPageFinished(WebView view, String url) {

                        if (!redirect) {
                            loadingFinished = true;

                            //todo hide all things
                            Hawk.put("intentmyweb",intent);
                            String loadingUrl= mywebService.this.webview.getUrl();
                            ServiceHandler.this.takeWebviewmyweb(intent.getStringExtra(mywebService.PARAM_FILE));
                            mywebService.this.webview.loadUrl("javascript: (function(){window.scrollTo(0,0)})();");
}
                        else {
                            redirect = false;

                        }
                    }
                });

                //todo----------- Interface to get value from page and assign it to java variable step 3

                mywebService.this.webview.addJavascriptInterface(new WebAppInterface(getApplicationContext()), "Android");

                mywebService.this.webview.loadUrl(intent.getStringExtra(mywebService.PARAM_URL));
//                Toast.makeText(mywebService.this, "loading url", Toast.LENGTH_SHORT).show();
                Log.i(mywebService.this.TAG, "Loading URL: " + intent.getStringExtra(mywebService.PARAM_URL));

            }

            catch (Exception e3) {
                e3.printStackTrace();
                try {
                    stopService();
                } catch (Exception e4) {
                    e4.printStackTrace();
                }
            }

        }

        public void takeWebviewmyweb(final String str) { String str2=str;
            if (!mywebService.isRunningtakeWebviewmyweb.booleanValue()) {
                Log.i(mywebService.this.TAG, "Page finished, getting thumbnail");
                Boolean unused = mywebService.isRunningtakeWebviewmyweb = true;
                new Thread(new Runnable() {
                    public void run() {
                        Bitmap bitmap;
                        try {
                            if (mywebService.this.tiempoCarga.intValue() < 1000) {
                                Integer unused = mywebService.this.tiempoCarga = 1000;
                            }
                            TimeUnit.MILLISECONDS.sleep((long) mywebService.this.tiempoCarga.intValue());
                        } catch (Exception e) {
                            Log.e(mywebService.this.TAG, "InterruptedException when taking webview myweb ", e);
                        }
                        Hawk.init(mywebService.this).build();
                        String file_name =  Hawk.get("widg_file_name","1.png" );

                        String str;
                        str = mywebService.this.getFilesDir().getAbsolutePath() + File.separator + "mm_Widget" + File.separator + str2;
                        Log.e("SS Service "," Bitmap "+str2+"------------------------------------------------------");

                        bitmap = Utils.getBitmapFromView(mywebService.this.getBaseContext(), mywebService.this.webview);

                        Log.e("Str is : ",str);
                        ServiceHandler.this.webviewmywebTaken = true;
                        ServiceHandler.this.saveBitmapToFile(bitmap, new File(str));
                        ServiceHandler.this.stopService();
                        Log.i(mywebService.this.TAG, "sendBroadcast BROADCASTRECIVER_MM_WIDGETS_FINISH");
                        Intent intent = new Intent(mywebService.BROADCASTRECIVER_MM_WIDGETS_FINISH);
                        intent.putExtra(mywebService.PARAM_ID_WIDGET, mywebService.this.mID_Widget);
                        intent.putExtra(mywebService.PARAM_ID_WIDGET_APP, mywebService.this.id_widget_app);
                        intent.putExtra("appWidgetId", mywebService.this.id_widget_app);
                        mywebService.this.sendBroadcast(intent);
                    }
                }).start();
            }

//            int id= android.os.Process.myPid();
//            Log.e("I'm Killing :",String.valueOf(id));
//            android.os.Process.killProcess(id);
        }

        public void saveBitmapToFile(Bitmap bitmap, File file) {
            Log.i(mywebService.this.TAG, "sendBroadcast saveBitmapToFile");
            if (bitmap != null) {
                file.getParentFile().mkdirs();
                try {
                    BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bufferedOutputStream);
                    bufferedOutputStream.flush();
                    bufferedOutputStream.close();
                } catch (IOException e) {
                    Log.e(mywebService.this.TAG, "IoException while saving bitmap to file", e);
                }

                Log.i(mywebService.this.TAG, "Saved Bitmap to file: " + file.getPath());
            }
        }

        public void stopService() {
            if (this.webviewmywebTaken) {
                Log.i(mywebService.this.TAG, "Service stopped, with startId " + this.currentStartId + " completed");
                if (Build.VERSION.SDK_INT >= 26) {
                    mywebService.this.stopForeground(true);
                } else {
                    mywebService.this.stopSelf(this.currentStartId);
                }
                mywebService.isRunning = false;

            }
        }
    }

    public void onCreate() {
        try {
            if (Utils.thread == null) {
                Utils.thread = new HandlerThread("WebpagemywebService", 10);
                Utils.thread.start();
            }
            this.mServiceHandler = new ServiceHandler(Utils.thread.getLooper());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void cancelNotificationForeground(Context context) {
        ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).cancel(NOTIFICATION_ID.intValue());
    }

    public int onStartCommand(Intent intent, int i, int i2) {
        isRunning = true;
        isRunningtakeWebviewmyweb = false;
        if (Build.VERSION.SDK_INT >= 26) {
            ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(new NotificationChannel("mm_Widget", "mm_Widget", NotificationManager.IMPORTANCE_MIN));
            Notification build = new NotificationCompat.Builder(this, "mm_Widget").setContentTitle("").setContentText("").build();
            Integer num = NOTIFICATION_ID;
            ((NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE)).cancel(num.intValue());
            startForeground(num.intValue(), build);
        }
        Message obtainMessage = this.mServiceHandler.obtainMessage();
        obtainMessage.arg1 = i2;
        obtainMessage.obj = intent;
        this.mServiceHandler.sendMessage(obtainMessage);
        return START_NOT_STICKY;
    }

}

Here is full logcat

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.naroda.walking, PID: 4656
    android.view.InflateException: Binary XML file line #34 in com.naroda.walking:layout/fragment_input_wordfest: Binary XML file line #34 in com.naroda.walking:layout/fragment_input_wordfest: Error inflating class android.webkit.WebView
    Caused by: android.view.InflateException: Binary XML file line #34 in com.naroda.walking:layout/fragment_input_wordfest: Error inflating class android.webkit.WebView
    Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:881)
        at android.view.LayoutInflater.createView(LayoutInflater.java:803)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:957)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:977)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1031)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:988)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1150)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:709)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:547)
        at com.naroda.walking.Fragment.WordFest_Fragments.InputScore.onCreateView(InputScore.java:107)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1899)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1817)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1760)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2985)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2895)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:263)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:351)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1456)
        at android.app.Activity.performStart(Activity.java:8210)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3765)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2260)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:210)
        at android.os.Looper.loop(Looper.java:299)
        at android.app.ActivityThread.main(ActivityThread.java:8168)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1037)
     Caused by: java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
        at com.android.webview.chromium.WebViewChromium.b(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:25)
        at com.android.webview.chromium.WebViewChromium.init(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:92)
2022-12-25 11:05:04.680 4656-4656/com.naroda.walking E/AndroidRuntime:     at android.webkit.WebView.<init>(WebView.java:443)
        at android.webkit.WebView.<init>(WebView.java:363)
        at android.webkit.WebView.<init>(WebView.java:345)
        at android.webkit.WebView.<init>(WebView.java:332)
            ... 40 more
2022-12-25 11:05:04.680 4656-5011/com.naroda.walking E/AndroidRuntime: FATAL EXCEPTION: WebpageScreenshotService
    Process: com.naroda.walking, PID: 4656
    java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
        at com.android.webview.chromium.WebViewChromium.b(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:12)
        at com.android.webview.chromium.WebViewChromium.init(chromium-TrichromeWebViewGoogle6432.aab-beta-541404444:92)
        at android.webkit.WebView.<init>(WebView.java:443)
        at android.webkit.WebView.<init>(WebView.java:363)
        at android.webkit.WebView.<init>(WebView.java:345)
        at android.webkit.WebView.<init>(WebView.java:332)
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:881)
        at android.view.LayoutInflater.createView(LayoutInflater.java:803)
        at com.android.internal.policy.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:58)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:957)
        at android.view.LayoutInflater.onCreateView(LayoutInflater.java:977)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:1031)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:988)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:1150)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:1111)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:709)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:547)
        at com.naroda.walking.Fragment.WordFest_Fragments.InputScore.onCreateView(InputScore.java:107)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:3104)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:524)
        at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:261)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1899)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1817)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1760)
        at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2985)
        at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2895)
        at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:263)
        at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:351)
        at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:248)
        at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1456)
        at android.app.Activity.performStart(Activity.java:8210)
        at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3765)
        at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
        at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
        at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2260)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loopOnce(Looper.java:210)
        at android.os.Looper.loop(Looper.java:299)
        at android.app.ActivityThread.main(ActivityThread.java:8168)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:556)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1037)
2022-12-25 11:05:04.684 4656-4656/com.naroda.walking D/OOMEventManagerFK: checkEventAndDumpForJE: 0
2022-12-25 11:05:04.684 4656-5011/com.naroda.walking D/OOMEventManagerFK: checkEventAndDumpForJE: 0
2022-12-25 11:05:04.690 4656-4656/com.naroda.walking I/Process: Sending signal. PID: 4656 SIG: 9


问:
CMAKE wont configure even when I point it to compiler
I am trying to install OPENCV for codeblocks but i cannot get it working. I cant even get past the CMAKE part as it is complaining about the compiler. I looked in codeblocks which compiler i have been using and where it is

When I do or do not use this directory for the configuration as below it still complains about the compiler

I get this error

I am using codeblocks 20.03, openCV 4.6.0 and cmake 3.25.1. I Would like to get started with opencv but can even get it installed.. Could someone maybe explain what CMAKE even does and why its so complicated to install opencv? Why cant it be as simple as including a .c and a .h file in your project?


问:
ERROR in ./src/pages/Yoga/Yoga.js 108:56-88 : export 'Supporteds' (imported as 'poseDetection') was not found in '@tensorflow-models/pose-detection'
Compiled with problems:

ERROR in

./src/pages/Yoga/Yoga.js 108:56-88

export

'Supporteds' (imported as 'poseDetection') was not found in
'@tensorflow-models/pose-detection' (possible exports:
SupportedModels, TrackerType, calculators, createDetector, movenet,
util)

My code looks like this :

```<code>
import * as poseDetection from '@tensorflow-models/pose-detection';
import * as tf from '@tensorflow/tfjs';
import React, { useRef, useState, useEffect } from 'react'
//import backend from '@tensorflow/tfjs-backend-webgl'
import Webcam from 'react-webcam'
import { count } from '../../utils/music';

import Instructions from '../../components/Instructions/Instructions';

import './Yoga.css'

import DropDown from '../../components/DropDown/DropDown';
import { poseImages } from '../../utils/pose_images';
import { POINTS, keypointConnections } from '../../utils/data';
import { drawPoint, drawSegment } from '../../utils/helper'

let skeletonColor = 'rgb(255,255,255)'
let poseList = [
  'boat','camel','cow','downdog','eagle','fish','garland','halfmoon','peacock','plank','plow','sitting','tree','warrior2'
]

let interval

// flag variable is used to help capture the time when AI just detect
// the pose as correct(probability more than threshold)
let flag = false

function Yoga() {
  const webcamRef = useRef(null)
  const canvasRef = useRef(null)

  const [startingTime, setStartingTime] = useState(0)
  const [currentTime, setCurrentTime] = useState(0)
  const [poseTime, setPoseTime] = useState(0)
  const [bestPerform, setBestPerform] = useState(0)
  const [currentPose, setCurrentPose] = useState('tree')
  const [isStartPose, setIsStartPose] = useState(false)

  useEffect(() => {
    const timeDiff = (currentTime - startingTime)/1000
    if(flag) {
      setPoseTime(timeDiff)
    }
    if((currentTime - startingTime)/1000 > bestPerform) {
      setBestPerform(timeDiff)
    }
  }, [bestPerform, currentTime, startingTime])

  useEffect(() => {
    setCurrentTime(0)
    setPoseTime(0)
    setBestPerform(0)
  }, [currentPose])

  const CLASS_NO = {
    boat: 0,
    camel: 1,
    cow: 2,
    downdog: 3,
    eagle: 4,
    fish: 5,
    garland: 6,
    goddess:7,
    halfmoon:8,
    peacock:9,
    plank:10,
    plow:11,
    sitting:12,
    tree: 13,
    warrior:14,
  }

  function get_center_point(landmarks, left_bodypart, right_bodypart) {
    let left = tf.gather(landmarks, left_bodypart, 1)
    let right = tf.gather(landmarks, right_bodypart, 1)
    const center = tf.add(tf.mul(left, 0.5), tf.mul(right, 0.5))
    return center

  }

  function get_pose_size(landmarks, torso_size_multiplier=2.5) {
    let hips_center = get_center_point(landmarks, POINTS.LEFT_HIP, POINTS.RIGHT_HIP)
    let shoulders_center = get_center_point(landmarks,POINTS.LEFT_SHOULDER, POINTS.RIGHT_SHOULDER)
    let torso_size = tf.norm(tf.sub(shoulders_center, hips_center))
    let pose_center_new = get_center_point(landmarks, POINTS.LEFT_HIP, POINTS.RIGHT_HIP)
    pose_center_new = tf.expandDims(pose_center_new, 1)

    pose_center_new = tf.broadcastTo(pose_center_new,
        [1, 17, 2]
      )
      // return: shape(17,2)
    let d = tf.gather(tf.sub(landmarks, pose_center_new), 0, 0)
    let max_dist = tf.max(tf.norm(d,'euclidean', 0))

    // normalize scale
    let pose_size = tf.maximum(tf.mul(torso_size, torso_size_multiplier), max_dist)
    return pose_size
  }

  function normalize_pose_landmarks(landmarks) {
    let pose_center = get_center_point(landmarks, POINTS.LEFT_HIP, POINTS.RIGHT_HIP)
    pose_center = tf.expandDims(pose_center, 1)
    pose_center = tf.broadcastTo(pose_center,
        [1, 17, 2]
      )
    landmarks = tf.sub(landmarks, pose_center)

    let pose_size = get_pose_size(landmarks)
    landmarks = tf.div(landmarks, pose_size)
    return landmarks
  }

  function landmarks_to_embedding(landmarks) {
    // normalize landmarks 2D
    landmarks = normalize_pose_landmarks(tf.expandDims(landmarks, 0))
    let embedding = tf.reshape(landmarks, [1,34])
    return embedding
  }

  const runMovenet = async () => {
    const detectorConfig = {modelType: poseDetection.movenet.modelType.SINGLEPOSE_THUNDER};
    const detector = await poseDetection.createDetector(poseDetection.Supporteds.MoveNet, detectorConfig);
    const poseClassifier = await tf.loadLayersModel('https://models.s3.jp-tok.cloud-object-storage.appdomain.cloud/model.json')
    const countAudio = new Audio(count)
    countAudio.loop = true
    interval = setInterval(() => {
        detectPose(detector, poseClassifier, countAudio)
    }, 100)
  }

  const detectPose = async (detector, poseClassifier, countAudio) => {
    if (
      typeof webcamRef.current !== "undefined" &&
      webcamRef.current !== null &&
      webcamRef.current.video.readyState === 4
    ) {
      let notDetected = 0
      const video = webcamRef.current.video
      const pose = await detector.estimatePoses(video)
      const ctx = canvasRef.current.getContext('2d')
      ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
      try {
        const keypoints = pose[0].keypoints
        let input = keypoints.map((keypoint) => {
          if(keypoint.score > 0.4) {
            if(!(keypoint.name === 'left_eye' || keypoint.name === 'right_eye')) {
              drawPoint(ctx, keypoint.x, keypoint.y, 8, 'rgb(255,255,255)')
              let connections = keypointConnections[keypoint.name]
              try {
                connections.forEach((connection) => {
                  let conName = connection.toUpperCase()
                  drawSegment(ctx, [keypoint.x, keypoint.y],
                      [keypoints[POINTS[conName]].x,
                       keypoints[POINTS[conName]].y]
                  , skeletonColor)
                })
              } catch(err) {

              }

            }
          } else {
            notDetected += 1
          }
          return [keypoint.x, keypoint.y]
        })
        if(notDetected > 4) {
          skeletonColor = 'rgb(255,255,255)'
          return
        }
        const processedInput = landmarks_to_embedding(input)
        const classification = poseClassifier.predict(processedInput)

        classification.array().then((data) => {
          const classNo = CLASS_NO[currentPose]
          console.log(data[0][classNo])
          if(data[0][classNo] > 0.97) {

            if(!flag) {
              countAudio.play()
              setStartingTime(new Date(Date()).getTime())
              flag = true
            }
            setCurrentTime(new Date(Date()).getTime())
            skeletonColor = 'rgb(0,255,0)'
          } else {
            flag = false
            skeletonColor = 'rgb(255,255,255)'
            countAudio.pause()
            countAudio.currentTime = 0
          }
        })
      } catch(err) {
        console.log(err)
      }

    }
  }

  function startYoga(){
    setIsStartPose(true)
    runMovenet()
  }

  function stopPose() {
    setIsStartPose(false)
    clearInterval(interval)
  }

  if(isStartPose) {
    return (
      <div className="yoga-container">
        <div className="performance-container">
            <div className="pose-performance">
              <h4>Pose Time: {poseTime} s</h4>
            </div>
            <div className="pose-performance">
              <h4>Best: {bestPerform} s</h4>
            </div>
          </div>
        <div>

          <Webcam
          width='640px'
          height='480px'
          id="webcam"
          ref={webcamRef}
          style={{
            position: 'absolute',
            left: 120,
            top: 100,
            padding: '0px',
          }}
        />
          <canvas
            ref={canvasRef}
            id="my-canvas"
            width='640px'
            height='480px'
            style={{
              position: 'absolute',
              left: 120,
              top: 100,
              zIndex: 1
            }}
          >
          </canvas>
        <div>
            <img
              src={poseImages[currentPose]}
              className="pose-img"
            alt="" />
          </div>

        </div>
        <button
          onClick={stopPose}
          className="secondary-btn"
        >Stop Pose</button>
      </div>
    )
  }

  return (
    <div
      className="yoga-container"
    >
      <DropDown
        poseList={poseList}
        currentPose={currentPose}
        setCurrentPose={setCurrentPose}
      />
      <Instructions
          currentPose={currentPose}
        />
      <button
          onClick={startYoga}
          className="secondary-btn"
        >Start Pose</button>
    </div>
  )
}

export default Yoga;

</code>```

My package.json looks like this :

```<code>
{
  "name": "yoga_guru",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@tensorflow-models/pose-detection": "^2.0.0",
    "@tensorflow/tfjs-converter": "^4.1.0",
    "@tensorflow/tfjs-core": "^4.1.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

</code>```

Any suggestions for how to resolve that error?

Body:
Compiled with problems:

ERROR in

./src/pages/Yoga/Yoga.js 108:56-88

export

'Supporteds' (imported as 'poseDetection') was not found in
'@tensorflow-models/pose-detection' (possible exports:
SupportedModels, TrackerType, calculators, createDetector, movenet,
util)

My code looks like this :

import * as poseDetection from '@tensorflow-models/pose-detection';
import * as tf from '@tensorflow/tfjs';
import React, { useRef, useState, useEffect } from 'react'
//import backend from '@tensorflow/tfjs-backend-webgl'
import Webcam from 'react-webcam'
import { count } from '../../utils/music';

import Instructions from '../../components/Instructions/Instructions';

import './Yoga.css'

import DropDown from '../../components/DropDown/DropDown';
import { poseImages } from '../../utils/pose_images';
import { POINTS, keypointConnections } from '../../utils/data';
import { drawPoint, drawSegment } from '../../utils/helper'

let skeletonColor = 'rgb(255,255,255)'
let poseList = [
  'boat','camel','cow','downdog','eagle','fish','garland','halfmoon','peacock','plank','plow','sitting','tree','warrior2'
]

let interval

// flag variable is used to help capture the time when AI just detect
// the pose as correct(probability more than threshold)
let flag = false

function Yoga() {
  const webcamRef = useRef(null)
  const canvasRef = useRef(null)

  const [startingTime, setStartingTime] = useState(0)
  const [currentTime, setCurrentTime] = useState(0)
  const [poseTime, setPoseTime] = useState(0)
  const [bestPerform, setBestPerform] = useState(0)
  const [currentPose, setCurrentPose] = useState('tree')
  const [isStartPose, setIsStartPose] = useState(false)

  useEffect(() => {
    const timeDiff = (currentTime - startingTime)/1000
    if(flag) {
      setPoseTime(timeDiff)
    }
    if((currentTime - startingTime)/1000 > bestPerform) {
      setBestPerform(timeDiff)
    }
  }, [bestPerform, currentTime, startingTime])

  useEffect(() => {
    setCurrentTime(0)
    setPoseTime(0)
    setBestPerform(0)
  }, [currentPose])

  const CLASS_NO = {
    boat: 0,
    camel: 1,
    cow: 2,
    downdog: 3,
    eagle: 4,
    fish: 5,
    garland: 6,
    goddess:7,
    halfmoon:8,
    peacock:9,
    plank:10,
    plow:11,
    sitting:12,
    tree: 13,
    warrior:14,
  }

  function get_center_point(landmarks, left_bodypart, right_bodypart) {
    let left = tf.gather(landmarks, left_bodypart, 1)
    let right = tf.gather(landmarks, right_bodypart, 1)
    const center = tf.add(tf.mul(left, 0.5), tf.mul(right, 0.5))
    return center

  }

  function get_pose_size(landmarks, torso_size_multiplier=2.5) {
    let hips_center = get_center_point(landmarks, POINTS.LEFT_HIP, POINTS.RIGHT_HIP)
    let shoulders_center = get_center_point(landmarks,POINTS.LEFT_SHOULDER, POINTS.RIGHT_SHOULDER)
    let torso_size = tf.norm(tf.sub(shoulders_center, hips_center))
    let pose_center_new = get_center_point(landmarks, POINTS.LEFT_HIP, POINTS.RIGHT_HIP)
    pose_center_new = tf.expandDims(pose_center_new, 1)

    pose_center_new = tf.broadcastTo(pose_center_new,
        [1, 17, 2]
      )
      // return: shape(17,2)
    let d = tf.gather(tf.sub(landmarks, pose_center_new), 0, 0)
    let max_dist = tf.max(tf.norm(d,'euclidean', 0))

    // normalize scale
    let pose_size = tf.maximum(tf.mul(torso_size, torso_size_multiplier), max_dist)
    return pose_size
  }

  function normalize_pose_landmarks(landmarks) {
    let pose_center = get_center_point(landmarks, POINTS.LEFT_HIP, POINTS.RIGHT_HIP)
    pose_center = tf.expandDims(pose_center, 1)
    pose_center = tf.broadcastTo(pose_center,
        [1, 17, 2]
      )
    landmarks = tf.sub(landmarks, pose_center)

    let pose_size = get_pose_size(landmarks)
    landmarks = tf.div(landmarks, pose_size)
    return landmarks
  }

  function landmarks_to_embedding(landmarks) {
    // normalize landmarks 2D
    landmarks = normalize_pose_landmarks(tf.expandDims(landmarks, 0))
    let embedding = tf.reshape(landmarks, [1,34])
    return embedding
  }

  const runMovenet = async () => {
    const detectorConfig = {modelType: poseDetection.movenet.modelType.SINGLEPOSE_THUNDER};
    const detector = await poseDetection.createDetector(poseDetection.Supporteds.MoveNet, detectorConfig);
    const poseClassifier = await tf.loadLayersModel('https://models.s3.jp-tok.cloud-object-storage.appdomain.cloud/model.json')
    const countAudio = new Audio(count)
    countAudio.loop = true
    interval = setInterval(() => {
        detectPose(detector, poseClassifier, countAudio)
    }, 100)
  }

  const detectPose = async (detector, poseClassifier, countAudio) => {
    if (
      typeof webcamRef.current !== "undefined" &&
      webcamRef.current !== null &&
      webcamRef.current.video.readyState === 4
    ) {
      let notDetected = 0
      const video = webcamRef.current.video
      const pose = await detector.estimatePoses(video)
      const ctx = canvasRef.current.getContext('2d')
      ctx.clearRect(0, 0, canvasRef.current.width, canvasRef.current.height);
      try {
        const keypoints = pose[0].keypoints
        let input = keypoints.map((keypoint) => {
          if(keypoint.score > 0.4) {
            if(!(keypoint.name === 'left_eye' || keypoint.name === 'right_eye')) {
              drawPoint(ctx, keypoint.x, keypoint.y, 8, 'rgb(255,255,255)')
              let connections = keypointConnections[keypoint.name]
              try {
                connections.forEach((connection) => {
                  let conName = connection.toUpperCase()
                  drawSegment(ctx, [keypoint.x, keypoint.y],
                      [keypoints[POINTS[conName]].x,
                       keypoints[POINTS[conName]].y]
                  , skeletonColor)
                })
              } catch(err) {

              }

            }
          } else {
            notDetected += 1
          }
          return [keypoint.x, keypoint.y]
        })
        if(notDetected > 4) {
          skeletonColor = 'rgb(255,255,255)'
          return
        }
        const processedInput = landmarks_to_embedding(input)
        const classification = poseClassifier.predict(processedInput)

        classification.array().then((data) => {
          const classNo = CLASS_NO[currentPose]
          console.log(data[0][classNo])
          if(data[0][classNo] > 0.97) {

            if(!flag) {
              countAudio.play()
              setStartingTime(new Date(Date()).getTime())
              flag = true
            }
            setCurrentTime(new Date(Date()).getTime())
            skeletonColor = 'rgb(0,255,0)'
          } else {
            flag = false
            skeletonColor = 'rgb(255,255,255)'
            countAudio.pause()
            countAudio.currentTime = 0
          }
        })
      } catch(err) {
        console.log(err)
      }

    }
  }

  function startYoga(){
    setIsStartPose(true)
    runMovenet()
  }

  function stopPose() {
    setIsStartPose(false)
    clearInterval(interval)
  }

  if(isStartPose) {
    return (

Pose Time: {poseTime} s

Best: {bestPerform} s

          <Webcam
          width='640px'
          height='480px'
          id="webcam"
          ref={webcamRef}
          style={{
            position: 'absolute',
            left: 120,
            top: 100,
            padding: '0px',
          }}
        />
          <canvas
            ref={canvasRef}
            id="my-canvas"
            width='640px'
            height='480px'
            style={{
              position: 'absolute',
              left: 120,
              top: 100,
              zIndex: 1
            }}
          >
          </canvas>

        <button
          onClick={stopPose}
          className="secondary-btn"
        >Stop Pose</button>

    )
  }

  return (

      <DropDown
        poseList={poseList}
        currentPose={currentPose}
        setCurrentPose={setCurrentPose}
      />
      <Instructions
          currentPose={currentPose}
        />
      <button
          onClick={startYoga}
          className="secondary-btn"
        >Start Pose</button>

  )
}

export default Yoga;

My package.json looks like this :

{
  "name": "yoga_guru",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@tensorflow-models/pose-detection": "^2.0.0",
    "@tensorflow/tfjs-converter": "^4.1.0",
    "@tensorflow/tfjs-core": "^4.1.0",
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Any suggestions for how to resolve that error?


问:
Java difference between write a code by 2 type
I am thinking about that. what is difference between writing code..

```<code>int[] arr1 = {1,2,3} ;
</code>```

and

```<code>int[] arr2 = new int[]{1,2,3} ;
</code>```

Recently I give a interview in which round-1 online test they write like this so i just think about it.

Body:
I am thinking about that. what is difference between writing code..

int[] arr1 = {1,2,3} ;

and

int[] arr2 = new int[]{1,2,3} ;

Recently I give a interview in which round-1 online test they write like this so i just think about it.


问:
Bookdown - Add space between side by side figures using knitr::include_graphics
The recomended way to include existing images in bookdown is using knitr::include_graphics.

For example, to put two images side by side code will be something like:

```<code>```{r myfigure fig.show='hold', fig.align='center', out.width='50%', fig.cap = ""}
fig1_path <- paste0(fig_path,"image1.png")
fig2_path <- paste0(fig_path,"image2.png")

knitr::include_graphics(c(fig1_path, fig2_path))
```
</code>```

However, this produces html and latex where the images are very close each other. It would be desirable to add some space/padding/margin between to look better.

For the html case, this is easy to fix because we can add some external css to control the space. However, for the latex output i don't have any decent solution yet.

Im thinking a portable workaround could be to add an extra empty image between or add lateral space to both images, but i prefer to hear better suggestions.

Body:
The recomended way to include existing images in bookdown is using knitr::include_graphics.

For example, to put two images side by side code will be something like:

```{r myfigure fig.show='hold', fig.align='center', out.width='50%', fig.cap = ""}
fig1_path <- paste0(fig_path,"image1.png")
fig2_path <- paste0(fig_path,"image2.png")

knitr::include_graphics(c(fig1_path, fig2_path))
```

However, this produces html and latex where the images are very close each other. It would be desirable to add some space/padding/margin between to look better.

For the html case, this is easy to fix because we can add some external css to control the space. However, for the latex output i don't have any decent solution yet.

Im thinking a portable workaround could be to add an extra empty image between or add lateral space to both images, but i prefer to hear better suggestions.


问:
Can't install R packages, getting error '& was unexpected at this time.'
I have a strange error which seems like it's not coming through R, but through powershell (at least based on the terminal-esque style). I just reinstalled R due to some issues, and it's been working alright. I installed the most recent R 4.2.2, then the most recent Rstudio, but then that Rstudio couldn't find my version of R even when I directed it to the folder. I gave in and uninstalled Rstudio and installed the version right before it. This seemed to work okay, until now when I'm trying to install packages (both through install.packages, and through devtools). It gives the error:

```<code>> install.packages('RSQLite')
Installing package into ‘C:/Users/Ryan/AppData/Local/R/win-library/4.2’
(as ‘lib’ is unspecified)

  There is a binary version available but the source version is later:
        binary source needs_compilation
RSQLite 2.2.19 2.2.20              TRUE

installing the source package ‘RSQLite’

trying URL 'https://cran.rstudio.com/src/contrib/RSQLite_2.2.20.tar.gz'
Content type 'application/x-gzip' length 3745301 bytes (3.6 MB)
downloaded 3.6 MB

& was unexpected at this time.
Warning in install.packages :
  installation of package ‘RSQLite’ had non-zero exit status

The downloaded source packages are in
    ‘C:\Users\Ryan\AppData\Local\Temp\Rtmp4uP1BH\downloaded_packages’
</code>```

or it gives:

```<code>> devtools::install_github("r-dbi/RSQLite")
Downloading GitHub repo r-dbi/RSQLite@HEAD
── R CMD build ───────────────────────────────────────────────────────────────────────
   & was unexpected at this time.
Error: Failed to install 'RSQLite' from GitHub:
  ! System command 'Rcmd.exe' failed
</code>```

I've previously installed packages on this R version and it just stopped working now. I'm no expert in R and I would appreciate any help or guidance. If you need any more information let me know and I'll update the post.

I'm running Windows 11.

Body:
I have a strange error which seems like it's not coming through R, but through powershell (at least based on the terminal-esque style). I just reinstalled R due to some issues, and it's been working alright. I installed the most recent R 4.2.2, then the most recent Rstudio, but then that Rstudio couldn't find my version of R even when I directed it to the folder. I gave in and uninstalled Rstudio and installed the version right before it. This seemed to work okay, until now when I'm trying to install packages (both through install.packages, and through devtools). It gives the error:

> install.packages('RSQLite')
Installing package into ‘C:/Users/Ryan/AppData/Local/R/win-library/4.2’
(as ‘lib’ is unspecified)

  There is a binary version available but the source version is later:
        binary source needs_compilation
RSQLite 2.2.19 2.2.20              TRUE

installing the source package ‘RSQLite’

trying URL 'https://cran.rstudio.com/src/contrib/RSQLite_2.2.20.tar.gz'
Content type 'application/x-gzip' length 3745301 bytes (3.6 MB)
downloaded 3.6 MB

& was unexpected at this time.
Warning in install.packages :
  installation of package ‘RSQLite’ had non-zero exit status

The downloaded source packages are in
    ‘C:\Users\Ryan\AppData\Local\Temp\Rtmp4uP1BH\downloaded_packages’

or it gives:

> devtools::install_github("r-dbi/RSQLite")
Downloading GitHub repo r-dbi/RSQLite@HEAD
── R CMD build ───────────────────────────────────────────────────────────────────────
   & was unexpected at this time.
Error: Failed to install 'RSQLite' from GitHub:
  ! System command 'Rcmd.exe' failed

I've previously installed packages on this R version and it just stopped working now. I'm no expert in R and I would appreciate any help or guidance. If you need any more information let me know and I'll update the post.

I'm running Windows 11.


问:
Divolte session don't time out within a page-view if window time beyond the session timeout (default 30 minutes)
Hi team can you guide me on this divolte issue
https://github.com/divolte/divolte-collector/issues/163

I am writing here actually that Divolte repository has been archived by the owner.

When a session is created and there is no activity (i-e no events/tags generated from the client .js) during a window time beyond the session timeout (default 30 minutes), the session id is not regenerated for the next event while it should be.

and I want TO FORCE_CLOSE my session as well so the user can force close it any time whenever they want before the time and intimate the server for the same that session is closed by user, so calculate the loss

If anybody guide me on this , this would be really helpful
If anybody wants to refer another open source library for tracking events then also please suggest

this would be really helpful